| 1 | package csblob |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "sort" |
| 6 | |
| 7 | ber "github.com/go-asn1-ber/asn1-ber" |
| 8 | |
| 9 | "github.com/sassoftware/relic/v7/lib/pkcs7" |
| 10 | ) |
| 11 | |
| 12 | type SigBlob struct { |
| 13 | // with blob header |
| 14 | Entitlement []byte |
| 15 | EntitlementDER []byte |
| 16 | RawRequirements []byte |
| 17 | NotaryTicket []byte |
| 18 | Unknowns [][]byte |
| 19 | |
| 20 | Directories []*CodeDirectory |
| 21 | CMS *pkcs7.ContentInfoSignedData |
| 22 | } |
| 23 | |
| 24 | func parseSignature(blob []byte) (*SigBlob, error) { |
| 25 | magic, items, err := parseSuper(blob) |
| 26 | if err != nil { |
| 27 | return nil, err |
| 28 | } |
| 29 | if magic != csEmbeddedSignature && magic != csDetachedSignature { |
| 30 | return nil, fmt.Errorf("expected embedded signature but got %08x", magic) |
| 31 | } |
| 32 | sig := new(SigBlob) |
| 33 | for _, item := range items { |
| 34 | switch { |
| 35 | case item.itype == cdRequirementsSlot: |
| 36 | sig.RawRequirements = item.data |
| 37 | case item.itype == cdEntitlementSlot: |
| 38 | sig.Entitlement = item.data |
| 39 | case item.itype == cdEntitlementDERSlot: |
| 40 | sig.EntitlementDER = item.data |
| 41 | case item.itype == cdTicketSlot: |
| 42 | sig.NotaryTicket = item.data |
| 43 | case item.itype == cdCodeDirectorySlot || item.itype >= cdAlternateCodeDirectorySlots && item.itype < cdAlternateCodeDirectorySlots+6: |
| 44 | dir, err := parseCodeDirectory(item.data, item.itype) |
| 45 | if err != nil { |
| 46 | return nil, err |
| 47 | } |
| 48 | sig.Directories = append(sig.Directories, dir) |
| 49 | case item.itype == cdSignatureSlot: |
| 50 | if len(item.data) <= 8 { |
| 51 | sig.CMS = nil |
| 52 | continue |
| 53 | } |
| 54 | // For some inane reason signatures are encoded with an indefinite |
| 55 | // length content, which go's asn1 lib chokes on because it's not |
| 56 | // DER. Use BER library to reencode. |
| 57 | pkt, err := ber.DecodePacketErr(item.data[8:]) |
| 58 | if err != nil { |
| 59 | return nil, err |
| 60 | } |
| 61 | der := pkt.Bytes() |
| 62 | psd, err := pkcs7.Unmarshal(der) |
| 63 | if err != nil { |
| 64 | return nil, err |
| 65 | } |
| 66 | sig.CMS = psd |
| 67 | default: |
| 68 | sig.Unknowns = append(sig.Unknowns, item.data) |
| 69 | } |
| 70 | } |
| 71 | sort.Slice(sig.Directories, func(i, j int) bool { |
| 72 | return sig.Directories[i].IType < sig.Directories[j].IType |
| 73 | }) |
| 74 | return sig, nil |
| 75 | } |