Repository navigation
Expand file tree
/
Copy pathexclusivecanonicalization.go
More file actions
521 lines (457 loc) · 14.2 KB
/
Copy pathexclusivecanonicalization.go
File metadata and controls
521 lines (457 loc) · 14.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
package signedxml
import (
"fmt"
"sort"
"github.com/beevik/etree"
)
// maxInScopeNamespaces caps prefix-to-URI mappings retained during exclusive
// canonicalization, and unique InclusiveNamespaces PrefixList tokens. Legitimate
// SAML/WS-Federation documents use a handful of prefixes; this bound rejects
// adversarial input that would otherwise grow without limit (many xmlns
// declarations on nested elements, or a long PrefixList walked at every node).
const maxInScopeNamespaces = 8192
// the attribute and attributes structs are used to implement the sort.Interface
type attribute struct {
prefix, uri, key, value string
}
type attributes []attribute
func (a attributes) Len() int {
return len(a)
}
// Less is part of the sort.Interface, and is used to order attributes by their
// namespace URIs and then by their keys.
func (a attributes) Less(i, j int) bool {
if a[i].uri == "" && a[j].uri != "" {
return true
}
if a[j].uri == "" && a[i].uri != "" {
return false
}
iQual := a[i].uri + a[i].key
jQual := a[j].uri + a[j].key
return iQual < jQual
}
func (a attributes) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
// ExclusiveCanonicalization implements the CanonicalizationAlgorithm
// interface and is used for processing the
// http://www.w3.org/2001/10/xml-exc-c14n# and
// http://www.w3.org/2001/10/xml-exc-c14n#WithComments transform
// algorithms
type ExclusiveCanonicalization struct {
WithComments bool
inclusiveNamespacePrefixSet map[string]struct{}
namespaces map[string]string
}
// nsScopeDelta records namespace map changes made at one element so they can
// be undone on the way back up the tree, instead of copying the whole map.
type nsScopeDelta struct {
added []string
previous map[string]string
}
// collectAncestorNamespaces walks up the element tree and collects all namespace
// declarations from ancestors. This is needed because when we copy an element,
// we lose the namespace context from its ancestors.
func collectAncestorNamespaces(elem *etree.Element) map[string]string {
namespaces := make(map[string]string)
// Walk up the tree collecting namespace declarations
for current := elem.Parent(); current != nil; {
for _, attr := range current.Attr {
// xmlns:prefix="uri" declarations
if attr.Space == "xmlns" {
if _, exists := namespaces[attr.Key]; !exists {
namespaces[attr.Key] = attr.Value
}
}
// xmlns="uri" default namespace declaration
if attr.Space == "" && attr.Key == "xmlns" {
if _, exists := namespaces[""]; !exists {
namespaces[""] = attr.Value
}
}
}
current = current.Parent()
}
return namespaces
}
// see CanonicalizationAlgorithm.ProcessElement
func (e ExclusiveCanonicalization) ProcessElement(inputXML *etree.Element, transformXML string) (outputXML string, err error) {
ancestorNamespaces := collectAncestorNamespaces(inputXML)
doc := etree.NewDocument()
doc.SetRoot(inputXML.Copy())
return e.processDocumentWithAncestorNS(doc, transformXML, ancestorNamespaces)
}
// see CanonicalizationAlgorithm.ProcessDocument
func (e ExclusiveCanonicalization) ProcessDocument(doc *etree.Document,
transformXML string) (outputXML string, err error) {
return e.processDocument(doc.Copy(), transformXML)
}
// see CanonicalizationAlgorithm.Process
func (e ExclusiveCanonicalization) Process(inputXML string, transformXML string) (outputXML string, err error) {
doc := etree.NewDocument()
doc.ReadSettings.PreserveCData = true
err = doc.ReadFromString(inputXML)
if err != nil {
return "", err
}
return e.ProcessDocument(doc, transformXML)
}
func (e *ExclusiveCanonicalization) processDocument(doc *etree.Document, transformXML string) (outputXML string, err error) {
e.namespaces = make(map[string]string)
doc.WriteSettings.CanonicalEndTags = true
doc.WriteSettings.CanonicalText = true
doc.WriteSettings.CanonicalAttrVal = true
if err := e.loadPrefixList(transformXML); err != nil {
return "", err
}
e.processDocLevelNodes(doc)
if err := e.processRecursive(doc.Root(), make(map[string]struct{}), ""); err != nil {
return "", err
}
outputXML, err = doc.WriteToString()
return outputXML, err
}
// processDocumentWithAncestorNS is like processDocument but pre-populates the
// namespace map with declarations from ancestor elements. This is needed when
// processing an element that was extracted from its original context.
func (e *ExclusiveCanonicalization) processDocumentWithAncestorNS(doc *etree.Document, transformXML string, ancestorNS map[string]string) (outputXML string, err error) {
e.namespaces = make(map[string]string)
for k, v := range ancestorNS {
e.namespaces[k] = v
}
doc.WriteSettings.CanonicalEndTags = true
doc.WriteSettings.CanonicalText = true
doc.WriteSettings.CanonicalAttrVal = true
if err := e.loadPrefixList(transformXML); err != nil {
return "", err
}
e.processDocLevelNodes(doc)
if len(e.namespaces) > maxInScopeNamespaces {
return "", fmt.Errorf("signedxml: exclusive canonicalization exceeded %d in-scope namespaces", maxInScopeNamespaces)
}
if err := e.processRecursive(doc.Root(), make(map[string]struct{}), ""); err != nil {
return "", err
}
outputXML, err = doc.WriteToString()
return outputXML, err
}
func (e *ExclusiveCanonicalization) loadPrefixList(transformXML string) error {
e.inclusiveNamespacePrefixSet = nil
if transformXML == "" {
return nil
}
tDoc := etree.NewDocument()
tDoc.ReadSettings.PreserveCData = true
if err := tDoc.ReadFromString(transformXML); err != nil {
return err
}
root := tDoc.Root()
if root == nil {
return nil
}
inclNSNode := root.SelectElement("InclusiveNamespaces")
if inclNSNode == nil {
return nil
}
prefixList := inclNSNode.SelectAttrValue("PrefixList", "")
if prefixList == "" {
return nil
}
set, err := parseInclusivePrefixList(prefixList)
if err != nil {
return err
}
e.inclusiveNamespacePrefixSet = set
return nil
}
func parseInclusivePrefixList(prefixList string) (map[string]struct{}, error) {
set := make(map[string]struct{})
start := -1
for i := 0; i <= len(prefixList); i++ {
if i < len(prefixList) {
c := prefixList[i]
if c != ' ' && c != '\t' && c != '\n' && c != '\r' {
if start < 0 {
start = i
}
continue
}
}
if start < 0 {
continue
}
prefix := prefixList[start:i]
start = -1
if _, dup := set[prefix]; dup {
continue
}
if len(set) >= maxInScopeNamespaces {
return nil, fmt.Errorf("signedxml: exclusive canonicalization exceeded %d InclusiveNamespaces prefixes", maxInScopeNamespaces)
}
set[prefix] = struct{}{}
}
if len(set) == 0 {
return nil, nil
}
return set, nil
}
// process nodes outside of the root element
func (e *ExclusiveCanonicalization) processDocLevelNodes(doc *etree.Document) {
// keep track of the previous node action to manage line returns in CharData
previousNodeRemoved := false
for i := 0; i < len(doc.Child); i++ {
c := doc.Child[i]
switch c := c.(type) {
case *etree.Comment:
if e.WithComments {
previousNodeRemoved = false
} else {
removeTokenFromDocument(c, doc)
i--
previousNodeRemoved = true
}
case *etree.CharData:
if isWhitespace(c.Data) {
if previousNodeRemoved {
removeTokenFromDocument(c, doc)
i--
previousNodeRemoved = true
} else {
c.Data = "\n"
}
}
case *etree.Directive:
removeTokenFromDocument(c, doc)
i--
previousNodeRemoved = true
case *etree.ProcInst:
// remove declaration, but leave other PI's
if c.Target == "xml" {
removeTokenFromDocument(c, doc)
i--
previousNodeRemoved = true
} else {
previousNodeRemoved = false
}
default:
previousNodeRemoved = false
}
}
// if the last line is CharData whitespace, then remove it
if c, ok := doc.Child[len(doc.Child)-1].(*etree.CharData); ok {
if isWhitespace(c.Data) {
removeTokenFromDocument(c, doc)
}
}
}
func (e *ExclusiveCanonicalization) processRecursive(node *etree.Element,
prefixesInScope map[string]struct{}, defaultNS string) error {
nsDelta, err := e.pushNamespaces(node)
if err != nil {
e.popNamespaces(nsDelta)
return err
}
newDefaultNS, addedPrefixes := e.renderAttributes(node, prefixesInScope, defaultNS)
for i := 0; i < len(node.Child); i++ {
child := node.Child[i]
switch child := child.(type) {
case *etree.Comment:
if !e.WithComments {
removeTokenFromElement(etree.Token(child), node)
i--
}
case *etree.CharData:
// Convert CDATA sections to regular text nodes for canonicalization
// CDATA sections must be converted to escaped text per XML canonicalization rules
if child.IsCData() {
// Replace CDATA with regular text node containing the same data
textNode := etree.NewText(child.Data)
node.Child[i] = textNode
}
case *etree.Element:
if err := e.processRecursive(child, prefixesInScope, newDefaultNS); err != nil {
popPrefixes(prefixesInScope, addedPrefixes)
e.popNamespaces(nsDelta)
return err
}
}
}
popPrefixes(prefixesInScope, addedPrefixes)
e.popNamespaces(nsDelta)
return nil
}
func (e *ExclusiveCanonicalization) pushNamespaces(node *etree.Element) (nsScopeDelta, error) {
var delta nsScopeDelta
for _, attr := range node.Attr {
if attr.Space != "xmlns" {
continue
}
if old, exists := e.namespaces[attr.Key]; exists {
if old != attr.Value {
if delta.previous == nil {
delta.previous = make(map[string]string)
}
if _, recorded := delta.previous[attr.Key]; !recorded {
delta.previous[attr.Key] = old
}
e.namespaces[attr.Key] = attr.Value
}
continue
}
if len(e.namespaces) >= maxInScopeNamespaces {
return delta, fmt.Errorf("signedxml: exclusive canonicalization exceeded %d in-scope namespaces", maxInScopeNamespaces)
}
e.namespaces[attr.Key] = attr.Value
delta.added = append(delta.added, attr.Key)
}
return delta, nil
}
func (e *ExclusiveCanonicalization) popNamespaces(delta nsScopeDelta) {
for _, k := range delta.added {
delete(e.namespaces, k)
}
for k, v := range delta.previous {
e.namespaces[k] = v
}
}
func popPrefixes(prefixesInScope map[string]struct{}, added []string) {
for _, prefix := range added {
delete(prefixesInScope, prefix)
}
}
func (e *ExclusiveCanonicalization) renderAttributes(node *etree.Element, prefixesInScope map[string]struct{}, defaultNS string) (newDefaultNS string, addedPrefixes []string) {
currentNS := node.SelectAttrValue("xmlns", defaultNS)
elementAttributes := []etree.Attr{}
nsListToRender := make(map[string]string)
attrListToRender := attributes{}
markInScope := func(prefix string) bool {
if _, ok := prefixesInScope[prefix]; ok {
return false
}
prefixesInScope[prefix] = struct{}{}
addedPrefixes = append(addedPrefixes, prefix)
return true
}
// handle the namespace of the node itself
if node.Space != "" {
if markInScope(node.Space) {
nsListToRender["xmlns:"+node.Space] = e.namespaces[node.Space]
}
} else if defaultNS != currentNS {
elementAttributes = append(elementAttributes, etree.Attr{Key: "xmlns", Value: currentNS})
}
// InclusiveNamespaces prefixes that are in scope from ancestors are always
// output, even if not visibly used on this element (exc-c14n PrefixList).
// Walk in-scope declarations and test the set so cost tracks namespace
// count (already capped), not the number of tokens in PrefixList.
if len(e.inclusiveNamespacePrefixSet) > 0 {
for prefix, uri := range e.namespaces {
if uri == "" {
continue
}
if _, inclusive := e.inclusiveNamespacePrefixSet[prefix]; !inclusive {
continue
}
if _, already := prefixesInScope[prefix]; already {
continue
}
nsListToRender["xmlns:"+prefix] = uri
markInScope(prefix)
}
}
for _, attr := range node.Attr {
// include the namespaces if they are in the InclusiveNamespaces PrefixList
if attr.Space == "xmlns" {
if _, already := prefixesInScope[attr.Key]; !already && e.hasInclusivePrefix(attr.Key) {
nsListToRender["xmlns:"+attr.Key] = attr.Value
markInScope(attr.Key)
}
}
// include namespaces for qualfied attributes
if attr.Space != "" &&
attr.Space != "xmlns" &&
markInScope(attr.Space) {
if attr.Space != "xml" {
nsListToRender["xmlns:"+attr.Space] = e.namespaces[attr.Space]
}
}
// inclued all non-namespace attributes
if attr.Space != "xmlns" && attr.Key != "xmlns" {
attrListToRender = append(attrListToRender,
attribute{
prefix: attr.Space,
uri: e.namespaces[attr.Space],
key: attr.Key,
value: attr.Value,
})
}
}
// sort and add the namespace attributes first
sortedNSList := getSortedNamespaces(nsListToRender)
elementAttributes = append(elementAttributes, sortedNSList...)
// then sort and add the non-namespace attributes
sortedAttributes := getSortedAttributes(attrListToRender)
elementAttributes = append(elementAttributes, sortedAttributes...)
// replace the nodes attributes with the sorted copy
node.Attr = elementAttributes
return currentNS, addedPrefixes
}
func (e *ExclusiveCanonicalization) hasInclusivePrefix(prefix string) bool {
_, ok := e.inclusiveNamespacePrefixSet[prefix]
return ok
}
// getSortedNamespaces sorts the namespace attributes by their prefix
func getSortedNamespaces(list map[string]string) []etree.Attr {
var keys []string
for k := range list {
keys = append(keys, k)
}
sort.Strings(keys)
elem := etree.Element{}
for _, k := range keys {
elem.CreateAttr(k, list[k])
}
return elem.Attr
}
// getSortedAttributes sorts attributes by their namespace URIs
func getSortedAttributes(list attributes) []etree.Attr {
sort.Sort(list)
attrs := make([]etree.Attr, len(list))
for i, a := range list {
attrs[i] = etree.Attr{
Space: a.prefix,
Key: a.key,
Value: a.value,
}
}
return attrs
}
func removeTokenFromElement(token etree.Token, e *etree.Element) *etree.Token {
for i, t := range e.Child {
if t == token {
e.Child = append(e.Child[0:i], e.Child[i+1:]...)
return &t
}
}
return nil
}
func removeTokenFromDocument(token etree.Token, d *etree.Document) *etree.Token {
for i, t := range d.Child {
if t == token {
d.Child = append(d.Child[0:i], d.Child[i+1:]...)
return &t
}
}
return nil
}
// isWhitespace returns true if the byte slice contains only
// whitespace characters.
func isWhitespace(s string) bool {
for i := 0; i < len(s); i++ {
if c := s[i]; c != ' ' && c != '\t' && c != '\n' && c != '\r' {
return false
}
}
return true
}