-
Notifications
You must be signed in to change notification settings - Fork 0
/
signcode.py
167 lines (139 loc) · 8.9 KB
/
signcode.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import zipfile
import pathlib
import tempfile
import subprocess
import getpass
import os
import argparse
from cryptography.hazmat.primitives.serialization import pkcs12
from cryptography.hazmat.primitives import hashes
from datetime import datetime, timezone
DEFAULT_VALUES = {
"src": pathlib.Path.home() / "Desktop/zips",
"dst": pathlib.Path.home() / "Desktop/signed_zips",
"keystore": pathlib.Path("F:/SignProcess/JWS/codesigning.p12"),
"alias": "codesigning",
"jarsigner": pathlib.Path('C:/Program Files/Java/jdk1.8.0_281/bin/jarsigner.exe'),
"signtool": pathlib.Path('C:/Program Files (x86)/Windows Kits/10/bin/10.0.19041.0/x86/signtool.exe'),
"tsa": "http://timestamp.digicert.com" # http://timestamp.globalsign.com/scripts/timestamp.dll"
}
PROXY_HOST = "-J-Dhttp.proxyHost=proxyusr.fediap.be"
PROXY_PORT = "-J-Dhttp.proxyPort=8080"
KNOWN_SIGNERS = {
'53a5f430eec5918b3e141d2acca3686c7218b7b6d2c25fa9f8f68619052caf2c': 'Signer 2018-2019 - EXPIRED',
'3fb5cedac685b02604f5a79211c6eff4d235bd62061a0da80d4cb0a16dce2828': 'Signer 2019-2022 - Expires end of Sept 2022',
'337eb5c6299083554180718faf994deb2bc580f50f23c01edd1c0206f8ff2638': 'Signer 2022-2024 - From Sept 2022',
}
def assert_path_exists(path, error_message):
if not path.exists():
print("ERROR", f"{error_message} [{str(path)}]")
return False
return True
def assert_external_toolresult(name, result, expected):
if result.returncode != 0:
message = f" ERROR: [{name}] signing/verifying library. OUTPUT: {str(result.stdout)}"
raise AssertionError(message)
else:
if expected not in str(result.stdout):
print(" ", "WARN", f"[{name}] signing/verifying library. OUTPUT: {str(result.stdout)}")
def is_java_library(path):
return path.suffix == '.jar'
def is_dotnet_library(path):
return path.suffix == '.dll'
def sign_java_library(lib, name, jarsigner_path, keystore_path, key_alias, keystore_password, timestamp_url):
result = subprocess.run([str(jarsigner_path),
"-storetype", "pkcs12", "-strict",
"-keystore", str(keystore_path), "-storepass", keystore_password,
"-keypass", keystore_password,
"-tsa", timestamp_url, PROXY_HOST, PROXY_PORT,
lib.name, key_alias], capture_output=True)
assert_external_toolresult(name, result, "jar signed")
result = subprocess.run([str(jarsigner_path), "-verify", "-storetype", "pkcs12", lib.name], capture_output=True)
assert_external_toolresult(name, result, "jar verified")
return lib
def sign_dotnet_library(lib, name, signtool_path, keystore_path, key_alias, keystore_password, timestamp_url):
result = subprocess.run([str(signtool_path), "verify", "/pa", lib.name], capture_output=True)
if result.returncode != 0:
result = subprocess.run([str(signtool_path), "sign", "/fd", "sha256", "/f", str(keystore_path), "/p", keystore_password, lib.name], capture_output=True)
assert_external_toolresult(name, result, "")
result = subprocess.run([str(signtool_path), "timestamp", "/t", timestamp_url, lib.name], capture_output=True)
assert_external_toolresult(name, result, "")
result = subprocess.run([str(signtool_path), "verify", "/pa", lib.name], capture_output=True)
assert_external_toolresult(name, result, "")
else:
print(" ", "WARN", f"[{name}] Library appears to be already signed, it will not be signed again")
return lib
if __name__ == "__main__":
parser = argparse.ArgumentParser(prog="signcode", description='signs java libraries for release for Java and .NET')
parser.add_argument('--src', help='folder containing assemblies to be signed', type=pathlib.Path)
parser.add_argument('--dst', help='folder to save signed assemblies', type=pathlib.Path)
parser.add_argument('--keystore', help='keystore location .p12 file', type=pathlib.Path)
parser.add_argument('--alias', help='key alias in the keystore', type=str, default="codesigning")
parser.add_argument('--jarsigner', help='java signing tool location: jarsigner.exe', type=pathlib.Path)
parser.add_argument('--signtool', help='.NET signing tool location: signtool.exe', type=pathlib.Path)
parser.add_argument('--tsa', help='public free timestamping server url', type=str)
parser.add_argument('--force_unknown', help='forces to accept an unknown certificate for signature', action='store_true')
parser.set_defaults(**DEFAULT_VALUES)
args = parser.parse_args()
print("Signing configuration:")
for key, value in vars(args).items():
print(" ", key.ljust(12), "=", value)
paths = [
(args.src, "Unsigned folder does not exist, create it or change it"),
(args.dst, "Folder for signed libraries does not exist, create it or change it"),
(args.keystore, "No keystore found at the given location"),
(args.jarsigner, "JDK tool jarSigner can't be found, this file is part of any JDK installation"),
(args.signtool, "Signtool can't be found, can be downloaded from Microsoft website")
]
if not all([assert_path_exists(path, error_message) for (path, error_message) in paths]):
raise AssertionError("ERROR: Some necessary locations are missing")
if len(os.listdir(args.src)) > 0:
print("WARN", f"destination folder does not seem to be empty [{str(args.dst)}]")
print("INFO", f"Keystore access and content will now be evaluated")
keystorePassword = getpass.getpass("Keystore password : ")
with open(args.keystore, 'rb') as p12:
keystore = pkcs12.load_pkcs12(p12.read(), keystorePassword.encode())
assert keystore.key, "No private key in this P12, can't sign"
assert keystore.cert, "Can't find certificate in this P12"
assert keystore.cert.friendly_name == args.alias.encode(), "Incorrect alias for the certificate"
fingerprint = keystore.cert.certificate.fingerprint(hashes.SHA256()).hex();
if args.force_unknown:
print("WARN", f'Known signer check disabled, using certificate with fingerprint {fingerprint}')
else:
assert fingerprint in KNOWN_SIGNERS, f"This certificate is unknown. If new, add {fingerprint} to the whitelist KNOWN_SIGNERS in the python file"
print("INFO", f"You will be signing with : {KNOWN_SIGNERS[fingerprint]}")
assert keystore.cert.certificate.fingerprint(hashes.SHA256()).hex() == "3fb5cedac685b02604f5a79211c6eff4d235bd62061a0da80d4cb0a16dce2828", "Unknown certificate, if new one please update fingerprint"
expiresIn = keystore.cert.certificate.not_valid_after.astimezone(timezone.utc) - datetime.now(timezone.utc)
if expiresIn.days < 90:
print("WARN", f"Signing certificate expires in {expiresIn.days} days")
else:
print("INFO", f"Signing certificate expires in {expiresIn.days} days")
print("INFO", f"Keystore sanity check successful")
cache = {}
globalCacheCounter = 0
for assembly in args.src.glob('*.zip'):
print("INFO", f"[{assembly.name}] processing assembly file")
with zipfile.ZipFile(assembly, mode='r') as sourceZip, zipfile.ZipFile(args.dst / assembly.name, mode='x', compression=zipfile.ZIP_DEFLATED, compresslevel=9) as targetZip:
cacheCounter = 0
signedCounter = 0
for zipEntry in sourceZip.infolist():
if not zipEntry.is_dir():
zipEntryPath = pathlib.PurePath(zipEntry.filename)
if is_java_library(zipEntryPath) or is_dotnet_library(zipEntryPath):
if zipEntry.CRC in cache:
library = cache[zipEntry.CRC]
cacheCounter += 1
else:
library = tempfile.NamedTemporaryFile(delete=False)
library.write(sourceZip.read(zipEntry))
library.close()
print(" ", "INFO", f"[{zipEntryPath.name}] signing library")
cache[zipEntry.CRC] = sign_java_library(library, zipEntryPath.name, args.jarsigner, args.keystore, args.alias, keystorePassword, args.tsa) if is_java_library(zipEntryPath) else sign_dotnet_library(library, zipEntryPath.name, args.signtool, args.keystore, args.alias, keystorePassword, args.tsa)
signedCounter += 1
with open(library.name, 'rb') as library:
targetZip.writestr(zipEntry.filename, library.read())
else:
targetZip.writestr(zipEntry.filename, sourceZip.read(zipEntry))
globalCacheCounter += cacheCounter
print("INFO", f"[{assembly.name}] finished processing assembly file. Signed: {signedCounter}, from cache: {cacheCounter}")
print("INFO", f"All Done ! Signed {len(cache)} libraries, {globalCacheCounter} from cache")