| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | // |
| 16 | |
| 17 | // Implements a useful subset of the xmldsig specification for creating |
| 18 | // signatures over XML documents. |
| 19 | package xmldsig |
| 20 | |
| 21 | import ( |
| 22 | "crypto" |
| 23 | "crypto/ecdsa" |
| 24 | "crypto/rand" |
| 25 | "crypto/rsa" |
| 26 | "crypto/x509" |
| 27 | "encoding/base64" |
| 28 | "errors" |
| 29 | "fmt" |
| 30 | "math/big" |
| 31 | |
| 32 | "github.com/sassoftware/relic/v7/lib/x509tools" |
| 33 | |
| 34 | "github.com/beevik/etree" |
| 35 | ) |
| 36 | |
| 37 | type SignOptions struct { |
| 38 | // Use non-standard namespace for SHA-256 found in Microsoft ClickOnce manifests |
| 39 | MsCompatHashNames bool |
| 40 | // Use REC namespace for c14n method instead of the finalized one |
| 41 | UseRecC14n bool |
| 42 | // Add the X509 certificate chain to the KeyInfo |
| 43 | IncludeX509 bool |
| 44 | // Add a KeyValue element with the public key |
| 45 | IncludeKeyValue bool |
| 46 | } |
| 47 | |
| 48 | func (s SignOptions) c14nNamespace() string { |
| 49 | if s.UseRecC14n { |
| 50 | return AlgXMLExcC14nRec |
| 51 | } else { |
| 52 | return AlgXMLExcC14n |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | // Create an enveloped signature from the document rooted at "root", replacing |
| 57 | // any existing signature and adding it as a last child of "parent". |
| 58 | func Sign(root, parent *etree.Element, hash crypto.Hash, privKey crypto.Signer, certs []*x509.Certificate, opts SignOptions) error { |
| 59 | pubKey := privKey.Public() |
| 60 | if len(certs) < 1 || !x509tools.SameKey(pubKey, certs[0].PublicKey) { |
| 61 | return errors.New("xmldsig: first certificate must match private key") |
| 62 | } |
| 63 | RemoveElements(parent, "Signature") |
| 64 | // canonicalize the enveloping document and digest it |
| 65 | refDigest, err := hashCanon(root, hash) |
| 66 | if err != nil { |
| 67 | return err |
| 68 | } |
| 69 | hashAlg, sigAlg, err := hashAlgs(hash, pubKey, opts) |
| 70 | if err != nil { |
| 71 | return err |
| 72 | } |
| 73 | // build a signedinfo that references the enveloping document |
| 74 | signature := parent.CreateElement("Signature") |
| 75 | signature.CreateAttr("xmlns", NsXMLDsig) |
| 76 | signedinfo := buildSignedInfo(signature, "", hashAlg, sigAlg, refDigest, opts) |
| 77 | return finishSignature(signature, signedinfo, hash, privKey, certs, opts) |
| 78 | } |
| 79 | |
| 80 | // Build an enveloping Signature document around the given Object element |
| 81 | func SignEnveloping(object *etree.Element, hash crypto.Hash, privKey crypto.Signer, certs []*x509.Certificate, opts SignOptions) (*etree.Element, error) { |
| 82 | pubKey := privKey.Public() |
| 83 | if len(certs) < 1 || !x509tools.SameKey(pubKey, certs[0].PublicKey) { |
| 84 | return nil, errors.New("xmldsig: first certificate must match private key") |
| 85 | } |
| 86 | // insert the object into the signature element before canonicalizing so |
| 87 | // that the namespace gets pushed down properly |
| 88 | signature := etree.NewElement("Signature") |
| 89 | signature.CreateAttr("xmlns", NsXMLDsig) |
| 90 | signature.AddChild(object) |
| 91 | refDigest, err := hashCanon(object, hash) |
| 92 | if err != nil { |
| 93 | return nil, err |
| 94 | } |
| 95 | hashAlg, sigAlg, err := hashAlgs(hash, pubKey, opts) |
| 96 | if err != nil { |
| 97 | return nil, err |
| 98 | } |
| 99 | if object.Tag != "Object" { |
| 100 | return nil, errors.New("object must have tag \"Object\"") |
| 101 | } |
| 102 | refId := object.SelectAttrValue("Id", "") |
| 103 | if refId == "" { |
| 104 | return nil, errors.New("object lacks an Id attribute") |
| 105 | } |
| 106 | // build a signedinfo that references the enveloping document |
| 107 | signedinfo := buildSignedInfo(signature, refId, hashAlg, sigAlg, refDigest, opts) |
| 108 | // canonicalize the signedinfo section and sign it |
| 109 | if err := finishSignature(signature, signedinfo, hash, privKey, certs, opts); err != nil { |
| 110 | return nil, err |
| 111 | } |
| 112 | signature.RemoveChild(object) |
| 113 | signature.AddChild(object) |
| 114 | return signature, nil |
| 115 | } |
| 116 | |
| 117 | func buildSignedInfo(signature *etree.Element, refId, hashAlg, sigAlg string, refDigest []byte, opts SignOptions) *etree.Element { |
| 118 | signedinfo := signature.CreateElement("SignedInfo") |
| 119 | signedinfo.CreateElement("CanonicalizationMethod").CreateAttr("Algorithm", opts.c14nNamespace()) |
| 120 | signedinfo.CreateElement("SignatureMethod").CreateAttr("Algorithm", sigAlg) |
| 121 | reference := signedinfo.CreateElement("Reference") |
| 122 | if refId == "" { |
| 123 | reference.CreateAttr("URI", "") |
| 124 | } else { |
| 125 | reference.CreateAttr("URI", "#"+refId) |
| 126 | reference.CreateAttr("Type", NsXMLDsig+"Object") |
| 127 | } |
| 128 | transforms := reference.CreateElement("Transforms") |
| 129 | if refId == "" { |
| 130 | transforms.CreateElement("Transform").CreateAttr("Algorithm", AlgDsigEnvelopedSignature) |
| 131 | } |
| 132 | transforms.CreateElement("Transform").CreateAttr("Algorithm", opts.c14nNamespace()) |
| 133 | reference.CreateElement("DigestMethod").CreateAttr("Algorithm", hashAlg) |
| 134 | reference.CreateElement("DigestValue").SetText(base64.StdEncoding.EncodeToString(refDigest)) |
| 135 | return signedinfo |
| 136 | } |
| 137 | |
| 138 | func finishSignature(signature, signedinfo *etree.Element, hash crypto.Hash, privKey crypto.Signer, certs []*x509.Certificate, opts SignOptions) error { |
| 139 | siDigest, err := hashCanon(signedinfo, hash) |
| 140 | if err != nil { |
| 141 | return err |
| 142 | } |
| 143 | sig, err := privKey.Sign(rand.Reader, siDigest, hash) |
| 144 | if err != nil { |
| 145 | return err |
| 146 | } |
| 147 | // build the rest of the signature element |
| 148 | if _, ok := privKey.Public().(*ecdsa.PublicKey); ok { |
| 149 | // reformat the signature without ASN.1 structure |
| 150 | esig, err := x509tools.UnmarshalEcdsaSignature(sig) |
| 151 | if err != nil { |
| 152 | return err |
| 153 | } |
| 154 | sig = esig.Pack() |
| 155 | } |
| 156 | signature.CreateElement("SignatureValue").SetText(base64.StdEncoding.EncodeToString(sig)) |
| 157 | keyinfo := etree.NewElement("KeyInfo") |
| 158 | if opts.IncludeKeyValue { |
| 159 | if err := addKeyInfo(keyinfo, privKey.Public()); err != nil { |
| 160 | return err |
| 161 | } |
| 162 | } |
| 163 | if opts.IncludeX509 && len(certs) > 0 { |
| 164 | addCerts(keyinfo, certs) |
| 165 | } |
| 166 | if len(keyinfo.Child) > 0 { |
| 167 | signature.AddChild(keyinfo) |
| 168 | } |
| 169 | return nil |
| 170 | } |
| 171 | |
| 172 | func hashCanon(root *etree.Element, hash crypto.Hash) ([]byte, error) { |
| 173 | canon, err := SerializeCanonical(root) |
| 174 | if err != nil { |
| 175 | return nil, fmt.Errorf("xmldsig: %w", err) |
| 176 | } |
| 177 | d := hash.New() |
| 178 | d.Write(canon) |
| 179 | return d.Sum(nil), nil |
| 180 | } |
| 181 | |
| 182 | // Remove all child elements with this tag from the element |
| 183 | func RemoveElements(root *etree.Element, tag string) { |
| 184 | for i := 0; i < len(root.Child); { |
| 185 | token := root.Child[i] |
| 186 | if elem, ok := token.(*etree.Element); ok && elem.Tag == tag { |
| 187 | root.Child = append(root.Child[:i], root.Child[i+1:]...) |
| 188 | } else { |
| 189 | i++ |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | // Determine algorithm URIs for hashing and signing |
| 195 | func hashAlgs(hash crypto.Hash, pubKey crypto.PublicKey, opts SignOptions) (string, string, error) { |
| 196 | hashName := hashNames[hash] |
| 197 | if hashName == "" { |
| 198 | return "", "", errors.New("unsupported hash type") |
| 199 | } |
| 200 | var pubName string |
| 201 | switch pubKey.(type) { |
| 202 | case *rsa.PublicKey: |
| 203 | pubName = "rsa" |
| 204 | case *ecdsa.PublicKey: |
| 205 | pubName = "ecdsa" |
| 206 | default: |
| 207 | return "", "", errors.New("unsupported key type") |
| 208 | } |
| 209 | var hashAlg, sigAlg string |
| 210 | if opts.MsCompatHashNames { |
| 211 | hashAlg = NsXMLDsig + hashName |
| 212 | } else { |
| 213 | hashAlg = HashUris[hash] |
| 214 | } |
| 215 | if pubName == "rsa" && (hashName == "sha1" || opts.MsCompatHashNames) { |
| 216 | sigAlg = NsXMLDsig + pubName + "-" + hashName |
| 217 | } else { |
| 218 | sigAlg = NsXMLDsigMore + pubName + "-" + hashName |
| 219 | } |
| 220 | return hashAlg, sigAlg, nil |
| 221 | } |
| 222 | |
| 223 | // Add public key and optional X509 certificate chain to KeyInfo |
| 224 | func addKeyInfo(keyinfo *etree.Element, pubKey crypto.PublicKey) error { |
| 225 | keyvalue := keyinfo.CreateElement("KeyValue") |
| 226 | switch k := pubKey.(type) { |
| 227 | case *rsa.PublicKey: |
| 228 | e := big.NewInt(int64(k.E)) |
| 229 | rkv := keyvalue.CreateElement("RSAKeyValue") |
| 230 | rkv.CreateElement("Modulus").SetText(base64.StdEncoding.EncodeToString(k.N.Bytes())) |
| 231 | rkv.CreateElement("Exponent").SetText(base64.StdEncoding.EncodeToString(e.Bytes())) |
| 232 | case *ecdsa.PublicKey: |
| 233 | curve, err := x509tools.CurveByCurve(k.Curve) |
| 234 | if err != nil { |
| 235 | return err |
| 236 | } |
| 237 | curveUrn := fmt.Sprintf("urn:oid:%s", curve.Oid) |
| 238 | ekv := keyvalue.CreateElement("ECDSAKeyValue") |
| 239 | ekv.CreateElement("DomainParameters").CreateElement("NamedCurve").CreateAttr("URN", curveUrn) |
| 240 | pk := ekv.CreateElement("PublicKey") |
| 241 | x := pk.CreateElement("X") |
| 242 | x.CreateAttr("Value", k.X.String()) |
| 243 | x.CreateAttr("xmlns:xsi", NsXsi) |
| 244 | x.CreateAttr("xsi:type", "PrimeFieldElemType") |
| 245 | y := pk.CreateElement("Y") |
| 246 | y.CreateAttr("Value", k.Y.String()) |
| 247 | y.CreateAttr("xmlns:xsi", NsXsi) |
| 248 | y.CreateAttr("xsi:type", "PrimeFieldElemType") |
| 249 | default: |
| 250 | return errors.New("unsupported key type") |
| 251 | } |
| 252 | return nil |
| 253 | } |
| 254 | |
| 255 | func addCerts(keyinfo *etree.Element, certs []*x509.Certificate) { |
| 256 | x509data := keyinfo.CreateElement("X509Data") |
| 257 | for _, cert := range certs { |
| 258 | x509data.CreateElement("X509Certificate").SetText(base64.StdEncoding.EncodeToString(cert.Raw)) |
| 259 | } |
| 260 | } |