CloudKit Server-to-Server 认证

CloudKit Server-to-Server authentication

Apple 发布了一种根据 CloudKit、server-to-server 进行身份验证的新方法。 https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/CloudKitWebServicesReference/SettingUpWebServices.html#//apple_ref/doc/uid/TP40015240-CH24-SW6

我尝试根据 CloudKit 和此方法进行身份验证。一开始我生成了密钥对,把public密钥给了CloudKit,目前没问题。

我开始构建请求 header。根据文档,它应该如下所示:

X-Apple-CloudKit-Request-KeyID: [keyID]  
X-Apple-CloudKit-Request-ISO8601Date: [date]  
X-Apple-CloudKit-Request-SignatureV1: [signature]

文档说:

The signature created in Step 1.

第 1 步说:

Concatenate the following parameters and separate them with colons.
[Current date]:[Request body]:[Web Service URL]

我问自己"Why do I have to generate the key pair?"。
但是第 2 步说:

Compute the ECDSA signature of this message with your private key.

也许他们的意思是用私钥签署串联签名并将其放入header?不管怎样,我都试过了……

我的这个(无符号)签名值示例如下:

2016-02-06T20:41:00Z:YTdkNzAwYTllNjI1M2EyZTllNDNiZjVmYjg0MWFhMGRiMTE2MjI1NTYwNTA2YzQyODc4MjUwNTQ0YTE5YTg4Yw==:https://api.apple-cloudkit.com/database/1/[iCloud Container]/development/public/records/lookup  

