codesign.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env -S python3 -B
  2. # Copyright (c) 2022 Project CHIP Authors
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import argparse
  16. import re
  17. import subprocess
  18. def run_command(command):
  19. print("Running {}".format(command))
  20. return str(subprocess.check_output(command.split()))
  21. def get_identity():
  22. command = "/usr/bin/security find-identity -v -p codesigning"
  23. command_result = run_command(command)
  24. failure_str = "Error: 0 valid identities found"
  25. if failure_str in command_result:
  26. print(
  27. "No valid identity has been found. Application will run without entitlements.")
  28. exit(0)
  29. command_result = command_result.replace("\\n", "\n")
  30. identity = re.search(r'\b[0-9a-fA-F]{40}\b(?![^\n]*\(CSSMERR_TP_CERT_EXPIRED\))', command_result)
  31. if identity is None:
  32. print(
  33. "No valid identity has been found. Application will run without entitlements.")
  34. exit(0)
  35. return identity.group()
  36. def codesign(args):
  37. command = "codesign --force -d --sign {identity} {target}".format(
  38. identity=get_identity(),
  39. target=args.target_path)
  40. command_result = run_command(command)
  41. print("Codesign Result: {}".format(command_result))
  42. with open(args.log_path, "w") as f:
  43. f.write(command_result)
  44. if __name__ == '__main__':
  45. parser = argparse.ArgumentParser(
  46. description='Codesign the binary')
  47. parser.add_argument(
  48. '--log_path', help='Output log file destination', required=True)
  49. parser.add_argument('--target_path', help='Binary to sign', required=True)
  50. args = parser.parse_args()
  51. codesign(args)