-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathXMLUtils.java
More file actions
1211 lines (1083 loc) · 43.5 KB
/
XMLUtils.java
File metadata and controls
1211 lines (1083 loc) · 43.5 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
/**
* 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.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.math.BigInteger;
import java.nio.file.Files;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.xml.security.c14n.CanonicalizationException;
import org.apache.xml.security.c14n.Canonicalizer;
import org.apache.xml.security.c14n.InvalidCanonicalizerException;
import org.apache.xml.security.parser.XMLParser;
import org.apache.xml.security.parser.XMLParserException;
import org.apache.xml.security.parser.XMLParserImpl;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* DOM and XML accessibility and comfort functions.
*
* @implNote
* The following system properties affect XML formatting:
* <ul>
* <li>{@systemProperty org.apache.xml.security.ignoreLineBreaks} - ignores all line breaks,
* making a single-line document. Overrides all other formatting options. Default: false</li>
* <li>{@systemProperty org.apache.xml.security.base64.ignoreLineBreaks} - ignores line breaks in base64Binary values.
* Takes precedence over line length and separator options (see below). Default: false</li>
* <li>{@systemProperty org.apache.xml.security.base64.lineSeparator} - Sets the line separator sequence in base64Binary values.
* Possible values: crlf, lf. Default: crlf</li>
* <li>{@systemProperty org.apache.xml.security.base64.lineLength} - Sets maximum line length in base64Binary values.
* The value is rounded down to the nearest multiple of 4. Values less than 4 are ignored. Default: 76</li>
* </ul>
*/
public final class XMLUtils {
private static final Logger LOG = System.getLogger(XMLUtils.class.getName());
private static final String IGNORE_LINE_BREAKS_PROP = "org.apache.xml.security.ignoreLineBreaks";
private static boolean ignoreLineBreaks =
AccessController.doPrivileged(
(PrivilegedAction<Boolean>) () -> Boolean.getBoolean(IGNORE_LINE_BREAKS_PROP));
private static Base64FormattingOptions base64Formatting =
AccessController.doPrivileged(
(PrivilegedAction<Base64FormattingOptions>) () -> new Base64FormattingOptions());
private static Base64.Encoder base64Encoder = (ignoreLineBreaks || base64Formatting.isIgnoreLineBreaks()) ?
Base64.getEncoder() :
Base64.getMimeEncoder(base64Formatting.getLineLength(), base64Formatting.getLineSeparator().getBytes());
private static Base64.Decoder base64Decoder = Base64.getMimeDecoder();
private static XMLParser xmlParserImpl =
AccessController.doPrivileged(
(PrivilegedAction<XMLParser>) () -> {
String xmlParserClass = System.getProperty("org.apache.xml.security.XMLParser");
if (xmlParserClass != null) {
try {
return (XMLParser) JavaUtils.newInstanceWithEmptyConstructor(
ClassLoaderUtils.loadClass(xmlParserClass, XMLUtils.class));
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
LOG.log(Level.ERROR, "Error instantiating XMLParser. Falling back to XMLParserImpl", e);
}
}
return new XMLParserImpl();
});
private static volatile String dsPrefix = "ds";
private static volatile String ds11Prefix = "dsig11";
private static volatile String xencPrefix = "xenc";
private static volatile String xenc11Prefix = "xenc11";
/**
* Constructor XMLUtils
*
*/
private XMLUtils() {
// we don't allow instantiation
}
/**
* Set the prefix for the digital signature namespace
* @param prefix the new prefix for the digital signature namespace
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to set the prefix
*/
public static void setDsPrefix(String prefix) {
JavaUtils.checkRegisterPermission();
dsPrefix = prefix;
}
/**
* Set the prefix for the digital signature 1.1 namespace
* @param prefix the new prefix for the digital signature 1.1 namespace
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to set the prefix
*/
public static void setDs11Prefix(String prefix) {
JavaUtils.checkRegisterPermission();
ds11Prefix = prefix;
}
/**
* Set the prefix for the encryption namespace
* @param prefix the new prefix for the encryption namespace
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to set the prefix
*/
public static void setXencPrefix(String prefix) {
JavaUtils.checkRegisterPermission();
xencPrefix = prefix;
}
/**
* Set the prefix for the encryption namespace 1.1
* @param prefix the new prefix for the encryption namespace 1.1
* @throws SecurityException if a security manager is installed and the
* caller does not have permission to set the prefix
*/
public static void setXenc11Prefix(String prefix) {
JavaUtils.checkRegisterPermission();
xenc11Prefix = prefix;
}
public static Element getNextElement(Node el) {
Node node = el;
while (node != null && node.getNodeType() != Node.ELEMENT_NODE) {
node = node.getNextSibling();
}
return (Element)node;
}
/**
* @param rootNode
* @param result
* @param exclude
* @param comments whether comments or not
*/
public static void getSet(Node rootNode, Set<Node> result, Node exclude, boolean comments) {
if (exclude != null && isDescendantOrSelf(exclude, rootNode)) {
return;
}
getSetRec(rootNode, result, exclude, comments);
}
private static void getSetRec(final Node rootNode, final Set<Node> result,
final Node exclude, final boolean comments) {
if (rootNode == exclude) {
return;
}
switch (rootNode.getNodeType()) { //NOPMD
case Node.ELEMENT_NODE:
result.add(rootNode);
Element el = (Element)rootNode;
if (el.hasAttributes()) {
NamedNodeMap nl = el.getAttributes();
int length = nl.getLength();
for (int i = 0; i < length; i++) {
result.add(nl.item(i));
}
}
//no return keep working
case Node.DOCUMENT_NODE:
for (Node r = rootNode.getFirstChild(); r != null; r = r.getNextSibling()) {
if (r.getNodeType() == Node.TEXT_NODE) {
result.add(r);
while (r != null && r.getNodeType() == Node.TEXT_NODE) {
r = r.getNextSibling();
}
if (r == null) {
return;
}
}
getSetRec(r, result, exclude, comments);
}
break;
case Node.COMMENT_NODE:
if (comments) {
result.add(rootNode);
}
break;
case Node.DOCUMENT_TYPE_NODE:
break;
default:
result.add(rootNode);
}
}
/**
* Outputs a DOM tree to a {@link File}.
*
* @param contextNode root node of the DOM tree
* @param outputFile the file to write to
* @throws IOException
*/
public static void outputDOM(Node contextNode, File outputFile) throws IOException {
try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(outputFile.toPath()), 8192)) {
outputDOM(contextNode, os, false);
}
}
/**
* Outputs a DOM tree to an {@link OutputStream}.
*
* @param contextNode root node of the DOM tree
* @param os the {@link OutputStream}
*/
public static void outputDOM(Node contextNode, OutputStream os) {
outputDOM(contextNode, os, false);
}
/**
* Outputs a DOM tree to an {@link OutputStream}. <I>If an Exception is
* thrown during execution, it's StackTrace is output to System.out, but the
* Exception is not re-thrown.</I>
*
* @param contextNode root node of the DOM tree
* @param os the {@link OutputStream}
* @param addPreamble
*/
public static void outputDOM(Node contextNode, OutputStream os, boolean addPreamble) {
try {
if (addPreamble) {
os.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes(UTF_8));
}
Canonicalizer.getInstance(
Canonicalizer.ALGO_ID_C14N_PHYSICAL).canonicalizeSubtree(contextNode, os);
} catch (IOException | InvalidCanonicalizerException | CanonicalizationException ex) {
LOG.log(Level.ERROR, ex.getMessage(), ex);
}
}
/**
* Serializes the <CODE>contextNode</CODE> into the OutputStream, <I>but
* suppresses all Exceptions</I>.
* <p></p>
* NOTE: <I>This should only be used for debugging purposes,
* NOT in a production environment; this method ignores all exceptions,
* so you won't notice if something goes wrong. If you're asking what is to
* be used in a production environment, simply use the code inside the
* <code>try{}</code> statement, but handle the Exceptions appropriately.</I>
*
* @param contextNode
* @param os
*/
public static void outputDOMc14nWithComments(Node contextNode, OutputStream os) {
try {
Canonicalizer.getInstance(
Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(contextNode, os);
} catch (InvalidCanonicalizerException | CanonicalizationException ex) {
LOG.log(Level.ERROR, ex.getMessage(), ex);
// throw new RuntimeException(ex.getMessage());
}
}
/**
* Method getFullTextChildrenFromNode
*
* @param node
* @return the string of children
*/
public static String getFullTextChildrenFromNode(Node node) {
StringBuilder sb = new StringBuilder();
Node child = node.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.TEXT_NODE) {
sb.append(((Text)child).getData());
}
child = child.getNextSibling();
}
return sb.toString();
}
/**
* Creates an Element in the XML Signature specification namespace.
*
* @param doc the factory Document
* @param elementName the local name of the Element
* @return the Element
*/
public static Element createElementInSignatureSpace(Document doc, String elementName) {
if (doc == null) {
throw new RuntimeException("Document is null");
}
if (dsPrefix == null || dsPrefix.length() == 0) {
return doc.createElementNS(Constants.SignatureSpecNS, elementName);
}
return doc.createElementNS(Constants.SignatureSpecNS, dsPrefix + ":" + elementName);
}
/**
* Creates an Element in the XML Signature 1.1 specification namespace.
*
* @param doc the factory Document
* @param elementName the local name of the Element
* @return the Element
*/
public static Element createElementInSignature11Space(Document doc, String elementName) {
if (doc == null) {
throw new RuntimeException("Document is null");
}
if (ds11Prefix == null || ds11Prefix.length() == 0) {
return doc.createElementNS(Constants.SignatureSpec11NS, elementName);
}
return doc.createElementNS(Constants.SignatureSpec11NS, ds11Prefix + ":" + elementName);
}
/**
* Creates an Element in the XML Encryption specification namespace.
*
* @param doc the factory Document
* @param elementName the local name of the Element
* @return the Element
*/
public static Element createElementInEncryptionSpace(Document doc, String elementName) {
if (doc == null) {
throw new RuntimeException("Document is null");
}
if (xencPrefix == null || xencPrefix.length() == 0) {
return doc.createElementNS(EncryptionConstants.EncryptionSpecNS, elementName);
}
return
doc.createElementNS(
EncryptionConstants.EncryptionSpecNS, xencPrefix + ":" + elementName
);
}
/**
* Creates an Element in the XML Encryption 1.1 specification namespace.
*
* @param doc the factory Document
* @param elementName the local name of the Element
* @return the Element
*/
public static Element createElementInEncryption11Space(Document doc, String elementName) {
if (doc == null) {
throw new RuntimeException("Document is null");
}
if (xenc11Prefix == null || xenc11Prefix.length() == 0) {
return doc.createElementNS(EncryptionConstants.EncryptionSpec11NS, elementName);
}
return
doc.createElementNS(
EncryptionConstants.EncryptionSpec11NS, xenc11Prefix + ":" + elementName
);
}
/**
* Returns true if the element is in XML Signature namespace and the local
* name equals the supplied one.
*
* @param element
* @param localName
* @return true if the element is in XML Signature namespace and the local name equals
* the supplied one
*/
public static boolean elementIsInSignatureSpace(Element element, String localName) {
if (element == null){
return false;
}
return Constants.SignatureSpecNS.equals(element.getNamespaceURI())
&& element.getLocalName().equals(localName);
}
/**
* Returns true if the element is in XML Signature 1.1 namespace and the local
* name equals the supplied one.
*
* @param element
* @param localName
* @return true if the element is in XML Signature namespace and the local name equals
* the supplied one
*/
public static boolean elementIsInSignature11Space(Element element, String localName) {
if (element == null) {
return false;
}
return Constants.SignatureSpec11NS.equals(element.getNamespaceURI())
&& element.getLocalName().equals(localName);
}
/**
* Returns true if the element is in XML Encryption namespace and the local
* name equals the supplied one.
*
* @param element
* @param localName
* @return true if the element is in XML Encryption namespace and the local name
* equals the supplied one
*/
public static boolean elementIsInEncryptionSpace(Element element, String localName) {
if (element == null){
return false;
}
return EncryptionConstants.EncryptionSpecNS.equals(element.getNamespaceURI())
&& element.getLocalName().equals(localName);
}
/**
* Returns true if the element is in XML Encryption 1.1 namespace and the local
* name equals the supplied one.
*
* @param element
* @param localName
* @return true if the element is in XML Encryption 1.1 namespace and the local name
* equals the supplied one
*/
public static boolean elementIsInEncryption11Space(Element element, String localName) {
if (element == null){
return false;
}
return EncryptionConstants.EncryptionSpec11NS.equals(element.getNamespaceURI())
&& element.getLocalName().equals(localName);
}
/**
* This method returns the owner document of a particular node.
* This method is necessary because it <I>always</I> returns a
* {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
* if the {@link Node} is a {@link Document}.
*
* @param node
* @return the owner document of the node
*/
public static Document getOwnerDocument(Node node) {
if (node.getNodeType() == Node.DOCUMENT_NODE) {
return (Document) node;
}
try {
return node.getOwnerDocument();
} catch (NullPointerException npe) {
throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0")
+ " Original message was \""
+ npe.getMessage() + "\"");
}
}
/**
* This method returns the first non-null owner document of the Nodes in this Set.
* This method is necessary because it <I>always</I> returns a
* {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
* if the {@link Node} is a {@link Document}.
*
* @param xpathNodeSet
* @return the owner document
*/
public static Document getOwnerDocument(Set<Node> xpathNodeSet) {
NullPointerException npe = null;
for (Node node : xpathNodeSet) {
int nodeType = node.getNodeType();
if (nodeType == Node.DOCUMENT_NODE) {
return (Document) node;
}
try {
if (nodeType == Node.ATTRIBUTE_NODE) {
return ((Attr)node).getOwnerElement().getOwnerDocument();
}
return node.getOwnerDocument();
} catch (NullPointerException e) {
npe = e;
}
}
throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0")
+ " Original message was \""
+ (npe == null ? "" : npe.getMessage()) + "\"");
}
/**
* Method addReturnToElement
*
* @param e
*/
public static void addReturnToElement(Element e) {
if (!ignoreLineBreaks) {
Document doc = e.getOwnerDocument();
e.appendChild(doc.createTextNode("\n"));
}
}
public static void addReturnToElement(Document doc, HelperNodeList nl) {
if (!ignoreLineBreaks) {
nl.appendChild(doc.createTextNode("\n"));
}
}
public static void addReturnBeforeChild(Element e, Node child) {
if (!ignoreLineBreaks) {
Document doc = e.getOwnerDocument();
e.insertBefore(doc.createTextNode("\n"), child);
}
}
public static String encodeToString(byte[] bytes) {
return base64Encoder.encodeToString(bytes);
}
/**
* Encodes bytes using Base64, with or without line breaks, depending on configuration (see {@link XMLUtils}).
* @param bytes Bytes to encode
* @return Base64 string
*/
public static String encodeElementValue(byte[] bytes) {
String encoded = encodeToString(bytes);
if (!ignoreLineBreaks && !base64Formatting.isIgnoreLineBreaks()
&& encoded.length() > base64Formatting.getLineLength()) {
encoded = "\n" + encoded + "\n";
}
return encoded;
}
/**
* Wraps output stream for Base64 encoding.
* Output data may contain line breaks or not, depending on configuration (see {@link XMLUtils})
* @param stream The underlying output stream to write Base64-encoded data
* @return Stream which writes binary data using Base64 encoder
*/
public static OutputStream encodeStream(OutputStream stream) {
return base64Encoder.wrap(stream);
}
public static byte[] decode(String encodedString) {
return base64Decoder.decode(encodedString);
}
public static byte[] decode(byte[] encodedBytes) {
return base64Decoder.decode(encodedBytes);
}
/**
* Wraps input stream for Base64 decoding.
* @param stream Input stream with Base64-encoded data
* @return Input stream with decoded binary data
*/
public static InputStream decodeStream(InputStream stream) {
return base64Decoder.wrap(stream);
}
public static boolean isIgnoreLineBreaks() {
return ignoreLineBreaks;
}
/**
* Method convertNodelistToSet
*
* @param xpathNodeSet
* @return the set with the nodelist
*/
public static Set<Node> convertNodelistToSet(NodeList xpathNodeSet) {
if (xpathNodeSet == null) {
return new HashSet<>();
}
int length = xpathNodeSet.getLength();
Set<Node> set = new HashSet<>(length);
for (int i = 0; i < length; i++) {
set.add(xpathNodeSet.item(i));
}
return set;
}
/**
* This method spreads all namespace attributes in a DOM document to their
* children. This is needed because the XML Signature XPath transform
* must evaluate the XPath against all nodes in the input, even against
* XPath namespace nodes. Through a bug in XalanJ2, the namespace nodes are
* not fully visible in the Xalan XPath model, so we have to do this by
* hand in DOM spaces so that the nodes become visible in XPath space.
*
* @param doc
* @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">
* Namespace axis resolution is not XPath compliant </A>
*/
public static void circumventBug2650(Document doc) {
Element documentElement = doc.getDocumentElement();
// if the document element has no xmlns definition, we add xmlns=""
Attr xmlnsAttr =
documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns");
if (xmlnsAttr == null) {
documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "");
}
XMLUtils.circumventBug2650internal(doc);
}
/**
* This is the work horse for {@link #circumventBug2650}.
*
* @param node
* @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">
* Namespace axis resolution is not XPath compliant </A>
*/
@SuppressWarnings("fallthrough")
private static void circumventBug2650internal(Node node) {
Node parent = null;
Node sibling = null;
final String namespaceNs = Constants.NamespaceSpecNS;
do { //NOPMD
switch (node.getNodeType()) {
case Node.ELEMENT_NODE :
Element element = (Element) node;
if (!element.hasChildNodes()) {
break;
}
if (element.hasAttributes()) {
NamedNodeMap attributes = element.getAttributes();
int attributesLength = attributes.getLength();
for (Node child = element.getFirstChild(); child!=null;
child = child.getNextSibling()) {
if (child.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
Element childElement = (Element) child;
for (int i = 0; i < attributesLength; i++) {
Attr currentAttr = (Attr) attributes.item(i);
if (!namespaceNs.equals(currentAttr.getNamespaceURI())) {
continue;
}
if (childElement.hasAttributeNS(namespaceNs,
currentAttr.getLocalName())) {
continue;
}
childElement.setAttributeNS(namespaceNs,
currentAttr.getName(),
currentAttr.getNodeValue());
}
}
}
case Node.ENTITY_REFERENCE_NODE :
case Node.DOCUMENT_NODE :
parent = node;
sibling = node.getFirstChild();
break;
}
while (sibling == null && parent != null) {
sibling = parent.getNextSibling();
parent = parent.getParentNode();
}
if (sibling == null) {
return;
}
node = sibling;
sibling = node.getNextSibling();
} while (true);
}
/**
* @param sibling
* @param nodeName
* @param number
* @return nodes with the constraint
*/
public static Element selectDsNode(Node sibling, String nodeName, int number) {
while (sibling != null) {
if (Constants.SignatureSpecNS.equals(sibling.getNamespaceURI())
&& sibling.getLocalName().equals(nodeName)) {
if (number == 0) {
return (Element)sibling;
}
number--;
}
sibling = sibling.getNextSibling();
}
return null;
}
/**
* @param sibling
* @param nodeName
* @param number
* @return nodes with the constraint
*/
public static Element selectDs11Node(Node sibling, String nodeName, int number) {
while (sibling != null) {
if (Constants.SignatureSpec11NS.equals(sibling.getNamespaceURI())
&& sibling.getLocalName().equals(nodeName)) {
if (number == 0) {
return (Element)sibling;
}
number--;
}
sibling = sibling.getNextSibling();
}
return null;
}
/**
* @param sibling
* @param nodeName
* @param number
* @return nodes with the constrain
*/
public static Element selectXencNode(Node sibling, String nodeName, int number) {
while (sibling != null) {
if (EncryptionConstants.EncryptionSpecNS.equals(sibling.getNamespaceURI())
&& sibling.getLocalName().equals(nodeName)) {
if (number == 0){
return (Element)sibling;
}
number--;
}
sibling = sibling.getNextSibling();
}
return null;
}
/**
* Helper method to get the "number"-th element for a given local
* name and namespace: http://www.w3.org/2009/xmlenc11#. If element with given search parameters is not found,
* null is returned.
*
* @param sibling the sibling node from which to start searching
* @param nodeName the local name of the element to search for
* @param number the index of the element to search for
* @return node with the given node name or null if not found.
*/
public static Element selectXenc11Node(Node sibling, String nodeName, int number) {
return selectNode(sibling, EncryptionConstants.EncryptionSpec11NS, nodeName, number);
}
/**
* @param sibling
* @param uri
* @param nodeName
* @param number
* @return nodes with the constrain
*/
public static Element selectNode(Node sibling, String uri, String nodeName, int number) {
while (sibling != null) {
if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri)
&& sibling.getLocalName().equals(nodeName)) {
if (number == 0) {
return (Element)sibling;
}
number--;
}
sibling = sibling.getNextSibling();
}
return null;
}
/**
* @param sibling
* @param nodeName
* @return nodes with the constrain
*/
public static Element[] selectDsNodes(Node sibling, String nodeName) {
return selectNodes(sibling, Constants.SignatureSpecNS, nodeName);
}
/**
* @param sibling
* @param nodeName
* @return nodes with the constrain
*/
public static Element[] selectDs11Nodes(Node sibling, String nodeName) {
return selectNodes(sibling, Constants.SignatureSpec11NS, nodeName);
}
/**
* @param sibling
* @param uri
* @param nodeName
* @return nodes with the constraint
*/
public static Element[] selectNodes(Node sibling, String uri, String nodeName) {
List<Element> list = new ArrayList<>();
while (sibling != null) {
if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri)
&& sibling.getLocalName().equals(nodeName)) {
list.add((Element)sibling);
}
sibling = sibling.getNextSibling();
}
return list.toArray(new Element[list.size()]);
}
/**
* @param signatureElement
* @param inputSet
* @return nodes with the constrain
*/
public static Set<Node> excludeNodeFromSet(Node signatureElement, Set<Node> inputSet) {
return inputSet.stream().filter((inputNode) ->
!XMLUtils.isDescendantOrSelf(signatureElement, inputNode)).collect(Collectors.toSet());
}
/**
* Method getStrFromNode
*
* @param xpathnode
* @return the string for the node.
*/
public static String getStrFromNode(Node xpathnode) {
if (xpathnode.getNodeType() == Node.TEXT_NODE) {
// we iterate over all siblings of the context node because eventually,
// the text is "polluted" with pi's or comments
StringBuilder sb = new StringBuilder();
for (Node currentSibling = xpathnode.getParentNode().getFirstChild();
currentSibling != null;
currentSibling = currentSibling.getNextSibling()) {
if (currentSibling.getNodeType() == Node.TEXT_NODE) {
sb.append(((Text) currentSibling).getData());
}
}
return sb.toString();
} else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) {
return xpathnode.getNodeValue();
} else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
return xpathnode.getNodeValue();
}
return null;
}
/**
* Returns true if the descendantOrSelf is on the descendant-or-self axis
* of the context node.
*
* @param ctx
* @param descendantOrSelf
* @return true if the node is descendant
*/
public static boolean isDescendantOrSelf(Node ctx, Node descendantOrSelf) {
if (ctx == descendantOrSelf) {
return true;
}
Node parent = descendantOrSelf;
while (true) {
if (parent == null) {
return false;
}
if (parent == ctx) {
return true;
}
if (parent.getNodeType() == Node.ATTRIBUTE_NODE) {
parent = ((Attr) parent).getOwnerElement();
} else {
parent = parent.getParentNode();
}
}
}
public static boolean ignoreLineBreaks() {
return ignoreLineBreaks;
}
/**
* This method is a tree-search to help prevent against wrapping attacks. It checks that no
* two Elements have ID Attributes that match the "value" argument, if this is the case then
* "false" is returned. Note that a return value of "true" does not necessarily mean that
* a matching Element has been found, just that no wrapping attack has been detected.
*/
public static boolean protectAgainstWrappingAttack(Node startNode, String value) {
String id = value.trim();
if (!id.isEmpty() && id.charAt(0) == '#') {
id = id.substring(1);
}
Node startParent = null;
Node processedNode = null;
Element foundElement = null;
if (startNode != null) {
startParent = startNode.getParentNode();
}
while (startNode != null) {
if (startNode.getNodeType() == Node.ELEMENT_NODE) {
Element se = (Element) startNode;
NamedNodeMap attributes = se.getAttributes();
if (attributes != null) {
int length = attributes.getLength();
for (int i = 0; i < length; i++) {
Attr attr = (Attr)attributes.item(i);
if (attr.isId() && id.equals(attr.getValue())) {
if (foundElement == null) {
// Continue searching to find duplicates
foundElement = attr.getOwnerElement();
} else {
LOG.log(Level.WARNING, "Multiple elements with the same 'Id' attribute value!");
return false;
}
}
}
}
}
processedNode = startNode;
startNode = startNode.getFirstChild();
// no child, this node is done.
if (startNode == null) {
// close node processing, get sibling
startNode = processedNode.getNextSibling();
}
// no more siblings, get parent, all children
// of parent are processed.
while (startNode == null) {
processedNode = processedNode.getParentNode();
if (processedNode == startParent) {
return true;
}
// close parent node processing (processed node now)
startNode = processedNode.getNextSibling();
}
}
return true;
}
/**
* This method is a tree-search to help prevent against wrapping attacks. It checks that no other
* Element than the given "knownElement" argument has an ID attribute that matches the "value"
* argument, which is the ID value of "knownElement". If this is the case then "false" is returned.
*/
public static boolean protectAgainstWrappingAttack(
Node startNode, Element knownElement, String value
) {
String id = value.trim();
if (!id.isEmpty() && id.charAt(0) == '#') {
id = id.substring(1);
}
Node startParent = null;
Node processedNode = null;
if (startNode != null) {
startParent = startNode.getParentNode();
}
while (startNode != null) {
if (startNode.getNodeType() == Node.ELEMENT_NODE) {
Element se = (Element) startNode;
NamedNodeMap attributes = se.getAttributes();
if (attributes != null) {
int length = attributes.getLength();
for (int i = 0; i < length; i++) {