forked from russellhaering/goxmldsig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sign.go
291 lines (240 loc) · 7.86 KB
/
sign.go
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
package dsig
import (
"crypto"
"crypto/rand"
"crypto/rsa"
_ "crypto/sha1"
_ "crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"github.com/avantir-tech/goxmldsig/etreeutils"
"github.com/beevik/etree"
)
type SigningContext struct {
Hash crypto.Hash
KeyStore X509KeyStore
IdAttribute string
ReferenceXPath string
Prefix string
SkipKeyInfo bool
Canonicalizer Canonicalizer
}
func NewDefaultSigningContext(ks X509KeyStore) *SigningContext {
return &SigningContext{
Hash: crypto.SHA256,
KeyStore: ks,
IdAttribute: DefaultIdAttr,
ReferenceXPath: "",
Prefix: DefaultPrefix,
SkipKeyInfo: false,
Canonicalizer: MakeC14N11Canonicalizer(),
}
}
func (ctx *SigningContext) SetSignatureMethod(algorithmID string) error {
hash, ok := signatureMethodsByIdentifier[algorithmID]
if !ok {
return fmt.Errorf("Unknown SignatureMethod: %s", algorithmID)
}
ctx.Hash = hash
return nil
}
func (ctx *SigningContext) digestAll(el *etree.Element, xpath string) ([]byte, error) {
var elems []*etree.Element
if xpath != "" {
elems = el.FindElements(ctx.ReferenceXPath)
} else {
elems = []*etree.Element{el}
}
var dataToCanonicalize []byte
for _, e := range elems {
canonical, err := ctx.Canonicalizer.Canonicalize(e)
if err != nil {
return nil, err
}
dataToCanonicalize = append(dataToCanonicalize, canonical...)
}
return ctx.digest(dataToCanonicalize)
}
func (ctx *SigningContext) digestElement(el *etree.Element) ([]byte, error) {
data, err := ctx.Canonicalizer.Canonicalize(el)
if err != nil {
return nil, err
}
return ctx.digest(data)
}
func (ctx *SigningContext) digest(data []byte) ([]byte, error) {
hash := ctx.Hash.New()
_, err := hash.Write(data)
if err != nil {
return nil, err
}
return hash.Sum(nil), nil
}
func (ctx *SigningContext) constructSignedInfo(el *etree.Element, enveloped bool) (*etree.Element, error) {
digestAlgorithmIdentifier := ctx.GetDigestAlgorithmIdentifier()
if digestAlgorithmIdentifier == "" {
return nil, errors.New("unsupported hash mechanism")
}
signatureMethodIdentifier := ctx.GetSignatureMethodIdentifier()
if signatureMethodIdentifier == "" {
return nil, errors.New("unsupported signature method")
}
digest, err := ctx.digestAll(el, ctx.ReferenceXPath)
if err != nil {
return nil, err
}
signedInfo := &etree.Element{
Tag: SignedInfoTag,
Space: ctx.Prefix,
}
// /SignedInfo/CanonicalizationMethod
canonicalizationMethod := ctx.createNamespacedElement(signedInfo, CanonicalizationMethodTag)
canonicalizationMethod.CreateAttr(AlgorithmAttr, string(ctx.Canonicalizer.Algorithm()))
// /SignedInfo/SignatureMethod
signatureMethod := ctx.createNamespacedElement(signedInfo, SignatureMethodTag)
signatureMethod.CreateAttr(AlgorithmAttr, signatureMethodIdentifier)
// /SignedInfo/Reference
reference := ctx.createNamespacedElement(signedInfo, ReferenceTag)
if ctx.ReferenceXPath != "" {
reference.CreateAttr(URIAttr, "#xpointer("+ctx.ReferenceXPath+")")
} else {
dataId := el.SelectAttrValue(ctx.IdAttribute, "")
if dataId == "" {
reference.CreateAttr(URIAttr, "")
} else {
reference.CreateAttr(URIAttr, "#"+dataId)
}
}
// /SignedInfo/Reference/Transforms
transforms := ctx.createNamespacedElement(reference, TransformsTag)
if enveloped {
envelopedTransform := ctx.createNamespacedElement(transforms, TransformTag)
envelopedTransform.CreateAttr(AlgorithmAttr, EnvelopedSignatureAltorithmId.String())
}
canonicalizationAlgorithm := ctx.createNamespacedElement(transforms, TransformTag)
canonicalizationAlgorithm.CreateAttr(AlgorithmAttr, string(ctx.Canonicalizer.Algorithm()))
// /SignedInfo/Reference/DigestMethod
digestMethod := ctx.createNamespacedElement(reference, DigestMethodTag)
digestMethod.CreateAttr(AlgorithmAttr, digestAlgorithmIdentifier)
// /SignedInfo/Reference/DigestValue
digestValue := ctx.createNamespacedElement(reference, DigestValueTag)
digestValue.SetText(base64.StdEncoding.EncodeToString(digest))
return signedInfo, nil
}
func (ctx *SigningContext) ConstructSignature(el *etree.Element, enveloped bool) (*etree.Element, error) {
signedInfo, err := ctx.constructSignedInfo(el, enveloped)
if err != nil {
return nil, err
}
sig := &etree.Element{
Tag: SignatureTag,
Space: ctx.Prefix,
}
xmlns := "xmlns"
if ctx.Prefix != "" {
xmlns += ":" + ctx.Prefix
}
sig.CreateAttr(xmlns, Namespace)
sig.AddChild(signedInfo)
// When using xml-c14n11 (ie, non-exclusive canonicalization) the canonical form
// of the SignedInfo must declare all namespaces that are in scope at it's final
// enveloped location in the document. In order to do that, we're going to construct
// a series of cascading NSContexts to capture namespace declarations:
// First get the context surrounding the element we are signing.
rootNSCtx, err := etreeutils.NSBuildParentContext(el)
if err != nil {
return nil, err
}
// Then capture any declarations on the element itself.
elNSCtx, err := rootNSCtx.SubContext(el)
if err != nil {
return nil, err
}
// Followed by declarations on the Signature (which we just added above)
sigNSCtx, err := elNSCtx.SubContext(sig)
if err != nil {
return nil, err
}
// Finally detatch the SignedInfo in order to capture all of the namespace
// declarations in the scope we've constructed.
detatchedSignedInfo, err := etreeutils.NSDetatch(sigNSCtx, signedInfo)
if err != nil {
return nil, err
}
digest, err := ctx.digestElement(detatchedSignedInfo)
if err != nil {
return nil, err
}
key, cert, err := ctx.KeyStore.GetKeyPair()
if err != nil {
return nil, err
}
rawSignature, err := rsa.SignPKCS1v15(rand.Reader, key, ctx.Hash, digest)
if err != nil {
return nil, err
}
signatureValue := ctx.createNamespacedElement(sig, SignatureValueTag)
signatureValue.SetText(base64.StdEncoding.EncodeToString(rawSignature))
if !ctx.SkipKeyInfo {
keyInfo := ctx.createNamespacedElement(sig, KeyInfoTag)
x509Data := ctx.createNamespacedElement(keyInfo, X509DataTag)
certs := [][]byte{cert}
if cs, ok := ctx.KeyStore.(X509ChainStore); ok {
certs, err = cs.GetChain()
if err != nil {
return nil, err
}
}
for _, cert := range certs {
x509Certificate := ctx.createNamespacedElement(x509Data, X509CertificateTag)
x509Certificate.SetText(base64.StdEncoding.EncodeToString(cert))
}
}
return sig, nil
}
func (ctx *SigningContext) createNamespacedElement(el *etree.Element, tag string) *etree.Element {
child := el.CreateElement(tag)
child.Space = ctx.Prefix
return child
}
func (ctx *SigningContext) SignEnveloped(el *etree.Element) (*etree.Element, error) {
sig, err := ctx.ConstructSignature(el, true)
if err != nil {
return nil, err
}
ret := el.Copy()
ret.Child = append(ret.Child, sig)
return ret, nil
}
func (ctx *SigningContext) GetSignatureMethodIdentifier() string {
if ident, ok := signatureMethodIdentifiers[ctx.Hash]; ok {
return ident
}
return ""
}
func (ctx *SigningContext) GetDigestAlgorithmIdentifier() string {
if ident, ok := digestAlgorithmIdentifiers[ctx.Hash]; ok {
return ident
}
return ""
}
// Useful for signing query string (including DEFLATED AuthnRequest) when
// using HTTP-Redirect to make a signed request.
// See 3.4.4.1 DEFLATE Encoding of https://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf
func (ctx *SigningContext) SignString(content string) ([]byte, error) {
hash := ctx.Hash.New()
if ln, err := hash.Write([]byte(content)); err != nil {
return nil, fmt.Errorf("error calculating hash: %v", err)
} else if ln < 1 {
return nil, fmt.Errorf("zero length hash")
}
digest := hash.Sum(nil)
var signature []byte
if key, _, err := ctx.KeyStore.GetKeyPair(); err != nil {
return nil, fmt.Errorf("unable to fetch key for signing: %v", err)
} else if signature, err = rsa.SignPKCS1v15(rand.Reader, key, ctx.Hash, digest); err != nil {
return nil, fmt.Errorf("error signing: %v", err)
}
return signature, nil
}