| 1 | package csblob |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto" |
| 6 | "encoding/binary" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "io/ioutil" |
| 11 | "time" |
| 12 | |
| 13 | "howett.net/plist" |
| 14 | |
| 15 | "github.com/sassoftware/relic/v7/lib/certloader" |
| 16 | "github.com/sassoftware/relic/v7/lib/pkcs7" |
| 17 | "github.com/sassoftware/relic/v7/lib/pkcs9" |
| 18 | "github.com/sassoftware/relic/v7/lib/x509tools" |
| 19 | ) |
| 20 | |
| 21 | type SignatureParams struct { |
| 22 | Pages io.Reader // read page contents |
| 23 | OldSignature io.Reader // read the existing signature, if any, after the pages |
| 24 | HashFunc crypto.Hash |
| 25 | InfoPlist []byte // manifest to bind to signature |
| 26 | Resources []byte // CodeResources to bind to signature |
| 27 | |
| 28 | // the following are copied from the old signature if empty |
| 29 | Flags SignatureFlags |
| 30 | Requirements []byte // requirements to embed in signature |
| 31 | Entitlement []byte // entitlement to embed in signature |
| 32 | EntitlementDER []byte // entitlement in DER format |
| 33 | RepSpecific []byte // DMG header |
| 34 | SigningIdentity string // bundle ID |
| 35 | TeamIdentifier string // team ID from signing cert (set automatically if empty) |
| 36 | ExecSegmentBase int64 |
| 37 | ExecSegmentLimit int64 |
| 38 | ExecSegmentFlags int64 |
| 39 | } |
| 40 | |
| 41 | func (p *SignatureParams) hashFuncs() []crypto.Hash { |
| 42 | return []crypto.Hash{p.HashFunc} |
| 43 | } |
| 44 | |
| 45 | func (p *SignatureParams) DefaultsFromSignature() error { |
| 46 | // parse old signature |
| 47 | if p.OldSignature == nil { |
| 48 | return nil |
| 49 | } |
| 50 | blob, err := ioutil.ReadAll(p.OldSignature) |
| 51 | if err != nil { |
| 52 | return err |
| 53 | } |
| 54 | oldSig, err := parseSignature(blob) |
| 55 | if err != nil { |
| 56 | return err |
| 57 | } |
| 58 | // copy embedded items |
| 59 | if p.Entitlement == nil && oldSig.Entitlement != nil { |
| 60 | p.Entitlement = oldSig.Entitlement[8:] |
| 61 | if p.EntitlementDER == nil && oldSig.EntitlementDER != nil { |
| 62 | // copy DER only if xml entitlements were also not set |
| 63 | p.EntitlementDER = oldSig.EntitlementDER[8:] |
| 64 | } |
| 65 | } |
| 66 | // copy code dir fields |
| 67 | oldDir := oldSig.bestDir() |
| 68 | if oldDir == nil { |
| 69 | return nil |
| 70 | } |
| 71 | if p.Flags == 0 { |
| 72 | p.Flags = oldDir.Header.Flags &^ clearFlags |
| 73 | } |
| 74 | if p.ExecSegmentBase == 0 && p.ExecSegmentLimit == 0 && p.ExecSegmentFlags == 0 { |
| 75 | p.ExecSegmentBase = oldDir.Header.ExecSegmentBase |
| 76 | p.ExecSegmentLimit = oldDir.Header.ExecSegmentLimit |
| 77 | p.ExecSegmentFlags = oldDir.Header.ExecSegmentFlags |
| 78 | } |
| 79 | return nil |
| 80 | } |
| 81 | |
| 82 | func (p *SignatureParams) DefaultsFromBundle(cert *certloader.Certificate) error { |
| 83 | if p.SigningIdentity == "" && len(p.InfoPlist) != 0 { |
| 84 | var bundle bundlePlist |
| 85 | if _, err := plist.Unmarshal(p.InfoPlist, &bundle); err != nil { |
| 86 | return fmt.Errorf("info.plist: %w", err) |
| 87 | } |
| 88 | p.SigningIdentity = bundle.BundleID |
| 89 | } |
| 90 | if p.TeamIdentifier == "" { |
| 91 | p.TeamIdentifier = TeamID(cert.Leaf) |
| 92 | } |
| 93 | if p.Requirements == nil { |
| 94 | req, err := DefaultRequirement(p.SigningIdentity, cert.Chain()) |
| 95 | if err != nil { |
| 96 | return fmt.Errorf("computing default designated requirement: %w", err) |
| 97 | } |
| 98 | p.Requirements = req |
| 99 | } |
| 100 | return nil |
| 101 | } |
| 102 | |
| 103 | const defaultPageSizeLog2 = 12 |
| 104 | |
| 105 | func Sign(ctx context.Context, cert *certloader.Certificate, params *SignatureParams) ([]byte, *pkcs9.TimestampedSignature, error) { |
| 106 | // hash code pages |
| 107 | hashFuncs := params.hashFuncs() |
| 108 | singlePage := params.RepSpecific != nil // DMG |
| 109 | codeSlots, slotCount, codeLimit, err := hashPages(hashFuncs, params.Pages, singlePage) |
| 110 | if err != nil { |
| 111 | return nil, nil, fmt.Errorf("hashing code pages: %w", err) |
| 112 | } |
| 113 | // read the old signature to extract entitlements etc. |
| 114 | if err := params.DefaultsFromSignature(); err != nil { |
| 115 | return nil, nil, fmt.Errorf("parsing old signature: %w", err) |
| 116 | } |
| 117 | if err := params.DefaultsFromBundle(cert); err != nil { |
| 118 | return nil, nil, fmt.Errorf("setting signature params: %w", err) |
| 119 | } |
| 120 | // build list of special slots to hash. for these the hash covers the blob |
| 121 | // header as well so they have to be marshalled here |
| 122 | var entBlob, entDERBlob, reqBlob []byte |
| 123 | var hashedItems []superItem |
| 124 | if params.Requirements != nil { |
| 125 | v := params.Requirements |
| 126 | if len(v) < 8 { |
| 127 | return nil, nil, errors.New("requirements blob must be a binary requirement or requirement set") |
| 128 | } |
| 129 | switch csMagic(binary.BigEndian.Uint32(v)) { |
| 130 | case csRequirements: |
| 131 | // already a set of requirements |
| 132 | case csRequirement: |
| 133 | // assume single requirement is the DR |
| 134 | j := newSuperItem(csRequirement, v[8:]) |
| 135 | j.itype = uint32(DesignatedRequirement) |
| 136 | v = marshalSuperBlob(csRequirements, []superItem{j}) |
| 137 | default: |
| 138 | return nil, nil, errors.New("requirements blob must be a binary requirement or requirement set") |
| 139 | } |
| 140 | // strip off the superblob header and let marshalSuperBlob put it back on |
| 141 | i := newSuperItem(csRequirements, v[8:]) |
| 142 | reqBlob = i.data |
| 143 | hashedItems = append(hashedItems, i) |
| 144 | } |
| 145 | if params.Entitlement != nil { |
| 146 | i := newSuperItem(csEntitlement, params.Entitlement) |
| 147 | entBlob = i.data |
| 148 | hashedItems = append(hashedItems, i) |
| 149 | } |
| 150 | if params.EntitlementDER != nil { |
| 151 | i := newSuperItem(csEntitlementDER, params.EntitlementDER) |
| 152 | entDERBlob = i.data |
| 153 | hashedItems = append(hashedItems, i) |
| 154 | } |
| 155 | specials := [][]byte{ |
| 156 | entDERBlob, // -7 entitlements DER |
| 157 | params.RepSpecific, // -6 DMG |
| 158 | entBlob, // -5 entitlements |
| 159 | nil, // -4 app-specific |
| 160 | params.Resources, // -3 resource manifest |
| 161 | reqBlob, // -2 requirements |
| 162 | params.InfoPlist, // -1 info manifest |
| 163 | } |
| 164 | for specials[0] == nil && len(specials) > 5 { |
| 165 | specials = specials[1:] |
| 166 | } |
| 167 | var plistHashes cdHashPlist |
| 168 | var attrHashes []cdHashAttrib |
| 169 | var firstCD []byte |
| 170 | var items []superItem |
| 171 | for i, hashFunc := range hashFuncs { |
| 172 | cdParams := codeDirParams{ |
| 173 | SignatureParams: params, |
| 174 | Specials: specials, |
| 175 | CodeSlots: codeSlots[i], |
| 176 | CodeSlotCount: slotCount, |
| 177 | CodeLimit: codeLimit, |
| 178 | HashFunc: hashFunc, |
| 179 | SinglePage: singlePage, |
| 180 | } |
| 181 | result, err := newCodeDirectory(cdParams) |
| 182 | if err != nil { |
| 183 | return nil, nil, fmt.Errorf("populating code directory: %w", err) |
| 184 | } |
| 185 | alg, ok := x509tools.PkixDigestAlgorithm(hashFunc) |
| 186 | if !ok { |
| 187 | return nil, nil, fmt.Errorf("unsupported algorithm %s", hashFunc) |
| 188 | } |
| 189 | attrHashes = append(attrHashes, cdHashAttrib{ |
| 190 | Algorithm: alg.Algorithm, |
| 191 | Digest: result.Digest, |
| 192 | }) |
| 193 | plistHashes.CDHashes = append(plistHashes.CDHashes, result.Digest[:20]) |
| 194 | item := superItem{magic: csCodeDirectory, data: result.Raw} |
| 195 | if i == 0 { |
| 196 | firstCD = item.data |
| 197 | item.itype = cdCodeDirectorySlot |
| 198 | } else { |
| 199 | item.itype = uint32(cdAlternateCodeDirectorySlots + i - 1) |
| 200 | } |
| 201 | items = append(items, item) |
| 202 | } |
| 203 | items = append(items, hashedItems...) |
| 204 | // sign |
| 205 | builder := pkcs7.NewBuilder(cert.Signer(), cert.Chain(), params.HashFunc) |
| 206 | if err := builder.SetContentData(firstCD); err != nil { |
| 207 | return nil, nil, err |
| 208 | } |
| 209 | if err := addCSHashes(builder, attrHashes); err != nil { |
| 210 | return nil, nil, fmt.Errorf("adding cdhashes: %w", err) |
| 211 | } |
| 212 | if err := addPlistHashes(builder, plistHashes); err != nil { |
| 213 | return nil, nil, fmt.Errorf("adding cdhash plist: %w", err) |
| 214 | } |
| 215 | if err := builder.AddAuthenticatedAttribute(pkcs7.OidAttributeSigningTime, time.Now().UTC()); err != nil { |
| 216 | return nil, nil, err |
| 217 | } |
| 218 | psd, err := builder.Sign() |
| 219 | if err != nil { |
| 220 | return nil, nil, err |
| 221 | } |
| 222 | tssig, err := pkcs9.TimestampAndMarshal(ctx, psd, cert.Timestamper, false) |
| 223 | if err != nil { |
| 224 | return nil, nil, err |
| 225 | } |
| 226 | // marshal |
| 227 | if _, err := psd.Detach(); err != nil { |
| 228 | return nil, nil, err |
| 229 | } |
| 230 | tssig.Raw, err = psd.Marshal() |
| 231 | if err != nil { |
| 232 | return nil, nil, err |
| 233 | } |
| 234 | items = append(items, newSuperItem(csBlobWrapper, tssig.Raw)) |
| 235 | blob := marshalSuperBlob(csEmbeddedSignature, items) |
| 236 | return blob, tssig, err |
| 237 | } |
| 238 | |
| 239 | type bundlePlist struct { |
| 240 | Executable string `plist:"CFBundleExecutable"` |
| 241 | BundleID string `plist:"CFBundleIdentifier"` |
| 242 | } |