forked from mozilla-releng/scriptworker-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sign.py
1550 lines (1260 loc) · 55.4 KB
/
sign.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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""Signingscript task functions."""
import asyncio
import base64
import difflib
import fnmatch
import glob
import hashlib
import json
import logging
import os
import re
import resource
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
import zipfile
from contextlib import ExitStack
from functools import wraps
from io import BytesIO
import mohawk
import winsign.sign
from mardor.reader import MarReader
from mardor.writer import add_signature_block
from scriptworker.utils import get_single_item_from_sequence, makedirs, raise_future_exceptions, retry_async, rm
from winsign.crypto import load_pem_certs
from signingscript import task, utils
from signingscript.createprecomplete import generate_precomplete
from signingscript.exceptions import SigningScriptError
log = logging.getLogger(__name__)
try:
# NB. The widevine module needs to be deployed separately
import widevine
except ImportError:
log.exception("Could not import widevine")
widevine = None
sys.path.append(os.path.abspath(os.path.join(os.path.realpath(os.path.dirname(__file__)), "vendored", "mozbuild"))) # append the mozbuild vendor
from mozpack import mozjar # noqa # isort:skip
_ZIP_ALIGNMENT = "4" # Value must always be 4, based on https://developer.android.com/studio/command-line/zipalign.html
# Blessed files call the other widevine files.
_WIDEVINE_BLESSED_FILENAMES = (
# plugin-container is the top of the calling stack
"plugin-container",
"plugin-container.exe",
)
# These are other files that need to be widevine-signed
_WIDEVINE_NONBLESSED_FILENAMES = (
# firefox
"firefox",
"firefox-bin",
"firefox.exe",
# xul
"libxul.so",
"XUL",
"xul.dll",
# clearkey for regression testing.
"clearkey.dll",
"libclearkey.dylib",
"libclearkey.so",
)
# These are the keys used to verify if a keyid isn't specified
_DEFAULT_MAR_VERIFY_KEYS = {
"autograph_stage_mar384": {"dep-signing": "autograph_stage.pem"},
"autograph_hash_only_mar384": {"release-signing": "release_primary.pem", "nightly-signing": "nightly_aurora_level3_primary.pem", "dep-signing": "dep1.pem"},
}
# Langpacks expect the following re to match for addon id
LANGPACK_RE = re.compile(r"^langpack-[a-zA-Z]+(?:-[a-zA-Z]+){0,2}@(?:firefox|devedition|pinebuild).mozilla.org$")
def get_rss():
"""Return the maximum resident set size for this process."""
return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
def time_async_function(f):
"""Time an async function."""
@wraps(f)
async def wrapped(*args, **kwargs):
start = time.time()
start_rss = get_rss()
try:
return await f(*args, **kwargs)
finally:
rss = get_rss()
log.debug("%s took %.2fs; RSS:%s (%+d)", f.__name__, time.time() - start, rss, rss - start_rss)
return wrapped
def time_function(f):
"""Time a sync function."""
@wraps(f)
def wrapped(*args, **kwargs):
start = time.time()
start_rss = get_rss()
try:
return f(*args, **kwargs)
finally:
rss = get_rss()
log.debug("%s took %.2fs; RSS:%s (%+d)", f.__name__, time.time() - start, rss, rss - start_rss)
return wrapped
# get_autograph_config {{{1
def get_autograph_config(autograph_configs, cert_type, signing_formats, raise_on_empty=False):
"""Get the autograph config for given `signing_formats` and `cert_type`.
Args:
autograph_configs (dict of lists of lists): the contents of
`autograph_configs`.
cert_type (str): the certificate type - essentially signing level,
separating release vs nightly vs dep.
signing_formats (list): the signing formats the server needs to support
raise_on_empty (bool): flag to raise errors. Optional. Defaults to False.
Raises:
SigningScriptError: when no suitable signing server is found
Returns:
An Autograph object
"""
for a in autograph_configs.get(cert_type, []):
if a and (set(a.formats) & set(signing_formats)):
return a
if raise_on_empty:
raise SigningScriptError(f"No autograph config found with cert type {cert_type} and formats {signing_formats}")
return None
# sign_file {{{1
async def sign_file(context, from_, fmt, to=None, **kwargs):
"""Send the file to autograph to be signed.
Args:
context (Context): the signing context
from_ (str): the source file to sign
fmt (str): the format to sign with
to (str, optional): the target path to sign to. If None, overwrite
`from_`. Defaults to None.
Raises:
FailedSubprocess: on subprocess error while signing.
Returns:
str: the path to the signed file
"""
log.info("sign_file(): signing %s with %s... using autograph /sign/file", from_, fmt)
await sign_file_with_autograph(context, from_, fmt, to=to)
return to or from_
# sign_gpg {{{1
async def sign_gpg(context, from_, fmt, **kwargs):
"""Create a detached armored signature with the gpg key.
Because this function returns a list, gpg must be the final signing format.
Args:
context (Context): the signing context
from_ (str): the source file to sign
fmt (str): the format to sign with
Returns:
list: the path to the signed file, and sig.
"""
to = f"{from_}.asc"
await sign_file(context, from_, fmt, to=to)
return [from_, to]
# sign_jar {{{1
async def sign_jar(context, from_, fmt, **kwargs):
"""Sign an apk, and zipalign.
Args:
context (Context): the signing context
from_ (str): the source file to sign
fmt (str): the format to sign with
Returns:
str: the path to the signed file
"""
await sign_file(context, from_, fmt)
await zip_align_apk(context, from_)
return from_
# sign_macapp {{{1
async def sign_macapp(context, from_, fmt, **kwargs):
"""Sign a macapp.
If given a dmg, convert to a tar.gz file first, then sign the internals.
Args:
context (Context): the signing context
from_ (str): the source file to sign
fmt (str): the format to sign with
Returns:
str: the path to the signed file
"""
file_base, file_extension = os.path.splitext(from_)
if file_extension == ".dmg":
await _convert_dmg_to_tar_gz(context, from_)
from_ = "{}.tar.gz".format(file_base)
await sign_file(context, from_, fmt)
return from_
# sign_xpi {{{1
async def sign_xpi(context, orig_path, fmt, **kwargs):
"""Sign language packs with autograph.
This validates both the file extension and the language pack ID is sane.
Args:
context (Context): the signing context
orig_path (str): the source file to sign
fmt (str): the format to sign with
Returns:
str: the path to the signed xpi
"""
file_base, file_extension = os.path.splitext(orig_path)
if file_extension not in (".xpi", ".zip"):
raise SigningScriptError("Expected a .xpi")
ext_id = _extension_id(orig_path, fmt)
log.info("Identified {} as extension id: {}".format(orig_path, id))
kwargs = {"extension_id": ext_id}
# Sign the appropriate inner files
await sign_file_with_autograph(context, orig_path, fmt, **kwargs)
return orig_path
# sign_widevine {{{1
@time_async_function
async def sign_widevine(context, orig_path, fmt, **kwargs):
"""Call the appropriate helper function to do widevine signing.
Args:
context (Context): the signing context
orig_path (str): the source file to sign
fmt (str): the format to sign with
Raises:
SigningScriptError: on unknown suffix.
Returns:
str: the path to the signed archive
"""
file_base, file_extension = os.path.splitext(orig_path)
# Convert dmg to tarball
if file_extension == ".dmg":
await _convert_dmg_to_tar_gz(context, orig_path)
orig_path = "{}.tar.gz".format(file_base)
ext_to_fn = {".zip": sign_widevine_zip, ".tar.bz2": sign_widevine_tar, ".tar.gz": sign_widevine_tar}
for ext, signing_func in ext_to_fn.items():
if orig_path.endswith(ext):
return await signing_func(context, orig_path, fmt)
raise SigningScriptError("Unknown widevine file format for {}".format(orig_path))
# sign_widevine_zip {{{1
@time_async_function
async def sign_widevine_zip(context, orig_path, fmt):
"""Sign the internals of a zipfile with the widevine key.
Extract the files to sign (see `_WIDEVINE_BLESSED_FILENAMES` and
`_WIDEVINE_UNBLESSED_FILENAMES), skipping already-signed files.
The blessed files should be signed with the `widevine_blessed` format.
Then append the sigfiles to the zipfile.
Args:
context (Context): the signing context
orig_path (str): the source file to sign
fmt (str): the format to sign with
Returns:
str: the path to the signed archive
"""
# This will get cleaned up when we nuke `work_dir`. Clean up at that point
# rather than immediately after `sign_widevine`, to optimize task runtime
# speed over disk space.
tmp_dir = tempfile.mkdtemp(prefix="wvzip", dir=context.config["work_dir"])
# Get file list
all_files = await _get_zipfile_files(orig_path)
files_to_sign = _get_widevine_signing_files(all_files)
log.debug("Widevine files to sign: %s", files_to_sign)
if files_to_sign:
# Extract all files so we can create `precomplete` with the full
# file list
all_files = await _extract_zipfile(context, orig_path, tmp_dir=tmp_dir)
tasks = []
# Sign the appropriate inner files
for from_, fmt in files_to_sign.items():
from_ = os.path.join(tmp_dir, from_)
to = f"{from_}.sig"
tasks.append(asyncio.ensure_future(sign_widevine_with_autograph(context, from_, "blessed" in fmt, to=to)))
all_files.append(to)
await raise_future_exceptions(tasks)
remove_extra_files(tmp_dir, all_files)
# Regenerate the `precomplete` file, which is used for cleanup before
# applying a complete mar.
_run_generate_precomplete(context, tmp_dir)
await _create_zipfile(context, orig_path, all_files, mode="w", tmp_dir=tmp_dir)
return orig_path
# sign_widevine_tar {{{1
@time_async_function
async def sign_widevine_tar(context, orig_path, fmt):
"""Sign the internals of a tarfile with the widevine key.
Extract the entire tarball, but only sign a handful of files (see
`_WIDEVINE_BLESSED_FILENAMES` and `_WIDEVINE_UNBLESSED_FILENAMES).
The blessed files should be signed with the `widevine_blessed` format.
Then recreate the tarball.
Ideally we would be able to append the sigfiles to the original tarball,
but that's not possible with compressed tarballs.
Args:
context (Context): the signing context
orig_path (str): the source file to sign
fmt (str): the format to sign with
Returns:
str: the path to the signed archive
"""
_, compression = os.path.splitext(orig_path)
# This will get cleaned up when we nuke `work_dir`. Clean up at that point
# rather than immediately after `sign_widevine`, to optimize task runtime
# speed over disk space.
tmp_dir = tempfile.mkdtemp(prefix="wvtar", dir=context.config["work_dir"])
# Get file list
all_files = await _get_tarfile_files(orig_path, compression)
files_to_sign = _get_widevine_signing_files(all_files)
log.debug("Widevine files to sign: %s", files_to_sign)
if files_to_sign:
# Extract all files so we can create `precomplete` with the full
# file list
all_files = await _extract_tarfile(context, orig_path, compression, tmp_dir=tmp_dir)
tasks = []
# Sign the appropriate inner files
for from_, fmt in files_to_sign.items():
from_ = os.path.join(tmp_dir, from_)
# Don't try to sign directories
if not os.path.isfile(from_):
continue
# Move the sig location on mac. This should be noop on linux.
to = _get_mac_sigpath(from_)
log.debug("Adding %s to the sigfile paths...", to)
makedirs(os.path.dirname(to))
tasks.append(asyncio.ensure_future(sign_widevine_with_autograph(context, from_, "blessed" in fmt, to=to)))
all_files.append(to)
await raise_future_exceptions(tasks)
remove_extra_files(tmp_dir, all_files)
# Regenerate the `precomplete` file, which is used for cleanup before
# applying a complete mar.
_run_generate_precomplete(context, tmp_dir)
await _create_tarfile(context, orig_path, all_files, compression, tmp_dir=tmp_dir)
return orig_path
# sign_omnija {{{1
@time_async_function
async def sign_omnija(context, orig_path, fmt, **kwargs):
"""Call the appropriate helper function to do omnija signing.
Args:
context (Context): the signing context
orig_path (str): the source file to sign
fmt (str): the format to sign with
Raises:
SigningScriptError: on unknown suffix.
Returns:
str: the path to the signed archive
"""
file_base, file_extension = os.path.splitext(orig_path)
# Convert dmg to tarball
if file_extension == ".dmg":
await _convert_dmg_to_tar_gz(context, orig_path)
orig_path = "{}.tar.gz".format(file_base)
ext_to_fn = {".zip": sign_omnija_zip, ".tar.bz2": sign_omnija_tar, ".tar.gz": sign_omnija_tar}
for ext, signing_func in ext_to_fn.items():
if orig_path.endswith(ext):
return await signing_func(context, orig_path, fmt)
raise SigningScriptError("Unknown omnija file format for {}".format(orig_path))
# sign_omnija_zip {{{1
async def sign_omnija_zip(context, orig_path, fmt):
"""Sign the internals of a zipfile with the omnija key for all omni.ja files.
Extract the files to sign, then sign them with autograph, recreating the omni.ja
from the original to preserve performance tweeks but adding signing info,
Then append the sigfiles to the zipfile.
Args:
context (Context): the signing context
orig_path (str): the source file to sign
fmt (str): the format to sign with
Returns:
str: the path to the signed archive
"""
# This will get cleaned up when we nuke `work_dir`. Clean up at that point
# rather than immediately after `sign_omnija`, to optimize task runtime
# speed over disk space.
tmp_dir = tempfile.mkdtemp(prefix="ojzip", dir=context.config["work_dir"])
# Get file list
all_files = await _get_zipfile_files(orig_path)
files_to_sign = _get_omnija_signing_files(all_files)
log.debug("Omnija files to sign: %s", files_to_sign)
if files_to_sign:
all_files = await _extract_zipfile(context, orig_path, tmp_dir=tmp_dir)
tasks = []
# Sign the appropriate inner files
for from_, fmt in files_to_sign.items():
from_ = os.path.join(tmp_dir, from_)
tasks.append(asyncio.ensure_future(sign_omnija_with_autograph(context, from_)))
await raise_future_exceptions(tasks)
await _create_zipfile(context, orig_path, all_files, mode="w", tmp_dir=tmp_dir)
return orig_path
# sign_omnija_tar {{{1
@time_async_function
async def sign_omnija_tar(context, orig_path, fmt):
"""Sign the internals of a tarfile with the omnija key for all omni.ja files.
Extract the files to sign, then sign them with autograph, recreating the omni.ja
from the original to preserve performance tweeks but adding signing info.
Then recreate the tarball.
Args:
context (Context): the signing context
orig_path (str): the source file to sign
fmt (str): the format to sign with
Returns:
str: the path to the signed archive
"""
_, compression = os.path.splitext(orig_path)
# This will get cleaned up when we nuke `work_dir`. Clean up at that point
# rather than immediately after `sign_widevine`, to optimize task runtime
# speed over disk space.
tmp_dir = tempfile.mkdtemp(prefix="ojtar", dir=context.config["work_dir"])
# Get file list
all_files = await _get_tarfile_files(orig_path, compression)
files_to_sign = _get_omnija_signing_files(all_files)
log.debug("Omnija files to sign: %s", files_to_sign)
if files_to_sign:
# Extract all files so we can create `precomplete` with the full
# file list
all_files = await _extract_tarfile(context, orig_path, compression, tmp_dir=tmp_dir)
tasks = []
# Sign the appropriate inner files
for from_, fmt in files_to_sign.items():
from_ = os.path.join(tmp_dir, from_)
# Don't try to sign directories
if not os.path.isfile(from_):
continue
tasks.append(asyncio.ensure_future(sign_omnija_with_autograph(context, from_)))
await raise_future_exceptions(tasks)
await _create_tarfile(context, orig_path, all_files, compression, tmp_dir=tmp_dir)
return orig_path
# _should_sign_windows {{{1
def _should_sign_windows(filename):
"""Return True if filename should be signed."""
# These should already be signed by Microsoft.
_dont_sign = ["D3DCompiler_42.dll", "d3dx9_42.dll", "D3DCompiler_43.dll", "d3dx9_43.dll", "msvc*.dll"]
ext = os.path.splitext(filename)[1]
b = os.path.basename(filename)
if ext in (".dll", ".exe", ".msi", ".msix", ".bin") and not any(fnmatch.fnmatch(b, p) for p in _dont_sign):
return True
return False
def _extension_id(filename, fmt):
"""Return a list of id's for the langpacks.
Side effect of additionally verifying langpack manifests.
"""
xpi = zipfile.ZipFile(filename, "r")
manifest = {}
for manifest_name in ("manifest.json", "webextension/manifest.json"):
try:
with xpi.open(manifest_name, "r") as f:
manifest = json.load(f)
break
except KeyError:
log.debug("{} doesn't exist in {}...".format(manifest_name, filename))
# Check for "browser_specific_settings" key first. Fall back to deprecated "applications" key
browser_specific_settings = manifest.get("browser_specific_settings", manifest.get("applications", {}))
gecko_id = browser_specific_settings.get("gecko", {}).get("id")
if not gecko_id:
raise SigningScriptError("{} is not a valid xpi".format(filename))
if "langpack" in fmt and not ("languages" in manifest and "langpack_id" in manifest and LANGPACK_RE.match(gecko_id) and filename.endswith(".xpi")):
raise SigningScriptError("{} is not a valid langpack".format(filename))
return gecko_id
# _get_mac_sigpath {{{1
def _get_mac_sigpath(from_):
"""For mac paths, replace the final Contents/MacOS/ with Contents/Resources/."""
to = from_
if "Contents/MacOS" in from_:
parts = from_.split("/")
parts.reverse()
i = parts.index("MacOS")
parts[i] = "Resources"
parts.reverse()
to = "/".join(parts)
log.debug("Sigfile for {} should be {}.sig".format(from_, to))
return "{}.sig".format(to)
# _get_widevine_signing_files {{{1
def _get_widevine_signing_files(file_list):
"""Return a dict of path:signing_format for each path to be signed."""
files = {}
for filename in file_list:
fmt = None
base_filename = os.path.basename(filename)
if base_filename in _WIDEVINE_BLESSED_FILENAMES:
fmt = "widevine_blessed"
elif base_filename in _WIDEVINE_NONBLESSED_FILENAMES:
fmt = "widevine"
if fmt:
log.debug("Found {} to sign {}".format(filename, fmt))
sigpath = _get_mac_sigpath(filename)
if sigpath not in file_list:
files[filename] = fmt
else:
log.debug("{} is already signed! Skipping...".format(filename))
return files
# _get_omnija_signing_files {{{1
def _get_omnija_signing_files(file_list):
"""Return a dict of path:signing_format for each path to be signed."""
files = {}
for filename in file_list:
fmt = None
base_filename = os.path.basename(filename)
if base_filename in {"omni.ja"}:
fmt = "omnija"
if fmt:
log.debug("Found {} to sign {}".format(filename, fmt))
files[filename] = fmt
return files
# _run_generate_precomplete {{{1
def _run_generate_precomplete(context, tmp_dir):
"""Regenerate `precomplete` file with widevine sig paths for complete mar."""
log.info("Generating `precomplete` file...")
path = _ensure_one_precomplete(tmp_dir, "before")
with open(path, "r") as fh:
before = fh.readlines()
generate_precomplete(os.path.dirname(path))
path = _ensure_one_precomplete(tmp_dir, "after")
with open(path, "r") as fh:
after = fh.readlines()
# Create diff file
diff_path = os.path.join(context.config["work_dir"], "precomplete.diff")
with open(diff_path, "w") as fh:
for line in difflib.ndiff(before, after):
fh.write(line)
utils.copy_to_dir(diff_path, context.config["artifact_dir"], target="public/logs/precomplete.diff")
# _ensure_one_precomplete {{{1
def _ensure_one_precomplete(tmp_dir, adj):
"""Ensure we only have one `precomplete` file in `tmp_dir`."""
return get_single_item_from_sequence(
glob.glob(os.path.join(tmp_dir, "**", "precomplete"), recursive=True),
condition=lambda _: True,
ErrorClass=SigningScriptError,
no_item_error_message='No `precomplete` file found in "{}"'.format(tmp_dir),
too_many_item_error_message='More than one `precomplete` file {} in "{}"'.format(adj, tmp_dir),
)
# remove_extra_files {{{1
def remove_extra_files(top_dir, file_list):
"""Find any extra files in `top_dir`, given an expected `file_list`.
Args:
top_dir (str): the dir to walk
file_list (list): the list of expected files
Returns:
list: the list of extra files
"""
all_files = [os.path.realpath(f) for f in glob.glob(os.path.join(top_dir, "**", "*"), recursive=True)]
good_files = [os.path.realpath(f) for f in file_list]
extra_files = list(set(all_files) - set(good_files))
for f in extra_files:
if os.path.isfile(f):
log.warning("Extra file to clean up: {}".format(f))
rm(f)
return extra_files
# zip_align_apk {{{1
@time_async_function
async def zip_align_apk(context, abs_to):
"""Optimize APK for better run-time performance.
This is necessary if the APK is uploaded to the Google Play Store.
https://developer.android.com/studio/command-line/zipalign.html
Args:
context (Context): the signing context
abs_to (str): the absolute path to the apk
"""
original_apk_location = abs_to
zipalign_executable_location = context.config["zipalign"]
with tempfile.TemporaryDirectory() as temp_dir:
temp_apk_location = os.path.join(temp_dir, "aligned.apk")
zipalign_command = [zipalign_executable_location]
if context.config["verbose"] is True:
zipalign_command += ["-v"]
zipalign_command += [_ZIP_ALIGNMENT, original_apk_location, temp_apk_location]
await utils.execute_subprocess(zipalign_command)
shutil.move(temp_apk_location, abs_to)
log.info('"{}" has been zip aligned'.format(abs_to))
# _convert_dmg_to_tar_gz {{{1
@time_async_function
async def _convert_dmg_to_tar_gz(context, from_):
"""Explode a dmg and tar up its contents. Return the relative tarball path."""
work_dir = context.config["work_dir"]
abs_from = os.path.join(work_dir, from_)
# replace .dmg suffix with .tar.gz (case insensitive)
to = re.sub(r"\.dmg$", ".tar.gz", from_, flags=re.I)
abs_to = os.path.join(work_dir, to)
dmg_executable_location = context.config["dmg"]
hfsplus_executable_location = context.config["hfsplus"]
with tempfile.TemporaryDirectory() as temp_dir:
app_dir = os.path.join(temp_dir, "app")
utils.mkdir(app_dir)
undmg_cmd = [dmg_executable_location, "extract", abs_from, "tmp.hfs"]
await utils.execute_subprocess(undmg_cmd, cwd=temp_dir, log_level=logging.DEBUG)
hfsplus_cmd = [hfsplus_executable_location, "tmp.hfs", "extractall", "/", app_dir]
await utils.execute_subprocess(hfsplus_cmd, cwd=temp_dir, log_level=logging.DEBUG)
tar_cmd = ["tar", "czf", abs_to, "."]
await utils.execute_subprocess(tar_cmd, cwd=app_dir)
return to
# _get_zipfile_files {{{1
@time_async_function
async def _get_zipfile_files(from_):
with zipfile.ZipFile(from_, mode="r") as z:
files = z.namelist()
return files
# _extract_zipfile {{{1
@time_async_function
async def _extract_zipfile(context, from_, files=None, tmp_dir=None):
work_dir = context.config["work_dir"]
tmp_dir = tmp_dir or os.path.join(work_dir, "unzipped")
log.debug("Extracting {} from {} to {}...".format(files or "all files", from_, tmp_dir))
try:
extracted_files = []
rm(tmp_dir)
utils.mkdir(tmp_dir)
with zipfile.ZipFile(from_, mode="r") as z:
if files is not None:
for name in files:
z.extract(name, path=tmp_dir)
extracted_files.append(os.path.join(tmp_dir, name))
else:
for name in z.namelist():
extracted_files.append(os.path.join(tmp_dir, name))
z.extractall(path=tmp_dir)
return extracted_files
except Exception as e:
raise SigningScriptError(e)
# _create_zipfile {{{1
@time_async_function
async def _create_zipfile(context, to, files, tmp_dir=None, mode="w"):
work_dir = context.config["work_dir"]
tmp_dir = tmp_dir or os.path.join(work_dir, "unzipped")
try:
log.info("Creating zipfile {}...".format(to))
with zipfile.ZipFile(to, mode=mode, compression=zipfile.ZIP_DEFLATED) as z:
for f in files:
relpath = os.path.relpath(f, tmp_dir)
z.write(f, arcname=relpath)
return to
except Exception as e:
raise SigningScriptError(e)
# _get_tarfile_compression {{{1
def _get_tarfile_compression(compression):
compression = compression.lstrip(".")
if compression not in ("bz2", "gz"):
raise SigningScriptError("{} not a supported tarfile compression format!".format(compression))
return compression
# _get_tarfile_files {{{1
@time_async_function
async def _get_tarfile_files(from_, compression):
compression = _get_tarfile_compression(compression)
with tarfile.open(from_, mode="r:{}".format(compression)) as t:
files = t.getmembers()
return [f.name for f in files if f.isfile()]
# _extract_tarfile {{{1
@time_async_function
async def _extract_tarfile(context, from_, compression, tmp_dir=None):
work_dir = context.config["work_dir"]
tmp_dir = tmp_dir or os.path.join(work_dir, "untarred")
compression = _get_tarfile_compression(compression)
try:
files = []
rm(tmp_dir)
utils.mkdir(tmp_dir)
with tarfile.open(from_, mode="r:{}".format(compression)) as t:
t.extractall(path=tmp_dir)
for name in t.getnames():
path = os.path.join(tmp_dir, name)
os.path.isfile(path) and files.append(path)
return files
except Exception as e:
raise SigningScriptError(e)
# _owner_filter {{{1
def _owner_filter(tarinfo_obj):
"""Force file ownership to be root, Bug 1473850."""
tarinfo_obj.uid = 0
tarinfo_obj.gid = 0
tarinfo_obj.uname = ""
tarinfo_obj.gname = ""
return tarinfo_obj
# _create_tarfile {{{1
@time_async_function
async def _create_tarfile(context, to, files, compression, tmp_dir=None):
work_dir = context.config["work_dir"]
tmp_dir = tmp_dir or os.path.join(work_dir, "untarred")
compression = _get_tarfile_compression(compression)
try:
log.info("Creating tarfile {}...".format(to))
with tarfile.open(to, mode="w:{}".format(compression)) as t:
for f in files:
relpath = os.path.relpath(f, tmp_dir)
t.add(f, arcname=relpath, filter=_owner_filter)
return to
except Exception as e:
raise SigningScriptError(e)
def _encode_single_file(fp, signing_req):
"""Write signing_req to fp.
Does proper base64 and json encoding.
Tries not to hold onto a lot of memory.
"""
fp.write(b"[{")
for k, v in signing_req.items():
fp.write(json.dumps(k).encode("utf8"))
fp.write(b":")
if hasattr(v, "read"):
# Make sure we're always reading from the beginning of the file
# Sometimes we have to retry the request
v.seek(0)
fp.write(b'"')
while True:
block = v.read(1020)
if not block:
break
e = b64encode(block).encode("utf8")
fp.write(e)
fp.write(b'"')
else:
fp.write(json.dumps(v).encode("utf8"))
fp.write(b",")
fp.seek(-1, 1)
fp.write(b"}]")
def _encode_multiple_files(fp, signing_req):
"""Write signing_req to fp.
Builds a JSON byte string from the signing_req.
Does a proper base64 encoding of the binary content in the request's file blobs.
Doesn't hold onto a lot of memory by chunking the file blobs.
Writes the request to the binary-stream fp.
"""
_signing_req = signing_req.copy()
input_files = _signing_req.pop("files")
encoded_signing_req_bytes_io = BytesIO()
encoded_signing_req_bytes_io.write(b"[{")
for k, v in _signing_req.items():
encoded_signing_req_bytes_io.write(json.dumps(k).encode("utf8"))
encoded_signing_req_bytes_io.write(b":")
encoded_signing_req_bytes_io.write(json.dumps(v).encode("utf8"))
encoded_signing_req_bytes_io.write(b",")
encoded_signing_req_bytes_io.write(json.dumps("files").encode("utf8"))
encoded_signing_req_bytes_io.write(b":")
encoded_signing_req_bytes_io.write(b"[")
for input_file in input_files:
encoded_signing_req_bytes_io.write(b"{")
encoded_signing_req_bytes_io.write(json.dumps("name").encode("utf8"))
encoded_signing_req_bytes_io.write(b":")
encoded_signing_req_bytes_io.write(json.dumps(os.path.basename(input_file["name"])).encode("utf8"))
encoded_signing_req_bytes_io.write(b",")
encoded_signing_req_bytes_io.write(json.dumps("content").encode("utf8"))
encoded_signing_req_bytes_io.write(b":")
input_file["content"].seek(0)
encoded_signing_req_bytes_io.write(b'"')
while True:
block = input_file["content"].read(1020)
if not block:
break
encoded_block = b64encode(block).encode("utf8")
encoded_signing_req_bytes_io.write(encoded_block)
encoded_signing_req_bytes_io.write(b'"')
encoded_signing_req_bytes_io.write(b"},")
encoded_signing_req_bytes_io.seek(-2, 1)
encoded_signing_req_bytes_io.write(b"}]}]")
encoded_signing_req_bytes_io.seek(0)
encoded_signing_req_bytes = encoded_signing_req_bytes_io.read()
fp.write(encoded_signing_req_bytes)
def write_signing_req_to_disk(fp, signing_req):
"""Write signing_req to fp.
Does proper base64 and json encoding.
Tries not to hold onto a lot of memory.
"""
if "files" in signing_req:
_encode_multiple_files(fp, signing_req)
else:
_encode_single_file(fp, signing_req)
def get_hawk_content_hash(request_body, content_type):
"""Generate the content hash of the given request."""
h = hashlib.new("sha256")
h.update(b"hawk.1.payload\n")
h.update(content_type.encode("utf8"))
h.update(b"\n")
while True:
block = request_body.read(1024)
if not block:
break
h.update(block)
h.update(b"\n")
return b64encode(h.digest())
def get_hawk_header(url, user, password, content_type, content_hash):
"""Create a HAWK Authentication header."""
r = mohawk.base.Resource(credentials={"id": user, "key": password, "algorithm": "sha256"}, url=url, method="POST", content_type=content_type)
r._content_hash = content_hash
mac = mohawk.util.calculate_mac("header", r, r.content_hash)
a = mohawk.base.HawkAuthority()
auth_header = a._make_header(r, mac)
return auth_header
@time_async_function
async def call_autograph(session, url, user, password, sign_req):
"""Call autograph and return the json response."""
content_type = "application/json"
request_body = tempfile.TemporaryFile("w+b")
write_signing_req_to_disk(request_body, sign_req)
request_body.seek(0)
content_hash = get_hawk_content_hash(request_body, content_type)
auth_header = get_hawk_header(url, user, password, content_type, content_hash)
request_body.seek(0, 2)
req_size = request_body.tell()
log.debug("req_size: %s", req_size)
request_body.seek(0)
resp = await session.post(url, data=request_body, headers={"Authorization": auth_header, "Content-Type": content_type, "Content-Length": str(req_size)})
log.debug("Autograph response: %s", resp.status)
resp.raise_for_status()
# TODO: Write this out to temporary file. The responses can be large,
# especially in the case of APK/omnija signing where the entire file is
# being sent and returned.
return await resp.json()
def b64encode(input_bytes):
"""Return a base64 encoded string."""
return base64.b64encode(input_bytes).decode("ascii")
def _is_xpi_format(fmt):
if "omnija" in fmt or "langpack" in fmt:
return True
if fmt in ("privileged_webextension", "system_addon"):
return True
return False
@time_function
def make_signing_req(input_file, fmt, keyid=None, extension_id=None):
"""Make a signing request object to pass to autograph."""
if isinstance(input_file, list):
sign_req = {"files": []}
for f in input_file:
sign_req["files"].append({"name": f.name, "content": f})
else:
sign_req = {"input": input_file}
if keyid:
sign_req["keyid"] = keyid
# TODO: Is this the right place to do this?
if utils.is_apk_autograph_signing_format(fmt):
# We don't want APKs to have their compression changed
sign_req["options"] = {"zip": "passthrough"}
if utils.is_sha1_apk_autograph_signing_format(fmt):
# We ask for a SHA1 digest from Autograph
# https://github.com/mozilla-services/autograph/pull/166/files
sign_req["options"]["pkcs7_digest"] = "SHA1"
if _is_xpi_format(fmt):
sign_req.setdefault("options", {})
# https://bugzilla.mozilla.org/show_bug.cgi?id=1533818#c9
sign_req["options"]["id"] = extension_id
sign_req["options"]["cose_algorithms"] = ["ES256"]
sign_req["options"]["pkcs7_digest"] = "SHA256"
return sign_req
@time_async_function
async def sign_with_autograph(session, server, input_file, fmt, autograph_method, keyid=None, extension_id=None):
"""Signs data with autograph and returns the result.
Args:
session (aiohttp.ClientSession): client session object
server (Autograph): the server to connect to sign