swupdate-common.bbclass 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. DEPENDS += "\
  2. cpio-native \
  3. ${@ 'openssl-native' if d.getVar('SWUPDATE_SIGNING', True) else ''} \
  4. "
  5. do_swuimage[umask] = "022"
  6. SSTATETASKS += "do_swuimage"
  7. SSTATE_SKIP_CREATION_task-swuimage = '1'
  8. SWUDEPLOYDIR = "${WORKDIR}/deploy-${PN}-swuimage"
  9. do_swuimage[dirs] = "${SWUDEPLOYDIR}"
  10. do_swuimage[cleandirs] += "${SWUDEPLOYDIR}"
  11. do_swuimage[sstate-inputdirs] = "${SWUDEPLOYDIR}"
  12. do_swuimage[sstate-outputdirs] = "${DEPLOY_DIR_IMAGE}"
  13. do_swuimage[stamp-extra-info] = "${MACHINE}"
  14. python () {
  15. deps = " " + swupdate_getdepends(d)
  16. d.appendVarFlag('do_swuimage', 'depends', deps)
  17. }
  18. def swupdate_getdepends(d):
  19. def adddep(depstr, deps):
  20. for i in (depstr or "").split():
  21. if i not in deps:
  22. deps.append(i)
  23. deps = []
  24. images = (d.getVar('IMAGE_DEPENDS', True) or "").split()
  25. for image in images:
  26. adddep(image , deps)
  27. depstr = ""
  28. for dep in deps:
  29. depstr += " " + dep + ":do_build"
  30. return depstr
  31. def swupdate_get_sha256(s, filename):
  32. import hashlib
  33. m = hashlib.sha256()
  34. with open(os.path.join(s, filename), 'rb') as f:
  35. while True:
  36. data = f.read(1024)
  37. if not data:
  38. break
  39. m.update(data)
  40. return m.hexdigest()
  41. def swupdate_extract_keys(keyfile_path):
  42. try:
  43. with open(keyfile_path, 'r') as f:
  44. lines = f.readlines()
  45. except IOError:
  46. bb.fatal("Failed to open file with keys %s" % (keyfile))
  47. data = {}
  48. for _ in lines:
  49. k,v = _.split('=',maxsplit=1)
  50. data[k.rstrip()] = v
  51. key = data['key'].rstrip('\n')
  52. iv = data['iv'].rstrip('\n')
  53. return key,iv
  54. def swupdate_encrypt_file(f, out, key, ivt):
  55. import subprocess
  56. encargs = ["openssl", "enc", "-aes-256-cbc", "-in", f, "-out", out]
  57. encargs += ["-K", key, "-iv", ivt, "-nosalt"]
  58. subprocess.run(encargs, check=True)
  59. def swupdate_write_sha256(s):
  60. import re
  61. write_lines = []
  62. with open(os.path.join(s, "sw-description"), 'r') as f:
  63. for line in f:
  64. shastr = r"sha256.+=.+@(.+\")"
  65. #m = re.match(r"^(?P<before_placeholder>.+)sha256.+=.+(?P<filename>\w+)", line)
  66. m = re.match(r"^(?P<before_placeholder>.+)sha256.+=.+(?P<quote>[\'\"])@(?P<filename>.*)(?P=quote)", line)
  67. if m:
  68. filename = m.group('filename')
  69. hash = swupdate_get_sha256(s, filename)
  70. write_lines.append(line.replace("@%s" % (filename), hash))
  71. else:
  72. write_lines.append(line)
  73. with open(os.path.join(s, "sw-description"), 'w+') as f:
  74. for line in write_lines:
  75. f.write(line)
  76. def swupdate_expand_bitbake_variables(d, s):
  77. write_lines = []
  78. with open(os.path.join(s, "sw-description"), 'r') as f:
  79. import re
  80. for line in f:
  81. found = False
  82. while True:
  83. m = re.match(r"^(?P<before_placeholder>.+)@@(?P<bitbake_variable_name>\w+)@@(?P<after_placeholder>.+)$", line)
  84. if m:
  85. bitbake_variable_value = d.getVar(m.group('bitbake_variable_name'), True)
  86. if bitbake_variable_value is None:
  87. bitbake_variable_value = ""
  88. bb.warn("BitBake variable %s not set" % (m.group('bitbake_variable_name')))
  89. line = m.group('before_placeholder') + bitbake_variable_value + m.group('after_placeholder')
  90. found = True
  91. continue
  92. else:
  93. m = re.match(r"^(?P<before_placeholder>.+)@@(?P<bitbake_variable_name>.+)\[(?P<flag_var_name>.+)\]@@(?P<after_placeholder>.+)$", line)
  94. if m:
  95. bitbake_variable_value = (d.getVarFlag(m.group('bitbake_variable_name'), m.group('flag_var_name'), True) or "")
  96. if bitbake_variable_value is None:
  97. bitbake_variable_value = ""
  98. line = m.group('before_placeholder') + bitbake_variable_value + m.group('after_placeholder')
  99. continue
  100. if found:
  101. line = line + "\n"
  102. break
  103. write_lines.append(line)
  104. with open(os.path.join(s, "sw-description"), 'w+') as f:
  105. for line in write_lines:
  106. f.write(line)
  107. def swupdate_expand_auto_versions(d, s):
  108. import re
  109. import oe.packagedata
  110. AUTO_VERSION_TAG = "@SWU_AUTO_VERSION"
  111. AUTOVERSION_REGEXP = "version\s*=\s*\"%s" % AUTO_VERSION_TAG
  112. with open(os.path.join(s, "sw-description"), 'r') as f:
  113. data = f.read()
  114. def get_package_name(group, file_list):
  115. package = None
  116. m = re.search(r"%s:(?P<package>.+?(?=[\"@]))" % (AUTOVERSION_REGEXP), group)
  117. if m:
  118. package = m.group('package')
  119. return (package, True)
  120. for filename in file_list:
  121. if filename in group:
  122. package = filename
  123. if not package:
  124. bb.fatal("Failed to find file in group %s" % (group))
  125. return (package, False)
  126. def get_packagedata_key(group):
  127. m = re.search(r"%s.+?(?<=@)(?P<key>.+?(?=\"))" % (AUTOVERSION_REGEXP), group)
  128. if m:
  129. return (m.group('key'), True)
  130. return ("PV", False)
  131. regexp = re.compile(r"\{[^\{]*%s.[^\}]*\}" % (AUTOVERSION_REGEXP))
  132. while True:
  133. m = regexp.search(data)
  134. if not m:
  135. break
  136. group = data[m.start():m.end()]
  137. (package, pkg_name_defined) = get_package_name(group, (d.getVar('SWUPDATE_IMAGES', True) or "").split())
  138. pkg_info = os.path.join(d.getVar('PKGDATA_DIR'), 'runtime-reverse', package)
  139. pkgdata = oe.packagedata.read_pkgdatafile(pkg_info)
  140. (key, key_defined) = get_packagedata_key(group)
  141. if not key in pkgdata.keys():
  142. bb.warn("\"%s\" not set for package %s - using \"1.0\"" % (key, package))
  143. version = "1.0"
  144. else:
  145. version = pkgdata[key].split('+')[0]
  146. replace_str = AUTO_VERSION_TAG
  147. if pkg_name_defined:
  148. replace_str = replace_str + ":" + package
  149. if key_defined:
  150. replace_str = replace_str + "@" + key
  151. group = group.replace(replace_str, version)
  152. data = data[:m.start()] + group + data[m.end():]
  153. with open(os.path.join(s, "sw-description"), 'w+') as f:
  154. f.write(data)
  155. def prepare_sw_description(d):
  156. import shutil
  157. s = d.getVar('S', True)
  158. swupdate_expand_bitbake_variables(d, s)
  159. swupdate_expand_auto_versions(d, s)
  160. swupdate_write_sha256(s)
  161. encrypt = d.getVar('SWUPDATE_ENCRYPT_SWDESC', True)
  162. if encrypt:
  163. bb.note("Encryption of sw-description")
  164. shutil.copyfile(os.path.join(s, 'sw-description'), os.path.join(s, 'sw-description.plain'))
  165. key,iv = swupdate_extract_keys(d.getVar('SWUPDATE_AES_FILE', True))
  166. swupdate_encrypt_file(os.path.join(s, 'sw-description.plain'), os.path.join(s, 'sw-description'), key, iv)
  167. signing = d.getVar('SWUPDATE_SIGNING', True)
  168. if signing == "1":
  169. bb.warn('SWUPDATE_SIGNING = "1" is deprecated, falling back to "RSA". It is advised to set it to "RSA" if using RSA signing.')
  170. signing = "RSA"
  171. if signing:
  172. if signing == "CUSTOM":
  173. sign_tool = d.getVar('SWUPDATE_SIGN_TOOL', True)
  174. if sign_tool:
  175. ret = os.system(sign_tool)
  176. if ret != 0:
  177. bb.fatal("Failed to sign with %s" % (sign_tool))
  178. else:
  179. bb.fatal("Custom SWUPDATE_SIGN_TOOL is not given")
  180. elif signing == "RSA":
  181. privkey = d.getVar('SWUPDATE_PRIVATE_KEY', True)
  182. if not privkey:
  183. bb.fatal("SWUPDATE_PRIVATE_KEY isn't set")
  184. if not os.path.exists(privkey):
  185. bb.fatal("SWUPDATE_PRIVATE_KEY %s doesn't exist" % (privkey))
  186. passout = d.getVar('SWUPDATE_PASSWORD_FILE', True)
  187. if passout:
  188. passout = "-passin file:'%s' " % (passout)
  189. else:
  190. passout = ""
  191. signcmd = "openssl dgst -sha256 -sign '%s' %s -out '%s' '%s'" % (
  192. privkey,
  193. passout,
  194. os.path.join(s, 'sw-description.sig'),
  195. os.path.join(s, 'sw-description.plain' if encrypt else 'sw-description'))
  196. if os.system(signcmd) != 0:
  197. bb.fatal("Failed to sign sw-description with %s" % (privkey))
  198. elif signing == "CMS":
  199. cms_cert = d.getVar('SWUPDATE_CMS_CERT', True)
  200. if not cms_cert:
  201. bb.fatal("SWUPDATE_CMS_CERT is not set")
  202. if not os.path.exists(cms_cert):
  203. bb.fatal("SWUPDATE_CMS_CERT %s doesn't exist" % (cms_cert))
  204. cms_key = d.getVar('SWUPDATE_CMS_KEY', True)
  205. if not cms_key:
  206. bb.fatal("SWUPDATE_CMS_KEY isn't set")
  207. if not os.path.exists(cms_key):
  208. bb.fatal("SWUPDATE_CMS_KEY %s doesn't exist" % (cms_key))
  209. passout = d.getVar('SWUPDATE_PASSWORD_FILE', True)
  210. if passout:
  211. passout = "-passin file:'%s' " % (passout)
  212. else:
  213. passout = ""
  214. signcmd = "openssl cms -sign -in '%s' -out '%s' -signer '%s' -inkey '%s' %s -outform DER -nosmimecap -binary" % (
  215. os.path.join(s, 'sw-description.plain' if encrypt else 'sw-description'),
  216. os.path.join(s, 'sw-description.sig'),
  217. cms_cert,
  218. cms_key,
  219. passout)
  220. if os.system(signcmd) != 0:
  221. bb.fatal("Failed to sign sw-description with %s" % (privkey))
  222. else:
  223. bb.fatal("Unrecognized SWUPDATE_SIGNING mechanism.");
  224. python do_swuimage () {
  225. import shutil
  226. workdir = d.getVar('WORKDIR', True)
  227. images = (d.getVar('SWUPDATE_IMAGES', True) or "").split()
  228. s = d.getVar('S', True)
  229. shutil.copyfile(os.path.join(workdir, "sw-description"), os.path.join(s, "sw-description"))
  230. fetch = bb.fetch2.Fetch([], d)
  231. list_for_cpio = ["sw-description"]
  232. if d.getVar('SWUPDATE_SIGNING', True):
  233. list_for_cpio.append('sw-description.sig')
  234. # Add files listed in SRC_URI to the swu file
  235. for url in fetch.urls:
  236. local = fetch.localpath(url)
  237. filename = os.path.basename(local)
  238. aes_file = d.getVar('SWUPDATE_AES_FILE', True)
  239. if aes_file:
  240. key,iv = swupdate_extract_keys(d.getVar('SWUPDATE_AES_FILE', True))
  241. if (filename != 'sw-description') and (os.path.isfile(local)):
  242. encrypted = (d.getVarFlag("SWUPDATE_IMAGES_ENCRYPTED", filename, True) or "")
  243. dst = os.path.join(s, "%s" % filename )
  244. if encrypted == '1':
  245. bb.note("Encryption requested for %s" %(filename))
  246. if not key or not iv:
  247. bb.fatal("Encryption required, but no key found")
  248. swupdate_encrypt_file(local, dst, key, iv)
  249. else:
  250. shutil.copyfile(local, dst)
  251. list_for_cpio.append(filename)
  252. def add_image_to_swu(deploydir, imagename, s, encrypt):
  253. src = os.path.join(deploydir, imagename)
  254. if not os.path.isfile(src):
  255. return False
  256. target_imagename = os.path.basename(imagename) # allow images in subfolders of DEPLOY_DIR_IMAGE
  257. dst = os.path.join(s, target_imagename)
  258. if encrypt == '1':
  259. key,iv = swupdate_extract_keys(d.getVar('SWUPDATE_AES_FILE', True))
  260. bb.note("Encryption requested for %s" %(imagename))
  261. swupdate_encrypt_file(src, dst, key, iv)
  262. else:
  263. shutil.copyfile(src, dst)
  264. list_for_cpio.append(target_imagename)
  265. return True
  266. # Search for images listed in SWUPDATE_IMAGES in the DEPLOY directory.
  267. deploydir = d.getVar('DEPLOY_DIR_IMAGE', True)
  268. imgdeploydir = d.getVar('SWUDEPLOYDIR', True)
  269. for image in images:
  270. fstypes = (d.getVarFlag("SWUPDATE_IMAGES_FSTYPES", image, True) or "").split()
  271. encrypted = (d.getVarFlag("SWUPDATE_IMAGES_ENCRYPTED", image, True) or "")
  272. if fstypes:
  273. noappend_machine = d.getVarFlag("SWUPDATE_IMAGES_NOAPPEND_MACHINE", image, True)
  274. if noappend_machine == "0": # Search for a file explicitly with MACHINE
  275. imagebases = [ image + '-' + d.getVar('MACHINE', True) ]
  276. elif noappend_machine == "1": # Search for a file explicitly without MACHINE
  277. imagebases = [ image ]
  278. else: # None, means auto mode. Just try to find an image file with MACHINE or without MACHINE
  279. imagebases = [ image + '-' + d.getVar('MACHINE', True), image ]
  280. for fstype in fstypes:
  281. image_found = False
  282. for imagebase in imagebases:
  283. image_found = add_image_to_swu(deploydir, imagebase + fstype, s, encrypted)
  284. if image_found:
  285. break
  286. if not image_found:
  287. bb.fatal("swupdate cannot find image file: %s" % os.path.join(deploydir, imagebase + fstype))
  288. else: # Allow also complete entries like "image.ext4.gz" in SWUPDATE_IMAGES
  289. if not add_image_to_swu(deploydir, image, s, encrypted):
  290. bb.fatal("swupdate cannot find %s image file" % image)
  291. prepare_sw_description(d)
  292. line = 'for i in ' + ' '.join(list_for_cpio) + '; do echo $i;done | cpio -ov -H crc >' + os.path.join(imgdeploydir,d.getVar('IMAGE_NAME', True) + '.swu')
  293. os.system("cd " + s + ";" + line)
  294. line = 'ln -sf ' + d.getVar('IMAGE_NAME', True) + '.swu ' + d.getVar('IMAGE_LINK_NAME', True) + '.swu'
  295. os.system("cd " + imgdeploydir + "; " + line)
  296. }