swupdate-lib.bbclass 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # Copyright (C) 2015-2022 Stefano Babic
  2. #
  3. # SPDX-License-Identifier: GPLv3
  4. DEPENDS += "python3-magic-native zstd-native"
  5. def swupdate_encrypt_file(f, out, key, ivt):
  6. import subprocess
  7. encargs = ["openssl", "enc", "-aes-256-cbc", "-in", f, "-out", out]
  8. encargs += ["-K", key, "-iv", ivt, "-nosalt"]
  9. subprocess.run(encargs, check=True)
  10. def swupdate_extract_keys(keyfile_path):
  11. try:
  12. with open(keyfile_path, 'r') as f:
  13. lines = f.readlines()
  14. except IOError:
  15. bb.fatal("Failed to open file with keys %s" % (keyfile))
  16. data = {}
  17. for _ in lines:
  18. k,v = _.split('=',maxsplit=1)
  19. data[k.rstrip()] = v
  20. key = data['key'].rstrip('\n')
  21. iv = data['iv'].rstrip('\n')
  22. return key,iv
  23. def swupdate_get_sha256(d, s, filename):
  24. import hashlib
  25. m = hashlib.sha256()
  26. with open(os.path.join(s, filename), 'rb') as f:
  27. while True:
  28. data = f.read(1024)
  29. if not data:
  30. break
  31. m.update(data)
  32. return m.hexdigest()
  33. def swupdate_sign_file(d, s, filename):
  34. import subprocess
  35. import magic
  36. import base64
  37. fname = os.path.join(s, filename)
  38. mime = magic.Magic(mime=True)
  39. ftype = mime.from_file(fname)
  40. if ftype == 'application/zstd':
  41. zcmd = 'zstdcat'
  42. elif ftype == 'application/gzip':
  43. zcmd = 'zcat'
  44. else:
  45. zcmd = 'cat'
  46. privkey = d.getVar('SWUPDATE_SIGN_PRIVATE_KEY')
  47. dump = subprocess.run([ zcmd, fname ], check=True, capture_output=True)
  48. signature = subprocess.run([ "openssl", "dgst", "-keyform", "PEM", "-sha256", "-sign", privkey ] + \
  49. get_pwd_file_args(d, 'SWUPDATE_SIGN_PASSWORD_FILE'), check=True, capture_output=True, input=dump.stdout)
  50. hash = base64.b64encode(signature.stdout).decode()
  51. # SWUpdate accepts attribute with a maximum size of 255. If the hash
  52. # exceeds this value, returns sha256 of the generated hash
  53. #
  54. if len(hash) > 255:
  55. m = hashlib.sha256()
  56. m.update(hash)
  57. hash = m.hexdigest()
  58. return hash