| 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 | package appmanifest |
| 18 | |
| 19 | import ( |
| 20 | "bytes" |
| 21 | "crypto" |
| 22 | "encoding/base64" |
| 23 | "encoding/hex" |
| 24 | "errors" |
| 25 | "fmt" |
| 26 | |
| 27 | "github.com/beevik/etree" |
| 28 | |
| 29 | "github.com/sassoftware/relic/v7/lib/certloader" |
| 30 | "github.com/sassoftware/relic/v7/lib/pkcs7" |
| 31 | "github.com/sassoftware/relic/v7/lib/pkcs9" |
| 32 | "github.com/sassoftware/relic/v7/lib/xmldsig" |
| 33 | ) |
| 34 | |
| 35 | const ( |
| 36 | NsMsRel = "http://schemas.microsoft.com/windows/rel/2005/reldata" |
| 37 | NsMpeg21 = "urn:mpeg:mpeg21:2003:01-REL-R-NS" |
| 38 | NsAuthenticode = "http://schemas.microsoft.com/windows/pki/2005/Authenticode" |
| 39 | ) |
| 40 | |
| 41 | type SignedManifest struct { |
| 42 | ManifestSignature |
| 43 | Signed []byte |
| 44 | EncryptedDigest []byte |
| 45 | } |
| 46 | |
| 47 | // Sign an application manifest |
| 48 | func Sign(manifest []byte, cert *certloader.Certificate, opts crypto.SignerOpts) (*SignedManifest, error) { |
| 49 | doc := etree.NewDocument() |
| 50 | if err := doc.ReadFromString(string(manifest)); err != nil { |
| 51 | return nil, err |
| 52 | } |
| 53 | root := doc.Root() |
| 54 | // Update signer-related attributes |
| 55 | asi, err := setAssemblyIdentity(root, cert) |
| 56 | if err != nil { |
| 57 | return nil, err |
| 58 | } |
| 59 | subjectName, err := setPublisherIdentity(root, cert) |
| 60 | if err != nil { |
| 61 | return nil, err |
| 62 | } |
| 63 | // Primary signature |
| 64 | sigopts := xmldsig.SignOptions{MsCompatHashNames: true, IncludeKeyValue: true} |
| 65 | if err := xmldsig.Sign(root, root, opts.HashFunc(), cert.Signer(), cert.Chain(), sigopts); err != nil { |
| 66 | return nil, err |
| 67 | } |
| 68 | sig, keyinfo := setSigIds(root, "StrongNameSignature", "StrongNameKeyInfo") |
| 69 | // Create authenticode structure |
| 70 | manifestHash := makeManifestHash(sig) |
| 71 | license, sigDestNode := makeLicense(asi, subjectName, manifestHash) |
| 72 | // Sign authenticode structure |
| 73 | sigopts.IncludeX509 = true |
| 74 | if err := xmldsig.Sign(license, sigDestNode, opts.HashFunc(), cert.Signer(), cert.Chain(), sigopts); err != nil { |
| 75 | return nil, err |
| 76 | } |
| 77 | aSig, _ := setSigIds(sigDestNode, "AuthenticodeSignature", "") |
| 78 | // Attach authenticode to the primary document |
| 79 | license.AddChild(sigDestNode) |
| 80 | reldata := keyinfo.CreateElement("msrel:RelData") |
| 81 | reldata.CreateAttr("xmlns:msrel", NsMsRel) |
| 82 | reldata.AddChild(license) |
| 83 | // Serialize |
| 84 | signed, err := doc.WriteToBytes() |
| 85 | if err != nil { |
| 86 | return nil, err |
| 87 | } |
| 88 | // Get authenticode signature value for timestamping |
| 89 | encryptedDigest, _ := base64.StdEncoding.DecodeString(aSig.SelectElement("SignatureValue").Text()) |
| 90 | return &SignedManifest{ |
| 91 | Signed: signed, |
| 92 | EncryptedDigest: encryptedDigest, |
| 93 | ManifestSignature: ManifestSignature{ |
| 94 | Signature: &pkcs9.TimestampedSignature{Signature: pkcs7.Signature{ |
| 95 | Certificate: cert.Leaf, |
| 96 | Intermediates: cert.Chain(), |
| 97 | }}, |
| 98 | AssemblyName: asi.SelectAttrValue("name", ""), |
| 99 | AssemblyVersion: asi.SelectAttrValue("version", ""), |
| 100 | Hash: opts.HashFunc(), |
| 101 | PublicKeyToken: asi.SelectAttrValue("publicKeyToken", ""), |
| 102 | }}, nil |
| 103 | } |
| 104 | |
| 105 | // Update the assemblyIdentity element with the actual signer public key. Only |
| 106 | // the top-level one is updated, not the ones underneath individual manifest |
| 107 | // entries. |
| 108 | func setAssemblyIdentity(root *etree.Element, cert *certloader.Certificate) (*etree.Element, error) { |
| 109 | token, err := PublicKeyToken(cert.Leaf.PublicKey) |
| 110 | if err != nil { |
| 111 | return nil, err |
| 112 | } |
| 113 | asi := root.SelectElement("assemblyIdentity") |
| 114 | if asi == nil { |
| 115 | return nil, errors.New("manifest has no top-level assemblyIdentity element") |
| 116 | } |
| 117 | asi.CreateAttr("publicKeyToken", token) |
| 118 | return asi, nil |
| 119 | } |
| 120 | |
| 121 | // Add/replace the publisherIdentity element |
| 122 | func setPublisherIdentity(root *etree.Element, cert *certloader.Certificate) (string, error) { |
| 123 | // add or replace publisherIdentity |
| 124 | subjectName, issuerKeyHash, err := PublisherIdentity(cert) |
| 125 | if err != nil { |
| 126 | return "", err |
| 127 | } |
| 128 | xmldsig.RemoveElements(root, "publisherIdentity") |
| 129 | ident := root.CreateElement("publisherIdentity") |
| 130 | ident.CreateAttr("name", subjectName) |
| 131 | ident.CreateAttr("issuerKeyHash", issuerKeyHash) |
| 132 | return subjectName, nil |
| 133 | } |
| 134 | |
| 135 | // Create the "license" block that goes inside the inner signature |
| 136 | func makeLicense(asi *etree.Element, subjectName, manifestHash string) (*etree.Element, *etree.Element) { |
| 137 | license := etree.NewElement("r:license") |
| 138 | license.CreateAttr("xmlns:r", NsMpeg21) |
| 139 | license.CreateAttr("xmlns:as", NsAuthenticode) |
| 140 | |
| 141 | grant := license.CreateElement("r:grant") |
| 142 | minfo := grant.CreateElement("as:ManifestInformation") |
| 143 | minfo.CreateAttr("Hash", manifestHash) |
| 144 | minfo.CreateAttr("Description", "") |
| 145 | minfo.CreateAttr("Url", "") |
| 146 | massy := asi.Copy() |
| 147 | massy.Space = "as" |
| 148 | minfo.AddChild(massy) |
| 149 | grant.CreateElement("as:SignedBy") |
| 150 | grant.CreateElement("as:AuthenticodePublisher").CreateElement("as:X509SubjectName").SetText(subjectName) |
| 151 | |
| 152 | issuer := license.CreateElement("r:issuer") |
| 153 | return license, issuer |
| 154 | } |
| 155 | |
| 156 | // ManifestInformation contains a hash value which is, for some inane reason, |
| 157 | // the same hash that the outer signature references but in reverse byte order. |
| 158 | func makeManifestHash(sig *etree.Element) string { |
| 159 | dv := sig.FindElement(".//DigestValue") |
| 160 | blob, _ := base64.StdEncoding.DecodeString(dv.Text()) |
| 161 | for i := 0; i < len(blob)/2; i++ { |
| 162 | j := len(blob) - i - 1 |
| 163 | blob[i], blob[j] = blob[j], blob[i] |
| 164 | } |
| 165 | return hex.EncodeToString(blob) |
| 166 | } |
| 167 | |
| 168 | // Set Id attributes on signature elements |
| 169 | func setSigIds(root *etree.Element, sigName, keyinfoName string) (sig, keyinfo *etree.Element) { |
| 170 | sig = root.SelectElement("Signature") |
| 171 | if sigName != "" { |
| 172 | sig.CreateAttr("Id", sigName) |
| 173 | } |
| 174 | keyinfo = sig.SelectElement("KeyInfo") |
| 175 | if keyinfoName != "" { |
| 176 | keyinfo.CreateAttr("Id", keyinfoName) |
| 177 | } |
| 178 | return sig, keyinfo |
| 179 | } |
| 180 | |
| 181 | // Attach a timestamp counter-signature |
| 182 | func (m *SignedManifest) AddTimestamp(token *pkcs7.ContentInfoSignedData) error { |
| 183 | doc := etree.NewDocument() |
| 184 | if err := doc.ReadFromString(string(m.Signed)); err != nil { |
| 185 | return err |
| 186 | } |
| 187 | aSig := doc.Root().FindElement("Signature/KeyInfo/msrel:RelData/r:license/r:issuer/Signature") |
| 188 | if aSig == nil { |
| 189 | return errors.New("manifest has no authenticode signature") |
| 190 | } |
| 191 | siblob, err := token.Marshal() |
| 192 | if err != nil { |
| 193 | return err |
| 194 | } |
| 195 | lines := (47 + len(siblob)) / 48 |
| 196 | buf := bytes.NewBuffer(make([]byte, 0, (64+2)*lines)) |
| 197 | for len(siblob) > 0 { |
| 198 | n := len(siblob) |
| 199 | if n > 48 { |
| 200 | n = 48 |
| 201 | } |
| 202 | chunk := siblob[:n] |
| 203 | siblob = siblob[n:] |
| 204 | |
| 205 | buf.WriteString(base64.StdEncoding.EncodeToString(chunk)) |
| 206 | buf.WriteString("\r\n") |
| 207 | } |
| 208 | aSig.CreateElement("Object").CreateElement("as:Timestamp").SetText(buf.String()) |
| 209 | signed, err := doc.WriteToBytes() |
| 210 | if err != nil { |
| 211 | return err |
| 212 | } |
| 213 | cs, err := VerifyTimestamp(token, m.EncryptedDigest, m.Signature.Intermediates) |
| 214 | if err != nil { |
| 215 | return fmt.Errorf("failed to validate timestamp: %w", err) |
| 216 | } |
| 217 | m.Signed = signed |
| 218 | m.Signature.CounterSignature = cs |
| 219 | return nil |
| 220 | } |