Repository Public
1package protocol23import (4 "crypto/ecdsa"5 "crypto/rand"6 "crypto/sha256"7 "encoding/base64"8 "encoding/hex"9 "strconv"10 "time"11)1213// Signed-request transport. An agent that cannot open a direct mTLS14// connection (macOS Local Network Privacy blocks LAN traffic from15// launchd-started binaries) reaches the ingest service through the public16// HTTPS front. TLS then ends at a proxy, so the agent proves possession of17// its enrolled certificate key on every request with these headers.18const (19 HeaderAgentCert = "X-MCC-Agent-Cert" // base64 (std) of the DER client certificate20 HeaderAgentTS = "X-MCC-Agent-Ts" // unix time, milliseconds21 HeaderAgentNonce = "X-MCC-Agent-Nonce" // 16 random bytes, base64url22 HeaderAgentSig = "X-MCC-Agent-Sig" // base64 (std) ECDSA-P256-SHA256 signature, ASN.1 DER2324 // RequestSigDomain separates request signatures from anything else the key signs.25 RequestSigDomain = "mcc-agent-request-v1"26 // MaxRequestSkew is the accepted distance between the request timestamp and the server clock.27 MaxRequestSkew = 90 * time.Second28)2930// BodyHashHex is the lowercase hex SHA-256 of the body exactly as sent on31// the wire (after compression, when the body is compressed).32func BodyHashHex(body []byte) string {33 h := sha256.Sum256(body)34 return hex.EncodeToString(h[:])35}3637// RequestSigningString returns the exact bytes covered by a request38// signature:39//40// "mcc-agent-request-v1\n" METHOD "\n" request-URI "\n" ts "\n" nonce "\n" hex(SHA-256(body))41//42// request-URI is the path, plus "?" and the raw query when there is one.43func RequestSigningString(method, requestURI string, tsMillis int64, nonce string, body []byte) []byte {44 s := RequestSigDomain + "\n" + method + "\n" + requestURI + "\n" + strconv.FormatInt(tsMillis, 10) + "\n" + nonce + "\n" + BodyHashHex(body)45 return []byte(s)46}4748// NewRequestNonce returns 16 random bytes, base64url without padding.49func NewRequestNonce() string { return NewNonce() }5051// SignRequest signs a request with the agent's certificate key.52func SignRequest(key *ecdsa.PrivateKey, method, requestURI string, tsMillis int64, nonce string, body []byte) (string, error) {53 digest := sha256.Sum256(RequestSigningString(method, requestURI, tsMillis, nonce, body))54 sig, err := ecdsa.SignASN1(rand.Reader, key, digest[:])55 if err != nil {56 return "", err57 }58 return base64.StdEncoding.EncodeToString(sig), nil59}6061// VerifyRequest checks a request signature (base64 std, ASN.1 DER).62func VerifyRequest(pub *ecdsa.PublicKey, method, requestURI string, tsMillis int64, nonce string, body []byte, sigB64 string) bool {63 sig, err := base64.StdEncoding.DecodeString(sigB64)64 if err != nil || len(sig) == 0 || pub == nil {65 return false66 }67 digest := sha256.Sum256(RequestSigningString(method, requestURI, tsMillis, nonce, body))68 return ecdsa.VerifyASN1(pub, digest[:], sig)69}70