swupdate-common.bbclass 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. # Copyright (C) 2015-2022 Stefano Babic
  2. #
  3. # SPDX-License-Identifier: GPLv3
  4. inherit swupdate-lib
  5. DEPENDS += "\
  6. cpio-native \
  7. ${@ 'openssl-native' if d.getVar('SWUPDATE_SIGNING') or d.getVar('SWUPDATE_ENCRYPT_SWDESC') or d.getVarFlags('SWUPDATE_IMAGES_ENCRYPTED') else ''} \
  8. "
  9. do_swuimage[umask] = "022"
  10. SSTATETASKS += "do_swuimage"
  11. SSTATE_SKIP_CREATION:task-swuimage = '1'
  12. SWUDEPLOYDIR = "${WORKDIR}/deploy-${PN}-swuimage"
  13. do_swuimage[dirs] = "${SWUDEPLOYDIR}"
  14. do_swuimage[cleandirs] += "${SWUDEPLOYDIR}"
  15. do_swuimage[sstate-inputdirs] = "${SWUDEPLOYDIR}"
  16. do_swuimage[sstate-outputdirs] = "${DEPLOY_DIR_IMAGE}"
  17. do_swuimage[stamp-extra-info] = "${MACHINE}"
  18. python () {
  19. deps = " " + swupdate_getdepends(d)
  20. d.appendVarFlag('do_swuimage', 'depends', deps)
  21. d.delVarFlag('do_fetch', 'noexec')
  22. d.delVarFlag('do_unpack', 'noexec')
  23. }
  24. def get_pwd_file_args(d, passfile):
  25. pwd_args = []
  26. pwd_file = d.getVar(passfile, True)
  27. if pwd_file:
  28. pwd_args = ["-passin", "file:%s" % pwd_file]
  29. return pwd_args
  30. def get_certfile_args(d):
  31. extra_certs = d.getVar('SWUPDATE_CMS_EXTRA_CERTS', True)
  32. if not extra_certs:
  33. return []
  34. certfile_args = []
  35. extra_paths = extra_certs.split()
  36. for crt_path in extra_paths:
  37. if not os.path.exists(crt_path):
  38. bb.fatal("SWUPDATE_CMS_EXTRA_CERTS path %s doesn't exist" % (crt_path))
  39. certfile_args.extend(["-certfile", crt_path])
  40. return certfile_args
  41. def swupdate_getdepends(d):
  42. def adddep(depstr, deps):
  43. for i in (depstr or "").split():
  44. if i not in deps:
  45. deps.append(i)
  46. deps = []
  47. images = (d.getVar('IMAGE_DEPENDS', True) or "").split()
  48. for image in images:
  49. adddep(image , deps)
  50. depstr = ""
  51. for dep in deps:
  52. depstr += " " + dep + ":do_build"
  53. return depstr
  54. def swupdate_write_sha256(s):
  55. import re
  56. write_lines = []
  57. with open(os.path.join(s, "sw-description"), 'r') as f:
  58. for line in f:
  59. shastr = r"sha256.+=.+@(.+\")"
  60. m = re.match(r"^(?P<before_placeholder>.+)(sha256|version).+[=:].*(?P<quote>[\'\"])@(?P<filename>.*)(?P=quote)", line)
  61. if m:
  62. filename = m.group('filename')
  63. bb.warn("Syntax for sha256 changed, please use $swupdate_get_sha256(%s)" % filename)
  64. hash = swupdate_get_sha256(None, s, filename)
  65. write_lines.append(line.replace("@%s" % (filename), hash))
  66. else:
  67. write_lines.append(line)
  68. with open(os.path.join(s, "sw-description"), 'w+') as f:
  69. for line in write_lines:
  70. f.write(line)
  71. def swupdate_exec_functions(d, s, write_lines):
  72. import re
  73. for index, line in enumerate(write_lines):
  74. m = re.match(r"^(?P<before_placeholder>.+)\$(?P<bitbake_function_name>\w+)\((?P<parms>.+)\)(?P<after_placeholder>.+)$", line)
  75. if m:
  76. fun = m.group('bitbake_function_name') + "(d, \"" + s + "\", \"" + m.group('parms') + "\")"
  77. ret = eval(fun)
  78. bb.debug (2, "%s return %s " % (m.group('bitbake_function_name'), ret))
  79. line = m.group('before_placeholder') + ret + m.group('after_placeholder') + "\n"
  80. write_lines[index] = line
  81. def swupdate_expand_bitbake_variables(d, s):
  82. write_lines = []
  83. with open(os.path.join(s, "sw-description"), 'r') as f:
  84. import re
  85. for line in f:
  86. found = False
  87. while True:
  88. m = re.match(r"^(?P<before_placeholder>.+)@@(?P<bitbake_variable_name>\w+)@@(?P<after_placeholder>.+)$", line)
  89. if m:
  90. bitbake_variable_value = d.getVar(m.group('bitbake_variable_name'), True)
  91. if bitbake_variable_value is None:
  92. bitbake_variable_value = ""
  93. bb.warn("BitBake variable %s not set" % (m.group('bitbake_variable_name')))
  94. line = m.group('before_placeholder') + bitbake_variable_value + m.group('after_placeholder')
  95. found = True
  96. continue
  97. else:
  98. m = re.match(r"^(?P<before_placeholder>.+)@@(?P<bitbake_variable_name>.+)\[(?P<flag_var_name>.+)\]@@(?P<after_placeholder>.+)$", line)
  99. if m:
  100. bitbake_variable_value = (d.getVarFlag(m.group('bitbake_variable_name'), m.group('flag_var_name'), True) or "")
  101. if bitbake_variable_value is None:
  102. bitbake_variable_value = ""
  103. line = m.group('before_placeholder') + bitbake_variable_value + m.group('after_placeholder')
  104. continue
  105. if found:
  106. line = line + "\n"
  107. break
  108. write_lines.append(line)
  109. swupdate_exec_functions(d, s, write_lines)
  110. with open(os.path.join(s, "sw-description"), 'w+') as f:
  111. for line in write_lines:
  112. f.write(line)
  113. # Get all the variables referred by the sw-description at parse time.
  114. def swupdate_find_bitbake_variables(d):
  115. import re
  116. vardeps = []
  117. filespath = d.getVar('FILESPATH')
  118. sw_desc_path = bb.utils.which(filespath, "sw-description")
  119. try:
  120. with open(sw_desc_path, "r") as f:
  121. for line in f:
  122. found = False
  123. while True:
  124. m = re.match(r"^(?P<before_placeholder>.+)@@(?P<bitbake_variable_name>\w+)@@(?P<after_placeholder>.+)$", line)
  125. if m:
  126. bitbake_variable_value = m.group('bitbake_variable_name')
  127. vardeps.append(bitbake_variable_value)
  128. line = m.group('before_placeholder') + bitbake_variable_value + m.group('after_placeholder')
  129. found = True
  130. continue
  131. else:
  132. m = re.match(r"^(?P<before_placeholder>.+)@@(?P<bitbake_variable_name>.+)\[(?P<flag_var_name>.+)\]@@(?P<after_placeholder>.+)$", line)
  133. if m:
  134. bitbake_variable_value = m.group('bitbake_variable_name')
  135. vardeps.append(bitbake_variable_value)
  136. flag_name = m.group('flag_var_name')
  137. vardeps.append(flag_name)
  138. line = m.group('before_placeholder') + bitbake_variable_value + m.group('after_placeholder')
  139. continue
  140. break
  141. except IOError:
  142. pass
  143. return ' '.join(set(vardeps))
  144. def prepare_sw_description(d):
  145. import shutil
  146. import subprocess
  147. s = d.getVar('S', True)
  148. swupdate_expand_bitbake_variables(d, s)
  149. swupdate_write_sha256(s)
  150. encrypt = d.getVar('SWUPDATE_ENCRYPT_SWDESC', True)
  151. if encrypt:
  152. bb.note("Encryption of sw-description")
  153. shutil.copyfile(os.path.join(s, 'sw-description'), os.path.join(s, 'sw-description.plain'))
  154. key,iv = swupdate_extract_keys(d.getVar('SWUPDATE_AES_FILE', True))
  155. swupdate_encrypt_file(os.path.join(s, 'sw-description.plain'), os.path.join(s, 'sw-description'), key, iv)
  156. signing = d.getVar('SWUPDATE_SIGNING', True)
  157. if signing == "1":
  158. bb.warn('SWUPDATE_SIGNING = "1" is deprecated, falling back to "RSA". It is advised to set it to "RSA" if using RSA signing.')
  159. signing = "RSA"
  160. if signing:
  161. sw_desc_sig = os.path.join(s, 'sw-description.sig')
  162. sw_desc = os.path.join(s, 'sw-description.plain' if encrypt else 'sw-description')
  163. if signing == "CUSTOM":
  164. signcmd = []
  165. sign_tool = d.getVar('SWUPDATE_SIGN_TOOL', True)
  166. signtool = sign_tool.split()
  167. for i in range(len(signtool)):
  168. signcmd.append(signtool[i])
  169. if not signcmd:
  170. bb.fatal("Custom SWUPDATE_SIGN_TOOL is not given")
  171. elif signing == "RSA":
  172. privkey = d.getVar('SWUPDATE_PRIVATE_KEY', True)
  173. if not privkey:
  174. bb.fatal("SWUPDATE_PRIVATE_KEY isn't set")
  175. if not os.path.exists(privkey):
  176. bb.fatal("SWUPDATE_PRIVATE_KEY %s doesn't exist" % (privkey))
  177. signcmd = ["openssl", "dgst", "-sha256", "-sign", privkey] + get_pwd_file_args(d, 'SWUPDATE_PASSWORD_FILE') + ["-out", sw_desc_sig, sw_desc]
  178. elif signing == "CMS":
  179. cms_cert = d.getVar('SWUPDATE_CMS_CERT', True)
  180. if not cms_cert:
  181. bb.fatal("SWUPDATE_CMS_CERT is not set")
  182. if not os.path.exists(cms_cert):
  183. bb.fatal("SWUPDATE_CMS_CERT %s doesn't exist" % (cms_cert))
  184. cms_key = d.getVar('SWUPDATE_CMS_KEY', True)
  185. if not cms_key:
  186. bb.fatal("SWUPDATE_CMS_KEY isn't set")
  187. if not os.path.exists(cms_key):
  188. bb.fatal("SWUPDATE_CMS_KEY %s doesn't exist" % (cms_key))
  189. signcmd = ["openssl", "cms", "-sign", "-in", sw_desc, "-out", sw_desc_sig, "-signer", cms_cert, "-inkey", cms_key] + \
  190. ["-outform", "DER", "-nosmimecap", "-binary"] + \
  191. get_pwd_file_args(d, 'SWUPDATE_PASSWORD_FILE') + \
  192. get_certfile_args(d)
  193. else:
  194. bb.fatal("Unrecognized SWUPDATE_SIGNING mechanism.")
  195. subprocess.run(' '.join(signcmd), shell=True, check=True)
  196. def swupdate_add_src_uri(d, list_for_cpio):
  197. import shutil
  198. s = d.getVar('S', True)
  199. exclude = (d.getVar("SWUPDATE_SRC_URI_EXCLUDE") or "").split()
  200. fetch = bb.fetch2.Fetch([], d)
  201. # Add files listed in SRC_URI to the swu file
  202. for url in fetch.urls:
  203. local = fetch.localpath(url)
  204. filename = os.path.basename(local)
  205. if filename in exclude:
  206. continue
  207. aes_file = d.getVar('SWUPDATE_AES_FILE', True)
  208. if aes_file:
  209. key,iv = swupdate_extract_keys(d.getVar('SWUPDATE_AES_FILE', True))
  210. if (filename != 'sw-description') and (os.path.isfile(local)):
  211. encrypted = (d.getVarFlag("SWUPDATE_IMAGES_ENCRYPTED", filename, True) or "")
  212. dst = os.path.join(s, "%s" % filename )
  213. if encrypted == '1':
  214. bb.note("Encryption requested for %s" %(filename))
  215. if not key or not iv:
  216. bb.fatal("Encryption required, but no key found")
  217. swupdate_encrypt_file(local, dst, key, iv)
  218. else:
  219. shutil.copyfile(local, dst)
  220. list_for_cpio.append(filename)
  221. def add_image_to_swu(d, deploydir, imagename, s, encrypt, list_for_cpio):
  222. import shutil
  223. src = os.path.join(deploydir, imagename)
  224. if not os.path.isfile(src):
  225. return False
  226. target_imagename = os.path.basename(imagename) # allow images in subfolders of DEPLOY_DIR_IMAGE
  227. dst = os.path.join(s, target_imagename)
  228. if encrypt == '1':
  229. key,iv = swupdate_extract_keys(d.getVar('SWUPDATE_AES_FILE', True))
  230. bb.note("Encryption requested for %s" %(imagename))
  231. swupdate_encrypt_file(src, dst, key, iv)
  232. else:
  233. shutil.copyfile(src, dst)
  234. list_for_cpio.append(target_imagename)
  235. return True
  236. def swupdate_add_artifacts(d, list_for_cpio):
  237. import shutil
  238. # Search for images listed in SWUPDATE_IMAGES in the DEPLOY directory.
  239. images = (d.getVar('SWUPDATE_IMAGES', True) or "").split()
  240. deploydir = d.getVar('DEPLOY_DIR_IMAGE', True)
  241. imgdeploydir = d.getVar('SWUDEPLOYDIR', True)
  242. s = d.getVar('S', True)
  243. for image in images:
  244. fstypes = (d.getVarFlag("SWUPDATE_IMAGES_FSTYPES", image, True) or "").split()
  245. encrypted = (d.getVarFlag("SWUPDATE_IMAGES_ENCRYPTED", image, True) or "")
  246. if fstypes:
  247. noappend_machine = d.getVarFlag("SWUPDATE_IMAGES_NOAPPEND_MACHINE", image, True)
  248. if noappend_machine == "0": # Search for a file explicitly with MACHINE
  249. imagebases = [ image + '-' + d.getVar('MACHINE', True) ]
  250. elif noappend_machine == "1": # Search for a file explicitly without MACHINE
  251. imagebases = [ image ]
  252. else: # None, means auto mode. Just try to find an image file with MACHINE or without MACHINE
  253. imagebases = [ image + '-' + d.getVar('MACHINE', True), image ]
  254. for fstype in fstypes:
  255. image_found = False
  256. for imagebase in imagebases:
  257. image_found = add_image_to_swu(d, deploydir, imagebase + fstype, s, encrypted, list_for_cpio)
  258. if image_found:
  259. break
  260. if not image_found:
  261. bb.fatal("swupdate cannot find image file: %s" % os.path.join(deploydir, imagebase + fstype))
  262. else: # Allow also complete entries like "image.ext4.gz" in SWUPDATE_IMAGES
  263. if not add_image_to_swu(d, deploydir, image, s, encrypted, list_for_cpio):
  264. bb.fatal("swupdate cannot find %s image file" % image)
  265. def swupdate_create_cpio(d, swudeploydir, list_for_cpio):
  266. s = d.getVar('S', True)
  267. os.chdir(s)
  268. updateimage = d.getVar('IMAGE_NAME', True) + '.swu'
  269. line = 'for i in ' + ' '.join(list_for_cpio) + '; do echo $i;done | cpio -ov -H crc --reproducible > ' + os.path.join(swudeploydir, updateimage)
  270. os.system(line)
  271. os.chdir(swudeploydir)
  272. updateimage_link = d.getVar('IMAGE_LINK_NAME', True)
  273. if updateimage_link:
  274. updateimage_link += '.swu'
  275. if updateimage_link != updateimage:
  276. os.symlink(updateimage, updateimage_link)
  277. python do_swuimage () {
  278. import shutil
  279. list_for_cpio = ["sw-description"]
  280. workdir = d.getVar('WORKDIR', True)
  281. s = d.getVar('S', True)
  282. imgdeploydir = d.getVar('SWUDEPLOYDIR', True)
  283. shutil.copyfile(os.path.join(workdir, "sw-description"), os.path.join(s, "sw-description"))
  284. if d.getVar('SWUPDATE_SIGNING', True):
  285. list_for_cpio.append('sw-description.sig')
  286. # Add artifacts added via SRC_URI
  287. if not d.getVar('INHIBIT_SWUPDATE_ADD_SRC_URI', True):
  288. swupdate_add_src_uri(d, list_for_cpio)
  289. # Add artifacts set via SWUPDATE_IMAGES
  290. swupdate_add_artifacts(d, list_for_cpio)
  291. prepare_sw_description(d)
  292. swupdate_create_cpio(d, imgdeploydir, list_for_cpio)
  293. }