| 1 | package machos |
| 2 | |
| 3 | import ( |
| 4 | "debug/macho" |
| 5 | "fmt" |
| 6 | "io" |
| 7 | |
| 8 | "github.com/sassoftware/relic/v7/lib/fruit/csblob" |
| 9 | "github.com/sassoftware/relic/v7/signers/sigerrors" |
| 10 | ) |
| 11 | |
| 12 | func Verify(r io.ReaderAt, infoPlist, resources []byte, skipDigests bool) (*csblob.VerifiedBlob, error) { |
| 13 | hdr, err := macho.NewFile(r) |
| 14 | if err != nil { |
| 15 | return nil, err |
| 16 | } |
| 17 | buf, err := readSigBlob(r, hdr) |
| 18 | if err != nil { |
| 19 | return nil, err |
| 20 | } |
| 21 | if infoPlist == nil { |
| 22 | // check if info.plist is embedded in the image |
| 23 | infoPlist, err = readPlist(hdr) |
| 24 | if err != nil { |
| 25 | return nil, err |
| 26 | } |
| 27 | } |
| 28 | sig, err := csblob.Verify(buf, csblob.VerifyParams{ |
| 29 | InfoPlist: infoPlist, |
| 30 | Resources: resources, |
| 31 | }) |
| 32 | if err != nil { |
| 33 | return nil, fmt.Errorf("verifying mach-O signature: %w", err) |
| 34 | } |
| 35 | if !skipDigests { |
| 36 | r := io.NewSectionReader(r, 0, sig.Blob.CodeSize()) |
| 37 | if err := sig.Blob.VerifyPages(r); err != nil { |
| 38 | return nil, err |
| 39 | } |
| 40 | } |
| 41 | return sig, nil |
| 42 | } |
| 43 | |
| 44 | func readSigBlob(r io.ReaderAt, hdr *macho.File) ([]byte, error) { |
| 45 | for _, loadCmd := range hdr.Loads { |
| 46 | raw := loadCmd.Raw() |
| 47 | cmd := macho.LoadCmd(hdr.ByteOrder.Uint32(raw)) |
| 48 | if cmd != loadCmdCodeSignature { |
| 49 | continue |
| 50 | } |
| 51 | if len(raw) != 16 { |
| 52 | return nil, fmt.Errorf("expected LC_CODE_SIGNATURE to be 16 bytes not %d bytes", len(raw)) |
| 53 | } |
| 54 | offset := int64(hdr.ByteOrder.Uint32(raw[8:])) |
| 55 | length := int64(hdr.ByteOrder.Uint32(raw[12:])) |
| 56 | if length > 10e6 { |
| 57 | return nil, fmt.Errorf("unreasonably large LC_CODE_SIGNATURE of %d bytes", length) |
| 58 | } |
| 59 | buf := make([]byte, length) |
| 60 | if _, err := r.ReadAt(buf, offset); err != nil { |
| 61 | return nil, fmt.Errorf("reading LC_CODE_SIGNATURE: %w", err) |
| 62 | } |
| 63 | return buf, nil |
| 64 | } |
| 65 | return nil, sigerrors.NotSignedError{Type: "Mach-O"} |
| 66 | } |
| 67 | |
| 68 | func readPlist(hdr *macho.File) ([]byte, error) { |
| 69 | for _, sec := range hdr.Sections { |
| 70 | if sec.Seg == "__TEXT" && sec.Name == "__info_plist" { |
| 71 | infoPlist, err := sec.Data() |
| 72 | if err != nil { |
| 73 | return nil, fmt.Errorf("reading embedded info_plist: %w", err) |
| 74 | } |
| 75 | return infoPlist, nil |
| 76 | } |
| 77 | } |
| 78 | return nil, nil |
| 79 | } |