| 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 vsix |
| 18 | |
| 19 | import ( |
| 20 | "crypto" |
| 21 | "crypto/hmac" |
| 22 | "crypto/x509" |
| 23 | "encoding/base32" |
| 24 | "encoding/base64" |
| 25 | "encoding/xml" |
| 26 | "errors" |
| 27 | "fmt" |
| 28 | "io" |
| 29 | "path" |
| 30 | "sort" |
| 31 | "strings" |
| 32 | |
| 33 | "github.com/beevik/etree" |
| 34 | |
| 35 | "github.com/sassoftware/relic/v7/lib/certloader" |
| 36 | "github.com/sassoftware/relic/v7/lib/pkcs7" |
| 37 | "github.com/sassoftware/relic/v7/lib/pkcs9" |
| 38 | "github.com/sassoftware/relic/v7/lib/xmldsig" |
| 39 | "github.com/sassoftware/relic/v7/signers" |
| 40 | "github.com/sassoftware/relic/v7/signers/sigerrors" |
| 41 | ) |
| 42 | |
| 43 | type oxmlManifest struct { |
| 44 | References []reference `xml:"Manifest>Reference"` |
| 45 | Properties []property `xml:"SignatureProperties>SignatureProperty"` |
| 46 | } |
| 47 | |
| 48 | type reference struct { |
| 49 | URI string `xml:",attr"` |
| 50 | Transforms []method `xml:"Transforms>Transform"` |
| 51 | DigestMethod method |
| 52 | DigestValue string |
| 53 | } |
| 54 | |
| 55 | type method struct { |
| 56 | Algorithm string `xml:",attr"` |
| 57 | } |
| 58 | |
| 59 | type property struct { |
| 60 | Id string `xml:",attr"` |
| 61 | SignatureTimeFormat string `xml:"SignatureTime>Format"` |
| 62 | SignatureTimeValue string `xml:"SignatureTime>Value"` |
| 63 | } |
| 64 | |
| 65 | func checkManifest(files zipFiles, manifest *etree.Element) error { |
| 66 | doc := etree.NewDocument() |
| 67 | doc.SetRoot(manifest.Copy()) |
| 68 | blob, err := doc.WriteToBytes() |
| 69 | if err != nil { |
| 70 | return fmt.Errorf("validation failed: %w", err) |
| 71 | } |
| 72 | var m oxmlManifest |
| 73 | if err := xml.Unmarshal(blob, &m); err != nil { |
| 74 | return fmt.Errorf("validation failed: %w", err) |
| 75 | } |
| 76 | for _, ref := range m.References { |
| 77 | p := path.Join("./" + ref.URI) |
| 78 | i := strings.IndexByte(p, '?') |
| 79 | if i >= 0 { |
| 80 | p = p[:i] |
| 81 | } |
| 82 | zf := files[p] |
| 83 | if zf == nil { |
| 84 | return fmt.Errorf("validation failed: file not found: %s", p) |
| 85 | } |
| 86 | f, err := zf.Open() |
| 87 | if err != nil { |
| 88 | return fmt.Errorf("validation failed: %w", err) |
| 89 | } |
| 90 | _, hash := xmldsig.HashAlgorithm(ref.DigestMethod.Algorithm) |
| 91 | if !hash.Available() { |
| 92 | return errors.New("validation failed: unsupported digest algorithm") |
| 93 | } |
| 94 | d := hash.New() |
| 95 | if _, err := io.Copy(d, f); err != nil { |
| 96 | return err |
| 97 | } |
| 98 | refCalc := d.Sum(nil) |
| 99 | refv, err := base64.StdEncoding.DecodeString(ref.DigestValue) |
| 100 | if err != nil { |
| 101 | return errors.New("validation failed: invalid digest") |
| 102 | } |
| 103 | if !hmac.Equal(refv, refCalc) { |
| 104 | return fmt.Errorf("validation failed: digest mismatch for %s: calculated %x, found %x", p, refCalc, refv) |
| 105 | } |
| 106 | } |
| 107 | return nil |
| 108 | } |
| 109 | |
| 110 | func checkTimestamp(root *etree.Element, encryptedDigest []byte) (*pkcs9.CounterSignature, error) { |
| 111 | tsEl := root.FindElement("Object/TimeStamp/EncodedTime") |
| 112 | if tsEl == nil { |
| 113 | return nil, nil |
| 114 | } |
| 115 | blob, err := base64.StdEncoding.DecodeString(tsEl.Text()) |
| 116 | if err != nil { |
| 117 | return nil, fmt.Errorf("timestamp check failed: %w", err) |
| 118 | } |
| 119 | tst, err := pkcs7.Unmarshal(blob) |
| 120 | if err != nil { |
| 121 | return nil, fmt.Errorf("timestamp check failed: %w", err) |
| 122 | } |
| 123 | return pkcs9.Verify(tst, encryptedDigest, nil) |
| 124 | } |
| 125 | |
| 126 | // looks sorta like the official vsixsigntool output, close enough |
| 127 | func calcFileName(cert *x509.Certificate) string { |
| 128 | d := crypto.SHA1.New() |
| 129 | d.Write(cert.Raw) |
| 130 | sum := d.Sum(nil) |
| 131 | return strings.ToLower(base32.StdEncoding.EncodeToString(sum))[:25] |
| 132 | } |
| 133 | |
| 134 | func readSignature(files zipFiles) ([]byte, []*x509.Certificate, error) { |
| 135 | top := relPath("") |
| 136 | if files[top] == nil { |
| 137 | return nil, nil, sigerrors.NotSignedError{Type: "vsix"} |
| 138 | } |
| 139 | // top rels file |
| 140 | r, err := parseRels(files, top) |
| 141 | if err != nil { |
| 142 | return nil, nil, err |
| 143 | } |
| 144 | origin := r.Find(sigOriginType) |
| 145 | if origin == "" { |
| 146 | return nil, nil, sigerrors.NotSignedError{Type: "vsix"} |
| 147 | } |
| 148 | // signature rels file |
| 149 | r, err = parseRels(files, relPath(origin)) |
| 150 | if err != nil { |
| 151 | return nil, nil, err |
| 152 | } |
| 153 | sigpath := r.Find(sigType) |
| 154 | if sigpath == "" { |
| 155 | return nil, nil, sigerrors.NotSignedError{Type: "vsix"} |
| 156 | } |
| 157 | sigblob, err := readZip(files, sigpath) |
| 158 | if err != nil { |
| 159 | return nil, nil, err |
| 160 | } |
| 161 | // certificates (optional) |
| 162 | var certs []*x509.Certificate |
| 163 | if files[relPath(sigpath)] != nil { |
| 164 | r, err := parseRels(files, relPath(sigpath)) |
| 165 | if err != nil { |
| 166 | return nil, nil, err |
| 167 | } |
| 168 | for _, rel := range r.Relationship { |
| 169 | if rel.Type != certType { |
| 170 | continue |
| 171 | } |
| 172 | p := path.Clean("./" + rel.Target) |
| 173 | blob, err := readZip(files, p) |
| 174 | if err != nil { |
| 175 | return nil, nil, err |
| 176 | } |
| 177 | certs2, err := x509.ParseCertificates(blob) |
| 178 | if err != nil { |
| 179 | return nil, nil, fmt.Errorf("failed to parse certificate %s: %w", p, err) |
| 180 | } |
| 181 | certs = append(certs, certs2...) |
| 182 | } |
| 183 | } |
| 184 | return sigblob, certs, nil |
| 185 | } |
| 186 | |
| 187 | func (m *mangler) makeSignature(cert *certloader.Certificate, opts signers.SignOpts, detachCerts bool) ([]byte, error) { |
| 188 | hashUri := xmldsig.HashUris[opts.Hash] |
| 189 | if hashUri == "" { |
| 190 | return nil, errors.New("unsupported digest algorithm") |
| 191 | } |
| 192 | pkg := etree.NewElement("Object") |
| 193 | pkg.CreateAttr("Id", "idPackageObject") |
| 194 | // file manifest |
| 195 | manifest := pkg.CreateElement("Manifest") |
| 196 | names := make([]string, 0, len(m.digests)) |
| 197 | for name := range m.digests { |
| 198 | names = append(names, name) |
| 199 | } |
| 200 | sort.Strings(names) |
| 201 | for _, name := range names { |
| 202 | digest := m.digests[name] |
| 203 | ctype := m.ctypes.Find(name) |
| 204 | if ctype == "" { |
| 205 | ext := path.Ext(path.Base(name)) |
| 206 | if ext[0] == '.' { |
| 207 | ctype = contentTypes[ext[1:]] |
| 208 | } |
| 209 | } |
| 210 | if ctype == "" { |
| 211 | ctype = defaultContentType |
| 212 | } |
| 213 | ref := manifest.CreateElement("Reference") |
| 214 | ref.CreateAttr("URI", "/"+name+"?ContentType="+ctype) |
| 215 | ref.CreateElement("DigestMethod").CreateAttr("Algorithm", hashUri) |
| 216 | ref.CreateElement("DigestValue").SetText(base64.StdEncoding.EncodeToString(digest)) |
| 217 | } |
| 218 | // signature time |
| 219 | props := pkg.CreateElement("SignatureProperties") |
| 220 | proptime := props.CreateElement("SignatureProperty") |
| 221 | proptime.CreateAttr("Id", "idSignatureTime") |
| 222 | proptime.CreateAttr("Target", "") |
| 223 | sigtime := proptime.CreateElement("SignatureTime") |
| 224 | sigtime.CreateAttr("xmlns", nsDigSig) |
| 225 | sigtime.CreateElement("Format").SetText(tsFormatXML) |
| 226 | sigtime.CreateElement("Value").SetText(opts.Time.Format(tsFormatGo)) |
| 227 | // sign |
| 228 | xopts := xmldsig.SignOptions{UseRecC14n: true, IncludeKeyValue: true} |
| 229 | if !detachCerts { |
| 230 | xopts.IncludeX509 = true |
| 231 | } |
| 232 | sigel, err := xmldsig.SignEnveloping(pkg, opts.Hash, cert.Signer(), cert.Chain(), xopts) |
| 233 | if err != nil { |
| 234 | return nil, err |
| 235 | } |
| 236 | // timestamp |
| 237 | if cert.Timestamper != nil { |
| 238 | encryptedDigest, _ := base64.StdEncoding.DecodeString(sigel.SelectElement("SignatureValue").Text()) |
| 239 | req := &pkcs9.Request{EncryptedDigest: encryptedDigest, Hash: opts.Hash} |
| 240 | tst, err := cert.Timestamper.Timestamp(opts.Context(), req) |
| 241 | if err != nil { |
| 242 | return nil, fmt.Errorf("failed to timestamp signature: %w", err) |
| 243 | } |
| 244 | blob, err := tst.Marshal() |
| 245 | if err != nil { |
| 246 | return nil, fmt.Errorf("failed to timestamp signature: %w", err) |
| 247 | } |
| 248 | tsob := sigel.CreateElement("Object") |
| 249 | tsob.CreateAttr("xmlns", xmldsig.NsXMLDsig) |
| 250 | ts := tsob.CreateElement("TimeStamp") |
| 251 | ts.CreateAttr("xmlns", nsDigSig) |
| 252 | ts.CreateAttr("Id", "idSignatureTimestamp") |
| 253 | ts.CreateElement("Comment") |
| 254 | ts.CreateElement("EncodedTime").SetText(base64.StdEncoding.EncodeToString(blob)) |
| 255 | } |
| 256 | doc := etree.NewDocument() |
| 257 | doc.SetRoot(sigel) |
| 258 | return doc.WriteToBytes() |
| 259 | } |