/
Main.java
2361 lines (2147 loc) · 96.4 KB
/
Main.java
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) 1997, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.tools.jarsigner;
import java.io.*;
import java.net.UnknownHostException;
import java.security.cert.CertPathValidatorException;
import java.security.cert.PKIXBuilderParameters;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.*;
import java.util.jar.*;
import java.net.URI;
import java.text.Collator;
import java.text.MessageFormat;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
import java.security.*;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.security.cert.CertPath;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.TrustAnchor;
import java.util.Map.Entry;
import jdk.security.jarsigner.JarSigner;
import jdk.security.jarsigner.JarSignerException;
import sun.security.pkcs.PKCS7;
import sun.security.pkcs.SignerInfo;
import sun.security.timestamp.TimestampToken;
import sun.security.tools.KeyStoreUtil;
import sun.security.validator.Validator;
import sun.security.validator.ValidatorException;
import sun.security.x509.*;
import sun.security.util.*;
/**
* <p>The jarsigner utility.
*
* The exit codes for the main method are:
*
* 0: success
* 1: any error that the jar cannot be signed or verified, including:
* keystore loading error
* TSP communication error
* jarsigner command line error...
* otherwise: error codes from -strict
*
* @author Roland Schemers
* @author Jan Luehe
*/
public class Main {
// for i18n
private static final java.util.ResourceBundle rb =
java.util.ResourceBundle.getBundle
("sun.security.tools.jarsigner.Resources");
private static final Collator collator = Collator.getInstance();
static {
// this is for case insensitive string comparisions
collator.setStrength(Collator.PRIMARY);
}
private static final String NONE = "NONE";
private static final String P11KEYSTORE = "PKCS11";
private static final long SIX_MONTHS = 180*24*60*60*1000L; //milliseconds
private static final long ONE_YEAR = 366*24*60*60*1000L;
private static final DisabledAlgorithmConstraints DISABLED_CHECK =
new DisabledAlgorithmConstraints(
DisabledAlgorithmConstraints.PROPERTY_JAR_DISABLED_ALGS);
private static final DisabledAlgorithmConstraints LEGACY_CHECK =
new DisabledAlgorithmConstraints(
DisabledAlgorithmConstraints.PROPERTY_SECURITY_LEGACY_ALGS);
private static final Set<CryptoPrimitive> DIGEST_PRIMITIVE_SET = Collections
.unmodifiableSet(EnumSet.of(CryptoPrimitive.MESSAGE_DIGEST));
private static final Set<CryptoPrimitive> SIG_PRIMITIVE_SET = Collections
.unmodifiableSet(EnumSet.of(CryptoPrimitive.SIGNATURE));
static final String VERSION = "1.0";
static final int IN_KEYSTORE = 0x01; // signer is in keystore
static final int NOT_ALIAS = 0x04; // alias list is NOT empty and
// signer is not in alias list
static final int SIGNED_BY_ALIAS = 0x08; // signer is in alias list
// Attention:
// This is the entry that get launched by the security tool jarsigner.
public static void main(String args[]) throws Exception {
Main js = new Main();
js.run(args);
}
X509Certificate[] certChain; // signer's cert chain (when composing)
PrivateKey privateKey; // private key
KeyStore store; // the keystore specified by -keystore
// or the default keystore, never null
String keystore; // key store file
boolean nullStream = false; // null keystore input stream (NONE)
boolean token = false; // token-based keystore
String jarfile; // jar files to sign or verify
String alias; // alias to sign jar with
List<String> ckaliases = new ArrayList<>(); // aliases in -verify
char[] storepass; // keystore password
boolean protectedPath; // protected authentication path
String storetype; // keystore type
String providerName; // provider name
List<String> providers = null; // list of provider names
List<String> providerClasses = null; // list of provider classes
// arguments for provider constructors
HashMap<String,String> providerArgs = new HashMap<>();
char[] keypass; // private key password
String sigfile; // name of .SF file
String sigalg; // name of signature algorithm
String digestalg; // name of digest algorithm
String signedjar; // output filename
String tsaUrl; // location of the Timestamping Authority
String tsaAlias; // alias for the Timestamping Authority's certificate
String altCertChain; // file to read alternative cert chain from
String tSAPolicyID;
String tSADigestAlg;
boolean verify = false; // verify the jar
String verbose = null; // verbose output when signing/verifying
boolean showcerts = false; // show certs when verifying
boolean debug = false; // debug
boolean signManifest = true; // "sign" the whole manifest
boolean externalSF = true; // leave the .SF out of the PKCS7 block
boolean strict = false; // treat warnings as error
boolean revocationCheck = false; // Revocation check flag
// read zip entry raw bytes
private String altSignerClass = null;
private String altSignerClasspath = null;
private ZipFile zipFile = null;
// Informational warnings
private boolean hasExpiringCert = false;
private boolean hasExpiringTsaCert = false;
private boolean noTimestamp = true;
// Expiration date. The value could be null if signed by a trusted cert.
private Date expireDate = null;
private Date tsaExpireDate = null;
// If there is a time stamp block inside the PKCS7 block file
boolean hasTimestampBlock = false;
private PublicKey weakPublicKey = null;
private boolean disabledAlgFound = false;
private String legacyDigestAlg = null;
private String legacyTsaDigestAlg = null;
private String legacySigAlg = null;
// Severe warnings.
// jarsigner used to check signer cert chain validity and key usages
// itself and set various warnings. Later CertPath validation is
// added but chainNotValidated is only flagged when no other existing
// warnings are set. TSA cert chain check is added separately and
// only tsaChainNotValidated is set, i.e. has no affect on hasExpiredCert,
// notYetValidCert, or any badXyzUsage.
private int legacyAlg = 0; // 1. digestalg, 2. sigalg, 4. tsadigestalg, 8. key
private int disabledAlg = 0; // 1. digestalg, 2. sigalg, 4. tsadigestalg, 8. key
private boolean hasExpiredCert = false;
private boolean hasExpiredTsaCert = false;
private boolean notYetValidCert = false;
private boolean chainNotValidated = false;
private boolean tsaChainNotValidated = false;
private boolean notSignedByAlias = false;
private boolean aliasNotInStore = false;
private boolean hasUnsignedEntry = false;
private boolean badKeyUsage = false;
private boolean badExtendedKeyUsage = false;
private boolean badNetscapeCertType = false;
private boolean signerSelfSigned = false;
private Throwable chainNotValidatedReason = null;
private Throwable tsaChainNotValidatedReason = null;
PKIXBuilderParameters pkixParameters;
Set<X509Certificate> trustedCerts = new HashSet<>();
public void run(String args[]) {
try {
args = parseArgs(args);
// Try to load and install the specified providers
if (providers != null) {
for (String provName: providers) {
try {
KeyStoreUtil.loadProviderByName(provName,
providerArgs.get(provName));
if (debug) {
System.out.println("loadProviderByName: " + provName);
}
} catch (IllegalArgumentException e) {
throw new Exception(String.format(rb.getString(
"provider.name.not.found"), provName));
}
}
}
if (providerClasses != null) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
for (String provClass: providerClasses) {
try {
KeyStoreUtil.loadProviderByClass(provClass,
providerArgs.get(provClass), cl);
if (debug) {
System.out.println("loadProviderByClass: " + provClass);
}
} catch (ClassCastException cce) {
throw new Exception(String.format(rb.getString(
"provclass.not.a.provider"), provClass));
} catch (IllegalArgumentException e) {
throw new Exception(String.format(rb.getString(
"provider.class.not.found"), provClass), e.getCause());
}
}
}
if (verify) {
try {
loadKeyStore(keystore, false);
} catch (Exception e) {
if ((keystore != null) || (storepass != null)) {
System.out.println(rb.getString("jarsigner.error.") +
e.getMessage());
if (debug) {
e.printStackTrace();
}
System.exit(1);
}
}
/* if (debug) {
SignatureFileVerifier.setDebug(true);
ManifestEntryVerifier.setDebug(true);
}
*/
verifyJar(jarfile);
} else {
loadKeyStore(keystore, true);
getAliasInfo(alias);
signJar(jarfile, alias);
}
} catch (Exception e) {
System.out.println(rb.getString("jarsigner.error.") + e);
if (debug) {
e.printStackTrace();
}
System.exit(1);
} finally {
// zero-out private key password
if (keypass != null) {
Arrays.fill(keypass, ' ');
keypass = null;
}
// zero-out keystore password
if (storepass != null) {
Arrays.fill(storepass, ' ');
storepass = null;
}
Event.clearReportListener();
}
if (strict) {
int exitCode = 0;
if (disabledAlg != 0 || chainNotValidated || hasExpiredCert
|| hasExpiredTsaCert || notYetValidCert || signerSelfSigned) {
exitCode |= 4;
}
if (badKeyUsage || badExtendedKeyUsage || badNetscapeCertType) {
exitCode |= 8;
}
if (hasUnsignedEntry) {
exitCode |= 16;
}
if (notSignedByAlias || aliasNotInStore) {
exitCode |= 32;
}
if (tsaChainNotValidated) {
exitCode |= 64;
}
if (exitCode != 0) {
System.exit(exitCode);
}
}
}
/*
* Parse command line arguments.
*/
String[] parseArgs(String args[]) throws Exception {
/* parse flags */
int n = 0;
if (args.length == 0) fullusage();
String confFile = null;
String command = "-sign";
for (n=0; n < args.length; n++) {
if (collator.compare(args[n], "-verify") == 0) {
command = "-verify";
} else if (collator.compare(args[n], "-conf") == 0) {
if (n == args.length - 1) {
usageNoArg();
}
confFile = args[++n];
}
}
if (confFile != null) {
args = KeyStoreUtil.expandArgs(
"jarsigner", confFile, command, null, args);
}
debug = Arrays.stream(args).anyMatch(
x -> collator.compare(x, "-debug") == 0);
if (debug) {
// No need to localize debug output
System.out.println("Command line args: " +
Arrays.toString(args));
}
for (n=0; n < args.length; n++) {
String flags = args[n];
String modifier = null;
if (flags.startsWith("-")) {
int pos = flags.indexOf(':');
if (pos > 0) {
modifier = flags.substring(pos+1);
flags = flags.substring(0, pos);
}
}
if (!flags.startsWith("-")) {
if (jarfile == null) {
jarfile = flags;
} else {
alias = flags;
ckaliases.add(alias);
}
} else if (collator.compare(flags, "-conf") == 0) {
if (++n == args.length) usageNoArg();
} else if (collator.compare(flags, "-keystore") == 0) {
if (++n == args.length) usageNoArg();
keystore = args[n];
} else if (collator.compare(flags, "-storepass") ==0) {
if (++n == args.length) usageNoArg();
storepass = getPass(modifier, args[n]);
} else if (collator.compare(flags, "-storetype") ==0) {
if (++n == args.length) usageNoArg();
storetype = args[n];
} else if (collator.compare(flags, "-providerName") ==0) {
if (++n == args.length) usageNoArg();
providerName = args[n];
} else if (collator.compare(flags, "-provider") == 0 ||
collator.compare(flags, "-providerClass") == 0) {
if (++n == args.length) usageNoArg();
if (providerClasses == null) {
providerClasses = new ArrayList<>(3);
}
providerClasses.add(args[n]);
if (args.length > (n+1)) {
flags = args[n+1];
if (collator.compare(flags, "-providerArg") == 0) {
if (args.length == (n+2)) usageNoArg();
providerArgs.put(args[n], args[n+2]);
n += 2;
}
}
} else if (collator.compare(flags, "-addprovider") == 0) {
if (++n == args.length) usageNoArg();
if (providers == null) {
providers = new ArrayList<>(3);
}
providers.add(args[n]);
if (args.length > (n+1)) {
flags = args[n+1];
if (collator.compare(flags, "-providerArg") == 0) {
if (args.length == (n+2)) usageNoArg();
providerArgs.put(args[n], args[n+2]);
n += 2;
}
}
} else if (collator.compare(flags, "-protected") ==0) {
protectedPath = true;
} else if (collator.compare(flags, "-certchain") ==0) {
if (++n == args.length) usageNoArg();
altCertChain = args[n];
} else if (collator.compare(flags, "-tsapolicyid") ==0) {
if (++n == args.length) usageNoArg();
tSAPolicyID = args[n];
} else if (collator.compare(flags, "-tsadigestalg") ==0) {
if (++n == args.length) usageNoArg();
tSADigestAlg = args[n];
} else if (collator.compare(flags, "-debug") ==0) {
// Already processed
} else if (collator.compare(flags, "-keypass") ==0) {
if (++n == args.length) usageNoArg();
keypass = getPass(modifier, args[n]);
} else if (collator.compare(flags, "-sigfile") ==0) {
if (++n == args.length) usageNoArg();
sigfile = args[n];
} else if (collator.compare(flags, "-signedjar") ==0) {
if (++n == args.length) usageNoArg();
signedjar = args[n];
} else if (collator.compare(flags, "-tsa") ==0) {
if (++n == args.length) usageNoArg();
tsaUrl = args[n];
} else if (collator.compare(flags, "-tsacert") ==0) {
if (++n == args.length) usageNoArg();
tsaAlias = args[n];
} else if (collator.compare(flags, "-altsigner") ==0) {
if (++n == args.length) usageNoArg();
altSignerClass = args[n];
System.err.println(
rb.getString("This.option.is.forremoval") +
"-altsigner");
} else if (collator.compare(flags, "-altsignerpath") ==0) {
if (++n == args.length) usageNoArg();
altSignerClasspath = args[n];
System.err.println(
rb.getString("This.option.is.forremoval") +
"-altsignerpath");
} else if (collator.compare(flags, "-sectionsonly") ==0) {
signManifest = false;
} else if (collator.compare(flags, "-internalsf") ==0) {
externalSF = false;
} else if (collator.compare(flags, "-verify") ==0) {
verify = true;
} else if (collator.compare(flags, "-verbose") ==0) {
verbose = (modifier != null) ? modifier : "all";
} else if (collator.compare(flags, "-sigalg") ==0) {
if (++n == args.length) usageNoArg();
sigalg = args[n];
} else if (collator.compare(flags, "-digestalg") ==0) {
if (++n == args.length) usageNoArg();
digestalg = args[n];
} else if (collator.compare(flags, "-certs") ==0) {
showcerts = true;
} else if (collator.compare(flags, "-strict") ==0) {
strict = true;
} else if (collator.compare(flags, "-?") == 0 ||
collator.compare(flags, "-h") == 0 ||
collator.compare(flags, "--help") == 0 ||
// -help: legacy.
collator.compare(flags, "-help") == 0) {
fullusage();
} else if (collator.compare(flags, "-revCheck") == 0) {
revocationCheck = true;
} else {
System.err.println(
rb.getString("Illegal.option.") + flags);
usage();
}
}
// -certs must always be specified with -verbose
if (verbose == null) showcerts = false;
if (jarfile == null) {
System.err.println(rb.getString("Please.specify.jarfile.name"));
usage();
}
if (!verify && alias == null) {
System.err.println(rb.getString("Please.specify.alias.name"));
usage();
}
if (!verify && ckaliases.size() > 1) {
System.err.println(rb.getString("Only.one.alias.can.be.specified"));
usage();
}
if (storetype == null) {
storetype = KeyStore.getDefaultType();
}
storetype = KeyStoreUtil.niceStoreTypeName(storetype);
try {
if (signedjar != null && new File(signedjar).getCanonicalPath().equals(
new File(jarfile).getCanonicalPath())) {
signedjar = null;
}
} catch (IOException ioe) {
// File system error?
// Just ignore it.
}
if (P11KEYSTORE.equalsIgnoreCase(storetype) ||
KeyStoreUtil.isWindowsKeyStore(storetype)) {
token = true;
if (keystore == null) {
keystore = NONE;
}
}
if (NONE.equals(keystore)) {
nullStream = true;
}
if (token && !nullStream) {
System.err.println(MessageFormat.format(rb.getString
(".keystore.must.be.NONE.if.storetype.is.{0}"), storetype));
usage();
}
if (token && keypass != null) {
System.err.println(MessageFormat.format(rb.getString
(".keypass.can.not.be.specified.if.storetype.is.{0}"), storetype));
usage();
}
if (protectedPath) {
if (storepass != null || keypass != null) {
System.err.println(rb.getString
("If.protected.is.specified.then.storepass.and.keypass.must.not.be.specified"));
usage();
}
}
if (KeyStoreUtil.isWindowsKeyStore(storetype)) {
if (storepass != null || keypass != null) {
System.err.println(rb.getString
("If.keystore.is.not.password.protected.then.storepass.and.keypass.must.not.be.specified"));
usage();
}
}
return args;
}
static char[] getPass(String modifier, String arg) {
char[] output =
KeyStoreUtil.getPassWithModifier(modifier, arg, rb, collator);
if (output != null) return output;
usage();
return null; // Useless, usage() already exit
}
static void usageNoArg() {
System.out.println(rb.getString("Option.lacks.argument"));
usage();
}
static void usage() {
System.out.println();
System.out.println(rb.getString("Please.type.jarsigner.help.for.usage"));
System.exit(1);
}
static void fullusage() {
System.out.println(rb.getString
("Usage.jarsigner.options.jar.file.alias"));
System.out.println(rb.getString
(".jarsigner.verify.options.jar.file.alias."));
System.out.println();
System.out.println(rb.getString
(".keystore.url.keystore.location"));
System.out.println();
System.out.println(rb.getString
(".storepass.password.password.for.keystore.integrity"));
System.out.println();
System.out.println(rb.getString
(".storetype.type.keystore.type"));
System.out.println();
System.out.println(rb.getString
(".keypass.password.password.for.private.key.if.different."));
System.out.println();
System.out.println(rb.getString
(".certchain.file.name.of.alternative.certchain.file"));
System.out.println();
System.out.println(rb.getString
(".sigfile.file.name.of.SF.DSA.file"));
System.out.println();
System.out.println(rb.getString
(".signedjar.file.name.of.signed.JAR.file"));
System.out.println();
System.out.println(rb.getString
(".digestalg.algorithm.name.of.digest.algorithm"));
System.out.println();
System.out.println(rb.getString
(".sigalg.algorithm.name.of.signature.algorithm"));
System.out.println();
System.out.println(rb.getString
(".verify.verify.a.signed.JAR.file"));
System.out.println();
System.out.println(rb.getString
(".verbose.suboptions.verbose.output.when.signing.verifying."));
System.out.println(rb.getString
(".suboptions.can.be.all.grouped.or.summary"));
System.out.println();
System.out.println(rb.getString
(".certs.display.certificates.when.verbose.and.verifying"));
System.out.println();
System.out.println(rb.getString
(".certs.revocation.check"));
System.out.println();
System.out.println(rb.getString
(".tsa.url.location.of.the.Timestamping.Authority"));
System.out.println();
System.out.println(rb.getString
(".tsacert.alias.public.key.certificate.for.Timestamping.Authority"));
System.out.println();
System.out.println(rb.getString
(".tsapolicyid.tsapolicyid.for.Timestamping.Authority"));
System.out.println();
System.out.println(rb.getString
(".tsadigestalg.algorithm.of.digest.data.in.timestamping.request"));
System.out.println();
System.out.println(rb.getString
(".altsigner.class.class.name.of.an.alternative.signing.mechanism"));
System.out.println();
System.out.println(rb.getString
(".altsignerpath.pathlist.location.of.an.alternative.signing.mechanism"));
System.out.println();
System.out.println(rb.getString
(".internalsf.include.the.SF.file.inside.the.signature.block"));
System.out.println();
System.out.println(rb.getString
(".sectionsonly.don.t.compute.hash.of.entire.manifest"));
System.out.println();
System.out.println(rb.getString
(".protected.keystore.has.protected.authentication.path"));
System.out.println();
System.out.println(rb.getString
(".providerName.name.provider.name"));
System.out.println();
System.out.println(rb.getString
(".add.provider.option"));
System.out.println(rb.getString
(".providerArg.option.1"));
System.out.println();
System.out.println(rb.getString
(".providerClass.option"));
System.out.println(rb.getString
(".providerArg.option.2"));
System.out.println();
System.out.println(rb.getString
(".strict.treat.warnings.as.errors"));
System.out.println();
System.out.println(rb.getString
(".conf.url.specify.a.pre.configured.options.file"));
System.out.println();
System.out.println(rb.getString
(".print.this.help.message"));
System.out.println();
System.exit(0);
}
void verifyJar(String jarName)
throws Exception
{
boolean anySigned = false; // if there exists entry inside jar signed
JarFile jf = null;
Map<String,String> digestMap = new HashMap<>();
Map<String,PKCS7> sigMap = new HashMap<>();
Map<String,String> sigNameMap = new HashMap<>();
Map<String,String> unparsableSignatures = new HashMap<>();
try {
jf = new JarFile(jarName, true);
Vector<JarEntry> entriesVec = new Vector<>();
byte[] buffer = new byte[8192];
String suffix1 = "-Digest-Manifest";
String suffix2 = "-Digest-" + ManifestDigester.MF_MAIN_ATTRS;
int suffixLength1 = suffix1.length();
int suffixLength2 = suffix2.length();
Enumeration<JarEntry> entries = jf.entries();
while (entries.hasMoreElements()) {
JarEntry je = entries.nextElement();
entriesVec.addElement(je);
try (InputStream is = jf.getInputStream(je)) {
String name = je.getName();
if (signatureRelated(name)
&& SignatureFileVerifier.isBlockOrSF(name)) {
String alias = name.substring(name.lastIndexOf('/') + 1,
name.lastIndexOf('.'));
try {
if (name.endsWith(".SF")) {
Manifest sf = new Manifest(is);
boolean found = false;
for (Object obj : sf.getMainAttributes().keySet()) {
String key = obj.toString();
if (key.endsWith(suffix1)) {
digestMap.put(alias, key.substring(
0, key.length() - suffixLength1));
found = true;
break;
} else if (key.endsWith(suffix2)) {
digestMap.put(alias, key.substring(
0, key.length() - suffixLength2));
found = true;
break;
}
}
if (!found) {
unparsableSignatures.putIfAbsent(alias,
String.format(
rb.getString("history.unparsable"),
name));
}
} else {
sigNameMap.put(alias, name);
sigMap.put(alias, new PKCS7(is));
}
} catch (IOException ioe) {
unparsableSignatures.putIfAbsent(alias, String.format(
rb.getString("history.unparsable"), name));
}
} else {
while (is.read(buffer, 0, buffer.length) != -1) {
// we just read. this will throw a SecurityException
// if a signature/digest check fails.
}
}
}
}
Manifest man = jf.getManifest();
boolean hasSignature = false;
// The map to record display info, only used when -verbose provided
// key: signer info string
// value: the list of files with common key
Map<String,List<String>> output = new LinkedHashMap<>();
if (man != null) {
if (verbose != null) System.out.println();
Enumeration<JarEntry> e = entriesVec.elements();
String tab = rb.getString("6SPACE");
while (e.hasMoreElements()) {
JarEntry je = e.nextElement();
String name = je.getName();
hasSignature = hasSignature
|| SignatureFileVerifier.isBlockOrSF(name);
CodeSigner[] signers = je.getCodeSigners();
boolean isSigned = (signers != null);
anySigned |= isSigned;
hasUnsignedEntry |= !je.isDirectory() && !isSigned
&& !signatureRelated(name);
int inStoreWithAlias = inKeyStore(signers);
boolean inStore = (inStoreWithAlias & IN_KEYSTORE) != 0;
notSignedByAlias |= (inStoreWithAlias & NOT_ALIAS) != 0;
if (keystore != null) {
aliasNotInStore |= isSigned && !inStore;
}
// Only used when -verbose provided
StringBuffer sb = null;
if (verbose != null) {
sb = new StringBuffer();
boolean inManifest =
((man.getAttributes(name) != null) ||
(man.getAttributes("./"+name) != null) ||
(man.getAttributes("/"+name) != null));
sb.append(isSigned ? rb.getString("s") : rb.getString("SPACE"))
.append(inManifest ? rb.getString("m") : rb.getString("SPACE"))
.append(inStore ? rb.getString("k") : rb.getString("SPACE"))
.append((inStoreWithAlias & NOT_ALIAS) != 0 ? 'X' : ' ')
.append(rb.getString("SPACE"));
sb.append('|');
}
// When -certs provided, display info has extra empty
// lines at the beginning and end.
if (isSigned) {
if (showcerts) sb.append('\n');
for (CodeSigner signer: signers) {
// signerInfo() must be called even if -verbose
// not provided. The method updates various
// warning flags.
String si = signerInfo(signer, tab);
if (showcerts) {
sb.append(si);
sb.append('\n');
}
}
} else if (showcerts && !verbose.equals("all")) {
// Print no info for unsigned entries when -verbose:all,
// to be consistent with old behavior.
if (signatureRelated(name)) {
sb.append('\n')
.append(tab)
.append(rb
.getString(".Signature.related.entries."))
.append("\n\n");
} else {
sb.append('\n').append(tab)
.append(rb.getString(".Unsigned.entries."))
.append("\n\n");
}
}
if (verbose != null) {
String label = sb.toString();
if (signatureRelated(name)) {
// Entries inside META-INF and other unsigned
// entries are grouped separately.
label = "-" + label;
}
// The label finally contains 2 parts separated by '|':
// The legend displayed before the entry names, and
// the cert info (if -certs specified).
if (!output.containsKey(label)) {
output.put(label, new ArrayList<String>());
}
StringBuilder fb = new StringBuilder();
String s = Long.toString(je.getSize());
for (int i = 6 - s.length(); i > 0; --i) {
fb.append(' ');
}
fb.append(s).append(' ').
append(new Date(je.getTime()).toString());
fb.append(' ').append(name);
output.get(label).add(fb.toString());
}
}
}
if (verbose != null) {
for (Entry<String,List<String>> s: output.entrySet()) {
List<String> files = s.getValue();
String key = s.getKey();
if (key.charAt(0) == '-') { // the signature-related group
key = key.substring(1);
}
int pipe = key.indexOf('|');
if (verbose.equals("all")) {
for (String f: files) {
System.out.println(key.substring(0, pipe) + f);
System.out.printf(key.substring(pipe+1));
}
} else {
if (verbose.equals("grouped")) {
for (String f: files) {
System.out.println(key.substring(0, pipe) + f);
}
} else if (verbose.equals("summary")) {
System.out.print(key.substring(0, pipe));
if (files.size() > 1) {
System.out.println(files.get(0) + " " +
String.format(rb.getString(
".and.d.more."), files.size()-1));
} else {
System.out.println(files.get(0));
}
}
System.out.printf(key.substring(pipe+1));
}
}
System.out.println();
System.out.println(rb.getString(
".s.signature.was.verified."));
System.out.println(rb.getString(
".m.entry.is.listed.in.manifest"));
System.out.println(rb.getString(
".k.at.least.one.certificate.was.found.in.keystore"));
if (ckaliases.size() > 0) {
System.out.println(rb.getString(
".X.not.signed.by.specified.alias.es."));
}
}
if (man == null) {
System.out.println();
System.out.println(rb.getString("no.manifest."));
}
// If signer is a trusted cert or private entry in user's own
// keystore, it can be self-signed. Please note aliasNotInStore
// is always false when ~/.keystore is used.
if (!aliasNotInStore && keystore != null) {
signerSelfSigned = false;
}
// Even if the verbose option is not specified, all out strings
// must be generated so disabledAlgFound can be updated.
if (!digestMap.isEmpty()
|| !sigMap.isEmpty()
|| !unparsableSignatures.isEmpty()) {
if (verbose != null) {
System.out.println();
}
for (String s : sigMap.keySet()) {
if (!digestMap.containsKey(s)) {
unparsableSignatures.putIfAbsent(s, String.format(
rb.getString("history.nosf"), s));
}
}
for (String s : digestMap.keySet()) {
PKCS7 p7 = sigMap.get(s);
if (p7 != null) {
String history;
try {
SignerInfo si = p7.getSignerInfos()[0];
X509Certificate signer = si.getCertificate(p7);
String digestAlg = digestMap.get(s);
String sigAlg = AlgorithmId.makeSigAlg(
si.getDigestAlgorithmId().getName(),
si.getDigestEncryptionAlgorithmId().getName());
PublicKey key = signer.getPublicKey();
PKCS7 tsToken = si.getTsToken();
if (tsToken != null) {
hasTimestampBlock = true;
SignerInfo tsSi = tsToken.getSignerInfos()[0];
X509Certificate tsSigner = tsSi.getCertificate(tsToken);
byte[] encTsTokenInfo = tsToken.getContentInfo().getData();
TimestampToken tsTokenInfo = new TimestampToken(encTsTokenInfo);
PublicKey tsKey = tsSigner.getPublicKey();
String tsDigestAlg = tsTokenInfo.getHashAlgorithm().getName();
String tsSigAlg = AlgorithmId.makeSigAlg(
tsSi.getDigestAlgorithmId().getName(),
tsSi.getDigestEncryptionAlgorithmId().getName());
Calendar c = Calendar.getInstance(
TimeZone.getTimeZone("UTC"),
Locale.getDefault(Locale.Category.FORMAT));
c.setTime(tsTokenInfo.getDate());
history = String.format(
rb.getString("history.with.ts"),
signer.getSubjectX500Principal(),
verifyWithWeak(digestAlg, DIGEST_PRIMITIVE_SET, false),
verifyWithWeak(sigAlg, SIG_PRIMITIVE_SET, false),
verifyWithWeak(key),
c,
tsSigner.getSubjectX500Principal(),
verifyWithWeak(tsDigestAlg, DIGEST_PRIMITIVE_SET, true),
verifyWithWeak(tsSigAlg, SIG_PRIMITIVE_SET, true),
verifyWithWeak(tsKey));
} else {
history = String.format(
rb.getString("history.without.ts"),
signer.getSubjectX500Principal(),
verifyWithWeak(digestAlg, DIGEST_PRIMITIVE_SET, false),
verifyWithWeak(sigAlg, SIG_PRIMITIVE_SET, false),
verifyWithWeak(key));
}
} catch (Exception e) {
// The only usage of sigNameMap, remember the name
// of the block file if it's invalid.
history = String.format(
rb.getString("history.unparsable"),
sigNameMap.get(s));
}
if (verbose != null) {
System.out.println(history);
}
} else {
unparsableSignatures.putIfAbsent(s, String.format(
rb.getString("history.nobk"), s));