| 1 | package machos |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "io/ioutil" |
| 9 | |
| 10 | "github.com/sassoftware/relic/v7/lib/binpatch" |
| 11 | "github.com/sassoftware/relic/v7/lib/certloader" |
| 12 | "github.com/sassoftware/relic/v7/lib/fruit/csblob" |
| 13 | "github.com/sassoftware/relic/v7/lib/pkcs9" |
| 14 | ) |
| 15 | |
| 16 | func Sign(ctx context.Context, r io.Reader, cert *certloader.Certificate, params *csblob.SignatureParams) (*binpatch.PatchSet, *pkcs9.TimestampedSignature, error) { |
| 17 | var saved bytes.Buffer |
| 18 | tee := io.TeeReader(r, &saved) |
| 19 | markers, err := scanFile(tee) |
| 20 | if err != nil { |
| 21 | return nil, nil, err |
| 22 | } |
| 23 | headerBuf := saved.Bytes() |
| 24 | // estimate size of signature |
| 25 | estimatedSize := markers.codeSize * int64(20+params.HashFunc.Size()) / 4096 |
| 26 | estimatedSize += int64(len(params.Entitlement) + len(params.Requirements)) |
| 27 | estimatedSize += 16384 |
| 28 | // patch header to make space |
| 29 | oldHeaderSize := len(headerBuf) |
| 30 | headerBuf, sigBuf, sigStart, patch, padding, err := markers.PatchSignature(headerBuf, estimatedSize) |
| 31 | if err != nil { |
| 32 | return nil, nil, err |
| 33 | } |
| 34 | // if PatchSignature extended the header then the bytes that its extension |
| 35 | // replaced haven't been read yet, so discard them now |
| 36 | if extended := len(headerBuf) - oldHeaderSize; extended > 0 { |
| 37 | if _, err := io.ReadFull(r, make([]byte, extended)); err != nil { |
| 38 | return nil, nil, err |
| 39 | } |
| 40 | } |
| 41 | // splice the patched header with the rest of the stream |
| 42 | params.Pages = io.LimitReader(io.MultiReader(bytes.NewReader(headerBuf), r, bytes.NewReader(make([]byte, padding))), sigStart) |
| 43 | if markers.sigLen != 0 { |
| 44 | // read the old signature after the pages are hashed |
| 45 | params.OldSignature = io.LimitReader(r, markers.sigLen) |
| 46 | } |
| 47 | blob, tsig, err := csblob.Sign(ctx, cert, params) |
| 48 | if err != nil { |
| 49 | return nil, nil, err |
| 50 | } |
| 51 | // fill patch buffer with signature |
| 52 | if len(blob) > len(sigBuf) { |
| 53 | return nil, nil, fmt.Errorf("signature overflows reserved space: have %d bytes, need %d", len(sigBuf), len(blob)) |
| 54 | } |
| 55 | copy(sigBuf, blob) |
| 56 | // discard remainder of stream |
| 57 | if _, err := io.Copy(ioutil.Discard, r); err != nil { |
| 58 | return nil, nil, err |
| 59 | } |
| 60 | return patch, tsig, nil |
| 61 | } |