This repository was archived by the owner on Aug 31, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 227
Expand file tree
/
Copy pathdeploy_sign.cpp
More file actions
1666 lines (1422 loc) · 51.9 KB
/
deploy_sign.cpp
File metadata and controls
1666 lines (1422 loc) · 51.9 KB
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
/* Copyright (C) 2003-2015 LiveCode Ltd.
This file is part of LiveCode.
LiveCode is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License v3 as published by the Free
Software Foundation.
LiveCode is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with LiveCode. If not see <http://www.gnu.org/licenses/>. */
#include "prefix.h"
#include "globdefs.h"
#include "objdefs.h"
#include "parsedef.h"
#include "filedefs.h"
#include "exec.h"
#include "handler.h"
#include "scriptpt.h"
#include "variable.h"
#include "statemnt.h"
#include "globals.h"
#include "util.h"
#include "param.h"
#include "object.h"
#include "deploy.h"
#include "osspec.h"
#include <openssl/err.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/pkcs7.h>
#include <openssl/asn1t.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
////////////////////////////////////////////////////////////////////////////////
// At first glance, digital signing is quite scary in terms of implementation;
// however, once one gets over the hurdle of nomenclature, it is actually quite
// straight-forward. Indeed, it is made even more straight-forward by the fact
// that OpenSSL pretty much does it all for us...
//
// The nomenclature is actually pretty horrendous but here goes a simplified
// view...
//
// PKCS stands for 'Public Key Cryptography Standards'. It is a collection of
// specifications devised and published by RSA Security. The ones of critical
// interest to us are:
// - PKCS#7: this contains the definition of the digital signature
// structure(s)
// - PKCS#8: this contains the definition private key structure(s).
// - PKCS#12: this contains the definitions of a container to store a
// certificate and private key together.
//
// Now, all the data structures needed by crypto related activities are
// defined using an abstract notation called ASN.1 - this is really just a
// way of describing hierarchical data structures in text. Indeed, ASN.1 itself
// does nothing for us, other then to tell us what order/type/kind of fields
// are present in any of the data structures defined in the PKCS standards.
//
// However, ASN.1 becomes useful when an encoding format is applied to it.
// There are a number of these, but the primary one in use for the signing
// activities is DER. The DER format is just a way of encoding an ASN.1
// described structure as a byte stream.
//
// The key element in the code-signing process is the X.509 v3 certificate that
// is issued by a Certificate Authority. Again, this object is defined as
// an ASN.1 object. However, it should be noted that 'in the wild' such
// certificates will generally be stored using a PKCS#7 SignedData structure
// with no actual content.
//
// Thus, to sum up - the various PKCS specifications define all the required
// data structures using ASN.1. These data structures are read an written
// using an encoding format called DER.
//
// The good news is now that we have these basic ideas, is that we can
// forget about most of it - OpenSSL handles all the ASN.1/DER/PKCS stuff
// for us... This is assuming it is possible to understand the rather cryptic
// (and undocumented!) OpenSSL functions that do all this for us!
////////////////////////////////////////////////////////////////////////////////
// This section contains all the Authenticode related definitions and ASN.1
// structure types.
// These OID values are taken from <wintrust.h>
#define SPC_TIME_STAMP_REQUEST_OBJID "1.3.6.1.4.1.311.3.2.1"
#define SPC_INDIRECT_DATA_OBJID "1.3.6.1.4.1.311.2.1.4"
#define SPC_SP_AGENCY_INFO_OBJID "1.3.6.1.4.1.311.2.1.10"
#define SPC_STATEMENT_TYPE_OBJID "1.3.6.1.4.1.311.2.1.11"
#define SPC_SP_OPUS_INFO_OBJID "1.3.6.1.4.1.311.2.1.12"
#define SPC_CERT_EXTENSIONS_OBJID "1.3.6.1.4.1.311.2.1.14"
#define SPC_PE_IMAGE_DATA_OBJID "1.3.6.1.4.1.311.2.1.15"
#define SPC_RAW_FILE_DATA_OBJID "1.3.6.1.4.1.311.2.1.18"
#define SPC_STRUCTURED_STORAGE_DATA_OBJID "1.3.6.1.4.1.311.2.1.19"
#define SPC_JAVA_CLASS_DATA_OBJID "1.3.6.1.4.1.311.2.1.20"
#define SPC_INDIVIDUAL_SP_KEY_PURPOSE_OBJID "1.3.6.1.4.1.311.2.1.21"
#define SPC_COMMERCIAL_SP_KEY_PURPOSE_OBJID "1.3.6.1.4.1.311.2.1.22"
#define SPC_CAB_DATA_OBJID "1.3.6.1.4.1.311.2.1.25"
#define SPC_GLUE_RDN_OBJID "1.3.6.1.4.1.311.2.1.25" // obsolete!
#define SPC_MINIMAL_CRITERIA_OBJID "1.3.6.1.4.1.311.2.1.26"
#define SPC_FINANCIAL_CRITERIA_OBJID "1.3.6.1.4.1.311.2.1.27"
#define SPC_LINK_OBJID "1.3.6.1.4.1.311.2.1.28"
#define SPC_SIGINFO_OBJID "1.3.6.1.4.1.311.2.1.30"
//////////
/* AlgorithmIdentifier ::= SEQUENCE {
algorithm ObjectID,
parameters [0] EXPLICIT ANY OPTIONAL
} */
struct AlgorithmIdentifier
{
ASN1_OBJECT *algorithm;
ASN1_NULL *parameters;
};
DECLARE_ASN1_FUNCTIONS(AlgorithmIdentifier)
ASN1_SEQUENCE(AlgorithmIdentifier) = {
ASN1_SIMPLE(AlgorithmIdentifier, algorithm, ASN1_OBJECT),
ASN1_SIMPLE(AlgorithmIdentifier, parameters, ASN1_NULL)
} ASN1_SEQUENCE_END(AlgorithmIdentifier)
IMPLEMENT_ASN1_FUNCTIONS(AlgorithmIdentifier)
//////////
/* DigestInfo ::= SEQUENCE {
digestAlgorithm AlgorithmIdentifier,
digest OCTETSTRING
} */
struct DigestInfo
{
AlgorithmIdentifier *algorithm;
ASN1_OCTET_STRING *digest;
};
DECLARE_ASN1_FUNCTIONS(DigestInfo)
ASN1_SEQUENCE(DigestInfo) = {
ASN1_SIMPLE(DigestInfo, algorithm, AlgorithmIdentifier),
ASN1_SIMPLE(DigestInfo, digest, ASN1_OCTET_STRING)
} ASN1_SEQUENCE_END(DigestInfo)
IMPLEMENT_ASN1_FUNCTIONS(DigestInfo)
//////////
/* SpcString ::= CHOICE {
unicode [0] IMPLICIT BMPSTRING,
ascii [1] IMPLICIT IA5STRING
} */
struct SpcString
{
int type;
union
{
ASN1_STRING *variant;
ASN1_BMPSTRING *unicode;
ASN1_IA5STRING *ascii;
} d;
};
DECLARE_ASN1_FUNCTIONS(SpcString)
ASN1_CHOICE(SpcString) = {
ASN1_IMP_OPT(SpcString, d.unicode, ASN1_BMPSTRING, 0),
ASN1_IMP_OPT(SpcString, d.ascii, ASN1_IA5STRING, 1)
} ASN1_CHOICE_END(SpcString)
IMPLEMENT_ASN1_FUNCTIONS(SpcString)
//////////
/* SpcSerializedObject ::= SEQUENCE {
classId SpcUuid,
serializedData OCTETSTRING
}
SpcUuid ::= OCTETSTRING */
struct SpcSerializedObject
{
ASN1_OCTET_STRING *class_id;
ASN1_OCTET_STRING *data;
};
DECLARE_ASN1_FUNCTIONS(SpcSerializedObject)
ASN1_SEQUENCE(SpcSerializedObject) = {
ASN1_SIMPLE(SpcSerializedObject, class_id, ASN1_OCTET_STRING),
ASN1_SIMPLE(SpcSerializedObject, data, ASN1_OCTET_STRING)
} ASN1_SEQUENCE_END(SpcSerializedObject)
IMPLEMENT_ASN1_FUNCTIONS(SpcSerializedObject)
//////////
/* SpcLink ::= CHOICE {
url [0] IMPLICIT IA5STRING,
moniker [1] IMPLICIT SpcSerializedObject,
file [2] EXPLICIT SpcString
} */
struct SpcLink
{
int type;
union
{
ASN1_IA5STRING *url;
SpcSerializedObject *moniker;
SpcString *file;
} d;
};
DECLARE_ASN1_FUNCTIONS(SpcLink)
ASN1_CHOICE(SpcLink) = {
ASN1_IMP_OPT(SpcLink, d.url, ASN1_IA5STRING, 0),
ASN1_IMP_OPT(SpcLink, d.moniker, SpcSerializedObject, 1),
ASN1_EXP_OPT(SpcLink, d.file, SpcString, 2)
} ASN1_CHOICE_END(SpcLink)
IMPLEMENT_ASN1_FUNCTIONS(SpcLink)
//////////
/* SpcSpOpusInfo ::= SEQUENCE {
programName [0] EXPLICIT SpcString OPTIONAL,
moreInfo [1] EXPLICIT SpcLink OPTIONAL,
} */
struct SpcSpOpusInfo
{
SpcString *description;
SpcLink *url;
};
DECLARE_ASN1_FUNCTIONS(SpcSpOpusInfo)
ASN1_SEQUENCE(SpcSpOpusInfo) = {
ASN1_EXP_OPT(SpcSpOpusInfo, description, SpcString, 0),
ASN1_EXP_OPT(SpcSpOpusInfo, url, SpcLink, 1)
} ASN1_SEQUENCE_END(SpcSpOpusInfo)
IMPLEMENT_ASN1_FUNCTIONS(SpcSpOpusInfo)
//////////
/* SpcPeImageData ::= SEQUENCE {
flags SpcPeImageFlags DEFAULT { includeResources },
file SpcLink
}
SpcPeImageFlags ::= BIT STRING {
includeResources (0),
includeDebugInfo (1),
includeImportAddressTable (2)
} */
struct SpcPeImageData
{
ASN1_BIT_STRING *flags;
SpcLink *file;
};
DECLARE_ASN1_FUNCTIONS(SpcPeImageData)
ASN1_SEQUENCE(SpcPeImageData) = {
ASN1_OPT(SpcPeImageData, flags, ASN1_BIT_STRING),
ASN1_EXP_OPT(SpcPeImageData, file, SpcLink, 0)
} ASN1_SEQUENCE_END(SpcPeImageData)
IMPLEMENT_ASN1_FUNCTIONS(SpcPeImageData)
//////////
// This is the 'official' definition of the object. However, we specialize
// for our purposes since 'value' is always a SPC_PE_IMAGE_DATA object in
// our case.
/* SpcAttributeTypeAndOptionalValue ::= SEQUENCE {
type ObjectID,
value [0] EXPLICIT ANY OPTIONAL
} */
struct SpcAttributeTypeAndOptionalValue
{
ASN1_OBJECT *type;
SpcPeImageData *value;
};
DECLARE_ASN1_FUNCTIONS(SpcAttributeTypeAndOptionalValue)
IMPLEMENT_ASN1_FUNCTIONS(SpcAttributeTypeAndOptionalValue)
ASN1_SEQUENCE(SpcAttributeTypeAndOptionalValue) = {
ASN1_SIMPLE(SpcAttributeTypeAndOptionalValue, type, ASN1_OBJECT),
ASN1_SIMPLE(SpcAttributeTypeAndOptionalValue, value, SpcPeImageData)
} ASN1_SEQUENCE_END(SpcAttributeTypeAndOptionalValue)
//////////
/* SpcIndirectDataContent ::= SEQUENCE {
data SpcAttributeTypeAndOptionalValue,
messageDigest DigestInfo
} */
struct SpcIndirectDataContent
{
SpcAttributeTypeAndOptionalValue *data;
DigestInfo *digest;
};
DECLARE_ASN1_FUNCTIONS(SpcIndirectDataContent)
ASN1_SEQUENCE(SpcIndirectDataContent) = {
ASN1_SIMPLE(SpcIndirectDataContent, data, SpcAttributeTypeAndOptionalValue),
ASN1_SIMPLE(SpcIndirectDataContent, digest, DigestInfo)
} ASN1_SEQUENCE_END(SpcIndirectDataContent)
IMPLEMENT_ASN1_FUNCTIONS(SpcIndirectDataContent)
//////////
/* SpcTimeStampRequestBlob ::= SEQUENCE {
type ObjectID,
signature [0] EXPLICIT OCTETSTRING OPTIONAL
} */
struct SpcTimeStampRequestBlob
{
ASN1_OBJECT *type;
ASN1_OCTET_STRING *signature;
};
DECLARE_ASN1_FUNCTIONS(SpcTimeStampRequestBlob)
ASN1_SEQUENCE(SpcTimeStampRequestBlob) = {
ASN1_SIMPLE(SpcTimeStampRequestBlob, type, ASN1_OBJECT),
ASN1_EXP_OPT(SpcTimeStampRequestBlob, signature, ASN1_OCTET_STRING, 0)
} ASN1_SEQUENCE_END(SpcTimeStampRequestBlob)
IMPLEMENT_ASN1_FUNCTIONS(SpcTimeStampRequestBlob)
//////////
/* SpcTimeStampRequest ::= SEQUENCE {
type ObjectID,
blob SpcTimeStampRequestBlob
} */
struct SpcTimeStampRequest
{
ASN1_OBJECT *type;
SpcTimeStampRequestBlob *blob;
};
DECLARE_ASN1_FUNCTIONS(SpcTimeStampRequest)
ASN1_SEQUENCE(SpcTimeStampRequest) = {
ASN1_SIMPLE(SpcTimeStampRequest, type, ASN1_OBJECT),
ASN1_SIMPLE(SpcTimeStampRequest, blob, SpcTimeStampRequestBlob)
} ASN1_SEQUENCE_END(SpcTimeStampRequest)
IMPLEMENT_ASN1_FUNCTIONS(SpcTimeStampRequest)
////////////////////////////////////////////////////////////////////////////////
// This method throws an error of the principal generic type, with any additional
// OpenSSL info.
static bool MCDeployThrowOpenSSL(MCDeployError p_error)
{
return MCDeployThrow(p_error);
}
////////////////////////////////////////////////////////////////////////////////
// This template simplifies conversion of a object structure to the DER
// binary encoding.
template<typename T> static bool i2d(int (*p_i2d)(T *, unsigned char **), T *p_object, uint8_t*& r_data, uint32_t& r_length)
{
bool t_success;
t_success = true;
uint32_t t_length;
t_length = 0;
if (t_success)
{
t_length = p_i2d(p_object, nil);
if (t_length == 0)
t_success = MCDeployThrowOpenSSL(kMCDeployErrorBadSignature);
}
uint8_t *t_data;
t_data = nil;
if (t_success)
{
t_data = (uint8_t *)OPENSSL_malloc(t_length);
if (t_data == nil)
t_success = MCDeployThrowOpenSSL(kMCDeployErrorNoMemory);
}
if (t_success)
{
p_i2d(p_object, &t_data);
r_data = t_data - t_length;
r_length = t_length;
}
else
{
if (t_data != nil)
OPENSSL_free(t_data);
}
return t_success;
}
////////////////////////////////////////////////////////////////////////////////
// Authenticode code-signing uses a PKCS#7 SignedData structure as the digital
// signature. The signature asserts two things:
// 1) The file originates from a specific software publisher.
// 2) The file has not been altered since it was signed.
//
// The PKCS#7 SignedData structure contains a number of things:
// - the executable file's hash value
// - a signature created by the software publisher's private key
// - the X.509 v3 certificates that bind the software publisher's signing key
// to a legal entity.
// - (optional) a description of the software publisher
// - (optional) the software publisher's URL
// - (optional) an Authenticode timestamp
//
// It should be noted that the timestamp can only be created with a valid TSA
// (time-stamping authority) - not all Authenticode CA's provide this facility.
// Having a timestamp, though, is a good thing as it unambiguously determines
// when the signature was created thus meaning later revocation or expiry of the
// digital certificate is irrelevant.
// This method loads a X.509v3 certificate stored in an empty PKCS#7 SignedData
// structure.
static bool MCDeployCertificateLoad(MCStringRef p_passphrase, MCStringRef p_certificate, PKCS7*& r_chain)
{
// SN-2014-01-10: The certificate filename can be in unicode.
// As a char* is required, the conversion must be done.
// On Mac, UTF8 suits the filesystem encoding requirements
// On Windows, BIO_new_file expects a UFT-8 path
// On Linux, a SysString is used
#ifdef _LINUX
MCAutoStringRefAsSysString t_certificate;
#else
MCAutoStringRefAsUTF8String t_certificate;
#endif
t_certificate . Lock(p_certificate);
BIO *t_file;
t_file = BIO_new_file(*t_certificate, "rb");
if (t_file == nil)
return MCDeployThrowOpenSSL(kMCDeployErrorNoCertificate);
PKCS7 *t_cert;
t_cert = d2i_PKCS7_bio(t_file, nil);
// If we failed to read the cert as binary, try as base64 encoded (VeriSign seems
// to provide such certs like that).
if (t_cert == nil)
{
BIO_seek(t_file, 0);
t_file = BIO_push(BIO_new(BIO_f_base64()), t_file);
t_cert = d2i_PKCS7_bio(t_file, nil);
}
BIO_free_all(t_file);
if (t_cert == nil)
return MCDeployThrowOpenSSL(kMCDeployErrorBadCertificate);
r_chain = t_cert;
return true;
}
// This method loads a private key stored in either PKCS#8 format, or in a the
// Microsoft PVK format.
static bool MCDeploySignLoadPVK(MCStringRef, MCStringRef, EVP_PKEY*&);
static bool MCDeployPrivateKeyLoad(MCStringRef p_passphrase, MCStringRef p_privatekey, EVP_PKEY*& r_private_key)
{
return MCDeploySignLoadPVK(p_privatekey, p_passphrase, r_private_key);
}
// This method loads a PKCS#12 privatekey/certificate pair.
static bool MCDeployCertStoreLoad(MCStringRef p_passphrase, MCStringRef p_store, PKCS7*& r_certificate, EVP_PKEY*& r_private_key)
{
return false;
}
static bool MCDeployBuildSpcString(const char *p_value, bool p_is_ascii, SpcString*& r_string)
{
bool t_success;
t_success = true;
SpcString *t_string;
t_string = nil;
if (t_success)
{
t_string = SpcString_new();
if (t_string == nil)
t_success = MCDeployThrowOpenSSL(kMCDeployErrorNoMemory);
}
ASN1_STRING *t_value;
t_value = nil;
if (t_success)
{
if (!ASN1_mbstring_copy(&t_value, (const unsigned char *)p_value, strlen(p_value), MBSTRING_UTF8, p_is_ascii ? B_ASN1_IA5STRING : B_ASN1_BMPSTRING))
t_success = MCDeployThrowOpenSSL(kMCDeployErrorBadString);
}
if (t_success)
{
t_string -> type = p_is_ascii ? 1 : 0;
t_string -> d . variant = t_value;
r_string = t_string;
}
else
{
if (t_string != nil)
SpcString_free(t_string);
if (t_value != nil)
ASN1_STRING_free(t_value);
}
return t_success;
}
static bool MCDeployBuildSpcIndirectDataContent(BIO *p_hash, SpcIndirectDataContent*& r_content)
{
bool t_success;
t_success = true;
// Read the hash from the bio
uint8_t t_hash_data[EVP_MAX_MD_SIZE];
uint32_t t_hash_length;
if (t_success)
{
t_hash_length = BIO_gets(p_hash, (char *)t_hash_data, EVP_MAX_MD_SIZE);
if (t_hash_length == 0)
t_success = MCDeployThrowOpenSSL(kMCDeployErrorBadHash);
}
// Construct all the ASN.1 objects we need.
SpcIndirectDataContent *t_content;
SpcAttributeTypeAndOptionalValue *t_data;
DigestInfo *t_message_digest;
AlgorithmIdentifier *t_digest_algorithm;
SpcPeImageData *t_image_data;
SpcLink *t_image_data_file;
t_data = nil;
t_message_digest = nil;
t_digest_algorithm = nil;
t_image_data = nil;
t_content = nil;
t_image_data_file = nil;
if (t_success)
{
t_content = SpcIndirectDataContent_new();
t_data = SpcAttributeTypeAndOptionalValue_new();
t_message_digest = DigestInfo_new();
t_digest_algorithm = AlgorithmIdentifier_new();
t_image_data = SpcPeImageData_new();
t_image_data_file = SpcLink_new();
if (t_content == nil || t_data == nil || t_message_digest == nil || t_digest_algorithm == nil ||
t_image_data == nil || t_image_data_file == nil)
t_success = MCDeployThrow(kMCDeployErrorNoMemory);
}
if (t_success)
t_success = MCDeployBuildSpcString("<<<Obsolete>>>", false, t_image_data_file -> d . file);
if (t_success)
{
t_image_data -> flags = ASN1_BIT_STRING_new();
if (t_image_data -> flags == nil)
t_success = MCDeployThrowOpenSSL(kMCDeployErrorNoMemory);
}
if (t_success)
{
t_message_digest -> digest = ASN1_OCTET_STRING_new();
if (t_message_digest -> digest == nil ||
!ASN1_OCTET_STRING_set(t_message_digest -> digest, t_hash_data, t_hash_length))
t_success = MCDeployThrowOpenSSL(kMCDeployErrorNoMemory);
}
if (t_success)
{
t_digest_algorithm -> parameters = ASN1_NULL_new();
if (t_digest_algorithm -> parameters == nil)
t_success = MCDeployThrowOpenSSL(kMCDeployErrorNoMemory);
}
if (t_success)
{
t_content -> data = t_data;
t_content -> digest = t_message_digest;
t_data -> type = OBJ_txt2obj(SPC_PE_IMAGE_DATA_OBJID, 0);
t_data -> value = t_image_data;
t_message_digest -> algorithm = t_digest_algorithm;
t_digest_algorithm -> algorithm = OBJ_nid2obj(NID_sha1); // NID_md5
t_image_data_file -> type = 2;
t_image_data -> file = t_image_data_file;
r_content = t_content;
}
else
{
if (t_image_data_file != nil)
SpcLink_free(t_image_data_file);
if (t_image_data != nil)
SpcPeImageData_free(t_image_data);
if (t_digest_algorithm != nil)
AlgorithmIdentifier_free(t_digest_algorithm);
if (t_message_digest != nil)
DigestInfo_free(t_message_digest);
if (t_data != nil)
SpcAttributeTypeAndOptionalValue_free(t_data);
if (t_content != nil)
SpcIndirectDataContent_free(t_content);
}
return t_success;
}
constexpr uint32_t kSecurityEntryOffset32 = 152;
constexpr uint32_t kSecurityEntryOffset64 = 168;
// This method checks to see if the input file is a valid Windows EXE (well, as
// valid as we need it to be). It then returns the offset to the PE header if
// successful. Additionally, we return the offset of the certificate entry, or
// the length of the file (if no current cert).
static bool MCDeploySignCheckWindowsExecutable(MCDeployFileRef p_input, uint32_t& r_pe_offset, uint32_t& r_cert_offset, MCDeployArchitecture &r_architecture)
{
// First get the length of the input file
uint32_t t_length;
if (!MCDeployFileMeasure(p_input, t_length))
return false;
uint32_t t_offset;
if (!MCDeployWindowsPEHeaderOffset(p_input, t_offset))
return false;
MCDeployArchitecture t_arch;
if (!MCDeployWindowsArchitecture(p_input, t_offset, t_arch))
return false;
uint32_t t_security_offset = t_offset;
if (t_arch == kMCDeployArchitecture_I386)
{
t_security_offset += kSecurityEntryOffset32;
}
else
{
t_security_offset += kSecurityEntryOffset64;
}
// Now read in the existing cert fields. Note that the offset here is
// that of the 5th data directory entry
uint32_t t_cert_section[2];
if (!MCDeployFileReadAt(p_input, t_cert_section, 2 * sizeof(uint32_t), t_security_offset))
{
return MCDeployThrow(kMCDeployErrorWindowsBadNTSignature);
}
MCDeployByteSwap32(false, t_cert_section[0]);
MCDeployByteSwap32(false, t_cert_section[1]);
// Make sure that if there is an existing certicate, that it is at the end
// of the file.
if (t_cert_section[0] != 0 && t_cert_section[0] + t_cert_section[1] != t_length)
return MCDeployThrow(kMCDeployErrorWindowsBadSecuritySection);
if (t_cert_section[0] != 0)
r_cert_offset = t_cert_section[0];
else
r_cert_offset = t_length;
r_pe_offset = t_offset;
r_architecture = t_arch;
return true;
}
// This method copies data from the input file to the output BIO.
static bool MCDeploySignCopyFileAt(BIO *p_output, MCDeployFileRef p_input, uint32_t p_offset, uint32_t p_amount)
{
bool t_success;
t_success = true;
if (!MCDeployFileSeekSet(p_input, p_offset))
return MCDeployThrow(kMCDeployErrorBadRead);
while(p_amount > 0)
{
char t_buffer[4096];
int t_size;
t_size = MCU_min(4096U, p_amount);
if (!MCDeployFileRead(p_input, t_buffer, t_size))
return MCDeployThrow(kMCDeployErrorBadRead);
if (BIO_write(p_output, t_buffer, t_size) != t_size)
return MCDeployThrowOpenSSL(kMCDeployErrorBadWrite);
p_amount -= t_size;
}
return true;
}
// This method reconstructs the output executable from the input executable
// while computing the hash of the critical parts of the file.
static bool MCDeploySignHashWindowsExecutable(MCDeployFileRef p_input, BIO *p_output, uint32_t p_pe_offset, uint32_t p_cert_offset, MCDeployArchitecture p_architecture, BIO*& r_hash)
{
bool t_success;
t_success = true;
// First construct a hash BIO and chain it to the output bio.
BIO *t_hash;
t_hash = nil;
if (t_success)
{
t_hash = BIO_new(BIO_f_md());
if (t_hash == nil)
t_success = MCDeployThrowOpenSSL(kMCDeployErrorNoMemory);
BIO_set_md(t_hash, EVP_sha1()); // EVP_md5
BIO_push(t_hash, p_output);
}
// Now we generate the new output file, hashing the appropriate portions of
// the input executable as we go.
// The first part of the output file is everything up to the start of the
// 'CheckSum' field of the IMAGE_OPTIONAL_HEADER structure. This is at
// offset 88 in both IMAGE_OPTIONAL_HEADER32 and IMAGE_OPTIONAL_HEADER64.
// This part is part of the hash.
if (t_success)
t_success = MCDeploySignCopyFileAt(t_hash, p_input, 0, p_pe_offset + 88);
// Next we write out an empty (0) CheckSum field - this section is not
// hashed.
if (t_success)
{
uint32_t t_checksum;
t_checksum = 0;
if (BIO_write(p_output, &t_checksum, sizeof(t_checksum)) != sizeof(uint32_t))
t_success = MCDeployThrowOpenSSL(kMCDeployErrorBadWrite);
}
uint32_t t_security_offset = p_pe_offset;
if (p_architecture == kMCDeployArchitecture_I386)
{
t_security_offset += kSecurityEntryOffset32;
}
else
{
t_security_offset += kSecurityEntryOffset64;
}
// Next is the section of the header after the CheckSum field and up to
// the 'Security' data directory entry.
if (t_success)
t_success = MCDeploySignCopyFileAt(t_hash, p_input, p_pe_offset + 92, t_security_offset - (p_pe_offset + 92));
// Now write out the (current) value of the Security data directory entry,
// but not into the hash.
if (t_success)
t_success = MCDeploySignCopyFileAt(p_output, p_input, t_security_offset, 8);
// After the Security data directory, everything up to the cert offset is
// hashed.
if (t_success)
t_success = MCDeploySignCopyFileAt(t_hash, p_input, t_security_offset + 8, p_cert_offset - (t_security_offset + 8));
// Finally we round the output up to the nearest 8 bytes.
if (t_success && (p_cert_offset % 8 != 0))
{
uint8_t t_pad[8];
MCMemoryClear(t_pad, 8);
int t_pad_length;
t_pad_length = 8 - (p_cert_offset % 8);
if (BIO_write(t_hash, t_pad, t_pad_length) != t_pad_length)
t_success = MCDeployThrowOpenSSL(kMCDeployErrorBadWrite);
}
// If we have failed, make sure we free the hash BIO, otherwise we return
// it.
if (t_success)
r_hash = t_hash;
else
BIO_free(t_hash);
return t_success;
}
static bool MCDeploySignWindowsAddOpusInfo(const MCDeploySignParameters& p_params, PKCS7_SIGNER_INFO *p_sign_info)
{
bool t_success;
t_success = true;
SpcSpOpusInfo *t_opus;
t_opus = nil;
if (t_success)
{
t_opus = SpcSpOpusInfo_new();
if (t_opus == nil)
t_success = MCDeployThrowOpenSSL(kMCDeployErrorNoMemory);
}
if (t_success && p_params . description != nil)
{
MCAutoStringRefAsUTF8String t_utf8_string;
t_success = t_utf8_string . Lock(p_params . description)
&& MCDeployBuildSpcString(*t_utf8_string, false, t_opus -> description);
}
if (t_success && p_params . url != nil)
{
t_opus -> url = SpcLink_new();
if (t_opus -> url != nil)
{
if (ASN1_mbstring_copy(&t_opus -> url -> d . url, MCStringGetNativeCharPtr(p_params.url), MCStringGetLength(p_params.url), MBSTRING_UTF8, B_ASN1_IA5STRING))
t_opus -> url -> type = 0;
else
t_success = MCDeployThrowOpenSSL(kMCDeployErrorBadString);
}
else
t_success = MCDeployThrowOpenSSL(kMCDeployErrorNoMemory);
}
uint8_t *t_opus_data;
uint32_t t_opus_length;
t_opus_data = nil;
t_opus_length = 0;
if (t_success)
t_success = i2d(i2d_SpcSpOpusInfo, t_opus, t_opus_data, t_opus_length);
ASN1_STRING *t_opus_string;
t_opus_string = nil;
if (t_success)
{
t_opus_string = ASN1_STRING_new();
if (t_opus_string == nil ||
!ASN1_STRING_set(t_opus_string, t_opus_data, t_opus_length))
t_success = MCDeployThrow(kMCDeployErrorNoMemory);
}
if (t_success)
{
if (!PKCS7_add_signed_attribute(p_sign_info, OBJ_txt2nid(SPC_SP_OPUS_INFO_OBJID), V_ASN1_SEQUENCE, t_opus_string))
t_success = MCDeployThrowOpenSSL(kMCDeployErrorBadSignature);
}
// Note that this is not owned by the sig if we failed.
if (!t_success)
{
if (t_opus_string != nil)
ASN1_STRING_free(t_opus_string);
}
if (t_opus_data != nil)
OPENSSL_free(t_opus_data);
if (t_opus != nil)
SpcSpOpusInfo_free(t_opus);
return t_success;
}
// This method adds a counter-signature to our signature that is used to verify the time
// at which it was generated. It uses the timestamping authority URL specified in the
// 'timestamper' parameter. The flow of this code is cribbed from 'osslsigncode.c' - the
// open-source implementation of the SignCode.exe utility.
static bool MCDeploySignWindowsAddTimeStamp(const MCDeploySignParameters& p_params, PKCS7 *p_signature)
{
bool t_success;
t_success = true;
// Fetch the signatures 'signer_info' structure
PKCS7_SIGNER_INFO *t_signer_info;
t_signer_info = sk_PKCS7_SIGNER_INFO_value(p_signature -> d . sign -> signer_info, 0);
// Build a request to send to the time-stamp authority. If there is a 'blob'
// field in this request, then we must reset the signature field before freeing
// it as that is borrowed from elsewhere.
SpcTimeStampRequest *t_request;
t_request = nil;
if (t_success)
{
t_request = SpcTimeStampRequest_new();
if (t_request != nil)
{
t_request -> type = OBJ_txt2obj(SPC_TIME_STAMP_REQUEST_OBJID, 1);
t_request -> blob = SpcTimeStampRequestBlob_new();
if (t_request -> blob != nil)
{
t_request -> blob -> type = OBJ_nid2obj(NID_pkcs7_data);
t_request -> blob -> signature = t_signer_info -> enc_digest;
}
else
t_success = MCDeployThrow(kMCDeployErrorNoMemory);
}
else
t_success = MCDeployThrow(kMCDeployErrorNoMemory);
}
// Convert the request to the binary encoding
uint8_t *t_request_data;
uint32_t t_request_length;
t_request_data = nil;
t_request_length = 0;
if (t_success)
t_success = i2d(i2d_SpcTimeStampRequest, t_request, t_request_data, t_request_length);
// Convert the request to base64
MCAutoDataRef t_req_dataref;
MCAutoStringRef t_req_base64;
/* UNCHECKED */ MCDataCreateWithBytes(t_request_data, t_request_length, &t_req_dataref);
MCU_base64encode(*t_req_dataref, &t_req_base64);
// Request the timestamp from the tsa
if (t_success)
{
// Set the HTTP headers appropriately to make sure no unpleasant caching goes on.
MCValueAssign(MChttpheaders, MCSTR("Content-Type: application/octet-stream\nAccept: application/octet-stream\nUser-Agent: Transport\nCache-Control: no-cache"));
// Use libURL to do the post - we attempt this 5 times with increasing sleep
// periods. This is because it looks like the timestamping service is a little
// unreliable (well, VeriSign's timestamping service anyway!).
uint32_t t_retry_count, t_retry_interval;
t_retry_count = 5;
t_retry_interval = 50;
bool t_failed;
t_failed = true;
while(t_retry_count > 0)
{
MCParameter t_data, t_url;
t_data . setvalueref_argument(*t_req_base64);
t_data . setnext(&t_url);
t_url . setvalueref_argument(p_params . timestamper);
extern MCExecContext *MCECptr;
if (MCECptr->GetObject() -> message(MCM_post_url, &t_data, False, True) == ES_NORMAL &&
MCresult -> isempty())
{
t_failed = false;
break;
}
// Sleep for retry_interval millisecs.
MCS_sleep(t_retry_interval / 1000.0);
t_retry_count -= 1;
t_retry_interval *= 2;
}
if (t_failed)
t_success = MCDeployThrow(kMCDeployErrorTimestampFailed);
}
// Now convert the reply to binary.
MCAutoValueRef t_result_value;
MCAutoStringRef t_result_base64;
MCAutoDataRef t_result_data;
extern MCExecContext *MCECptr;
if (t_success)
{
MCurlresult -> copyasvalueref(&t_result_value);
t_success = MCECptr->ConvertToString(*t_result_value, &t_result_base64);
}
if (t_success)
MCU_base64decode(*t_result_base64, &t_result_data);
// Decode the PKCS7 structure
PKCS7 *t_counter_sig;
t_counter_sig = nil;
if (t_success)
{
const unsigned char *t_data;
t_data = (const unsigned char *)MCDataGetBytePtr(*t_result_data);
int t_length;
t_length = MCDataGetLength(*t_result_data);
t_counter_sig = d2i_PKCS7(&t_counter_sig, &t_data, t_length);
if (t_counter_sig == nil)
t_success = MCDeployThrow(kMCDeployErrorBadTimestamp);
}
// Add the certificates we need to our signature
if (t_success)
for(int32_t i = sk_X509_num(t_counter_sig -> d . sign -> cert) - 1; i >= 0 && t_success; i--)
if (!PKCS7_add_certificate(p_signature, sk_X509_value(t_counter_sig -> d . sign -> cert, i)))