-
Notifications
You must be signed in to change notification settings - Fork 131
/
appx.c
2813 lines (2652 loc) · 97.7 KB
/
appx.c
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
/*
* APPX file support library
* https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
*
* Copyright (C) Maciej Panek <maciej.panek_malpa_punxworks.com>
* Copyright (C) 2023 Michał Trojnara <[email protected]>
* Author: Małgorzata Olszówka <[email protected]>
*
* APPX files do not support nesting (multiple signature)
*/
#define _FILE_OFFSET_BITS 64
#include "osslsigncode.h"
#include "helpers.h"
#include <zlib.h>
#include <inttypes.h>
#ifndef PRIX64
#if defined(_MSC_VER)
#define PRIX64 "I64X"
#else /* _MSC_VER */
#if ULONG_MAX == 0xFFFFFFFFFFFFFFFF
#define PRIX64 "lX"
#else /* ULONG_MAX == 0xFFFFFFFFFFFFFFFF */
#define PRIX64 "llX"
#endif /* ULONG_MAX == 0xFFFFFFFFFFFFFFFF */
#endif /* _MSC_VER */
#endif /* PRIX64 */
#define EOCDR_SIZE 22
#define ZIP64_EOCD_LOCATOR_SIZE 20
#define ZIP64_HEADER 0x01
#define COMPRESSION_NONE 0
#define COMPRESSION_DEFLATE 8
#define DATA_DESCRIPTOR_BIT (1 << 3)
static const char PKZIP_LH_SIGNATURE[4] = { 'P', 'K', 3, 4 };
static const char PKZIP_CD_SIGNATURE[4] = { 'P', 'K', 1, 2 };
static const char PKZIP_EOCDR_SIGNATURE[4] = { 'P', 'K', 5, 6 };
static const char PKZIP_DATA_DESCRIPTOR_SIGNATURE[4] = { 'P', 'K', 7, 8 };
static const char PKZIP64_EOCD_LOCATOR_SIGNATURE[4] = { 'P', 'K', 6, 7 };
static const char PKZIP64_EOCDR_SIGNATURE[4] = { 'P', 'K', 6, 6 };
static const char *APP_SIGNATURE_FILENAME = "AppxSignature.p7x";
static const char *CONTENT_TYPES_FILENAME = "[Content_Types].xml";
static const char *BLOCK_MAP_FILENAME = "AppxBlockMap.xml";
static const char *APPXBUNDLE_MANIFEST_FILENAME = "AppxMetadata/AppxBundleManifest.xml";
static const char *CODE_INTEGRITY_FILENAME = "AppxMetadata/CodeIntegrity.cat";
static const char *SIGNATURE_CONTENT_TYPES_ENTRY = "<Override PartName=\"/AppxSignature.p7x\" ContentType=\"application/vnd.ms-appx.signature\"/>";
static const char *SIGNATURE_CONTENT_TYPES_CLOSING_TAG = "</Types>";
static const u_char APPX_UUID[] = { 0x4B, 0xDF, 0xC5, 0x0A, 0x07, 0xCE, 0xE2, 0x4D, 0xB7, 0x6E, 0x23, 0xC8, 0x39, 0xA0, 0x9F, 0xD1 };
static const u_char APPXBUNDLE_UUID[] = { 0xB3, 0x58, 0x5F, 0x0F, 0xDE, 0xAA, 0x9A, 0x4B, 0xA4, 0x34, 0x95, 0x74, 0x2D, 0x92, 0xEC, 0xEB };
static const char PKCX_SIGNATURE[4] = { 'P', 'K', 'C', 'X' }; /* P7X format header */
static const char APPX_SIGNATURE[4] = { 'A', 'P', 'P', 'X' }; /* APPX header */
static const char AXPC_SIGNATURE[4] = { 'A', 'X', 'P', 'C' }; /* digest of zip file records */
static const char AXCD_SIGNATURE[4] = { 'A', 'X', 'C', 'D' }; /* digest zip file central directory */
static const char AXCT_SIGNATURE[4] = { 'A', 'X', 'C', 'T' }; /* digest of uncompressed [ContentTypes].xml */
static const char AXBM_SIGNATURE[4] = { 'A', 'X', 'B', 'M' }; /* digest of uncompressed AppxBlockMap.xml */
static const char AXCI_SIGNATURE[4] = { 'A', 'X', 'C', 'I' }; /* digest of uncompressed AppxMetadata/CodeIntegrity.cat (optional) */
static const char *HASH_METHOD_TAG = "HashMethod";
static const char *HASH_METHOD_SHA256 = "http://www.w3.org/2001/04/xmlenc#sha256";
static const char *HASH_METHOD_SHA384 = "http://www.w3.org/2001/04/xmldsig-more#sha384";
static const char *HASH_METHOD_SHA512 = "http://www.w3.org/2001/04/xmlenc#sha512";
/*
* Overall .ZIP file format:
*
* [local file header 1]
* [encryption header 1]
* [file data 1]
* [data descriptor 1]
* .
* .
* .
* [local file header n]
* [encryption header n]
* [file data n]
* [data descriptor n]
* [archive decryption header]
* [archive extra data record]
* [central directory header 1]
* .
* .
* .
* [central directory header n]
* [zip64 end of central directory record]
* [zip64 end of central directory locator]
* [end of central directory record]
*/
/* Local file header */
typedef struct {
uint16_t version;
uint16_t flags;
uint16_t compression;
uint16_t modTime;
uint16_t modDate;
uint32_t crc32;
uint64_t compressedSize;
uint64_t uncompressedSize;
uint16_t fileNameLen;
uint16_t extraFieldLen;
char *fileName;
uint8_t *extraField;
int compressedSizeInZip64;
int uncompressedSizeInZip64;
} ZIP_LOCAL_HEADER;
/* Data descriptor */
typedef struct {
uint32_t crc32;
uint64_t compressedSize;
uint64_t uncompressedSize;
uint8_t *data;
} ZIP_OVERRIDE_DATA;
/* Central directory structure */
typedef struct zipCentralDirectoryEntry_struct {
uint16_t creatorVersion;
uint16_t viewerVersion;
uint16_t flags;
uint16_t compression;
uint16_t modTime;
uint16_t modDate;
uint32_t crc32;
uint64_t compressedSize;
uint64_t uncompressedSize;
uint16_t fileNameLen;
uint16_t extraFieldLen;
uint16_t fileCommentLen;
uint32_t diskNoStart;
uint16_t internalAttr;
uint32_t externalAttr;
uint64_t offsetOfLocalHeader;
char *fileName;
uint8_t *extraField;
char *fileComment;
int64_t fileOffset;
int64_t entryLen;
int compressedSizeInZip64;
int uncompressedSizeInZip64;
int offsetInZip64;
int diskNoInZip64;
ZIP_OVERRIDE_DATA *overrideData;
struct zipCentralDirectoryEntry_struct *next;
} ZIP_CENTRAL_DIRECTORY_ENTRY;
DEFINE_STACK_OF(ZIP_CENTRAL_DIRECTORY_ENTRY)
/* Zip64 end of central directory record */
typedef struct {
uint64_t eocdrSize;
uint16_t creatorVersion;
uint16_t viewerVersion;
uint32_t diskNumber;
uint32_t diskWithCentralDirectory;
uint64_t diskEntries;
uint64_t totalEntries;
uint64_t centralDirectorySize;
uint64_t centralDirectoryOffset;
uint64_t commentLen;
char *comment;
} ZIP64_EOCDR;
/* Zip64 end of central directory locator */
typedef struct {
uint32_t diskWithEOCD;
uint64_t eocdOffset;
uint32_t totalNumberOfDisks;
} ZIP64_EOCD_LOCATOR;
/* End of central directory record */
typedef struct {
uint16_t diskNumber;
uint16_t centralDirectoryDiskNumber;
uint16_t diskEntries;
uint16_t totalEntries;
uint32_t centralDirectorySize;
uint32_t centralDirectoryOffset;
uint16_t commentLen;
char *comment;
} ZIP_EOCDR;
typedef struct {
FILE *file;
ZIP_CENTRAL_DIRECTORY_ENTRY *centralDirectoryHead;
uint64_t centralDirectorySize;
uint64_t centralDirectoryOffset;
uint64_t centralDirectoryRecordCount;
uint64_t eocdrOffset;
int64_t eocdrLen;
int64_t fileSize;
int isZip64;
/* this will come handy to rewrite the eocdr */
ZIP_EOCDR eocdr;
ZIP64_EOCD_LOCATOR locator;
ZIP64_EOCDR eocdr64;
} ZIP_FILE;
typedef struct {
ASN1_INTEGER *a;
ASN1_OCTET_STRING *string;
ASN1_INTEGER *b;
ASN1_INTEGER *c;
ASN1_INTEGER *d;
ASN1_INTEGER *e;
ASN1_INTEGER *f;
} AppxSpcSipInfo;
DECLARE_ASN1_FUNCTIONS(AppxSpcSipInfo)
ASN1_SEQUENCE(AppxSpcSipInfo) = {
ASN1_SIMPLE(AppxSpcSipInfo, a, ASN1_INTEGER),
ASN1_SIMPLE(AppxSpcSipInfo, string, ASN1_OCTET_STRING),
ASN1_SIMPLE(AppxSpcSipInfo, b, ASN1_INTEGER),
ASN1_SIMPLE(AppxSpcSipInfo, c, ASN1_INTEGER),
ASN1_SIMPLE(AppxSpcSipInfo, d, ASN1_INTEGER),
ASN1_SIMPLE(AppxSpcSipInfo, e, ASN1_INTEGER),
ASN1_SIMPLE(AppxSpcSipInfo, f, ASN1_INTEGER),
} ASN1_SEQUENCE_END(AppxSpcSipInfo)
IMPLEMENT_ASN1_FUNCTIONS(AppxSpcSipInfo)
struct appx_ctx_st {
ZIP_FILE *zip;
u_char *calculatedBMHash;
u_char *calculatedCTHash;
u_char *calculatedCDHash;
u_char *calculatedDataHash;
u_char *calculatedCIHash;
u_char *existingBMHash;
u_char *existingCTHash;
u_char *existingCDHash;
u_char *existingDataHash;
u_char *existingCIHash;
int isBundle;
const EVP_MD *md;
int hashlen;
} appx_ctx_t;
/* FILE_FORMAT method prototypes */
static FILE_FORMAT_CTX *appx_ctx_new(GLOBAL_OPTIONS *options, BIO *hash, BIO *outdata);
static const EVP_MD *appx_md_get(FILE_FORMAT_CTX *ctx);
static ASN1_OBJECT *appx_spc_sip_info_get(u_char **p, int *plen, FILE_FORMAT_CTX *ctx);
static PKCS7 *appx_pkcs7_contents_get(FILE_FORMAT_CTX *ctx, BIO *hash, const EVP_MD *md);
static int appx_hash_length_get(FILE_FORMAT_CTX *ctx);
static int appx_verify_digests(FILE_FORMAT_CTX *ctx, PKCS7 *p7);
static PKCS7 *appx_pkcs7_extract(FILE_FORMAT_CTX *ctx);
static int appx_remove_pkcs7(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata);
static int appx_process_data(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata);
static PKCS7 *appx_pkcs7_signature_new(FILE_FORMAT_CTX *ctx, BIO *hash);
static int appx_append_pkcs7(FILE_FORMAT_CTX *ctx, BIO *outdata, PKCS7 *p7);
static void appx_bio_free(BIO *hash, BIO *outdata);
static void appx_ctx_cleanup(FILE_FORMAT_CTX *ctx);
FILE_FORMAT file_format_appx = {
.ctx_new = appx_ctx_new,
.md_get = appx_md_get,
.data_blob_get = appx_spc_sip_info_get,
.pkcs7_contents_get = appx_pkcs7_contents_get,
.hash_length_get = appx_hash_length_get,
.verify_digests = appx_verify_digests,
.pkcs7_extract = appx_pkcs7_extract,
.remove_pkcs7 = appx_remove_pkcs7,
.process_data = appx_process_data,
.pkcs7_signature_new = appx_pkcs7_signature_new,
.append_pkcs7 = appx_append_pkcs7,
.bio_free = appx_bio_free,
.ctx_cleanup = appx_ctx_cleanup,
};
/* Prototypes */
static BIO *appx_calculate_hashes(FILE_FORMAT_CTX *ctx);
static BIO *appx_hash_blob_get(FILE_FORMAT_CTX *ctx);
static uint8_t *appx_calc_zip_central_directory_hash(ZIP_FILE *zip, const EVP_MD *md, uint64_t cdOffset);
static int appx_write_central_directory(BIO *bio, ZIP_FILE *zip, int removeSignature, uint64_t cdOffset);
static uint8_t *appx_calc_zip_data_hash(uint64_t *cdOffset, ZIP_FILE *zip, const EVP_MD *md);
static int appx_extract_hashes(FILE_FORMAT_CTX *ctx, SpcIndirectDataContent *content);
static int appx_compare_hashes(FILE_FORMAT_CTX *ctx);
static int appx_remove_ct_signature_entry(ZIP_FILE *zip, ZIP_CENTRAL_DIRECTORY_ENTRY *entry);
static int appx_append_ct_signature_entry(ZIP_FILE *zip, ZIP_CENTRAL_DIRECTORY_ENTRY *entry);
static const EVP_MD *appx_get_md(ZIP_FILE *zip);
static ZIP_CENTRAL_DIRECTORY_ENTRY *zipGetCDEntryByName(ZIP_FILE *zip, const char *name);
static void zipWriteCentralDirectoryEntry(BIO *bio, uint64_t *sizeOnDisk, ZIP_CENTRAL_DIRECTORY_ENTRY *entry, uint64_t offsetDiff);
static int zipAppendSignatureFile(BIO *bio, ZIP_FILE *zip, uint8_t *data, uint64_t dataSize);
static int zipOverrideFileData(ZIP_CENTRAL_DIRECTORY_ENTRY *entry, uint8_t *data, uint64_t dataSize);
static int zipRewriteData(ZIP_FILE *zip, ZIP_CENTRAL_DIRECTORY_ENTRY *entry, BIO *bio, uint64_t *sizeOnDisk);
static void zipWriteLocalHeader(BIO *bio, uint64_t *sizeonDisk, ZIP_LOCAL_HEADER *heade);
static int zipEntryExist(ZIP_FILE *zip, const char *name);
static u_char *zipCalcDigest(ZIP_FILE *zip, const char *fileName, const EVP_MD *md);
static size_t zipReadFileDataByName(uint8_t **pData, ZIP_FILE *zip, const char *name);
static size_t zipReadFileData(ZIP_FILE *zip, uint8_t **pData, ZIP_CENTRAL_DIRECTORY_ENTRY *entry);
static int zipReadLocalHeader(ZIP_LOCAL_HEADER *header, ZIP_FILE *zip, uint64_t compressedSize);
static int zipInflate(uint8_t *dest, uint64_t *destLen, uint8_t *source, uLong *sourceLen);
static int zipDeflate(uint8_t *dest, uint64_t *destLen, uint8_t *source, uLong sourceLen);
static ZIP_FILE *openZip(const char *filename);
static void freeZip(ZIP_FILE *zip);
static ZIP_FILE *zipSortCentralDirectory(ZIP_FILE *zip);
static void zipPrintCentralDirectory(ZIP_FILE *zip);
static int zipReadCentralDirectory(ZIP_FILE *zip, FILE *file);
static ZIP_CENTRAL_DIRECTORY_ENTRY *zipReadNextCentralDirectoryEntry(FILE *file);
static void freeZipCentralDirectoryEntry(ZIP_CENTRAL_DIRECTORY_ENTRY *entry);
static int readZipEOCDR(ZIP_EOCDR *eocdr, FILE *file);
static int readZip64EOCDLocator(ZIP64_EOCD_LOCATOR *locator, FILE *file);
static int readZip64EOCDR(ZIP64_EOCDR *eocdr, FILE *file, uint64_t offset);
static int get_current_position(BIO *bio, uint64_t *offset);
static uint64_t fileGetU64(FILE *file);
static uint32_t fileGetU32(FILE *file);
static uint16_t fileGetU16(FILE *file);
static uint64_t bufferGetU64(uint8_t *buffer, uint64_t *pos);
static uint32_t bufferGetU32(uint8_t *buffer, uint64_t *pos);
static uint16_t bufferGetU16(uint8_t *buffer, uint64_t *pos);
static void bioAddU64(BIO *bio, uint64_t v);
static void bioAddU32(BIO *bio, uint32_t v);
static void bioAddU16(BIO *bio, uint16_t v);
/*
* FILE_FORMAT method definitions
*/
/*
* Allocate and return a PE file format context.
* [in, out] options: structure holds the input data
* [out] hash: message digest BIO
* [in] outdata: outdata file BIO
* [returns] pointer to PE file format context
*/
static FILE_FORMAT_CTX *appx_ctx_new(GLOBAL_OPTIONS *options, BIO *hash, BIO *outdata)
{
FILE_FORMAT_CTX *ctx;
const EVP_MD *md;
ZIP_FILE *zip = openZip(options->infile);
/* squash unused parameter warnings */
(void)hash;
(void)outdata;
if (!zip) {
return NULL; /* FAILED */
}
if (options->verbose) {
zipPrintCentralDirectory(zip);
}
md = appx_get_md(zip);
if (!md) {
freeZip(zip);
return NULL; /* FAILED */
}
ctx = OPENSSL_malloc(sizeof(FILE_FORMAT_CTX));
ctx->appx_ctx = OPENSSL_zalloc(sizeof(appx_ctx_t));
ctx->appx_ctx->zip = zip;
ctx->format = &file_format_appx;
ctx->options = options;
ctx->appx_ctx->md = md;
if (zipGetCDEntryByName(zip, APPXBUNDLE_MANIFEST_FILENAME)) {
ctx->appx_ctx->isBundle = 1;
}
if (options->cmd == CMD_SIGN || options->cmd==CMD_ATTACH
|| options->cmd==CMD_ADD || options->cmd == CMD_EXTRACT_DATA) {
printf("Warning: Ignore -h option, use the hash algorithm specified in AppxBlockMap.xml\n");
}
if (options->pagehash == 1)
printf("Warning: -ph option is only valid for PE files\n");
if (options->jp >= 0)
printf("Warning: -jp option is only valid for CAB files\n");
if (options->add_msi_dse == 1)
printf("Warning: -add-msi-dse option is only valid for MSI files\n");
return ctx;
}
/*
* Return a hash algorithm specified in the AppxBlockMap.xml file.
* [in] ctx: structure holds input and output data
* [returns] hash algorithm
*/
static const EVP_MD *appx_md_get(FILE_FORMAT_CTX *ctx)
{
return ctx->appx_ctx->md;
}
/*
* Allocate and return SpcSipInfo object.
* [out] p: SpcSipInfo data
* [out] plen: SpcSipInfo data length
* [in] ctx: structure holds input and output data
* [returns] pointer to ASN1_OBJECT structure corresponding to SPC_SIPINFO_OBJID
*/
static ASN1_OBJECT *appx_spc_sip_info_get(u_char **p, int *plen, FILE_FORMAT_CTX *ctx)
{
ASN1_OBJECT *dtype;
AppxSpcSipInfo *si = AppxSpcSipInfo_new();
ASN1_INTEGER_set(si->a, 0x01010000);
ASN1_INTEGER_set(si->b, 0);
ASN1_INTEGER_set(si->c, 0);
ASN1_INTEGER_set(si->d, 0);
ASN1_INTEGER_set(si->e, 0);
ASN1_INTEGER_set(si->f, 0);
if (ctx->appx_ctx->isBundle) {
printf("Signing as a bundle\n");
ASN1_OCTET_STRING_set(si->string, APPXBUNDLE_UUID, sizeof(APPXBUNDLE_UUID));
} else {
printf("Signing as a package\n");
ASN1_OCTET_STRING_set(si->string, APPX_UUID, sizeof(APPX_UUID));
}
*plen = i2d_AppxSpcSipInfo(si, NULL);
*p = OPENSSL_malloc((size_t)*plen);
i2d_AppxSpcSipInfo(si, p);
*p -= *plen;
dtype = OBJ_txt2obj(SPC_SIPINFO_OBJID, 1);
AppxSpcSipInfo_free(si);
return dtype; /* OK */
}
/*
* Allocate and return a data content to be signed.
* [in] ctx: structure holds input and output data
* [in] hash: message digest BIO
* [in] md: message digest algorithm
* [returns] data content
*/
static PKCS7 *appx_pkcs7_contents_get(FILE_FORMAT_CTX *ctx, BIO *hash, const EVP_MD *md)
{
ASN1_OCTET_STRING *content;
ZIP_CENTRAL_DIRECTORY_ENTRY *entry;
BIO *bhash;
/* squash unused parameter warnings */
(void)md;
(void)hash;
/* Create and append a new signature content types entry */
entry = zipGetCDEntryByName(ctx->appx_ctx->zip, CONTENT_TYPES_FILENAME);
if (!entry) {
fprintf(stderr, "Not a valid .appx file: content types file missing\n");
return NULL; /* FAILED */
}
if (!appx_append_ct_signature_entry(ctx->appx_ctx->zip, entry)) {
return NULL; /* FAILED */
}
bhash = appx_calculate_hashes(ctx);
if (!bhash) {
return NULL; /* FAILED */
}
content = spc_indirect_data_content_get(bhash, ctx);
BIO_free_all(bhash);
return pkcs7_set_content(content);
}
/*
* Get concatenated hashes length.
* [in] ctx: structure holds input and output data
* [returns] the length of concatenated hashes
*/
static int appx_hash_length_get(FILE_FORMAT_CTX *ctx)
{
return ctx->appx_ctx->hashlen;
}
/*
* Calculate message digest and compare to value retrieved from PKCS#7 signedData.
* [in] ctx: structure holds input and output data
* [in] p7: PKCS#7 signature
* [returns] 0 on error or 1 on success
*/
static int appx_verify_digests(FILE_FORMAT_CTX *ctx, PKCS7 *p7)
{
if (is_content_type(p7, SPC_INDIRECT_DATA_OBJID)) {
ASN1_STRING *content_val = p7->d.sign->contents->d.other->value.sequence;
const u_char *p = content_val->data;
SpcIndirectDataContent *idc = d2i_SpcIndirectDataContent(NULL, &p, content_val->length);
if (idc) {
BIO *hashes;
if (!appx_extract_hashes(ctx, idc)) {
fprintf(stderr, "Failed to extract hashes from the signature\n");
SpcIndirectDataContent_free(idc);
return 0; /* FAILED */
}
hashes = appx_calculate_hashes(ctx);
if (!hashes) {
SpcIndirectDataContent_free(idc);
return 0; /* FAILED */
}
BIO_free_all(hashes);
if (!appx_compare_hashes(ctx)) {
fprintf(stderr, "Signature hash verification failed\n");
SpcIndirectDataContent_free(idc);
return 0; /* FAILED */
}
SpcIndirectDataContent_free(idc);
}
}
return 1; /* OK */
}
/*
* Extract existing signature in DER format.
* [in] ctx: structure holds input and output data
* [returns] pointer to PKCS#7 structure
*/
static PKCS7 *appx_pkcs7_extract(FILE_FORMAT_CTX *ctx)
{
PKCS7 *p7;
uint8_t *data = NULL;
const u_char *blob;
size_t dataSize;
/* Check if the signature exists */
if (!zipEntryExist(ctx->appx_ctx->zip, APP_SIGNATURE_FILENAME)) {
fprintf(stderr, "%s does not exist\n", APP_SIGNATURE_FILENAME);
return NULL; /* FAILED */
}
dataSize = zipReadFileDataByName(&data, ctx->appx_ctx->zip, APP_SIGNATURE_FILENAME);
if (dataSize <= 0) {
return NULL; /* FAILED */
}
/* P7X format is just 0x504B4358 (PKCX) followed by PKCS#7 data in the DER format */
if (memcmp(data, PKCX_SIGNATURE, 4)) {
fprintf(stderr, "Invalid PKCX header\n");
OPENSSL_free(data);
return NULL; /* FAILED */
}
blob = (u_char *)data + 4;
p7 = d2i_PKCS7(NULL, &blob, (int)dataSize - 4);
OPENSSL_free(data);
return p7;
}
/*
* Remove existing signature.
* [in, out] ctx: structure holds input and output data
* [out] hash: message digest BIO
* [out] outdata: outdata file BIO
* [returns] 1 on error or 0 on success
*/
static int appx_remove_pkcs7(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata)
{
uint8_t *data = NULL;
size_t dataSize;
uint64_t cdOffset, noEntries = 0;
ZIP_FILE *zip = ctx->appx_ctx->zip;
ZIP_CENTRAL_DIRECTORY_ENTRY *entry = zipGetCDEntryByName(zip, CONTENT_TYPES_FILENAME);
/* squash the unused parameter warning */
(void)hash;
if (!entry) {
fprintf(stderr, "Not a valid .appx file: content types file missing\n");
return 1; /* FAILED */
}
/* read signature data */
dataSize = zipReadFileDataByName(&data, ctx->appx_ctx->zip, APP_SIGNATURE_FILENAME);
if (dataSize <= 0) {
return 1; /* FAILED, no signature */
}
OPENSSL_free(data);
if (!appx_remove_ct_signature_entry(zip, entry)) {
fprintf(stderr, "Failed to remove signature entry\n");
return 1; /* FAILED */
}
for (entry = zip->centralDirectoryHead; entry != NULL; entry = entry->next) {
if (noEntries == zip->centralDirectoryRecordCount) {
fprintf(stderr, "Corrupted central directory structure\n");
return 1; /* FAILED */
}
noEntries++;
if (!entry->fileName || (entry->fileNameLen == 0)) {
fprintf(stderr, "Corrupted file name\n");
return 1; /* FAILED */
}
if (strcmp(entry->fileName, APP_SIGNATURE_FILENAME)) {
uint64_t dummy;
if (!zipRewriteData(zip, entry, outdata, &dummy)) {
return 1; /* FAILED */
}
}
}
if (!get_current_position(outdata, &cdOffset)) {
fprintf(stderr, "Unable to get offset\n");
return 1; /* FAILED */
}
if (!appx_write_central_directory(outdata, zip, 1, cdOffset)) {
fprintf(stderr, "Unable to write central directory\n");
return 1; /* FAILED */
}
return 0; /* OK */
}
/*
* Modify specific type data.
* [in, out] ctx: structure holds input and output data
* [out] hash: message digest BIO (unused)
* [out] outdata: outdata file BIO (unused)
* [returns] 1 on error or 0 on success
*/
static int appx_process_data(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata)
{
ZIP_CENTRAL_DIRECTORY_ENTRY *entry;
/* squash unused parameter warnings */
(void)outdata;
(void)hash;
/* Create and append a new signature content types entry */
entry = zipGetCDEntryByName(ctx->appx_ctx->zip, CONTENT_TYPES_FILENAME);
if (!entry) {
fprintf(stderr, "Not a valid .appx file: content types file missing\n");
return 0; /* FAILED */
}
if (!appx_append_ct_signature_entry(ctx->appx_ctx->zip, entry)) {
return 0; /* FAILED */
}
return 1; /* OK */
}
/*
* Create a new PKCS#7 signature.
* [in, out] ctx: structure holds input and output data
* [out] hash: message digest BIO (unused)
* [returns] pointer to PKCS#7 structure
*/
static PKCS7 *appx_pkcs7_signature_new(FILE_FORMAT_CTX *ctx, BIO *hash)
{
ASN1_OCTET_STRING *content;
PKCS7 *p7 = NULL;
BIO *hashes;
/* squash unused parameter warnings */
(void)hash;
/* Create hash blob from concatenated APPX hashes */
hashes = appx_calculate_hashes(ctx);
if (!hashes) {
return NULL; /* FAILED */
}
p7 = pkcs7_create(ctx);
if (!p7) {
fprintf(stderr, "Creating a new signature failed\n");
BIO_free_all(hashes);
return NULL; /* FAILED */
}
if (!add_indirect_data_object(p7)) {
fprintf(stderr, "Adding SPC_INDIRECT_DATA_OBJID failed\n");
PKCS7_free(p7);
BIO_free_all(hashes);
return NULL; /* FAILED */
}
content = spc_indirect_data_content_get(hashes, ctx);
BIO_free_all(hashes);
if (!content) {
fprintf(stderr, "Failed to get spcIndirectDataContent\n");
PKCS7_free(p7);
return NULL; /* FAILED */
}
if (!sign_spc_indirect_data_content(p7, content)) {
fprintf(stderr, "Failed to set signed content\n");
PKCS7_free(p7);
ASN1_OCTET_STRING_free(content);
return NULL; /* FAILED */
}
ASN1_OCTET_STRING_free(content);
return p7; /* OK */
}
/*
* Append signature to the outfile.
* [in, out] ctx: structure holds input and output data
* [out] outdata: outdata file BIO
* [in] p7: PKCS#7 signature
* [returns] 1 on error or 0 on success
*/
static int appx_append_pkcs7(FILE_FORMAT_CTX *ctx, BIO *outdata, PKCS7 *p7)
{
ZIP_FILE *zip = ctx->appx_ctx->zip;
ZIP_CENTRAL_DIRECTORY_ENTRY *prev = NULL;
ZIP_CENTRAL_DIRECTORY_ENTRY *last = NULL;
ZIP_CENTRAL_DIRECTORY_ENTRY *entry;
u_char *blob, *der = NULL;
int len;
uint64_t cdOffset, noEntries = 0;
for (entry = zip->centralDirectoryHead; entry != NULL;) {
if (noEntries >= zip->centralDirectoryRecordCount) {
fprintf(stderr, "Corrupted central directory structure\n");
return 1; /* FAILED */
}
noEntries++;
last = entry;
if (!entry->fileName || (entry->fileNameLen == 0)) {
fprintf(stderr, "Corrupted file name\n");
return 1; /* FAILED */
}
if (strcmp(entry->fileName, APP_SIGNATURE_FILENAME)) {
uint64_t dummy = 0;
if (!zipRewriteData(zip, entry, outdata, &dummy)) {
return 1; /* FAILED */
}
prev = entry;
entry = entry->next;
} else {
/* remove the entry
* actually this code is pretty naive - if you remove the entry that was not at the end
* everything will go south - the offsets in the CD will not match the local header offsets.
* that can be fixed here or left as is - signtool and this tool always appends the signature file at the end.
* Might be a problem when someone decides to unpack & repack the .appx zip file */
ZIP_CENTRAL_DIRECTORY_ENTRY *current = entry;
entry = entry->next;
if (prev) {
prev->next = entry;
}
freeZipCentralDirectoryEntry(current);
}
}
if (!last) {
/* not really possible unless an empty zip file, but who knows */
return 1; /* FAILED */
}
/* create the signature entry */
if (((len = i2d_PKCS7(p7, NULL)) <= 0) ||
(der = OPENSSL_malloc((size_t)len)) == NULL)
return 1; /* FAILED */
i2d_PKCS7(p7, &der);
der -= len;
blob = OPENSSL_malloc((size_t)(len + 4));
memcpy(blob, PKCX_SIGNATURE, 4);
memcpy(blob + 4, der, (size_t)len);
len += 4;
if (!zipAppendSignatureFile(outdata, zip, blob, (uint64_t)len)) {
OPENSSL_free(blob);
fprintf(stderr, "Failed to append zip file\n");
return 1; /* FAILED */
}
OPENSSL_free(der);
OPENSSL_free(blob);
if (!get_current_position(outdata, &cdOffset)) {
fprintf(stderr, "Unable to get offset\n");
return 1; /* FAILED */
}
if (!appx_write_central_directory(outdata, zip, 0, cdOffset)) {
fprintf(stderr, "Unable to write central directory\n");
return 1; /* FAILED */
}
return 0; /* OK */
}
/*
* Free up an entire message digest BIO chain.
* [out] hash: message digest BIO
* [out] outdata: outdata file BIO
* [returns] none
*/
static void appx_bio_free(BIO *hash, BIO *outdata)
{
BIO_free_all(outdata);
BIO_free_all(hash);
}
/*
* Deallocate a FILE_FORMAT_CTX structure and PE format specific structure.
* [out] ctx: structure holds input and output data
* [out] hash: message digest BIO
* [in] outdata: outdata file BIO
* [returns] none
*/
static void appx_ctx_cleanup(FILE_FORMAT_CTX *ctx)
{
freeZip(ctx->appx_ctx->zip);
OPENSSL_free(ctx->appx_ctx->calculatedBMHash);
OPENSSL_free(ctx->appx_ctx->calculatedCTHash);
OPENSSL_free(ctx->appx_ctx->calculatedCDHash);
OPENSSL_free(ctx->appx_ctx->calculatedDataHash);
OPENSSL_free(ctx->appx_ctx->calculatedCIHash);
OPENSSL_free(ctx->appx_ctx->existingBMHash);
OPENSSL_free(ctx->appx_ctx->existingCTHash);
OPENSSL_free(ctx->appx_ctx->existingCDHash);
OPENSSL_free(ctx->appx_ctx->existingDataHash);
OPENSSL_free(ctx->appx_ctx->existingCIHash);
OPENSSL_free(ctx->appx_ctx);
OPENSSL_free(ctx);
}
/*
* APPX helper functions
*/
/*
* Calculate ZIP hashes.
* [in, out] ctx: structure holds input and output data
* [returns] pointer to BIO with calculated APPX hashes
*/
static BIO *appx_calculate_hashes(FILE_FORMAT_CTX *ctx)
{
uint64_t cdOffset = 0;
ctx->appx_ctx->calculatedBMHash = zipCalcDigest(ctx->appx_ctx->zip, BLOCK_MAP_FILENAME, ctx->appx_ctx->md);
ctx->appx_ctx->calculatedCTHash = zipCalcDigest(ctx->appx_ctx->zip, CONTENT_TYPES_FILENAME, ctx->appx_ctx->md);
ctx->appx_ctx->calculatedDataHash = appx_calc_zip_data_hash(&cdOffset, ctx->appx_ctx->zip, ctx->appx_ctx->md);
ctx->appx_ctx->calculatedCDHash = appx_calc_zip_central_directory_hash(ctx->appx_ctx->zip, ctx->appx_ctx->md, cdOffset);
ctx->appx_ctx->calculatedCIHash = zipCalcDigest(ctx->appx_ctx->zip, CODE_INTEGRITY_FILENAME, ctx->appx_ctx->md);
if (!ctx->appx_ctx->calculatedBMHash || !ctx->appx_ctx->calculatedCTHash
|| !ctx->appx_ctx->calculatedCDHash || !ctx->appx_ctx->calculatedDataHash) {
fprintf(stderr, "One or more hashes calculation failed\n");
return NULL; /* FAILED */
}
if (zipEntryExist(ctx->appx_ctx->zip, CODE_INTEGRITY_FILENAME) && !ctx->appx_ctx->calculatedCIHash) {
fprintf(stderr, "Code integrity file exists, but CI hash calculation failed\n");
return NULL; /* FAILED */
}
return appx_hash_blob_get(ctx);
}
/*
* Create hash blob from concatenated APPX hashes.
* [in] ctx: structure holds input and output data
* [returns] pointer to BIO with calculated APPX hashes
*/
static BIO *appx_hash_blob_get(FILE_FORMAT_CTX *ctx)
{
int mdlen = EVP_MD_size(ctx->appx_ctx->md);
int dataSize = ctx->appx_ctx->calculatedCIHash ? 4 + 5 * (mdlen + 4) : 4 + 4 * (mdlen + 4);
u_char *data = OPENSSL_malloc((size_t)dataSize);
int pos = 0;
BIO *hashes = BIO_new(BIO_s_mem());
memcpy(data + pos, APPX_SIGNATURE, 4);
pos += 4;
memcpy(data + pos, AXPC_SIGNATURE, 4);
pos += 4;
memcpy(data + pos, ctx->appx_ctx->calculatedDataHash, (size_t)mdlen);
pos += mdlen;
memcpy(data + pos, AXCD_SIGNATURE, 4);
pos += 4;
memcpy(data + pos, ctx->appx_ctx->calculatedCDHash, (size_t)mdlen);
pos += mdlen;
memcpy(data + pos, AXCT_SIGNATURE, 4);
pos += 4;
memcpy(data + pos, ctx->appx_ctx->calculatedCTHash, (size_t)mdlen);
pos += mdlen;
memcpy(data + pos, AXBM_SIGNATURE, 4);
pos += 4;
memcpy(data + pos, ctx->appx_ctx->calculatedBMHash, (size_t)mdlen);
pos += mdlen;
if (ctx->appx_ctx->calculatedCIHash) {
memcpy(data + pos, AXCI_SIGNATURE, 4);
pos += 4;
memcpy(data + pos, ctx->appx_ctx->calculatedCIHash, (size_t)mdlen);
pos += mdlen;
}
if (ctx->options->verbose) {
print_hash("Hash of file: ", "\n", data, pos);
}
ctx->appx_ctx->hashlen = BIO_write(hashes, data, pos);
OPENSSL_free(data);
return hashes;
}
/*
* Calculate ZIP central directory hash.
* [in] zip: structure holds specific ZIP data
* [in] md: message digest algorithm type
* [in] cdOffset: central directory offset
* [returns] hash
*/
static uint8_t *appx_calc_zip_central_directory_hash(ZIP_FILE *zip, const EVP_MD *md, uint64_t cdOffset)
{
u_char *mdbuf = NULL;
BIO *bhash = BIO_new(BIO_f_md());
if (!BIO_set_md(bhash, md)) {
fprintf(stderr, "Unable to set the message digest of BIO\n");
BIO_free_all(bhash);
return NULL; /* FAILED */
}
BIO_push(bhash, BIO_new(BIO_s_null()));
if (!appx_write_central_directory(bhash, zip, 1, cdOffset)) {
fprintf(stderr, "Unable to write central directory\n");
BIO_free_all(bhash);
return NULL; /* FAILED */
}
mdbuf = OPENSSL_malloc((size_t)EVP_MD_size(md));
BIO_gets(bhash, (char*)mdbuf, EVP_MD_size(md));
BIO_free_all(bhash);
return mdbuf;
}
/*
* Write central directory structure.
* [out] bio: outdata file BIO
* [in] zip: structure holds specific ZIP data
* [in] removeSignature: remove signature switch
* [in] cdOffset: central directory offset
* [returns] 0 on error or 1 on success
*/
static int appx_write_central_directory(BIO *bio, ZIP_FILE *zip, int removeSignature, uint64_t cdOffset)
{
ZIP_CENTRAL_DIRECTORY_ENTRY *entry;
uint64_t offsetDiff = 0, cdSize = 0;
uint16_t noEntries = 0;
for (entry = zip->centralDirectoryHead; entry != NULL; entry = entry->next) {
/* the signature file is considered non existent for hashing purposes */
uint64_t sizeOnDisk = 0;
if (noEntries > zip->centralDirectoryRecordCount) {
fprintf(stderr, "Corrupted central directory structure\n");
return 0; /* FAILED */
}
if (!entry->fileName || (entry->fileNameLen == 0)) {
fprintf(stderr, "Corrupted file name\n");
return 0; /* FAILED */
}
if (removeSignature && !strcmp(entry->fileName, APP_SIGNATURE_FILENAME)) {
continue;
}
/* APP_SIGNATURE is nt 'tainted' by offset shift after replacing the contents of [content_types] */
zipWriteCentralDirectoryEntry(bio, &sizeOnDisk, entry, strcmp(entry->fileName, APP_SIGNATURE_FILENAME) ? offsetDiff : 0);
cdSize += sizeOnDisk;
if (entry->overrideData) {
offsetDiff += entry->overrideData->compressedSize - entry->compressedSize;
}
noEntries++;
}
if (zip->isZip64) {
/* eocdr */
BIO_write(bio, PKZIP64_EOCDR_SIGNATURE, 4);
bioAddU64(bio, zip->eocdr64.eocdrSize);
bioAddU16(bio, zip->eocdr64.creatorVersion);
bioAddU16(bio, zip->eocdr64.viewerVersion);
bioAddU32(bio, zip->eocdr64.diskNumber);
bioAddU32(bio, zip->eocdr64.diskWithCentralDirectory);
bioAddU64(bio, (uint64_t)noEntries);
bioAddU64(bio, (uint64_t)noEntries);
bioAddU64(bio, cdSize);
bioAddU64(bio, cdOffset);
if (zip->eocdr64.commentLen > 0) {
size_t check;
if (!BIO_write_ex(bio, zip->eocdr64.comment, zip->eocdr64.commentLen, &check)
|| check != zip->eocdr64.commentLen) {
return 0; /* FAILED */
}
}
/* eocdr locator */
BIO_write(bio, PKZIP64_EOCD_LOCATOR_SIGNATURE, 4);
bioAddU32(bio, zip->locator.diskWithEOCD);
bioAddU64(bio, cdOffset + cdSize);
bioAddU32(bio, zip->locator.totalNumberOfDisks);
}
BIO_write(bio, PKZIP_EOCDR_SIGNATURE, 4);
/* those need to be 0s even though packaging tool writes FFFFs here
* it will fail verification if not zeros */
bioAddU16(bio, 0);
bioAddU16(bio, 0);
if (zip->eocdr.diskEntries != UINT16_MAX) {
bioAddU16(bio, noEntries);
} else {
bioAddU16(bio, UINT16_MAX);
}
if (zip->eocdr.totalEntries != UINT16_MAX) {
bioAddU16(bio, noEntries);
} else {
bioAddU16(bio, UINT16_MAX);
}
if (zip->eocdr.centralDirectorySize != UINT32_MAX) {
bioAddU32(bio, (uint32_t)cdSize);
} else {
bioAddU32(bio, UINT32_MAX);
}
if (zip->eocdr.centralDirectoryOffset != UINT32_MAX) {
bioAddU32(bio, (uint32_t)cdOffset);
} else {
bioAddU32(bio, UINT32_MAX);
}
bioAddU16(bio, zip->eocdr.commentLen);
if (zip->eocdr.commentLen > 0) {
BIO_write(bio, zip->eocdr.comment, zip->eocdr.commentLen);
}
return 1; /* OK */
}
/*
* Calculate ZIP data hash.
* [out] cdOffset: central directory offset
* [in] zip: structure holds specific ZIP data
* [in] md: message digest algorithm type
* [returns] hash
*/
static uint8_t *appx_calc_zip_data_hash(uint64_t *cdOffset, ZIP_FILE *zip, const EVP_MD *md)
{
ZIP_CENTRAL_DIRECTORY_ENTRY *entry;
u_char *mdbuf = NULL;
BIO *bhash = BIO_new(BIO_f_md());