| 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 apk |
| 18 | |
| 19 | import ( |
| 20 | "crypto" |
| 21 | "crypto/x509" |
| 22 | "fmt" |
| 23 | ) |
| 24 | |
| 25 | type apkSigner struct { |
| 26 | SignedData apkRaw |
| 27 | Signatures []apkSignature |
| 28 | PublicKey []byte |
| 29 | } |
| 30 | |
| 31 | type apkSignedData struct { |
| 32 | Digests []apkDigest |
| 33 | Certificates [][]byte |
| 34 | Attributes []apkAttribute |
| 35 | } |
| 36 | |
| 37 | type apkAttribute struct { |
| 38 | ID uint32 |
| 39 | Value []byte |
| 40 | } |
| 41 | |
| 42 | type apkSignature apkAttribute |
| 43 | type apkDigest apkAttribute |
| 44 | |
| 45 | func (sd *apkSignedData) ParseCertificates() (certs []*x509.Certificate, err error) { |
| 46 | certs = make([]*x509.Certificate, len(sd.Certificates)) |
| 47 | for i, der := range sd.Certificates { |
| 48 | certs[i], err = x509.ParseCertificate(der) |
| 49 | if err != nil { |
| 50 | return nil, err |
| 51 | } |
| 52 | } |
| 53 | return |
| 54 | } |
| 55 | |
| 56 | type sigType struct { |
| 57 | id uint32 |
| 58 | hash crypto.Hash |
| 59 | alg x509.PublicKeyAlgorithm |
| 60 | pss bool |
| 61 | } |
| 62 | |
| 63 | var sigTypes = []sigType{ |
| 64 | sigType{0x0101, crypto.SHA256, x509.RSA, true}, // RSASSA-PSS with SHA2-256 digest |
| 65 | sigType{0x0102, crypto.SHA512, x509.RSA, true}, // RSASSA-PSS with SHA2-512 digest |
| 66 | sigType{0x0103, crypto.SHA256, x509.RSA, false}, // RSASSA-PKCS1-v1_5 with SHA2-256 digest |
| 67 | sigType{0x0104, crypto.SHA512, x509.RSA, false}, // RSASSA-PKCS1-v1_5 with SHA2-512 digest |
| 68 | sigType{0x0201, crypto.SHA256, x509.ECDSA, false}, // ECDSA with SHA2-256 digest |
| 69 | sigType{0x0202, crypto.SHA512, x509.ECDSA, false}, // ECDSA with SHA2-512 digest |
| 70 | sigType{0x0301, crypto.SHA256, x509.DSA, false}, // DSA with SHA2-256 digest |
| 71 | } |
| 72 | |
| 73 | func sigTypeByID(id uint32) (st sigType, err error) { |
| 74 | for _, s := range sigTypes { |
| 75 | if s.id == id { |
| 76 | st = s |
| 77 | break |
| 78 | } |
| 79 | } |
| 80 | if st.id == 0 { |
| 81 | return st, fmt.Errorf("unknown signature type 0x%04x", id) |
| 82 | } |
| 83 | if !st.hash.Available() { |
| 84 | return st, fmt.Errorf("unsupported signature type 0x%04x", id) |
| 85 | } |
| 86 | return |
| 87 | } |