请求 body 值经过 SHA256 哈希处理,然后进行 base64 编码。我的问题是,我应该用“:”连接,但 url 和日期也包含“:”。这是正确的吗? (我也试过 URL-Encode 和 URL 并删除日期中的“:”。
接下来我用ECDSA对这个签名串进行了签名,放入header中发送。但我总是得到 401 "Authentication failed" 回来。为了对其进行签名,我使用了 ecdsa python 模块,并使用以下命令:

from ecdsa import SigningKey  
a = SigningKey.from_pem(open("path_to_pem_file").read())  
b = "[date]:[base64(request_body)]:/database/1/iCloud....."  
print a.sign(b).encode('hex')

可能 python 模块无法正常工作。但是它可以从私钥生成正确的 public 密钥。所以我希望其他功能也能正常工作。

是否有任何body使用server-to-server方法针对CloudKit进行了身份验证?它如何正确工作?

编辑:更正 python 有效的版本

from ecdsa import SigningKey
import ecdsa, base64, hashlib  

a = SigningKey.from_pem(open("path_to_pem_file").read())  
b = "[date]:[base64(sha256(request_body))]:/database/1/iCloud....."  
signature = a.sign(b, hashfunc=hashlib.sha256, sigencode=ecdsa.util.sigencode_der)  
signature = base64.b64encode(signature)
print signature #include this into the header

留言的最后一部分

[Current date]:[Request body]:[Web Service URL]

不得包含域(它必须包含任何查询参数):

2016-02-06T20:41:00Z:YTdkNzAwYTllNjI1M2EyZTllNDNiZjVmYjg0MWFhMGRiMTE2MjI1NTYwNTA2YzQyODc4MjUwNTQ0YTE5YTg4Yw==:/database/1/[iCloud Container]/development/public/records/lookup

使用换行符以提高可读性:

2016-02-06T20:41:00Z
:YTdkNzAwYTllNjI1M2EyZTllNDNiZjVmYjg0MWFhMGRiMTE2MjI1NTYwNTA2YzQyODc4MjUwNTQ0YTE5YTg4Yw==
:/database/1/[iCloud Container]/development/public/records/lookup

下面展示了如何用伪代码计算头部值

确切的 API 调用取决于您使用的具体语言和加密库。

//1. Date
//Example: 2016-02-07T18:58:24Z
//Pitfall: make sure to not include milliseconds
date = isoDateWithoutMilliseconds() 

//2. Payload
//Example (empty string base64 encoded; GET requests):
//47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=
//Pitfall: make sure the output is base64 encoded (not hex)
payload = base64encode(sha256(body))  

//3. Path
//Example: /database/1/[containerIdentifier]/development/public/records/lookup
//Pitfall: Don't include the domain; do include any query parameter
path = stripDomainKeepQueryParams(url) 

//4. Message
//Join date, payload, and path with colons
message = date + ':' + payload + ':' + path

//5. Compute a signature for the message using your private key.
//This step looks very different for every language/crypto lib.
//Pitfall: make sure the output is base64 encoded.
//Hint: the key itself contains information about the signature algorithm 
//      (on NodeJS you can use the signature name 'RSA-SHA256' to compute a 
//      the correct ECDSA signature with an ECDSA key).
signature = base64encode(sign(message, key))

//6. Set headers
X-Apple-CloudKit-Request-KeyID = keyID 
X-Apple-CloudKit-Request-ISO8601Date = date  
X-Apple-CloudKit-Request-SignatureV1 = signature

//7. For POST requests, don't forget to actually send the unsigned request body
//   (not just the headers)

提取 Apple 的 cloudkit.js implementation and using the first call from the Apple sample code node-client-s2s/index.js 你可以构造如下:

您使用 sha256:

对请求正文请求进行哈希处理
var crypto = require('crypto');
var bodyHasher = crypto.createHash('sha256');
bodyHasher.update(requestBody);
var hashedBody = bodyHasher.digest("base64");

使用配置中提供的私钥对 [Current date]:[Request body]:[Web Service URL] 负载签名。

var c = crypto.createSign("RSA-SHA256");
c.update(rawPayload);
var requestSignature = c.sign(key, "base64");

另一个注意事项是 [Web Service URL] 有效负载组件 不得包含域 但它确实需要任何查询参数。

确保 X-Apple-CloudKit-Request-ISO8601Date 中的日期值与签名中的日期值相同。 (这些细节没有完整记录,但可以通过查看 CloudKit.js 实现来观察)。

一个更完整的 nodejs 示例如下所示:

(function() {

const https = require('https');
var fs = require('fs');
var crypto = require('crypto');

var key = fs.readFileSync(__dirname + '/eckey.pem', "utf8");
var authKeyID = 'auth-key-id';

// path of our request (domain not included)
var requestPath = "/database/1/iCloud.containerIdentifier/development/public/users/current";

// request body (GET request is blank)
var requestBody = '';

// date string without milliseconds
var requestDate = (new Date).toISOString().replace(/(\.\d\d\d)Z/, "Z");

var bodyHasher = crypto.createHash('sha256');
bodyHasher.update(requestBody);
var hashedBody = bodyHasher.digest("base64");

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

// sign payload
var c = crypto.createSign("sha256");
c.update(rawPayload);
var requestSignature = c.sign(key, "base64");

// put headers together
var headers = {
    'X-Apple-CloudKit-Request-KeyID': authKeyID,
    'X-Apple-CloudKit-Request-ISO8601Date': requestDate,
    'X-Apple-CloudKit-Request-SignatureV1': requestSignature
};

var options = {
    hostname: 'api.apple-cloudkit.com',
    port: 443,
    path: requestPath,
    method: 'GET',
    headers: headers
};

var req = https.request(options, (res) => {
   //... handle nodejs response
});

req.end();

})();

这也作为要点存在:https://gist.github.com/jessedc/a3161186b450317a9cb5

在命令行上使用 openssl(更新)

第一次散列可以用这个命令完成:

openssl sha -sha256 -binary < body.txt | base64

要签署请求的第二部分,您需要比 OSX 10.11 附带的更现代的 openSSL 版本,并使用以下命令:

/usr/local/bin/openssl dgst -sha256WithRSAEncryption -binary -sign ck-server-key.pem raw_signature.txt | base64

感谢@maurice_vB below and on twitter for this info

我在 PHP 中制作了一个工作代码示例:https://gist.github.com/Mauricevb/87c144cec514c5ce73bd (基于@Jessedc 的 JavaScript 示例)

顺便说一下,请确保您设置的日期时间为 UTC 时区。因此,我的代码不起作用。

从我在 Node.js 中从事的项目中提炼出来的。也许你会发现它很有用。替换 X-Apple-CloudKit-Request-KeyIDrequestOptions.path 中的容器标识符以使其工作。

私钥/pem 生成:openssl ecparam -name prime256v1 -genkey -noout -out eckey.pem 并生成 public 密钥以在 CloudKit 仪表板 openssl ec -in eckey.pem -pubout.

上注册
var crypto = require("crypto"),
    https = require("https"),
    fs = require("fs")

var CloudKitRequest = function(payload) {
  this.payload = payload
  this.requestOptions = { // Used with `https.request`
    hostname: "api.apple-cloudkit.com",
    port: 443,
    path: '/database/1/iCloud.com.your.container/development/public/records/modify',
    method: 'POST',
    headers: { // We will add more headers in the sign methods
      "X-Apple-CloudKit-Request-KeyID": "your-ck-request-keyID"
    }
  }
}

签署请求:

CloudKitRequest.prototype.sign = function(privateKey) {
  var dateString = new Date().toISOString().replace(/\.[0-9]+?Z/, "Z"), // NOTE: No milliseconds
      hash = crypto.createHash("sha256"),
      sign = crypto.createSign("RSA-SHA256")

  // Create the hash of the payload
  hash.update(this.payload, "utf8")
  var payloadSignature = hash.digest("base64")

  // Create the signature string to sign
  var signatureData = [
    dateString,
    payloadSignature,
    this.requestOptions.path
  ].join(":") // [Date]:[Request body]:[Web Service URL]

  // Construct the signature
  sign.update(signatureData)
  var signature = sign.sign(privateKey, "base64")

  // Update the request headers
  this.requestOptions.headers["X-Apple-CloudKit-Request-ISO8601Date"] = dateString
  this.requestOptions.headers["X-Apple-CloudKit-Request-SignatureV1"] = signature

  return signature // This might be useful to keep around
}

现在您可以发送请求了:

CloudKitRequest.prototype.send = function(cb) {
  var request = https.request(this.requestOptions, function(response) {
    var responseBody = ""

    response.on("data", function(chunk) {
      responseBody += chunk.toString("utf8")
    })

    response.on("end", function() {
      cb(null, JSON.parse(responseBody))
    })
  })

  request.on("error", function(err) {
    cb(err, null)
  })

  request.end(this.payload)
}

因此给出以下内容:

var privateKey = fs.readFileSync("./eckey.pem"),
    creationPayload = JSON.stringify({
      "operations": [{
          "operationType" : "create",
          "record" : {
            "recordType" : "Post",
            "fields" : {
              "title" : { "value" : "A Post From The Server" }
          }
        }
      }]
    })

使用请求:

var creationRequest = new CloudKitRequest(creationPayload)
creationRequest.sign(privateKey)
creationRequest.send(function(err, response) {
  console.log("Created a new entry with error", err, "and respone", response)
})

为了您的复制粘贴乐趣:https://gist.github.com/spllr/4bf3fadb7f6168f67698(已编辑)

我遇到了同样的问题,最终编写了一个与 python-requests 一起工作的库,以与 Python 中的 CloudKit API 交互。

pip install requests-cloudkit

安装后,只需导入身份验证处理程序 (CloudKitAuth) 并直接将其用于请求。它将透明地验证您向 CloudKit API.

发出的任何请求
>>> import requests
>>> from requests_cloudkit import CloudKitAuth
>>> auth = CloudKitAuth(key_id=YOUR_KEY_ID, key_file_name=YOUR_PRIVATE_KEY_PATH)
>>> requests.get("https://api.apple-cloudkit.com/database/[version]/[container]/[environment]/public/zones/list", auth=auth)

如果您想贡献或报告问题,GitHub 项目可在 https://github.com/lionheart/requests-cloudkit 获得。

如果其他人试图通过 Ruby 执行此操作,则需要一个关键方法别名来猴子修补 OpenSSL lib 以使其工作:

def signature_for_request(body_json, url, iso8601_date)
  body_sha_hash = Digest::SHA256.digest(body_json)

  payload_for_signature = [iso8601_date, Base64.strict_encode64(body_sha_hash), url].join(":")

  OpenSSL::PKey::EC.send(:alias_method, :private?, :private_key?)

  ec = OpenSSL::PKey::EC.new(CK_PEM_STRING)
  digest = OpenSSL::Digest::SHA256.new
  signature = ec.sign(digest, payload_for_signature)
  base64_signature = Base64.strict_encode64(signature)

  return base64_signature
end

请注意,在上面的示例中,url 是排除域组件的路径(以 /database... 开头),而 CK_PEM_STRING 只是 pem 的 File.read在设置 private/public 密钥对时生成。

iso8601_date 最容易生成使用:

Time.now.utc.iso8601

当然,您希望将其存储在一个变量中以包含在您的最终请求中。可以使用以下模式构建最终请求:

def perform_request(url, body, iso8601_date)

  signature = self.signature_for_request(body, url, iso8601_date)

  uri = URI.parse(CK_SERVICE_BASE + url)

  header = {
    "Content-Type" => "text/plain",
    "X-Apple-CloudKit-Request-KeyID" => CK_KEY_ID,
    "X-Apple-CloudKit-Request-ISO8601Date" => iso8601_date,
    "X-Apple-CloudKit-Request-SignatureV1" => signature
  }

  # Create the HTTP objects
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Post.new(uri.request_uri, header)
  request.body = body

  # Send the request
  response = http.request(request)

  return response
end

现在对我来说就像一个魅力。