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]
文档说:
在步骤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
答案 0 :(得分:12)
消息的最后部分
[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)
答案 1 :(得分:6)
提取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 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
答案 2 :(得分:6)
我在PHP中创建了一个有效的代码示例:https://gist.github.com/Mauricevb/87c144cec514c5ce73bd (基于@ Jessedc的JavaScript示例)
顺便提一下,请确保以UTC时区设置日期时间。我的代码因为这个而无效。
答案 3 :(得分:5)
从我在Node中工作的项目中提取出来。也许你会发现它很有用。将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(已编辑)
答案 4 :(得分:3)
如果其他人试图通过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。 / p>
使用以下方法最容易生成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
现在对我来说就像一个魅力。
答案 5 :(得分:1)
我遇到了同样的问题,最后编写了一个与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项目。