27

Apple 发布了一种针对 CloudKit 的服务器到服务器进行身份验证的新方法。https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/CloudKitWebServicesReference/SettingUpWebServices.html#//apple_ref/doc/uid/TP40015240-CH24-SW6

我试图针对 CloudKit 和这种方法进行身份验证。起初我生成了密钥对并将公钥提供给 CloudKit,到目前为止没有问题。

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

X-Apple-CloudKit-Request-KeyID: [keyID]  
X-Apple-CloudKit-Request-ISO8601Date: [date]  
X-Apple-CloudKit-Request-SignatureV1: [signature]
  • [keyID],没问题。您可以在 CloudKit 仪表板中找到它。
  • [日期],我认为这应该工作:2016-02-06T20:41:00Z
  • [签名],问题来了……

文档说:

在步骤 1 中创建的签名。

步骤 1 说:

连接以下参数并用冒号分隔它们。
[Current date]:[Request body]:[Web Service URL]

我问自己“为什么我必须生成密钥对?”。
但是第2步说:

使用您的私钥计算此消息的 ECDSA 签名。

也许他们的意思是用私钥签署连接签名并将其放入标题中?反正我两个都试过了...

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

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

请求正文值经过 SHA256 散列,然后经过 base64 编码。我的问题是,我应该用“:”连接,但网址和日期也包含“:”。这是正确的吗?(我还尝试对 URL 进行 URL 编码并删除日期中的“:”)。
接下来,我用 ECDSA 签署了这个签名字符串,将其放入标头并发送。但我总是得到 401“身份验证失败”。为了签署它,我使用了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模块不能正常工作。但它可以从私钥生成正确的公钥。所以我希望其他功能也能工作。

有没有人设法使用服务器到服务器的方法对 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
4

6 回答 6

13

消息的最后一部分

[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)
于 2016-02-07T19:56:28.213 回答
8

提取 Apple 的cloudkit.js实现并使用 Apple 示例代码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 和推特上的此信息

于 2016-02-07T20:40:46.603 回答
7

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

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

于 2016-02-07T21:37:30.257 回答
6

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

私钥/ pem 使用:openssl ecparam -name prime256v1 -genkey -noout -out eckey.pem生成并生成公钥以在 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 (已编辑)

于 2016-02-09T20:01:05.433 回答
3

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

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。

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

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

于 2016-06-09T14:32:34.880 回答
2

我遇到了同样的问题,最终编写了一个与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)

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

于 2016-05-29T01:54:34.700 回答