Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/sun/security/x509/NameConstraintsExtension.java
41159 views
1
/*
2
* Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package sun.security.x509;
27
28
import java.io.IOException;
29
import java.io.OutputStream;
30
import java.security.cert.CertificateException;
31
import java.security.cert.X509Certificate;
32
import java.util.*;
33
34
import javax.security.auth.x500.X500Principal;
35
36
import sun.net.util.IPAddressUtil;
37
import sun.security.util.*;
38
import sun.security.pkcs.PKCS9Attribute;
39
40
/**
41
* This class defines the Name Constraints Extension.
42
* <p>
43
* The name constraints extension provides permitted and excluded
44
* subtrees that place restrictions on names that may be included within
45
* a certificate issued by a given CA. Restrictions may apply to the
46
* subject distinguished name or subject alternative names. Any name
47
* matching a restriction in the excluded subtrees field is invalid
48
* regardless of information appearing in the permitted subtrees.
49
* <p>
50
* The ASN.1 syntax for this is:
51
* <pre>
52
* NameConstraints ::= SEQUENCE {
53
* permittedSubtrees [0] GeneralSubtrees OPTIONAL,
54
* excludedSubtrees [1] GeneralSubtrees OPTIONAL
55
* }
56
* GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
57
* </pre>
58
*
59
* @author Amit Kapoor
60
* @author Hemma Prafullchandra
61
* @see Extension
62
* @see CertAttrSet
63
*/
64
public class NameConstraintsExtension extends Extension
65
implements CertAttrSet<String>, Cloneable {
66
/**
67
* Identifier for this attribute, to be used with the
68
* get, set, delete methods of Certificate, x509 type.
69
*/
70
public static final String IDENT = "x509.info.extensions.NameConstraints";
71
/**
72
* Attribute names.
73
*/
74
public static final String NAME = "NameConstraints";
75
public static final String PERMITTED_SUBTREES = "permitted_subtrees";
76
public static final String EXCLUDED_SUBTREES = "excluded_subtrees";
77
78
// Private data members
79
private static final byte TAG_PERMITTED = 0;
80
private static final byte TAG_EXCLUDED = 1;
81
82
private GeneralSubtrees permitted = null;
83
private GeneralSubtrees excluded = null;
84
85
private boolean hasMin;
86
private boolean hasMax;
87
private boolean minMaxValid = false;
88
89
// Recalculate hasMin and hasMax flags.
90
private void calcMinMax() throws IOException {
91
hasMin = false;
92
hasMax = false;
93
if (excluded != null) {
94
for (int i = 0; i < excluded.size(); i++) {
95
GeneralSubtree subtree = excluded.get(i);
96
if (subtree.getMinimum() != 0)
97
hasMin = true;
98
if (subtree.getMaximum() != -1)
99
hasMax = true;
100
}
101
}
102
103
if (permitted != null) {
104
for (int i = 0; i < permitted.size(); i++) {
105
GeneralSubtree subtree = permitted.get(i);
106
if (subtree.getMinimum() != 0)
107
hasMin = true;
108
if (subtree.getMaximum() != -1)
109
hasMax = true;
110
}
111
}
112
minMaxValid = true;
113
}
114
115
// Encode this extension value.
116
private void encodeThis() throws IOException {
117
minMaxValid = false;
118
if (permitted == null && excluded == null) {
119
this.extensionValue = null;
120
return;
121
}
122
DerOutputStream seq = new DerOutputStream();
123
124
DerOutputStream tagged = new DerOutputStream();
125
if (permitted != null) {
126
DerOutputStream tmp = new DerOutputStream();
127
permitted.encode(tmp);
128
tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
129
true, TAG_PERMITTED), tmp);
130
}
131
if (excluded != null) {
132
DerOutputStream tmp = new DerOutputStream();
133
excluded.encode(tmp);
134
tagged.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
135
true, TAG_EXCLUDED), tmp);
136
}
137
seq.write(DerValue.tag_Sequence, tagged);
138
this.extensionValue = seq.toByteArray();
139
}
140
141
/**
142
* The default constructor for this class. Both parameters
143
* are optional and can be set to null. The extension criticality
144
* is set to true.
145
*
146
* @param permitted the permitted GeneralSubtrees (null for optional).
147
* @param excluded the excluded GeneralSubtrees (null for optional).
148
*/
149
public NameConstraintsExtension(GeneralSubtrees permitted,
150
GeneralSubtrees excluded)
151
throws IOException {
152
this.permitted = permitted;
153
this.excluded = excluded;
154
155
this.extensionId = PKIXExtensions.NameConstraints_Id;
156
this.critical = true;
157
encodeThis();
158
}
159
160
/**
161
* Create the extension from the passed DER encoded value.
162
*
163
* @param critical true if the extension is to be treated as critical.
164
* @param value an array of DER encoded bytes of the actual value.
165
* @exception ClassCastException if value is not an array of bytes
166
* @exception IOException on error.
167
*/
168
public NameConstraintsExtension(Boolean critical, Object value)
169
throws IOException {
170
this.extensionId = PKIXExtensions.NameConstraints_Id;
171
this.critical = critical.booleanValue();
172
173
this.extensionValue = (byte[]) value;
174
DerValue val = new DerValue(this.extensionValue);
175
if (val.tag != DerValue.tag_Sequence) {
176
throw new IOException("Invalid encoding for" +
177
" NameConstraintsExtension.");
178
}
179
180
// NB. this is always encoded with the IMPLICIT tag
181
// The checks only make sense if we assume implicit tagging,
182
// with explicit tagging the form is always constructed.
183
// Note that all the fields in NameConstraints are defined as
184
// being OPTIONAL, i.e., there could be an empty SEQUENCE, resulting
185
// in val.data being null.
186
if (val.data == null)
187
return;
188
while (val.data.available() != 0) {
189
DerValue opt = val.data.getDerValue();
190
191
if (opt.isContextSpecific(TAG_PERMITTED) && opt.isConstructed()) {
192
if (permitted != null) {
193
throw new IOException("Duplicate permitted " +
194
"GeneralSubtrees in NameConstraintsExtension.");
195
}
196
opt.resetTag(DerValue.tag_Sequence);
197
permitted = new GeneralSubtrees(opt);
198
199
} else if (opt.isContextSpecific(TAG_EXCLUDED) &&
200
opt.isConstructed()) {
201
if (excluded != null) {
202
throw new IOException("Duplicate excluded " +
203
"GeneralSubtrees in NameConstraintsExtension.");
204
}
205
opt.resetTag(DerValue.tag_Sequence);
206
excluded = new GeneralSubtrees(opt);
207
} else
208
throw new IOException("Invalid encoding of " +
209
"NameConstraintsExtension.");
210
}
211
minMaxValid = false;
212
}
213
214
/**
215
* Return the printable string.
216
*/
217
public String toString() {
218
StringBuilder sb = new StringBuilder();
219
sb.append(super.toString())
220
.append("NameConstraints: [");
221
if (permitted != null) {
222
sb.append("\n Permitted:")
223
.append(permitted);
224
}
225
if (excluded != null) {
226
sb.append("\n Excluded:")
227
.append(excluded);
228
}
229
sb.append(" ]\n");
230
return sb.toString();
231
}
232
233
/**
234
* Write the extension to the OutputStream.
235
*
236
* @param out the OutputStream to write the extension to.
237
* @exception IOException on encoding errors.
238
*/
239
public void encode(OutputStream out) throws IOException {
240
DerOutputStream tmp = new DerOutputStream();
241
if (this.extensionValue == null) {
242
this.extensionId = PKIXExtensions.NameConstraints_Id;
243
this.critical = true;
244
encodeThis();
245
}
246
super.encode(tmp);
247
out.write(tmp.toByteArray());
248
}
249
250
/**
251
* Set the attribute value.
252
*/
253
public void set(String name, Object obj) throws IOException {
254
if (name.equalsIgnoreCase(PERMITTED_SUBTREES)) {
255
if (!(obj instanceof GeneralSubtrees)) {
256
throw new IOException("Attribute value should be"
257
+ " of type GeneralSubtrees.");
258
}
259
permitted = (GeneralSubtrees)obj;
260
} else if (name.equalsIgnoreCase(EXCLUDED_SUBTREES)) {
261
if (!(obj instanceof GeneralSubtrees)) {
262
throw new IOException("Attribute value should be "
263
+ "of type GeneralSubtrees.");
264
}
265
excluded = (GeneralSubtrees)obj;
266
} else {
267
throw new IOException("Attribute name not recognized by " +
268
"CertAttrSet:NameConstraintsExtension.");
269
}
270
encodeThis();
271
}
272
273
/**
274
* Get the attribute value.
275
*/
276
public GeneralSubtrees get(String name) throws IOException {
277
if (name.equalsIgnoreCase(PERMITTED_SUBTREES)) {
278
return (permitted);
279
} else if (name.equalsIgnoreCase(EXCLUDED_SUBTREES)) {
280
return (excluded);
281
} else {
282
throw new IOException("Attribute name not recognized by " +
283
"CertAttrSet:NameConstraintsExtension.");
284
}
285
}
286
287
/**
288
* Delete the attribute value.
289
*/
290
public void delete(String name) throws IOException {
291
if (name.equalsIgnoreCase(PERMITTED_SUBTREES)) {
292
permitted = null;
293
} else if (name.equalsIgnoreCase(EXCLUDED_SUBTREES)) {
294
excluded = null;
295
} else {
296
throw new IOException("Attribute name not recognized by " +
297
"CertAttrSet:NameConstraintsExtension.");
298
}
299
encodeThis();
300
}
301
302
/**
303
* Return an enumeration of names of attributes existing within this
304
* attribute.
305
*/
306
public Enumeration<String> getElements() {
307
AttributeNameEnumeration elements = new AttributeNameEnumeration();
308
elements.addElement(PERMITTED_SUBTREES);
309
elements.addElement(EXCLUDED_SUBTREES);
310
311
return (elements.elements());
312
}
313
314
/**
315
* Return the name of this attribute.
316
*/
317
public String getName() {
318
return (NAME);
319
}
320
321
/**
322
* Merge additional name constraints with existing ones.
323
* This function is used in certification path processing
324
* to accumulate name constraints from successive certificates
325
* in the path. Note that NameConstraints can never be
326
* expanded by a merge, just remain constant or become more
327
* limiting.
328
* <p>
329
* IETF RFC 5280 specifies the processing of Name Constraints as
330
* follows:
331
* <p>
332
* (j) If permittedSubtrees is present in the certificate, set the
333
* constrained subtrees state variable to the intersection of its
334
* previous value and the value indicated in the extension field.
335
* <p>
336
* (k) If excludedSubtrees is present in the certificate, set the
337
* excluded subtrees state variable to the union of its previous
338
* value and the value indicated in the extension field.
339
*
340
* @param newConstraints additional NameConstraints to be applied
341
* @throws IOException on error
342
*/
343
public void merge(NameConstraintsExtension newConstraints)
344
throws IOException {
345
346
if (newConstraints == null) {
347
// absence of any explicit constraints implies unconstrained
348
return;
349
}
350
351
/*
352
* If excludedSubtrees is present in the certificate, set the
353
* excluded subtrees state variable to the union of its previous
354
* value and the value indicated in the extension field.
355
*/
356
357
GeneralSubtrees newExcluded = newConstraints.get(EXCLUDED_SUBTREES);
358
if (excluded == null) {
359
excluded = (newExcluded != null) ?
360
(GeneralSubtrees)newExcluded.clone() : null;
361
} else {
362
if (newExcluded != null) {
363
// Merge new excluded with current excluded (union)
364
excluded.union(newExcluded);
365
}
366
}
367
368
/*
369
* If permittedSubtrees is present in the certificate, set the
370
* constrained subtrees state variable to the intersection of its
371
* previous value and the value indicated in the extension field.
372
*/
373
374
GeneralSubtrees newPermitted = newConstraints.get(PERMITTED_SUBTREES);
375
if (permitted == null) {
376
permitted = (newPermitted != null) ?
377
(GeneralSubtrees)newPermitted.clone() : null;
378
} else {
379
if (newPermitted != null) {
380
// Merge new permitted with current permitted (intersection)
381
newExcluded = permitted.intersect(newPermitted);
382
383
// Merge new excluded subtrees to current excluded (union)
384
if (newExcluded != null) {
385
if (excluded != null) {
386
excluded.union(newExcluded);
387
} else {
388
excluded = (GeneralSubtrees)newExcluded.clone();
389
}
390
}
391
}
392
}
393
394
// Optional optimization: remove permitted subtrees that are excluded.
395
// This is not necessary for algorithm correctness, but it makes
396
// subsequent operations on the NameConstraints faster and require
397
// less space.
398
if (permitted != null) {
399
permitted.reduce(excluded);
400
}
401
402
// The NameConstraints have been changed, so re-encode them. Methods in
403
// this class assume that the encodings have already been done.
404
encodeThis();
405
406
}
407
408
/**
409
* check whether a certificate conforms to these NameConstraints.
410
* This involves verifying that the subject name and subjectAltName
411
* extension (critical or noncritical) is consistent with the permitted
412
* subtrees state variables. Also verify that the subject name and
413
* subjectAltName extension (critical or noncritical) is consistent with
414
* the excluded subtrees state variables.
415
*
416
* @param cert X509Certificate to be verified
417
* @return true if certificate verifies successfully
418
* @throws IOException on error
419
*/
420
public boolean verify(X509Certificate cert) throws IOException {
421
422
if (cert == null) {
423
throw new IOException("Certificate is null");
424
}
425
426
// Calculate hasMin and hasMax booleans (if necessary)
427
if (!minMaxValid) {
428
calcMinMax();
429
}
430
431
if (hasMin) {
432
throw new IOException("Non-zero minimum BaseDistance in"
433
+ " name constraints not supported");
434
}
435
436
if (hasMax) {
437
throw new IOException("Maximum BaseDistance in"
438
+ " name constraints not supported");
439
}
440
441
X500Principal subjectPrincipal = cert.getSubjectX500Principal();
442
X500Name subject = X500Name.asX500Name(subjectPrincipal);
443
444
// Check subject as an X500Name
445
if (subject.isEmpty() == false) {
446
if (verify(subject) == false) {
447
return false;
448
}
449
}
450
451
GeneralNames altNames = null;
452
// extract altNames
453
try {
454
// extract extensions, if any, from certInfo
455
// following returns null if certificate contains no extensions
456
X509CertImpl certImpl = X509CertImpl.toImpl(cert);
457
SubjectAlternativeNameExtension altNameExt =
458
certImpl.getSubjectAlternativeNameExtension();
459
if (altNameExt != null) {
460
// extract altNames from extension; this call does not
461
// return an IOException on null altnames
462
altNames = altNameExt.get(
463
SubjectAlternativeNameExtension.SUBJECT_NAME);
464
}
465
} catch (CertificateException ce) {
466
throw new IOException("Unable to extract extensions from " +
467
"certificate: " + ce.getMessage());
468
}
469
470
if (altNames == null) {
471
altNames = new GeneralNames();
472
473
// RFC 5280 4.2.1.10:
474
// When constraints are imposed on the rfc822Name name form,
475
// but the certificate does not include a subject alternative name,
476
// the rfc822Name constraint MUST be applied to the attribute of
477
// type emailAddress in the subject distinguished name.
478
for (AVA ava : subject.allAvas()) {
479
ObjectIdentifier attrOID = ava.getObjectIdentifier();
480
if (attrOID.equals(PKCS9Attribute.EMAIL_ADDRESS_OID)) {
481
String attrValue = ava.getValueString();
482
if (attrValue != null) {
483
try {
484
altNames.add(new GeneralName(
485
new RFC822Name(attrValue)));
486
} catch (IOException ioe) {
487
continue;
488
}
489
}
490
}
491
}
492
}
493
494
// If there is no IPAddressName or DNSName in subjectAlternativeNames,
495
// see if the last CN inside subjectName can be used instead.
496
DerValue derValue = subject.findMostSpecificAttribute
497
(X500Name.commonName_oid);
498
String cn = derValue == null ? null : derValue.getAsString();
499
500
if (cn != null) {
501
try {
502
if (IPAddressUtil.isIPv4LiteralAddress(cn) ||
503
IPAddressUtil.isIPv6LiteralAddress(cn)) {
504
if (!hasNameType(altNames, GeneralNameInterface.NAME_IP)) {
505
altNames.add(new GeneralName(new IPAddressName(cn)));
506
}
507
} else {
508
if (!hasNameType(altNames, GeneralNameInterface.NAME_DNS)) {
509
altNames.add(new GeneralName(new DNSName(cn)));
510
}
511
}
512
} catch (IOException ioe) {
513
// OK, cn is neither IP nor DNS
514
}
515
}
516
517
// verify each subjectAltName
518
for (int i = 0; i < altNames.size(); i++) {
519
GeneralNameInterface altGNI = altNames.get(i).getName();
520
if (!verify(altGNI)) {
521
return false;
522
}
523
}
524
525
// All tests passed.
526
return true;
527
}
528
529
private static boolean hasNameType(GeneralNames names, int type) {
530
for (GeneralName name : names.names()) {
531
if (name.getType() == type) {
532
return true;
533
}
534
}
535
return false;
536
}
537
538
/**
539
* check whether a name conforms to these NameConstraints.
540
* This involves verifying that the name is consistent with the
541
* permitted and excluded subtrees variables.
542
*
543
* @param name GeneralNameInterface name to be verified
544
* @return true if certificate verifies successfully
545
* @throws IOException on error
546
*/
547
public boolean verify(GeneralNameInterface name) throws IOException {
548
if (name == null) {
549
throw new IOException("name is null");
550
}
551
552
// Verify that the name is consistent with the excluded subtrees
553
if (excluded != null && excluded.size() > 0) {
554
555
for (int i = 0; i < excluded.size(); i++) {
556
GeneralSubtree gs = excluded.get(i);
557
if (gs == null)
558
continue;
559
GeneralName gn = gs.getName();
560
if (gn == null)
561
continue;
562
GeneralNameInterface exName = gn.getName();
563
if (exName == null)
564
continue;
565
566
// if name matches or narrows any excluded subtree,
567
// return false
568
switch (exName.constrains(name)) {
569
case GeneralNameInterface.NAME_DIFF_TYPE:
570
case GeneralNameInterface.NAME_WIDENS: // name widens excluded
571
case GeneralNameInterface.NAME_SAME_TYPE:
572
break;
573
case GeneralNameInterface.NAME_MATCH:
574
case GeneralNameInterface.NAME_NARROWS: // subject name excluded
575
return false;
576
}
577
}
578
}
579
580
// Verify that the name is consistent with the permitted subtrees
581
if (permitted != null && permitted.size() > 0) {
582
583
boolean sameType = false;
584
585
for (int i = 0; i < permitted.size(); i++) {
586
GeneralSubtree gs = permitted.get(i);
587
if (gs == null)
588
continue;
589
GeneralName gn = gs.getName();
590
if (gn == null)
591
continue;
592
GeneralNameInterface perName = gn.getName();
593
if (perName == null)
594
continue;
595
596
// if Name matches any type in permitted,
597
// and Name does not match or narrow some permitted subtree,
598
// return false
599
switch (perName.constrains(name)) {
600
case GeneralNameInterface.NAME_DIFF_TYPE:
601
continue; // continue checking other permitted names
602
case GeneralNameInterface.NAME_WIDENS: // name widens permitted
603
case GeneralNameInterface.NAME_SAME_TYPE:
604
sameType = true;
605
continue; // continue to look for a match or narrow
606
case GeneralNameInterface.NAME_MATCH:
607
case GeneralNameInterface.NAME_NARROWS:
608
// name narrows permitted
609
return true; // name is definitely OK, so break out of loop
610
}
611
}
612
if (sameType) {
613
return false;
614
}
615
}
616
return true;
617
}
618
619
/**
620
* Clone all objects that may be modified during certificate validation.
621
*/
622
public Object clone() {
623
try {
624
NameConstraintsExtension newNCE =
625
(NameConstraintsExtension) super.clone();
626
627
if (permitted != null) {
628
newNCE.permitted = (GeneralSubtrees) permitted.clone();
629
}
630
if (excluded != null) {
631
newNCE.excluded = (GeneralSubtrees) excluded.clone();
632
}
633
return newNCE;
634
} catch (CloneNotSupportedException cnsee) {
635
throw new RuntimeException("CloneNotSupportedException while " +
636
"cloning NameConstraintsException. This should never happen.");
637
}
638
}
639
}
640
641