forked from apache/santuario-xml-security-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathManifest.java
More file actions
581 lines (511 loc) · 21.2 KB
/
Manifest.java
File metadata and controls
581 lines (511 loc) · 21.2 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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.xml.security.signature;
import java.io.IOException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.xml.security.c14n.CanonicalizationException;
import org.apache.xml.security.c14n.InvalidCanonicalizerException;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.parser.XMLParserException;
import org.apache.xml.security.transforms.Transforms;
import org.apache.xml.security.utils.Constants;
import org.apache.xml.security.utils.I18n;
import org.apache.xml.security.utils.SignatureElementProxy;
import org.apache.xml.security.utils.XMLUtils;
import org.apache.xml.security.utils.resolver.ResourceResolverSpi;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Handles <code><ds:Manifest></code> elements.
* <p> This element holds the <code>Reference</code> elements</p>
*/
public class Manifest extends SignatureElementProxy {
/**
* The default maximum number of references per Manifest, if secure validation is enabled.
*/
public static final int MAXIMUM_REFERENCE_COUNT = 30;
private static final Logger LOG = System.getLogger(Manifest.class.getName());
private static Integer referenceCount =
AccessController.doPrivileged(
(PrivilegedAction<Integer>) () -> Integer.parseInt(System.getProperty("org.apache.xml.security.maxReferences",
Integer.toString(MAXIMUM_REFERENCE_COUNT))));
/** Field references */
private List<Reference> references;
private Element[] referencesEl;
/** Field verificationResults[] */
private List<VerifiedReference> verificationResults;
/** Field resolverProperties */
private Map<String, String> resolverProperties;
/** Field perManifestResolvers */
private List<ResourceResolverSpi> perManifestResolvers;
private boolean secureValidation = true;
/**
* Constructs {@link Manifest}
*
* @param doc the {@link Document} in which <code>XMLsignature</code> is placed
*/
public Manifest(Document doc) {
super(doc);
addReturnToSelf();
this.references = new ArrayList<>();
}
/**
* Constructor Manifest
*
* @param element
* @param baseURI
* @throws XMLSecurityException
*/
public Manifest(Element element, String baseURI) throws XMLSecurityException {
this(element, baseURI, true);
}
/**
* Constructor Manifest
*
* @param element
* @param baseURI
* @param secureValidation
* @throws XMLSecurityException
*/
public Manifest(
Element element, String baseURI, boolean secureValidation
) throws XMLSecurityException {
super(element, baseURI);
Attr attr = element.getAttributeNodeNS(null, "Id");
if (attr != null) {
element.setIdAttributeNode(attr, true);
}
this.secureValidation = secureValidation;
// check out Reference children
this.referencesEl =
XMLUtils.selectDsNodes(
getFirstChild(), Constants._TAG_REFERENCE
);
int le = this.referencesEl.length;
if (le == 0) {
// At least one Reference must be present. Bad.
Object[] exArgs = { Constants._TAG_REFERENCE, Constants._TAG_MANIFEST };
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR,
I18n.translate("xml.WrongContent", exArgs));
}
if (secureValidation && le > referenceCount) {
Object[] exArgs = { le, referenceCount };
throw new XMLSecurityException("signature.tooManyReferences", exArgs);
}
// create List
this.references = new ArrayList<>(le);
for (int i = 0; i < le; i++) {
Element refElem = referencesEl[i];
Attr refAttr = refElem.getAttributeNodeNS(null, "Id");
if (refAttr != null) {
refElem.setIdAttributeNode(refAttr, true);
}
this.references.add(null);
}
}
/**
* This <code>addDocument</code> method is used to add a new resource to the
* signed info. A {@link org.apache.xml.security.signature.Reference} is built
* from the supplied values.
*
* @param baseURI the URI of the resource where the XML instance was stored
* @param referenceURI <code>URI</code> attribute in <code>Reference</code> for specifying
* where data is
* @param transforms org.apache.xml.security.signature.Transforms object with an ordered
* list of transformations to be performed.
* @param digestURI The digest algorithm URI to be used.
* @param referenceId
* @param referenceType
* @throws XMLSignatureException
*/
public void addDocument(
String baseURI, String referenceURI, Transforms transforms,
String digestURI, String referenceId, String referenceType
) throws XMLSignatureException {
// the this.doc is handed implicitly by the this.getOwnerDocument()
Reference ref =
new Reference(getDocument(), baseURI, referenceURI, this, transforms, digestURI);
if (referenceId != null) {
ref.setId(referenceId);
}
if (referenceType != null) {
ref.setType(referenceType);
}
// add Reference object to our cache vector
this.references.add(ref);
// add the Element of the Reference object to the Manifest/SignedInfo
appendSelf(ref);
addReturnToSelf();
}
/**
* The calculation of the DigestValues in the References must be after the
* References are already added to the document and during the signing
* process. This ensures that all necessary data is in place.
*
* @throws ReferenceNotInitializedException
* @throws XMLSignatureException
*/
public void generateDigestValues()
throws XMLSignatureException, ReferenceNotInitializedException {
for (int i = 0; i < this.getLength(); i++) {
// update the cached Reference object, the Element content is automatically updated
Reference currentRef = this.references.get(i);
currentRef.generateDigestValue();
}
}
/**
* Return the nonnegative number of added references.
*
* @return the number of references
*/
public int getLength() {
return this.references.size();
}
/**
* Return the <i>i</i><sup>th</sup> reference. Valid <code>i</code>
* values are 0 to <code>{@link #getLength()}-1</code>.
*
* @param i Index of the requested {@link Reference}
* @return the <i>i</i><sup>th</sup> reference
* @throws XMLSecurityException
*/
public Reference item(int i) throws XMLSecurityException {
if (this.references.get(i) == null) {
// not yet constructed, so _we_ have to
Reference ref =
new Reference(referencesEl[i], this.baseURI, this, secureValidation);
this.references.set(i, ref);
}
return this.references.get(i);
}
/**
* Sets the <code>Id</code> attribute
*
* @param Id the <code>Id</code> attribute in <code>ds:Manifest</code>
*/
public void setId(String Id) {
if (Id != null) {
setLocalIdAttribute(Constants._ATT_ID, Id);
}
}
/**
* Returns the <code>Id</code> attribute
*
* @return the <code>Id</code> attribute in <code>ds:Manifest</code>
*/
public String getId() {
return getLocalAttribute(Constants._ATT_ID);
}
/**
* Used to do a <A HREF="http://www.w3.org/TR/xmldsig-core/#def-ValidationReference">reference
* validation</A> of all enclosed references using the {@link Reference#verify} method.
*
* <p>This step loops through all {@link Reference}s and does verify the hash
* values. If one or more verifications fail, the method returns
* <code>false</code>. If <i>all</i> verifications are successful,
* it returns <code>true</code>. The results of the individual reference
* validations are available by using the {@link #getVerificationResult(int)} method
*
* @return true if all References verify, false if one or more do not verify.
* @throws MissingResourceFailureException if a {@link Reference} does not verify
* (throws a {@link org.apache.xml.security.signature.ReferenceNotInitializedException}
* because of an uninitialized {@link XMLSignatureInput}
* @see org.apache.xml.security.signature.Reference#verify
* @see org.apache.xml.security.signature.SignedInfo#verify()
* @see org.apache.xml.security.signature.MissingResourceFailureException
* @throws XMLSecurityException
*/
public boolean verifyReferences()
throws MissingResourceFailureException, XMLSecurityException {
return this.verifyReferences(false);
}
/**
* Used to do a <A HREF="http://www.w3.org/TR/xmldsig-core/#def-ValidationReference">reference
* validation</A> of all enclosed references using the {@link Reference#verify} method.
*
* <p>This step loops through all {@link Reference}s and does verify the hash
* values. If one or more verifications fail, the method returns
* <code>false</code>. If <i>all</i> verifications are successful,
* it returns <code>true</code>. The results of the individual reference
* validations are available by using the {@link #getVerificationResult(int)} method
*
* @param followManifests
* @return true if all References verify, false if one or more do not verify.
* @throws MissingResourceFailureException if a {@link Reference} does not verify
* (throws a {@link org.apache.xml.security.signature.ReferenceNotInitializedException}
* because of an uninitialized {@link XMLSignatureInput}
* @see org.apache.xml.security.signature.Reference#verify
* @see org.apache.xml.security.signature.SignedInfo#verify(boolean)
* @see org.apache.xml.security.signature.MissingResourceFailureException
* @throws XMLSecurityException
*/
public boolean verifyReferences(boolean followManifests)
throws MissingResourceFailureException, XMLSecurityException {
if (referencesEl == null) {
this.referencesEl =
XMLUtils.selectDsNodes(
getFirstChild(), Constants._TAG_REFERENCE
);
}
LOG.log(Level.DEBUG, "verify {0} References", referencesEl.length);
LOG.log(Level.DEBUG, "I am {0} requested to follow nested Manifests", followManifests
? "" : "not");
if (referencesEl.length == 0) {
throw new XMLSecurityException("empty", new Object[]{"References are empty"});
}
if (secureValidation && referencesEl.length > referenceCount) {
Object[] exArgs = { referencesEl.length, referenceCount };
throw new XMLSecurityException("signature.tooManyReferences", exArgs);
}
this.verificationResults = new ArrayList<>(referencesEl.length);
boolean verify = true;
for (int i = 0; i < this.referencesEl.length; i++) {
Reference currentRef =
new Reference(referencesEl[i], this.baseURI, this, secureValidation);
this.references.set(i, currentRef);
// if only one item does not verify, the whole verification fails
try {
boolean currentRefVerified = currentRef.verify();
if (!currentRefVerified) {
verify = false;
}
LOG.log(Level.DEBUG, "The Reference has Type {0}", currentRef.getType());
List<VerifiedReference> manifestReferences = Collections.emptyList();
// was verification successful till now and do we want to verify the Manifest?
if (verify && followManifests && currentRef.typeIsReferenceToManifest()) {
LOG.log(Level.DEBUG, "We have to follow a nested Manifest");
try {
XMLSignatureInput signedManifestNodes =
currentRef.dereferenceURIandPerformTransforms(null);
Set<Node> nl = signedManifestNodes.getNodeSet();
Manifest referencedManifest = null;
for (Node n : nl) {
if (n.getNodeType() == Node.ELEMENT_NODE
&& ((Element) n).getNamespaceURI().equals(Constants.SignatureSpecNS)
&& ((Element) n).getLocalName().equals(Constants._TAG_MANIFEST)
) {
try {
referencedManifest =
new Manifest(
(Element)n, signedManifestNodes.getSourceURI(), secureValidation
);
break;
} catch (XMLSecurityException ex) {
LOG.log(Level.DEBUG, ex.getMessage(), ex);
// Hm, seems not to be a ds:Manifest
}
}
}
if (referencedManifest == null) {
// The Reference stated that it points to a ds:Manifest
// but we did not find a ds:Manifest in the signed area
throw new MissingResourceFailureException(currentRef, "empty",
new Object[]{"No Manifest found"});
}
referencedManifest.perManifestResolvers = this.perManifestResolvers;
referencedManifest.resolverProperties = this.resolverProperties;
boolean referencedManifestValid =
referencedManifest.verifyReferences(followManifests);
if (!referencedManifestValid) {
verify = false;
LOG.log(Level.WARNING, "The nested Manifest was invalid (bad)");
} else {
LOG.log(Level.DEBUG, "The nested Manifest was valid (good)");
}
manifestReferences = referencedManifest.getVerificationResults();
} catch (IOException ex) {
throw new ReferenceNotInitializedException(ex);
} catch (XMLParserException ex) {
throw new ReferenceNotInitializedException(ex);
}
}
verificationResults.add(new VerifiedReference(currentRefVerified, currentRef.getURI(), manifestReferences));
} catch (ReferenceNotInitializedException ex) {
Object[] exArgs = { currentRef.getURI() };
throw new MissingResourceFailureException(
ex, currentRef, "signature.Verification.Reference.NoInput", exArgs
);
}
}
return verify;
}
/**
* After verifying a {@link Manifest} or a {@link SignedInfo} using the
* {@link Manifest#verifyReferences()} or {@link SignedInfo#verify()} methods,
* the individual results can be retrieved with this method.
*
* @param index an index of into a {@link Manifest} or a {@link SignedInfo}
* @return the results of reference validation at the specified index
* @throws XMLSecurityException
*/
public boolean getVerificationResult(int index) throws XMLSecurityException {
if (index < 0 || index > this.getLength() - 1) {
Object[] exArgs = { Integer.toString(index), Integer.toString(this.getLength()) };
Exception e =
new IndexOutOfBoundsException(
I18n.translate("signature.Verification.IndexOutOfBounds", exArgs)
);
throw new XMLSecurityException(e);
}
if (this.verificationResults == null) {
try {
this.verifyReferences();
} catch (Exception ex) {
throw new XMLSecurityException(ex);
}
}
return verificationResults.get(index).isValid();
}
/**
* Get the list of verification result objects
*/
public List<VerifiedReference> getVerificationResults() {
if (verificationResults == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(verificationResults);
}
/**
* Adds Resource Resolver for retrieving resources at specified <code>URI</code> attribute
* in <code>reference</code> element
*
* @param resolver {@link ResourceResolverSpi} can provide the implementation subclass of
* {@link ResourceResolverSpi} for retrieving resource.
*/
public void addResourceResolver(ResourceResolverSpi resolver) {
if (resolver == null) {
return;
}
if (perManifestResolvers == null) {
perManifestResolvers = new ArrayList<>();
}
this.perManifestResolvers.add(resolver);
}
/**
* Get the Per-Manifest Resolver List
* @return the per-manifest Resolver List
*/
public List<ResourceResolverSpi> getPerManifestResolvers() {
return perManifestResolvers;
}
/**
* Get the resolver property map
* @return the resolver property map
*/
public Map<String, String> getResolverProperties() {
return resolverProperties;
}
/**
* Used to pass parameters like proxy servers etc to the ResourceResolver
* implementation.
*
* @param key the key
* @param value the value
*/
public void setResolverProperty(String key, String value) {
if (resolverProperties == null) {
resolverProperties = new HashMap<>(10);
}
this.resolverProperties.put(key, value);
}
/**
* Returns the value at specified key
*
* @param key the key
* @return the value
*/
public String getResolverProperty(String key) {
return this.resolverProperties.get(key);
}
/**
* Method getSignedContentItem
*
* @param i
* @return The signed content of the i reference.
*
* @throws XMLSignatureException
*/
public byte[] getSignedContentItem(int i) throws XMLSignatureException {
try {
return this.getReferencedContentAfterTransformsItem(i).getBytes();
} catch (IOException ex) {
throw new XMLSignatureException(ex);
} catch (CanonicalizationException ex) {
throw new XMLSignatureException(ex);
} catch (InvalidCanonicalizerException ex) {
throw new XMLSignatureException(ex);
} catch (XMLSecurityException ex) {
throw new XMLSignatureException(ex);
}
}
/**
* Method getReferencedContentPriorTransformsItem
*
* @param i
* @return The contents before transformation of the reference i.
* @throws XMLSecurityException
*/
public XMLSignatureInput getReferencedContentBeforeTransformsItem(int i)
throws XMLSecurityException {
return this.item(i).getContentsBeforeTransformation();
}
/**
* Method getReferencedContentAfterTransformsItem
*
* @param i
* @return The contents after transformation of the reference i.
* @throws XMLSecurityException
*/
public XMLSignatureInput getReferencedContentAfterTransformsItem(int i)
throws XMLSecurityException {
return this.item(i).getContentsAfterTransformation();
}
/**
* Method getSignedContentLength
*
* @return The number of references contained in this reference.
*/
public int getSignedContentLength() {
return this.getLength();
}
/**
* Method getBaseLocalName
*
* {@inheritDoc}
*/
@Override
public String getBaseLocalName() {
return Constants._TAG_MANIFEST;
}
public boolean isSecureValidation() {
return secureValidation;
}
}