fix(installer): authenticate Apple recovery downloads
This commit is contained in:
1 parent
f26f5be4c3
commit
ae253be3e1
6 files changed
+242
-30
No files matched your search
@@ -5,6 +5,8 @@ package downloader
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
@@ -20,21 +22,35 @@ const (
|
||||
|
||||
// Request describes a single file or file-region download handed to a Provider.
|
||||
type Request struct {
|
||||
URL string `json:"url"`
|
||||
DestPath string `json:"dest_path"`
|
||||
DestOffset int64 `json:"dest_offset,omitempty"`
|
||||
ExpectedSize int64 `json:"expected_size,omitempty"`
|
||||
IntegrityURL string `json:"integrity_url,omitempty"`
|
||||
IntegrityBytes []byte `json:"integrity_bytes,omitempty"`
|
||||
ExpectedSHA256 string `json:"expected_sha256,omitempty"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
Resume bool `json:"resume"`
|
||||
DirectHint bool `json:"direct_hint,omitempty"`
|
||||
URL string `json:"url"`
|
||||
DestPath string `json:"dest_path"`
|
||||
DestOffset int64 `json:"dest_offset,omitempty"`
|
||||
ExpectedSize int64 `json:"expected_size,omitempty"`
|
||||
IntegrityURL string `json:"integrity_url,omitempty"`
|
||||
IntegrityBytes []byte `json:"integrity_bytes,omitempty"`
|
||||
ExpectedSHA256 string `json:"expected_sha256,omitempty"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
Resume bool `json:"resume"`
|
||||
DirectHint bool `json:"direct_hint,omitempty"`
|
||||
SameOriginRedirects bool `json:"same_origin_redirects,omitempty"`
|
||||
// RefreshHeaders optionally fetches fresh auth headers (such as a new Apple
|
||||
// osrecovery AssetToken cookie) when a range request returns HTTP 401/403.
|
||||
RefreshHeaders func(ctx context.Context) (map[string]string, error) `json:"-"`
|
||||
}
|
||||
|
||||
// CheckSameOriginRedirect limits redirects for downloads carrying origin-bound
|
||||
// credentials and preserves net/http's default redirect limit.
|
||||
func CheckSameOriginRedirect(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 10 {
|
||||
return fmt.Errorf("stopped after %d redirects", len(via))
|
||||
}
|
||||
origin := via[0].URL
|
||||
if req.URL.Scheme != origin.Scheme || !strings.EqualFold(req.URL.Host, origin.Host) || req.URL.User != nil {
|
||||
return fmt.Errorf("download redirected outside its origin")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Progress reports live download state back to the host UI/CLI.
|
||||
type Progress struct {
|
||||
Done int64 `json:"done"`
|
||||
|
||||
@@ -187,6 +187,9 @@ func (p *ParallelDownloader) Download(ctx context.Context, req Request, onProgre
|
||||
}
|
||||
opts := p.options()
|
||||
client := buildHTTPClient(opts, req.URL, req.DirectHint)
|
||||
if req.SameOriginRedirects {
|
||||
client.CheckRedirect = CheckSameOriginRedirect
|
||||
}
|
||||
defer client.CloseIdleConnections()
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(req.DestPath), 0o755); err != nil {
|
||||
|
||||
@@ -231,14 +231,15 @@ func (c *Client) downloadOfflineAccelerated(ctx context.Context, version string,
|
||||
recStep := fmt.Sprintf("downloading %s recovery (%s)", onRel.Name, prov.ID())
|
||||
onUpdate(Update{Kind: KindStep, Message: recStep, Step: recStep, Percent: -1})
|
||||
rErr := prov.Download(ctx, downloader.Request{
|
||||
URL: asset.AssetURL,
|
||||
DestPath: partPath,
|
||||
DestOffset: rec.dmgOffset,
|
||||
ExpectedSize: rec.dmgSize,
|
||||
IntegrityBytes: rec.chunklist,
|
||||
Headers: recoveryHeaders(asset.AssetToken),
|
||||
Resume: true,
|
||||
DirectHint: true,
|
||||
URL: asset.AssetURL,
|
||||
DestPath: partPath,
|
||||
DestOffset: rec.dmgOffset,
|
||||
ExpectedSize: rec.dmgSize,
|
||||
IntegrityBytes: rec.chunklist,
|
||||
Headers: recoveryHeaders(asset.AssetToken),
|
||||
Resume: true,
|
||||
DirectHint: true,
|
||||
SameOriginRedirects: true,
|
||||
RefreshHeaders: func(rctx context.Context) (map[string]string, error) {
|
||||
fresh, ferr := fetchRecoveryAsset(rctx, httpClient, osRecoveryBaseURL, onRel.BoardID, osType)
|
||||
if ferr != nil {
|
||||
@@ -478,7 +479,7 @@ func inspectRecoveryPartition(imagePath string, verifyData bool) (*recoveryParti
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
cl, err := downloader.ParseCNKL(chuBytes)
|
||||
cl, err := parseSignedRecoveryChunklist(chuBytes)
|
||||
if err != nil || cl.TotalSize != int64(dmgEnt.size) {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -20,7 +21,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
osRecoveryBaseURL = "http://osrecovery.apple.com"
|
||||
osRecoveryBaseURL = "https://osrecovery.apple.com"
|
||||
osRecoveryUserAgent = "InternetRecovery/1.0"
|
||||
)
|
||||
|
||||
@@ -119,7 +120,21 @@ func randUpperHex(nBytes int) string {
|
||||
func newDirectRecoveryHTTPClient() *http.Client {
|
||||
tr := http.DefaultTransport.(*http.Transport).Clone()
|
||||
tr.Proxy = nil // Direct connection to osrecovery.apple.com / oscdn.apple.com.
|
||||
return &http.Client{Transport: tr, Timeout: 25 * time.Second}
|
||||
return &http.Client{Transport: tr, Timeout: 25 * time.Second, CheckRedirect: downloader.CheckSameOriginRedirect}
|
||||
}
|
||||
|
||||
func appleRecoveryAssetURL(raw string) bool {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.User != nil || u.Port() != "" {
|
||||
return false
|
||||
}
|
||||
host := strings.ToLower(u.Hostname())
|
||||
// Apple Internet Recovery still issues HTTP URLs on this CDN. Recovery
|
||||
// bytes are authenticated separately by Apple's signed chunklist.
|
||||
if host == "oscdn.apple.com" {
|
||||
return u.Scheme == "http" || u.Scheme == "https"
|
||||
}
|
||||
return u.Scheme == "https" && strings.HasSuffix(host, ".cdn-apple.com")
|
||||
}
|
||||
|
||||
// fetchRecoveryAsset performs Apple's 2-step osrecovery handshake to obtain
|
||||
@@ -222,6 +237,9 @@ func fetchRecoveryAssetOnce(ctx context.Context, client *http.Client, baseURL, b
|
||||
if kv["AU"] == "" {
|
||||
return nil, errors.New("osrecovery response missing asset URL (AU)")
|
||||
}
|
||||
if baseURL == osRecoveryBaseURL && (!appleRecoveryAssetURL(kv["AU"]) || !appleRecoveryAssetURL(kv["CU"])) {
|
||||
return nil, errors.New("osrecovery returned an untrusted recovery asset or chunklist URL")
|
||||
}
|
||||
return &recoveryAsset{
|
||||
AssetURL: kv["AU"],
|
||||
AssetToken: kv["AT"],
|
||||
@@ -352,9 +370,9 @@ func (c *Client) downloadOnlineAccelerated(ctx context.Context, version string,
|
||||
}
|
||||
return nil, false, nil
|
||||
}
|
||||
cl, err := downloader.ParseCNKL(clBytes)
|
||||
cl, err := parseSignedRecoveryChunklist(clBytes)
|
||||
if err != nil {
|
||||
return nil, false, nil
|
||||
return nil, true, err
|
||||
}
|
||||
|
||||
partPath := finalPath + ".part"
|
||||
@@ -362,13 +380,14 @@ func (c *Client) downloadOnlineAccelerated(ctx context.Context, version string,
|
||||
onUpdate(Update{Kind: KindStep, Message: dlStep, Step: dlStep, Percent: -1})
|
||||
|
||||
dlErr := prov.Download(ctx, downloader.Request{
|
||||
URL: asset.AssetURL,
|
||||
DestPath: partPath,
|
||||
ExpectedSize: cl.TotalSize,
|
||||
IntegrityBytes: clBytes,
|
||||
Headers: recoveryHeaders(asset.AssetToken),
|
||||
Resume: true,
|
||||
DirectHint: true,
|
||||
URL: asset.AssetURL,
|
||||
DestPath: partPath,
|
||||
ExpectedSize: cl.TotalSize,
|
||||
IntegrityBytes: clBytes,
|
||||
Headers: recoveryHeaders(asset.AssetToken),
|
||||
Resume: true,
|
||||
DirectHint: true,
|
||||
SameOriginRedirects: true,
|
||||
RefreshHeaders: func(rctx context.Context) (map[string]string, error) {
|
||||
fresh, rerr := fetchRecoveryAsset(rctx, httpClient, osRecoveryBaseURL, rel.BoardID, osType)
|
||||
if rerr != nil {
|
||||
@@ -393,6 +412,9 @@ func (c *Client) downloadOnlineAccelerated(ctx context.Context, version string,
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
if err := verifyRecoveryImage(ctx, partPath, cl); err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
if err := os.Rename(partPath, finalPath); err != nil {
|
||||
return nil, true, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package installer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"os"
|
||||
"slices"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/downloader"
|
||||
)
|
||||
|
||||
// Apple EFI ROM public key 1, as documented by OpenCorePkg's macrecovery
|
||||
// verifier and reims-util 7867384, src/chunklist.rs:24-31.
|
||||
var appleRecoveryKey = rsa.PublicKey{
|
||||
N: func() *big.Int {
|
||||
n, _ := new(big.Int).SetString(
|
||||
"C3E748CAD9CD384329E10E25A91E43E1A762FF529ADE578C935BDDF9B13F2179"+
|
||||
"D4855E6FC89E9E29CA12517D17DFA1EDCE0BEBF0EA7B461FFE61D94E2BDF72C196F89ACD3536B644064014DAE25A15DB"+
|
||||
"6BB0852ECBD120916318D1CCDEA3C84C92ED743FC176D0BACA920D3FCF3158AFF731F88CE0623182A8ED67E650515F7"+
|
||||
"5745909F07D415F55FC15A35654D118C55A462D37A3ACDA08612F3F3F6571761EFCCBCC299AEE99B3A4FD6212CCFFF5E"+
|
||||
"F37A2C334E871191F7E1C31960E010A54E86FA3F62E6D6905E1CD57732410A3EB0C6B4DEFDABE9F59BF1618758C751C"+
|
||||
"D56CEF851D1C0EAA1C558E37AC108DA9089863D20E2E7E4BF475EC66FE6B3EFDCF", 16)
|
||||
return n
|
||||
}(),
|
||||
E: 65537,
|
||||
}
|
||||
|
||||
func parseSignedRecoveryChunklist(data []byte) (*downloader.Chunklist, error) {
|
||||
return verifySignedRecoveryChunklist(data, &appleRecoveryKey)
|
||||
}
|
||||
|
||||
func verifySignedRecoveryChunklist(data []byte, key *rsa.PublicKey) (*downloader.Chunklist, error) {
|
||||
const headerSize, entrySize, rsaMethod = 36, 36, 1
|
||||
if len(data) < headerSize+key.Size() || data[10] != rsaMethod {
|
||||
return nil, fmt.Errorf("recovery chunklist is missing an Apple RSA signature")
|
||||
}
|
||||
end := len(data) - key.Size()
|
||||
if binary.LittleEndian.Uint32(data[4:8]) != headerSize ||
|
||||
binary.LittleEndian.Uint64(data[20:28]) != headerSize ||
|
||||
binary.LittleEndian.Uint64(data[28:36]) != uint64(end) ||
|
||||
(end-headerSize)%entrySize != 0 ||
|
||||
binary.LittleEndian.Uint64(data[12:20]) != uint64((end-headerSize)/entrySize) {
|
||||
return nil, fmt.Errorf("invalid signed recovery chunklist layout")
|
||||
}
|
||||
sig := bytes.Clone(data[end:])
|
||||
slices.Reverse(sig) // CNKL stores the RSA signature little-endian.
|
||||
sum := sha256.Sum256(data[:end])
|
||||
if err := rsa.VerifyPKCS1v15(key, crypto.SHA256, sum[:], sig); err != nil {
|
||||
return nil, fmt.Errorf("verify Apple recovery chunklist: %w", err)
|
||||
}
|
||||
return downloader.ParseCNKL(data)
|
||||
}
|
||||
|
||||
// Verify the actual file before publishing it, including bytes resumed from
|
||||
// disk and bytes written by an external download provider.
|
||||
func verifyRecoveryImage(ctx context.Context, path string, cl *downloader.Chunklist) error {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
info, err := f.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.Size() != cl.TotalSize {
|
||||
return fmt.Errorf("recovery image size %d differs from signed size %d", info.Size(), cl.TotalSize)
|
||||
}
|
||||
hash := sha256.New()
|
||||
for _, chunk := range cl.Chunks {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
hash.Reset()
|
||||
if _, err := io.CopyN(hash, f, chunk.Size); err != nil {
|
||||
return fmt.Errorf("read recovery image chunk %d: %w", chunk.Index, err)
|
||||
}
|
||||
if !bytes.Equal(hash.Sum(nil), chunk.SHA256[:]) {
|
||||
return fmt.Errorf("recovery image chunk %d differs from its signed checksum", chunk.Index)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package installer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSignedRecoveryIntegrity(t *testing.T) {
|
||||
payload := []byte("synthetic recovery image")
|
||||
digestOnly := buildCNKLBytes(payload, 16)
|
||||
digest := sha256.Sum256(digestOnly)
|
||||
if _, err := parseSignedRecoveryChunklist(append(bytes.Clone(digestOnly), digest[:]...)); err == nil {
|
||||
t.Fatal("accepted chunklist without an Apple signature")
|
||||
}
|
||||
if appleRecoveryKey.N.BitLen() != 2048 {
|
||||
t.Fatal("unexpected Apple public key length")
|
||||
}
|
||||
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
signed := bytes.Clone(digestOnly)
|
||||
signed[10] = 1
|
||||
digest = sha256.Sum256(signed)
|
||||
sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, digest[:])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
slices.Reverse(sig)
|
||||
signed = append(signed, sig...)
|
||||
cl, err := verifySignedRecoveryChunklist(signed, &key.PublicKey)
|
||||
if err != nil {
|
||||
t.Fatalf("rejected valid signature: %v", err)
|
||||
}
|
||||
if _, err := parseSignedRecoveryChunklist(signed); err == nil {
|
||||
t.Fatal("accepted a recovery chunklist signed by a different key")
|
||||
}
|
||||
signed[45] ^= 1
|
||||
if _, err := verifySignedRecoveryChunklist(signed, &key.PublicKey); err == nil {
|
||||
t.Fatal("accepted modified signed chunklist")
|
||||
}
|
||||
|
||||
image := filepath.Join(t.TempDir(), "test.part")
|
||||
if err := os.WriteFile(image, payload, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := verifyRecoveryImage(t.Context(), image, cl); err != nil {
|
||||
t.Fatalf("valid image: %v", err)
|
||||
}
|
||||
payload[0] ^= 1
|
||||
if err := os.WriteFile(image, payload, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := verifyRecoveryImage(t.Context(), image, cl); err == nil {
|
||||
t.Fatal("accepted damaged image of the correct size")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppleRecoveryAssetURL(t *testing.T) {
|
||||
for raw, want := range map[string]bool{
|
||||
"http://oscdn.apple.com/recovery.dmg": true,
|
||||
"https://updates.cdn-apple.com/recovery.chunklist": true,
|
||||
"http://updates.cdn-apple.com/recovery.chunklist": false,
|
||||
"http://oscdn.apple.com.example/recovery.dmg": false,
|
||||
"http://oscdn.apple.com:8080/recovery.dmg": false,
|
||||
"http://user@oscdn.apple.com/recovery.dmg": false,
|
||||
} {
|
||||
if got := appleRecoveryAssetURL(raw); got != want {
|
||||
t.Errorf("appleRecoveryAssetURL(%q) = %v, want %v", raw, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user