如何执行CloudKit服务器到服务器身份验证

问题描述:

I'm following Composing Web Service Requests

To perform the Discovering All User Identities (GET users/discover).

The idea is to get this simple request working and later make more sophisticated requests like uploading an asset.

The code below is returning an error from the request.


import (
    "bytes"
    "crypto/ecdsa"
    "crypto/rand"
    "crypto/sha256"
    "crypto/x509"
    "encoding/base64"
    "encoding/pem"
    "fmt"
    "math/big"
    "net/http"
    "time"
    //...
)

func main() {

    fmt.Printf("
private key:
")

    const privPEM = `-----BEGIN EC PRIVATE KEY-----
MyProvateKey
-----END EC PRIVATE KEY-----`

    // https://golang.org/pkg/crypto/x509/#example_ParsePKIXPublicKey
    privBlock, _ := pem.Decode([]byte(privPEM))
    if privBlock == nil {
        panic("failed to parse PEM block containing the public key")
    }

    requestPathStr := "/database/1/iCloud.<MyContainer>/development/public/users/discover"

    var requestPath []byte
    requestPath = []byte(requestPathStr)
    fmt.Printf("requestPath: %s
", requestPath)

    requestBody := ""
    var jsonStr = []byte(requestBody)
    //
    h := sha256.New()
    h.Write([]byte(requestBody))
    b := h.Sum(nil)
    hashedBody := base64.StdEncoding.EncodeToString(b)
    //

    f := "2006-01-02T15:04:05Z"
    requestDate := time.Now().UTC().Format(f)
    fmt.Println(requestDate)

    rawPayload := []byte(requestDate + ":" + hashedBody + ":" + requestPathStr)

    r, s, err := pkSign(rawPayload, privBlock)
    if err != nil {
        fmt.Printf("signing hash error: %s
", err)
    }
    fmt.Printf("r: %v
", r)
    fmt.Printf("s: %v
", s)

    fmt.Printf("
public key:
")

    const pubPEM = `-----BEGIN PUBLIC KEY-----
MyPublicKey
-----END PUBLIC KEY-----`
    pubBlock, _ := pem.Decode([]byte(pubPEM))
    if pubBlock == nil {
        panic("failed to parse PEM block containing the public key")
    }
    // ECDSA signature
    ECDSAsignature := r.Bytes()
    ECDSAsignature = append(ECDSAsignature, s.Bytes()...)

    fmt.Printf("ECDSAsignature : %x
", ECDSAsignature)

    verify := pkVerify(rawPayload, pubBlock, r, s)
    fmt.Printf("signature verification result: %t
", verify)

    // GET [path]/database/[version]/[container]/[environment]/public/users/discover

    url := "https://api.apple-cloudkit.com/" + requestPathStr
    fmt.Printf("
url:%v
", url)
    fmt.Printf("
jsonStr:%s
", jsonStr)
    fmt.Printf("
requestDate:%s
", requestDate)

    client := &http.Client{}

    // GET [path]/database/[version]/[container]/[environment]/public/users/discover

    req, err := http.NewRequest("GET", url, bytes.NewBuffer(jsonStr))
    var authKeyID = "MyKeyID"

    req.Header.Add("content-type", "text/plain")
    req.Header.Add("X-Apple-CloudKit-Request-KeyID", authKeyID)
    req.Header.Add("X-Apple-CloudKit-Request-ISO8601Date", requestDate)

    ECDSAsignatureBase64 := base64.StdEncoding.EncodeToString(ECDSAsignature)

    req.Header.Add("X-Apple-CloudKit-Request-SignatureV1", ECDSAsignatureBase64)
    resp, _ := client.Do(req)
    fmt.Printf("
resp:%v
", resp)

    resp, err = client.Do(req)
    if err != nil {
        fmt.Printf("
err:%v
", err.Error())

    } else {
        resp.Body.Close()
        fmt.Printf("
resp.Body:%v
", resp.Body)

    }
    fmt.Printf("
resp:%v
", resp)

}

func pkSign(hash []byte, block *pem.Block) (r, s *big.Int, err error) {
    zero := big.NewInt(0)
    private_key, err := x509.ParseECPrivateKey(block.Bytes)
    if err != nil {
        return zero, zero, err
    }

    // Sign signs a hash (which should be the result of hashing a larger message)
    // using the private key, priv.
    // If the hash is longer than the bit-length of the private key's curve order,
    // the hash will be truncated to that length.
    // It returns the signature as a pair of integers.
    // The security of the private key depends on the entropy of rand.

    r, s, err = ecdsa.Sign(rand.Reader, private_key, hash)
    if err != nil {
        return zero, zero, err
    }
    return r, s, nil
}

func pkVerify(hash []byte, block *pem.Block, r *big.Int, s *big.Int) (result bool) {
    public_key, err := x509.ParsePKIXPublicKey(block.Bytes)
    if err != nil {
        return false
    }

    switch public_key := public_key.(type) {
    case *ecdsa.PublicKey:
        return ecdsa.Verify(public_key, hash, r, s)
    default:
        return false
    }
}

The error I got is following:

resp:&{503 Service Unavailable 503 HTTP/1.1 1 1 map[Access-Control-Expose-Headers:[X-Apple-Request-UUID Via] Connection:[keep-alive] Content-Length:[0] Content-Type:[text/plain] Date:[Mon, 24 Jun 2019 07:47:52 GMT] Retry-After:[30] Server:[AppleHttpServer/70a91026] Via:[icloudedge:mi01p00ic-zteu02110401:7401:19RC207:Miami] X-Apple-Cache:[false] X-Apple-Request-Uuid:[ddeb0fa3-ea16-40e9-a15b-c2e68cb5fe78]] {} 0 [] false false map[] 0xc00015c000 0xc0000ce2c0}

resp.Body:{}

If anybody needs it here is a working solution.

package main

import (
    "bytes"
    "crypto/ecdsa"
    "crypto/rand"
    "crypto/sha256"
    "crypto/x509"
    "encoding/asn1"
    "encoding/base64"
    "encoding/pem"
    "fmt"
    "io/ioutil"
    "math/big"
    "net/http"
    "time"
)

const projectID = "<your ID>"

//
const authKeyID = "your ID"
const path = "https://api.apple-cloudkit.com"
const version = "1"
const container = "your container"
const environment = "development"
const database = "public"

const privPEM = `-----BEGIN EC PRIVATE KEY-----
your privste key
-----END EC PRIVATE KEY-----`

const pubPEM = `-----BEGIN PUBLIC KEY-----
your public key
-----END PUBLIC KEY-----`

type ecdsaSignature struct {
    R, S *big.Int
}

func main() {
    t0 := time.Now().UTC()
    t1 := time.Now().UTC()

    // fmt.Printf("
private key:
")
    // https://golang.org/pkg/crypto/x509/#example_ParsePKIXPublicKey
    privBlock, _ := pem.Decode([]byte(privPEM))
    if privBlock == nil {
        panic("failed to parse PEM block containing the public key")
    }

    private_key, err := x509.ParseECPrivateKey(privBlock.Bytes)
    if err != nil {
        panic("failed to parse PEM block containing the public key")
    }

    pubBlock, _ := pem.Decode([]byte(pubPEM))
    if pubBlock == nil {
        panic("failed to parse PEM block containing the public key")
    }

    var public_key *ecdsa.PublicKey
    public_k, err := x509.ParsePKIXPublicKey(pubBlock.Bytes)
    if err != nil {
        panic("failed to parse PEM block containing the public key")
    }
    switch public_k1 := public_k.(type) {
    case *ecdsa.PublicKey:
        public_key = public_k1
    default:
        //return false
    }
    //////////
    // Config
    //////////
    requestPath := "/database/" +
        version + "/" +
        container + "/" +
        environment + "/" +
        database + "/" +
        "records/query"

    requestBody := `{"query": {"recordType": "<your record type"}}`

    f := "2006-01-02T15:04:05Z"
    requestDate := time.Now().UTC().Format(f)

    h := sha256.New()
    h.Write([]byte(requestBody))
    b := h.Sum(nil)
    hashedBody := base64.StdEncoding.EncodeToString(b)

    rawPayload := requestDate + ":" + hashedBody + ":" + requestPath

    signedSignature, err := SignMessage(private_key, []byte(rawPayload))
    if err != nil {
        fmt.Printf("SignMessage  error: %s
", err.Error())
    }

    verify := VerifyMessage(public_key, []byte(rawPayload), signedSignature)
    fmt.Printf("signature verification result: %t
", verify)

    requestSignature := base64.StdEncoding.EncodeToString(signedSignature)
    url := path + requestPath

    req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(requestBody)))

    req.Header.Add("content-type", "text/plain")
    req.Header.Add("X-Apple-CloudKit-Request-KeyID", authKeyID)

    req.Header.Add("X-Apple-CloudKit-Request-ISO8601Date", requestDate)

    req.Header.Add("X-Apple-CloudKit-Request-SignatureV1", requestSignature)

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        fmt.Printf("
resp.err:%v
", err.Error())

    }

    defer resp.Body.Close()
    rbody, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("
ioutil.ReadAll.err:%v
", err.Error())

    }
    fmt.Printf("
rbody:%s
", rbody)

    curl := "curl -X POST -H \"content-type: text/plain\"" + " " +
        "-H X-Apple-CloudKit-Request-KeyID:" + authKeyID + " " +
        "-H X-Apple-CloudKit-Request-ISO8601Date:" + requestDate + " " +
        "-H X-Apple-CloudKit-Request-SignatureV1:" + base64.StdEncoding.EncodeToString(signedSignature) + " " +
        " -d " + "'" + requestBody + "'" + " " +
        url

    fmt.Printf("
%s
", curl)

}

func SignMessage(priv *ecdsa.PrivateKey, message []byte) ([]byte, error) {
    hashed := sha256.Sum256(message)
    r, s, err := ecdsa.Sign(rand.Reader, priv, hashed[:])
    if err != nil {
        return nil, err
    }

    return asn1.Marshal(ecdsaSignature{r, s})
}

func VerifyMessage(pub *ecdsa.PublicKey, message []byte, signature []byte) bool {
    var rs ecdsaSignature

    if _, err := asn1.Unmarshal(signature, &rs); err != nil {
        return false
    }

    hashed := sha256.Sum256(message)
    return ecdsa.Verify(pub, hashed[:], rs.R, rs.S)
}