Debian Codegraph @

src/lockdown-cu.c

raw
1 /*
2 * lockdown-cu.c
3 * com.apple.mobile.lockdownd service CU additions
4 *
5 * Copyright (c) 2021 Nikias Bassen, All Rights Reserved.
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <string.h>
27 #include <stdlib.h>
28 #define _GNU_SOURCE 1
29 #define __USE_GNU 1
30 #include <stdio.h>
31 #include <ctype.h>
32
33 #ifndef _MSC_VER
34 #include <unistd.h>
35 #endif
36
37 #include <plist/plist.h>
38
39 #include "idevice.h"
40 #include "lockdown.h"
41 #include "common/debug.h"
42
43 #ifdef HAVE_WIRELESS_PAIRING
44
45 #include <libimobiledevice-glue/utils.h>
46 #include <libimobiledevice-glue/socket.h>
47 #include <libimobiledevice-glue/opack.h>
48 #include <libimobiledevice-glue/tlv.h>
49
50 #if defined(HAVE_OPENSSL)
51 #include <openssl/hmac.h>
52 #include <openssl/evp.h>
53 #include <openssl/rand.h>
54 #if defined(LIBRESSL_VERSION_NUMBER) && (LIBRESSL_VERSION_NUMBER < 0x2030200fL)
55 #include <openssl/chacha.h>
56 #include <openssl/poly1305.h>
57 #endif
58 #elif defined(HAVE_GCRYPT)
59 #include <gcrypt.h>
60 #elif defined(HAVE_MBEDTLS)
61 #include <mbedtls/md.h>
62 #include <mbedtls/chachapoly.h>
63 #endif
64
65 #ifdef __APPLE__
66 #include <sys/sysctl.h>
67 #include <SystemConfiguration/SystemConfiguration.h>
68 #include <CoreFoundation/CoreFoundation.h>
69 #include <TargetConditionals.h>
70 #endif
71
72 #include "property_list_service.h"
73 #include "common/userpref.h"
74
75 #include "endianness.h"
76
77 #include "srp.h"
78 #include "ed25519.h"
79
80 /* {{{ SRP6a parameters */
81 static const unsigned char kSRPModulus3072[384] = {
82 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34,
83 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74,
84 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd,
85 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, 0xf2, 0x5f, 0x14, 0x37,
86 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6,
87 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed,
88 0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, 0x1f, 0xe6,
89 0x49, 0x28, 0x66, 0x51, 0xec, 0xe4, 0x5b, 0x3d, 0xc2, 0x00, 0x7c, 0xb8, 0xa1, 0x63, 0xbf, 0x05,
90 0x98, 0xda, 0x48, 0x36, 0x1c, 0x55, 0xd3, 0x9a, 0x69, 0x16, 0x3f, 0xa8, 0xfd, 0x24, 0xcf, 0x5f,
91 0x83, 0x65, 0x5d, 0x23, 0xdc, 0xa3, 0xad, 0x96, 0x1c, 0x62, 0xf3, 0x56, 0x20, 0x85, 0x52, 0xbb,
92 0x9e, 0xd5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6d, 0x67, 0x0c, 0x35, 0x4e, 0x4a, 0xbc, 0x98, 0x04,
93 0xf1, 0x74, 0x6c, 0x08, 0xca, 0x18, 0x21, 0x7c, 0x32, 0x90, 0x5e, 0x46, 0x2e, 0x36, 0xce, 0x3b,
94 0xe3, 0x9e, 0x77, 0x2c, 0x18, 0x0e, 0x86, 0x03, 0x9b, 0x27, 0x83, 0xa2, 0xec, 0x07, 0xa2, 0x8f,
95 0xb5, 0xc5, 0x5d, 0xf0, 0x6f, 0x4c, 0x52, 0xc9, 0xde, 0x2b, 0xcb, 0xf6, 0x95, 0x58, 0x17, 0x18,
96 0x39, 0x95, 0x49, 0x7c, 0xea, 0x95, 0x6a, 0xe5, 0x15, 0xd2, 0x26, 0x18, 0x98, 0xfa, 0x05, 0x10,
97 0x15, 0x72, 0x8e, 0x5a, 0x8a, 0xaa, 0xc4, 0x2d, 0xad, 0x33, 0x17, 0x0d, 0x04, 0x50, 0x7a, 0x33,
98 0xa8, 0x55, 0x21, 0xab, 0xdf, 0x1c, 0xba, 0x64, 0xec, 0xfb, 0x85, 0x04, 0x58, 0xdb, 0xef, 0x0a,
99 0x8a, 0xea, 0x71, 0x57, 0x5d, 0x06, 0x0c, 0x7d, 0xb3, 0x97, 0x0f, 0x85, 0xa6, 0xe1, 0xe4, 0xc7,
100 0xab, 0xf5, 0xae, 0x8c, 0xdb, 0x09, 0x33, 0xd7, 0x1e, 0x8c, 0x94, 0xe0, 0x4a, 0x25, 0x61, 0x9d,
101 0xce, 0xe3, 0xd2, 0x26, 0x1a, 0xd2, 0xee, 0x6b, 0xf1, 0x2f, 0xfa, 0x06, 0xd9, 0x8a, 0x08, 0x64,
102 0xd8, 0x76, 0x02, 0x73, 0x3e, 0xc8, 0x6a, 0x64, 0x52, 0x1f, 0x2b, 0x18, 0x17, 0x7b, 0x20, 0x0c,
103 0xbb, 0xe1, 0x17, 0x57, 0x7a, 0x61, 0x5d, 0x6c, 0x77, 0x09, 0x88, 0xc0, 0xba, 0xd9, 0x46, 0xe2,
104 0x08, 0xe2, 0x4f, 0xa0, 0x74, 0xe5, 0xab, 0x31, 0x43, 0xdb, 0x5b, 0xfc, 0xe0, 0xfd, 0x10, 0x8e,
105 0x4b, 0x82, 0xd1, 0x20, 0xa9, 0x3a, 0xd2, 0xca, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
106 };
107
108 static const unsigned char kSRPGenerator5 = 5;
109 /* }}} */
110
111 /* {{{ HKDF */
112 #if defined(HAVE_OPENSSL)
113 #define MD_ALGO_SHA512 EVP_sha512()
114 typedef const EVP_MD* MD_ALGO_TYPE_T;
115 #define MD_ALGO_DIGEST_SIZE EVP_MD_size
116 #define MD_MAX_DIGEST_SIZE EVP_MAX_MD_SIZE
117
118 #elif defined(HAVE_GCRYPT)
119 #define MD_ALGO_SHA512 GCRY_MD_SHA512
120 typedef int MD_ALGO_TYPE_T;
121 #define MD_ALGO_DIGEST_SIZE gcry_md_get_algo_dlen
122 #define MD_MAX_DIGEST_SIZE 64
123
124 static void HMAC(MD_ALGO_TYPE_T md, unsigned char* key, unsigned int key_len, unsigned char* data, unsigned int data_len, unsigned char* out, unsigned int* out_len)
125 {
126 gcry_md_hd_t hd;
127 if (gcry_md_open(&hd, md, GCRY_MD_FLAG_HMAC)) {
128 debug_info("gcry_md_open() failed");
129 return;
130 }
131 if (gcry_md_setkey(hd, key, key_len)) {
132 gcry_md_close (hd);
133 debug_info("gcry_md_setkey() failed");
134 return;
135 }
136 gcry_md_write(hd, data, data_len);
137
138 unsigned char* digest = gcry_md_read(hd, md);
139 if (!digest) {
140 gcry_md_close(hd);
141 debug_info("gcry_md_read() failed");
142 return;
143 }
144
145 *out_len = gcry_md_get_algo_dlen(md);
146 memcpy(out, digest, *out_len);
147 gcry_md_close(hd);
148 }
149 #elif defined(HAVE_MBEDTLS)
150 #define MD_ALGO_SHA512 MBEDTLS_MD_SHA512
151 typedef mbedtls_md_type_t MD_ALGO_TYPE_T;
152 #define MD_ALGO_DIGEST_SIZE(x) mbedtls_md_get_size(mbedtls_md_info_from_type(x))
153 #define MD_MAX_DIGEST_SIZE MBEDTLS_MD_MAX_SIZE
154
155 static void HMAC(MD_ALGO_TYPE_T md, unsigned char* key, unsigned int key_len, unsigned char* data, unsigned int data_len, unsigned char* out, unsigned int* out_len)
156 {
157 mbedtls_md_context_t mdctx;
158 mbedtls_md_init(&mdctx);
159 int mr = mbedtls_md_setup(&mdctx, mbedtls_md_info_from_type(md), 1);
160 if (mr != 0) {
161 debug_info("mbedtls_md_setup() failed: %d", mr);
162 return;
163 }
164
165 mr = mbedtls_md_hmac_starts(&mdctx, key, key_len);
166 if (mr != 0) {
167 mbedtls_md_free(&mdctx);
168 debug_info("mbedtls_md_hmac_starts() failed: %d", mr);
169 return;
170 }
171
172 mbedtls_md_hmac_update(&mdctx, data, data_len);
173
174 mr = mbedtls_md_hmac_finish(&mdctx, out);
175 if (mr == 0) {
176 *out_len = mbedtls_md_get_size(mbedtls_md_info_from_type(md));
177 } else {
178 debug_info("mbedtls_md_hmac_finish() failed: %d", mr);
179 }
180 mbedtls_md_free(&mdctx);
181 }
182 #endif
183
184 static void hkdf_md_extract(MD_ALGO_TYPE_T md, unsigned char* salt, unsigned int salt_len, unsigned char* input_key_material, unsigned int input_key_material_len, unsigned char* out, unsigned int* out_len)
185 {
186 unsigned char empty_salt[MD_MAX_DIGEST_SIZE];
187 if (!md || !out || !out_len || !*out_len) return;
188 if (salt_len == 0) {
189 salt_len = MD_ALGO_DIGEST_SIZE(md);
190 salt = (unsigned char*)empty_salt;
191 }
192 HMAC(md, salt, salt_len, input_key_material, input_key_material_len, out, out_len);
193 }
194
195 static void hkdf_md_expand(MD_ALGO_TYPE_T md, unsigned char* prk, unsigned int prk_len, unsigned char* info, unsigned int info_len, unsigned char* out, unsigned int* out_len)
196 {
197 if (!md || !out || !out_len || !*out_len) return;
198 unsigned int md_size = MD_ALGO_DIGEST_SIZE(md);
199 if (*out_len > 255 * md_size) {
200 *out_len = 0;
201 return;
202 }
203 int blocks_needed = (*out_len) / md_size;
204 if (((*out_len) % md_size) != 0) blocks_needed++;
205 unsigned int okm_len = 0;
206 unsigned char okm_block[MD_MAX_DIGEST_SIZE];
207 unsigned int okm_block_len = 0;
208 int i;
209 for (i = 0; i < blocks_needed; i++) {
210 unsigned int output_block_len = okm_block_len + info_len + 1;
211 unsigned char* output_block = malloc(output_block_len);
212 if (okm_block_len > 0) {
213 memcpy(output_block, okm_block, okm_block_len);
214 }
215 memcpy(output_block + okm_block_len, info, info_len);
216 output_block[okm_block_len + info_len] = (uint8_t)(i+1);
217
218 HMAC(md, prk, prk_len, output_block, output_block_len, okm_block, &okm_block_len);
219 if (okm_len < *out_len) {
220 memcpy(out + okm_len, okm_block, (okm_len + okm_block_len > *out_len) ? *out_len - okm_len : okm_block_len);
221 }
222 okm_len += okm_block_len;
223 free(output_block);
224 }
225 }
226
227 static void hkdf_md(MD_ALGO_TYPE_T md, unsigned char* salt, unsigned int salt_len, unsigned char* info, unsigned int info_len, unsigned char* initial_key_material, unsigned int initial_key_material_size, unsigned char* out, unsigned int *out_len)
228 {
229 if (!md || !initial_key_material || !out || !out_len || !*out_len) return;
230
231 unsigned char prk[MD_MAX_DIGEST_SIZE];
232 unsigned int prk_len = MD_ALGO_DIGEST_SIZE(md);
233
234 hkdf_md_extract(md, salt, salt_len, initial_key_material, initial_key_material_size, prk, &prk_len);
235 if (prk_len > 0) {
236 hkdf_md_expand(md, prk, prk_len, info, info_len, out, out_len);
237 } else {
238 *out_len = 0;
239 }
240 }
241 /* }}} */
242
243 /* {{{ chacha20 poly1305 encryption/decryption */
244 #if defined(HAVE_OPENSSL) && defined(LIBRESSL_VERSION_NUMBER) && (LIBRESSL_VERSION_NUMBER < 0x2030200fL)
245 /* {{{ From: OpenBSD's e_chacha20poly1305.c */
246 /*
247 * Copyright (c) 2015 Reyk Floter <[email protected]>
248 * Copyright (c) 2014, Google Inc.
249 *
250 * Permission to use, copy, modify, and/or distribute this software for any
251 * purpose with or without fee is hereby granted, provided that the above
252 * copyright notice and this permission notice appear in all copies.
253 *
254 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
255 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
256 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
257 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
258 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
259 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
260 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
261 */
262 static void
263 poly1305_update_with_length(poly1305_state *poly1305,
264 const unsigned char *data, size_t data_len)
265 {
266 size_t j = data_len;
267 unsigned char length_bytes[8];
268 unsigned i;
269
270 for (i = 0; i < sizeof(length_bytes); i++) {
271 length_bytes[i] = j;
272 j >>= 8;
273 }
274
275 if (data != NULL)
276 CRYPTO_poly1305_update(poly1305, data, data_len);
277 CRYPTO_poly1305_update(poly1305, length_bytes, sizeof(length_bytes));
278 }
279
280 static void
281 poly1305_update_with_pad16(poly1305_state *poly1305,
282 const unsigned char *data, size_t data_len)
283 {
284 static const unsigned char zero_pad16[16];
285 size_t pad_len;
286
287 CRYPTO_poly1305_update(poly1305, data, data_len);
288
289 /* pad16() is defined in RFC 7539 2.8.1. */
290 if ((pad_len = data_len % 16) == 0)
291 return;
292
293 CRYPTO_poly1305_update(poly1305, zero_pad16, 16 - pad_len);
294 }
295 /* }}} */
296 #endif
297
298 static void chacha20_poly1305_encrypt_96(unsigned char* key, unsigned char* nonce, unsigned char* ad, size_t ad_len, unsigned char* in, size_t in_len, unsigned char* out, size_t* out_len)
299 {
300 #if defined(HAVE_OPENSSL)
301 #if defined(LIBRESSL_VERSION_NUMBER) && (LIBRESSL_VERSION_NUMBER < 0x3050000fL)
302 #if (LIBRESSL_VERSION_NUMBER >= 0x2040000fL)
303 const EVP_AEAD *aead = EVP_aead_chacha20_poly1305();
304 EVP_AEAD_CTX ctx;
305 EVP_AEAD_CTX_init(&ctx, aead, key, EVP_AEAD_key_length(aead), EVP_AEAD_DEFAULT_TAG_LENGTH, NULL);
306 EVP_AEAD_CTX_seal(&ctx, out, out_len, *out_len, nonce, 12, in, in_len, ad, ad_len);
307 #else
308 unsigned char poly1305_key[32];
309 poly1305_state poly1305;
310 uint64_t ctr = (uint64_t)(nonce[0] | nonce[1] << 8 | nonce[2] << 16 | nonce[3] << 24) << 32;
311 const unsigned char* iv = nonce + 4;
312
313 memset(poly1305_key, 0, sizeof(poly1305_key));
314 CRYPTO_chacha_20(poly1305_key, poly1305_key, sizeof(poly1305_key), key, iv, ctr);
315
316 CRYPTO_poly1305_init(&poly1305, poly1305_key);
317 poly1305_update_with_pad16(&poly1305, ad, ad_len);
318 CRYPTO_chacha_20(out, in, in_len, key, iv, ctr + 1);
319 poly1305_update_with_pad16(&poly1305, out, in_len);
320 poly1305_update_with_length(&poly1305, NULL, ad_len);
321 poly1305_update_with_length(&poly1305, NULL, in_len);
322
323 CRYPTO_poly1305_finish(&poly1305, out + in_len);
324
325 *out_len = in_len + 16;
326 #endif
327 #elif defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x10100000L)
328 int outl = 0;
329 EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
330 EVP_EncryptInit_ex(ctx, EVP_chacha20_poly1305(), NULL, key, nonce);
331 EVP_EncryptUpdate(ctx, out, &outl, in, in_len);
332 *out_len = outl;
333 outl = 0;
334 EVP_EncryptFinal_ex(ctx, out + *out_len, &outl);
335 *out_len += outl;
336 EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, 16, out + *out_len);
337 EVP_CIPHER_CTX_free(ctx);
338 *out_len += 16;
339 #else
340 #error Please use a newer version of OpenSSL (>= 1.1.0)
341 #endif
342 #elif defined(HAVE_GCRYPT)
343 #if defined(GCRYPT_VERSION_NUMBER) && (GCRYPT_VERSION_NUMBER >= 0x010700)
344 gcry_cipher_hd_t hd;
345 if (gcry_cipher_open(&hd, GCRY_CIPHER_CHACHA20, GCRY_CIPHER_MODE_POLY1305, 0)) {
346 debug_info("gcry_cipher_open() failed");
347 return;
348 }
349 gcry_cipher_setkey(hd, key, 32);
350 gcry_cipher_setiv(hd, nonce, 12);
351 gcry_cipher_authenticate(hd, ad, ad_len);
352 *out_len = in_len + 16;
353 if (gcry_cipher_encrypt(hd, out, *out_len, in, in_len)) {
354 *out_len = 0;
355 }
356 gcry_cipher_gettag(hd, out+in_len, 16);
357 gcry_cipher_close(hd);
358 #else
359 #error Please use a newer version of libgcrypt (>= 1.7.0)
360 #endif
361 #elif defined (HAVE_MBEDTLS)
362 mbedtls_chachapoly_context ctx;
363 mbedtls_chachapoly_init(&ctx);
364 mbedtls_chachapoly_setkey(&ctx, key);
365 if (mbedtls_chachapoly_encrypt_and_tag(&ctx, in_len, nonce, ad, ad_len, in, out, out+in_len) != 0) {
366 *out_len = 0;
367 }
368 mbedtls_chachapoly_free(&ctx);
369 #else
370 #error chacha20_poly1305_encrypt_96 is not implemented
371 #endif
372 }
373
374 static void chacha20_poly1305_encrypt_64(unsigned char* key, unsigned char* nonce, unsigned char* ad, size_t ad_len, unsigned char* in, size_t in_len, unsigned char* out, size_t* out_len)
375 {
376 unsigned char _nonce[12];
377 *(uint32_t*)(&_nonce[0]) = 0;
378 memcpy(&_nonce[4], nonce, 8);
379 chacha20_poly1305_encrypt_96(key, _nonce, ad, ad_len, in, in_len, out, out_len);
380 }
381
382 static void chacha20_poly1305_decrypt_96(unsigned char* key, unsigned char* nonce, unsigned char* ad, size_t ad_len, unsigned char* in, size_t in_len, unsigned char* out, size_t* out_len)
383 {
384 #if defined(HAVE_OPENSSL)
385 #if defined(LIBRESSL_VERSION_NUMBER) && (LIBRESSL_VERSION_NUMBER < 0x3050000fL)
386 #if (LIBRESSL_VERSION_NUMBER >= 0x2040000fL)
387 const EVP_AEAD *aead = EVP_aead_chacha20_poly1305();
388 EVP_AEAD_CTX ctx;
389 EVP_AEAD_CTX_init(&ctx, aead, key, EVP_AEAD_key_length(aead), EVP_AEAD_DEFAULT_TAG_LENGTH, NULL);
390 EVP_AEAD_CTX_open(&ctx, out, out_len, *out_len, nonce, 12, in, in_len, ad, ad_len);
391 #else
392 unsigned char mac[16];
393 unsigned char poly1305_key[32];
394 poly1305_state poly1305;
395 size_t plaintext_len = in_len - 16;
396 uint64_t ctr = (uint64_t)(nonce[0] | nonce[1] << 8 | nonce[2] << 16 | nonce[3] << 24) << 32;
397 const unsigned char *iv = nonce + 4;
398
399 memset(poly1305_key, 0, sizeof(poly1305_key));
400 CRYPTO_chacha_20(poly1305_key, poly1305_key, sizeof(poly1305_key), key, iv, ctr);
401
402 CRYPTO_poly1305_init(&poly1305, poly1305_key);
403 poly1305_update_with_pad16(&poly1305, ad, ad_len);
404 poly1305_update_with_pad16(&poly1305, in, plaintext_len);
405 poly1305_update_with_length(&poly1305, NULL, ad_len);
406 poly1305_update_with_length(&poly1305, NULL, plaintext_len);
407
408 CRYPTO_poly1305_finish(&poly1305, mac);
409
410 if (memcmp(mac, in + plaintext_len, 16) != 0) {
411 *out_len = 0;
412 return;
413 }
414
415 CRYPTO_chacha_20(out, in, plaintext_len, key, iv, ctr + 1);
416 *out_len = plaintext_len;
417 #endif
418 #elif defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x10100000L)
419 int outl = 0;
420 size_t plaintext_len = in_len - 16;
421 EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
422 EVP_DecryptInit_ex(ctx, EVP_chacha20_poly1305(), NULL, key, nonce);
423 EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, 16, in + plaintext_len);
424 EVP_DecryptUpdate(ctx, out, &outl, in, plaintext_len);
425 *out_len = outl;
426 outl = 0;
427 if (EVP_DecryptFinal_ex(ctx, out + *out_len, &outl) == 1) {
428 *out_len += outl;
429 } else {
430 *out_len = 0;
431 }
432 EVP_CIPHER_CTX_free(ctx);
433 #else
434 #error Please use a newer version of OpenSSL (>= 1.1.0)
435 #endif
436 #elif defined(HAVE_GCRYPT)
437 #if defined(GCRYPT_VERSION_NUMBER) && (GCRYPT_VERSION_NUMBER >= 0x010700)
438 gcry_cipher_hd_t hd;
439 if (gcry_cipher_open(&hd, GCRY_CIPHER_CHACHA20, GCRY_CIPHER_MODE_POLY1305, 0)) {
440 debug_info("gcry_cipher_open() failed");
441 return;
442 }
443 gcry_cipher_setkey(hd, key, 32);
444 gcry_cipher_setiv(hd, nonce, 12);
445 gcry_cipher_authenticate(hd, ad, ad_len);
446 unsigned int plaintext_len = in_len - 16;
447 gcry_cipher_decrypt(hd, out, *out_len, in, plaintext_len);
448 if (gcry_cipher_checktag(hd, in + plaintext_len, 16) == 0) {
449 *out_len = plaintext_len;
450 } else {
451 *out_len = 0;
452 }
453 gcry_cipher_close(hd);
454 #else
455 #error Please use a newer version of libgcrypt (>= 1.7.0)
456 #endif
457 #elif defined(HAVE_MBEDTLS)
458 mbedtls_chachapoly_context ctx;
459 mbedtls_chachapoly_init(&ctx);
460 mbedtls_chachapoly_setkey(&ctx, key);
461 unsigned int plaintext_len = in_len - 16;
462 if (mbedtls_chachapoly_auth_decrypt(&ctx, plaintext_len, nonce, ad, ad_len, in + plaintext_len, in, out) == 0) {
463 *out_len = plaintext_len;
464 } else {
465 *out_len = 0;
466 }
467 mbedtls_chachapoly_free(&ctx);
468 #else
469 #error chacha20_poly1305_decrypt_96 is not implemented
470 #endif
471 }
472
473 static void chacha20_poly1305_decrypt_64(unsigned char* key, unsigned char* nonce, unsigned char* ad, size_t ad_len, unsigned char* in, size_t in_len, unsigned char* out, size_t* out_len)
474 {
475 unsigned char _nonce[12];
476 *(uint32_t*)(&_nonce[0]) = 0;
477 memcpy(&_nonce[4], nonce, 8);
478 chacha20_poly1305_decrypt_96(key, _nonce, ad, ad_len, in, in_len, out, out_len);
479 }
480 /* }}} */
481
482 #define PAIRING_ERROR(x) \
483 debug_info(x); \
484 if (pairing_callback) { \
485 pairing_callback(LOCKDOWN_CU_PAIRING_ERROR, cb_user_data, (char*)x, NULL); \
486 }
487
488 #define PAIRING_ERROR_FMT(...) \
489 sprintf(tmp, __VA_ARGS__); \
490 debug_info(tmp); \
491 if (pairing_callback) { \
492 pairing_callback(LOCKDOWN_CU_PAIRING_ERROR, cb_user_data, tmp, NULL); \
493 }
494
495 #endif /* HAVE_WIRELESS_PAIRING */
496
497 lockdownd_error_t lockdownd_cu_pairing_create(lockdownd_client_t client, lockdownd_cu_pairing_cb_t pairing_callback, void* cb_user_data, plist_t host_info, plist_t acl)
498 {
499 #ifdef HAVE_WIRELESS_PAIRING
500 if (!client || !pairing_callback || (host_info && plist_get_node_type(host_info) != PLIST_DICT) || (acl && plist_get_node_type(acl) != PLIST_DICT))
501 return LOCKDOWN_E_INVALID_ARG;
502
503 lockdownd_error_t ret = LOCKDOWN_E_UNKNOWN_ERROR;
504
505 if (client->device && client->device->version == 0) {
506 plist_t p_version = NULL;
507 if (lockdownd_get_value(client, NULL, "ProductVersion", &p_version) == LOCKDOWN_E_SUCCESS) {
508 int vers[3] = {0, 0, 0};
509 char *s_version = NULL;
510 plist_get_string_val(p_version, &s_version);
511 if (s_version && sscanf(s_version, "%d.%d.%d", &vers[0], &vers[1], &vers[2]) >= 2) {
512 client->device->version = IDEVICE_DEVICE_VERSION(vers[0], vers[1], vers[2]);
513 }
514 free(s_version);
515 }
516 plist_free(p_version);
517 }
518
519 char* pairing_uuid = NULL;
520 if (host_info) {
521 plist_t accountid = plist_dict_get_item(host_info, "accountID");
522 if (accountid && plist_get_node_type(accountid) == PLIST_STRING) {
523 plist_get_string_val(accountid, &pairing_uuid);
524 }
525 }
526 if (!pairing_uuid) {
527 userpref_read_system_buid(&pairing_uuid);
528 }
529 if (!pairing_uuid) {
530 pairing_uuid = generate_uuid();
531 }
532 unsigned int pairing_uuid_len = strlen(pairing_uuid);
533
534 SRP_initialize_library();
535
536 SRP* srp = SRP_new(SRP6a_sha512_client_method());
537 if (!srp) {
538 PAIRING_ERROR("Failed to initialize SRP")
539 return LOCKDOWN_E_UNKNOWN_ERROR;
540 }
541
542 char tmp[256];
543 plist_t dict = NULL;
544 uint8_t current_state = 0;
545 uint8_t final_state = 6;
546
547 unsigned char* salt = NULL;
548 unsigned int salt_size = 0;
549 unsigned char* pubkey = NULL;
550 unsigned int pubkey_size = 0;
551
552 unsigned char setup_encryption_key[32];
553
554 cstr *thekey = NULL;
555
556 do {
557 current_state++;
558
559 dict = plist_new_dict();
560 plist_dict_set_item(dict, "Request", plist_new_string("CUPairingCreate"));
561 if (current_state == 1) {
562 plist_dict_set_item(dict, "Flags", plist_new_uint(1));
563 } else {
564 plist_dict_set_item(dict, "Flags", plist_new_uint(0));
565 }
566
567 tlv_buf_t tlv = tlv_buf_new();
568
569 if (current_state == 1) {
570 /* send method */
571 tlv_buf_append(tlv, 0x00, 1, (void*)"\x00"); // 0x00 (Method), 1 bytes, 00
572 } else if (current_state == 3) {
573 /* generate public key */
574 cstr* own_pub = NULL;
575 SRP_gen_pub(srp, &own_pub);
576
577 if (!own_pub) {
578 PAIRING_ERROR("[SRP] Failed to generate public key")
579 ret = LOCKDOWN_E_PAIRING_FAILED;
580 break;
581 }
582
583 /* compute key from remote's public key */
584 if (SRP_compute_key(srp, &thekey, pubkey, pubkey_size) != 0) {
585 cstr_free(own_pub);
586 PAIRING_ERROR("[SRP] Failed to compute key")
587 ret = LOCKDOWN_E_PAIRING_FAILED;
588 break;
589 }
590
591 /* compute response */
592 cstr *response = NULL;
593 SRP_respond(srp, &response);
594
595 /* send our public key + response */
596 tlv_buf_append(tlv, 0x03, own_pub->length, own_pub->data);
597 tlv_buf_append(tlv, 0x04, response->length, response->data);
598 cstr_free(response);
599 cstr_free(own_pub);
600 } else if (current_state == 5) {
601 /* send encrypted info */
602
603 static const char PAIR_SETUP_ENCRYPT_SALT[] = "Pair-Setup-Encrypt-Salt";
604 static const char PAIR_SETUP_ENCRYPT_INFO[] = "Pair-Setup-Encrypt-Info";
605 static const char PAIR_SETUP_CONTROLLER_SIGN_SALT[] = "Pair-Setup-Controller-Sign-Salt";
606 static const char PAIR_SETUP_CONTROLLER_SIGN_INFO[] = "Pair-Setup-Controller-Sign-Info";
607
608 // HKDF with above computed key (SRP_compute_key) + Pair-Setup-Encrypt-Salt + Pair-Setup-Encrypt-Info
609 // result used as key for chacha20-poly1305
610 unsigned int setup_encryption_key_len = sizeof(setup_encryption_key);
611 hkdf_md(MD_ALGO_SHA512, (unsigned char*)PAIR_SETUP_ENCRYPT_SALT, sizeof(PAIR_SETUP_ENCRYPT_SALT)-1, (unsigned char*)PAIR_SETUP_ENCRYPT_INFO, sizeof(PAIR_SETUP_ENCRYPT_INFO)-1, (unsigned char*)thekey->data, thekey->length, setup_encryption_key, &setup_encryption_key_len);
612
613 unsigned char ed25519_pubkey[32];
614 unsigned char ed25519_privkey[64];
615 unsigned char ed25519seed[32];
616 ed25519_create_seed(ed25519seed);
617
618 ed25519_create_keypair(ed25519_pubkey, ed25519_privkey, ed25519seed);
619
620 unsigned int signbuf_len = pairing_uuid_len + 64;
621 unsigned char* signbuf = malloc(signbuf_len);
622 unsigned int hkdf_len = 32;
623 // HKDF with above computed key (SRP_compute_key) + Pair-Setup-Controller-Sign-Salt + Pair-Setup-Controller-Sign-Info
624 hkdf_md(MD_ALGO_SHA512, (unsigned char*)PAIR_SETUP_CONTROLLER_SIGN_SALT, sizeof(PAIR_SETUP_CONTROLLER_SIGN_SALT)-1, (unsigned char*)PAIR_SETUP_CONTROLLER_SIGN_INFO, sizeof(PAIR_SETUP_CONTROLLER_SIGN_INFO)-1, (unsigned char*)thekey->data, thekey->length, signbuf, &hkdf_len);
625
626 memcpy(signbuf + 32, pairing_uuid, pairing_uuid_len);
627 memcpy(signbuf + 32 + pairing_uuid_len, ed25519_pubkey, 32);
628
629 unsigned char ed_sig[64];
630 ed25519_sign(ed_sig, signbuf, 0x64, ed25519_pubkey, ed25519_privkey);
631
632 tlv_buf_t tlvbuf = tlv_buf_new();
633 tlv_buf_append(tlvbuf, 0x01, pairing_uuid_len, (void*)pairing_uuid);
634 tlv_buf_append(tlvbuf, 0x03, sizeof(ed25519_pubkey), ed25519_pubkey);
635 tlv_buf_append(tlvbuf, 0x0a, sizeof(ed_sig), ed_sig);
636
637 /* ACL */
638 unsigned char* odata = NULL;
639 unsigned int olen = 0;
640 if (acl) {
641 opack_encode_from_plist(acl, &odata, &olen);
642 } else {
643 /* defaut ACL */
644 plist_t acl_plist = plist_new_dict();
645 plist_dict_set_item(acl_plist, "com.apple.ScreenCapture", plist_new_bool(1));
646 plist_dict_set_item(acl_plist, "com.apple.developer", plist_new_bool(1));
647 opack_encode_from_plist(acl_plist, &odata, &olen);
648 plist_free(acl_plist);
649 }
650 tlv_buf_append(tlvbuf, 0x12, olen, odata);
651 free(odata);
652
653 /* HOST INFORMATION */
654 char hostname[256];
655 #if defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
656 CFStringRef cname = SCDynamicStoreCopyComputerName(NULL, NULL);
657 CFStringGetCString(cname, hostname, sizeof(hostname), kCFStringEncodingUTF8);
658 CFRelease(cname);
659 #else
660 #ifdef _WIN32
661 DWORD hostname_len = sizeof(hostname);
662 GetComputerName(hostname, &hostname_len);
663 #else
664 gethostname(hostname, sizeof(hostname));
665 #endif
666 #endif
667
668 char modelname[256];
669 modelname[0] = '\0';
670 #ifdef __APPLE__
671 size_t len = sizeof(modelname);
672 sysctlbyname("hw.model", &modelname, &len, NULL, 0);
673 #endif
674 if (strlen(modelname) == 0) {
675 strcpy(modelname, "HackbookPro13,37");
676 }
677
678 unsigned char primary_mac_addr[6] = { 0, 0, 0, 0, 0, 0 };
679 if (get_primary_mac_address(primary_mac_addr) != 0) {
680 debug_info("Failed to get primary mac address");
681 }
682 debug_info("Primary mac address: %02x:%02x:%02x:%02x:%02x:%02x\n", primary_mac_addr[0], primary_mac_addr[1], primary_mac_addr[2], primary_mac_addr[3], primary_mac_addr[4], primary_mac_addr[5]);
683
684 // "OPACK" encoded device info
685 plist_t info_plist = plist_new_dict();
686 //plist_dict_set_item(info_plist, "altIRK", plist_new_data((char*)altIRK, 16));
687 plist_dict_set_item(info_plist, "accountID", plist_new_string(pairing_uuid));
688 plist_dict_set_item(info_plist, "model", plist_new_string(modelname));
689 plist_dict_set_item(info_plist, "name", plist_new_string(hostname));
690 plist_dict_set_item(info_plist, "mac", plist_new_data((char*)primary_mac_addr, 6));
691 if (host_info) {
692 plist_dict_merge(&info_plist, host_info);
693 }
694 opack_encode_from_plist(info_plist, &odata, &olen);
695 plist_free(info_plist);
696 tlv_buf_append(tlvbuf, 0x11, olen, odata);
697 free(odata);
698
699 size_t encrypted_len = tlvbuf->length + 16;
700 unsigned char* encrypted_buf = (unsigned char*)malloc(encrypted_len);
701
702 chacha20_poly1305_encrypt_64(setup_encryption_key, (unsigned char*)"PS-Msg05", NULL, 0, tlvbuf->data, tlvbuf->length, encrypted_buf, &encrypted_len);
703
704 tlv_buf_free(tlvbuf);
705
706 tlv_buf_append(tlv, 0x05, encrypted_len, encrypted_buf);
707 free(encrypted_buf);
708 } else {
709 tlv_buf_free(tlv);
710 PAIRING_ERROR("[SRP] Invalid state");
711 ret = LOCKDOWN_E_PAIRING_FAILED;
712 break;
713 }
714 tlv_buf_append(tlv, 0x06, 1, &current_state);
715 plist_dict_set_item(dict, "Payload", plist_new_data((char*)tlv->data, tlv->length));
716 tlv_buf_free(tlv);
717
718 plist_dict_set_item(dict, "Label", plist_new_string(client->label));
719 plist_dict_set_item(dict, "ProtocolVersion", plist_new_uint(2));
720
721 ret = lockdownd_send(client, dict);
722 plist_free(dict);
723 dict = NULL;
724
725 if (ret != LOCKDOWN_E_SUCCESS) {
726 break;
727 }
728
729 current_state++;
730
731 ret = lockdownd_receive(client, &dict);
732 if (ret != LOCKDOWN_E_SUCCESS) {
733 break;
734 }
735 ret = lockdown_check_result(dict, "CUPairingCreate");
736 if (ret != LOCKDOWN_E_SUCCESS) {
737 break;
738 }
739
740 plist_t extresp = plist_dict_get_item(dict, "ExtendedResponse");
741 if (!extresp) {
742 ret = LOCKDOWN_E_PLIST_ERROR;
743 break;
744 }
745 plist_t blob = plist_dict_get_item(extresp, "Payload");
746 if (!blob) {
747 ret = LOCKDOWN_E_PLIST_ERROR;
748 break;
749 }
750 uint64_t data_len = 0;
751 const char* data = plist_get_data_ptr(blob, &data_len);
752
753 uint8_t state = 0;
754 if (!tlv_data_get_uint8(data, data_len, 0x06, &state)) {
755 PAIRING_ERROR("[SRP] ERROR: Could not find state in response");
756 ret = LOCKDOWN_E_PAIRING_FAILED;
757 break;
758 }
759 if (state != current_state) {
760 PAIRING_ERROR_FMT("[SRP] ERROR: Unexpected state %d, expected %d", state, current_state);
761 ret = LOCKDOWN_E_PAIRING_FAILED;
762 break;
763 }
764
765 unsigned int errval = 0;
766 uint64_t u64val = 0;
767 tlv_data_get_uint(data, data_len, 0x07, &u64val);
768 debug_buffer(data, data_len);
769 errval = (unsigned int)u64val;
770 if (errval > 0) {
771 if (errval == 3) {
772 u64val = 0;
773 tlv_data_get_uint(data, data_len, 0x08, &u64val);
774 if (u64val > 0) {
775 uint32_t retry_delay = (uint32_t)u64val;
776 PAIRING_ERROR_FMT("[SRP] Pairing is blocked for another %u seconds", retry_delay)
777 ret = LOCKDOWN_E_PAIRING_FAILED;
778 break;
779 }
780 } else if (errval == 2 && state == 4) {
781 PAIRING_ERROR_FMT("[SRP] Invalid PIN")
782 ret = LOCKDOWN_E_PAIRING_FAILED;
783 break;
784 } else {
785 PAIRING_ERROR_FMT("[SRP] Received error %u in state %d.", errval, state);
786 ret = LOCKDOWN_E_PAIRING_FAILED;
787 break;
788 }
789 }
790
791 if (state == 2) {
792 /* receive salt and public key */
793 if (!tlv_data_copy_data(data, data_len, 0x02, (void**)&salt, &salt_size)) {
794 PAIRING_ERROR("[SRP] ERROR: Could not find salt in response");
795 ret = LOCKDOWN_E_PAIRING_FAILED;
796 break;
797 }
798 if (!tlv_data_copy_data(data, data_len, 0x03, (void**)&pubkey, &pubkey_size)) {
799 PAIRING_ERROR("[SRP] ERROR: Could not find public key in response");
800
801 ret = LOCKDOWN_E_PAIRING_FAILED;
802 break;
803 }
804
805 const char PAIR_SETUP[] = "Pair-Setup";
806 if (SRP_set_user_raw(srp, (const unsigned char*)PAIR_SETUP, sizeof(PAIR_SETUP)-1) != 0) {
807 PAIRING_ERROR("[SRP] Failed to set SRP user");
808 ret = LOCKDOWN_E_PAIRING_FAILED;
809 break;
810 }
811
812 /* kSRPParameters_3072_SHA512 */
813 if (SRP_set_params(srp, kSRPModulus3072, sizeof(kSRPModulus3072), &kSRPGenerator5, 1, salt, salt_size) != 0) {
814 PAIRING_ERROR("[SRP] Failed to set SRP parameters");
815 ret = LOCKDOWN_E_PAIRING_FAILED;
816 break;
817
818 }
819
820 if (pairing_callback) {
821 char pin[64];
822 unsigned int pin_len = sizeof(pin);
823 pairing_callback(LOCKDOWN_CU_PAIRING_PIN_REQUESTED, cb_user_data, pin, &pin_len);
824
825 SRP_set_auth_password_raw(srp, (const unsigned char*)pin, pin_len);
826 }
827 } else if (state == 4) {
828 /* receive proof */
829 unsigned char* proof = NULL;
830 unsigned int proof_len = 0;
831
832 if (!tlv_data_copy_data(data, data_len, 0x04, (void**)&proof, &proof_len)) {
833 PAIRING_ERROR("[SRP] ERROR: Could not find proof data in response");
834 ret = LOCKDOWN_E_PAIRING_FAILED;
835 break;
836 }
837
838 /* verify */
839 int vrfy_result = SRP_verify(srp, proof, proof_len);
840 free(proof);
841
842 if (vrfy_result == 0) {
843 debug_info("[SRP] PIN verified successfully");
844 } else {
845 PAIRING_ERROR("[SRP] PIN verification failure");
846 ret = LOCKDOWN_E_PAIRING_FAILED;
847 break;
848 }
849
850 } else if (state == 6) {
851 int srp_pair_success = 0;
852 plist_t node = plist_dict_get_item(extresp, "doSRPPair");
853 if (node) {
854 const char* strv = plist_get_string_ptr(node, NULL);
855 if (strcmp(strv, "succeed") == 0) {
856 srp_pair_success = 1;
857 }
858 }
859 if (!srp_pair_success) {
860 PAIRING_ERROR("SRP Pairing failed");
861 ret = LOCKDOWN_E_PAIRING_FAILED;
862 break;
863 }
864
865 /* receive encrypted info */
866 unsigned char* encrypted_buf = NULL;
867 unsigned int enc_len = 0;
868 if (!tlv_data_copy_data(data, data_len, 0x05, (void**)&encrypted_buf, &enc_len)) {
869 PAIRING_ERROR("[SRP] ERROR: Could not find encrypted data in response");
870 ret = LOCKDOWN_E_PAIRING_FAILED;
871 break;
872 }
873 size_t plain_len = enc_len-16;
874 unsigned char* plain_buf = malloc(plain_len);
875 chacha20_poly1305_decrypt_64(setup_encryption_key, (unsigned char*)"PS-Msg06", NULL, 0, encrypted_buf, enc_len, plain_buf, &plain_len);
876 free(encrypted_buf);
877
878 unsigned char* dev_info = NULL;
879 unsigned int dev_info_len = 0;
880 int res = tlv_data_copy_data(plain_buf, plain_len, 0x11, (void**)&dev_info, &dev_info_len);
881 free(plain_buf);
882 if (!res) {
883 PAIRING_ERROR("[SRP] ERROR: Failed to locate device info in response");
884 ret = LOCKDOWN_E_PAIRING_FAILED;
885 break;
886 }
887 plist_t device_info = NULL;
888 opack_decode_to_plist(dev_info, dev_info_len, &device_info);
889 free(dev_info);
890
891 if (!device_info) {
892 PAIRING_ERROR("[SRP] ERROR: Failed to parse device info");
893 ret = LOCKDOWN_E_PAIRING_FAILED;
894 break;
895 }
896
897 if (pairing_callback) {
898 pairing_callback(LOCKDOWN_CU_PAIRING_DEVICE_INFO, cb_user_data, device_info, NULL);
899 }
900 plist_free(device_info);
901 } else {
902 PAIRING_ERROR("[SRP] ERROR: Invalid state");
903 ret = LOCKDOWN_E_PAIRING_FAILED;
904 break;
905 }
906 plist_free(dict);
907 dict = NULL;
908
909 } while (current_state != final_state);
910
911 plist_free(dict);
912
913 free(salt);
914 free(pubkey);
915
916 SRP_free(srp);
917 srp = NULL;
918
919 if (ret != LOCKDOWN_E_SUCCESS) {
920 if (thekey) {
921 cstr_free(thekey);
922 }
923 return ret;
924 }
925
926 free(client->cu_key);
927 client->cu_key = malloc(thekey->length);
928 memcpy(client->cu_key, thekey->data, thekey->length);
929 client->cu_key_len = thekey->length;
930 cstr_free(thekey);
931
932 return LOCKDOWN_E_SUCCESS;
933 #else
934 debug_info("not supported");
935 return LOCKDOWN_E_UNKNOWN_ERROR;
936 #endif
937 }
938
939 lockdownd_error_t lockdownd_cu_send_request_and_get_reply(lockdownd_client_t client, const char* request, plist_t request_payload, plist_t* reply)
940 {
941 #ifdef HAVE_WIRELESS_PAIRING
942 if (!client || !request)
943 return LOCKDOWN_E_INVALID_ARG;
944
945 if (!client->cu_key)
946 return LOCKDOWN_E_NO_RUNNING_SESSION;
947
948 lockdownd_error_t ret = LOCKDOWN_E_UNKNOWN_ERROR;
949
950 /* derive keys */
951 unsigned char cu_write_key[32];
952 unsigned int cu_write_key_len = sizeof(cu_write_key);
953 static const char WRITE_KEY_SALT_MDLD[] = "WriteKeySaltMDLD";
954 static const char WRITE_KEY_INFO_MDLD[] = "WriteKeyInfoMDLD";
955 hkdf_md(MD_ALGO_SHA512, (unsigned char*)WRITE_KEY_SALT_MDLD, sizeof(WRITE_KEY_SALT_MDLD)-1, (unsigned char*)WRITE_KEY_INFO_MDLD, sizeof(WRITE_KEY_INFO_MDLD)-1, client->cu_key, client->cu_key_len, cu_write_key, &cu_write_key_len);
956
957 unsigned char cu_read_key[32];
958 unsigned int cu_read_key_len = sizeof(cu_write_key);
959 static const char READ_KEY_SALT_MDLD[] = "ReadKeySaltMDLD";
960 static const char READ_KEY_INFO_MDLD[] = "ReadKeyInfoMDLD";
961 hkdf_md(MD_ALGO_SHA512, (unsigned char*)READ_KEY_SALT_MDLD, sizeof(READ_KEY_SALT_MDLD)-1, (unsigned char*)READ_KEY_INFO_MDLD, sizeof(READ_KEY_INFO_MDLD)-1, client->cu_key, client->cu_key_len, cu_read_key, &cu_read_key_len);
962
963 // Starting with iOS/tvOS 11.2 and WatchOS 4.2, this nonce is random and sent along with the request. Before, the request doesn't have a nonce and it uses hardcoded nonce "sendone01234".
964 unsigned char cu_nonce[] = "sendone01234"; // guaranteed to be random by fair dice troll
965 if (client->device->version >= IDEVICE_DEVICE_VERSION(11,2,0)) {
966 #if defined(HAVE_OPENSSL)
967 RAND_bytes(cu_nonce, sizeof(cu_nonce)-1);
968 #elif defined(HAVE_GCRYPT)
969 gcry_create_nonce(cu_nonce, sizeof(cu_nonce)-1);
970 #endif
971 }
972
973 debug_plist(request_payload);
974
975 /* convert request payload to binary */
976 uint32_t bin_len = 0;
977 char* bin = NULL;
978 plist_to_bin(request_payload, &bin, &bin_len);
979
980 /* encrypt request */
981 size_t encrypted_len = bin_len + 16;
982 unsigned char* encrypted_buf = malloc(encrypted_len);
983 chacha20_poly1305_encrypt_96(cu_write_key, cu_nonce, NULL, 0, (unsigned char*)bin, bin_len, encrypted_buf, &encrypted_len);
984 free(bin);
985 bin = NULL;
986
987 plist_t dict = plist_new_dict();
988 plist_dict_set_item(dict,"Request", plist_new_string(request));
989 plist_dict_set_item(dict, "Payload", plist_new_data((char*)encrypted_buf, encrypted_len));
990 free(encrypted_buf);
991 plist_dict_set_item(dict, "Nonce", plist_new_data((char*)cu_nonce, sizeof(cu_nonce)));
992 plist_dict_set_item(dict, "Label", plist_new_string(client->label));
993 plist_dict_set_item(dict, "ProtocolVersion", plist_new_uint(2));
994
995 /* send to device */
996 ret = lockdownd_send(client, dict);
997 plist_free(dict);
998 dict = NULL;
999
1000 if (ret != LOCKDOWN_E_SUCCESS)
1001 return ret;
1002
1003 /* Now get device's answer */
1004 ret = lockdownd_receive(client, &dict);
1005 if (ret != LOCKDOWN_E_SUCCESS)
1006 return ret;
1007
1008 ret = lockdown_check_result(dict, request);
1009 if (ret != LOCKDOWN_E_SUCCESS) {
1010 plist_free(dict);
1011 return ret;
1012 }
1013
1014 /* get payload */
1015 plist_t blob = plist_dict_get_item(dict, "Payload");
1016 if (!blob) {
1017 plist_free(dict);
1018 return LOCKDOWN_E_DICT_ERROR;
1019 }
1020
1021 uint64_t dl = 0;
1022 const char* dt = plist_get_data_ptr(blob, &dl);
1023
1024 /* see if we have a nonce */
1025 blob = plist_dict_get_item(dict, "Nonce");
1026 const unsigned char* rnonce = (unsigned char*)"receiveone01";
1027 if (blob) {
1028 uint64_t rl = 0;
1029 rnonce = (const unsigned char*)plist_get_data_ptr(blob, &rl);
1030 }
1031
1032 /* decrypt payload */
1033 size_t decrypted_len = dl-16;
1034 unsigned char* decrypted = malloc(decrypted_len);
1035 chacha20_poly1305_decrypt_96(cu_read_key, (unsigned char*)rnonce, NULL, 0, (unsigned char*)dt, dl, decrypted, &decrypted_len);
1036 plist_free(dict);
1037 dict = NULL;
1038
1039 plist_from_memory((const char*)decrypted, decrypted_len, &dict, NULL);
1040 if (!dict) {
1041 ret = LOCKDOWN_E_PLIST_ERROR;
1042 debug_info("Failed to parse PLIST from decrypted payload:");
1043 debug_buffer((const char*)decrypted, decrypted_len);
1044 free(decrypted);
1045 return ret;
1046 }
1047 free(decrypted);
1048
1049 debug_plist(dict);
1050
1051 if (reply) {
1052 *reply = dict;
1053 } else {
1054 plist_free(dict);
1055 }
1056
1057 return LOCKDOWN_E_SUCCESS;
1058 #else
1059 debug_info("not supported");
1060 return LOCKDOWN_E_UNKNOWN_ERROR;
1061 #endif
1062 }
1063
1064 lockdownd_error_t lockdownd_get_value_cu(lockdownd_client_t client, const char* domain, const char* key, plist_t* value)
1065 {
1066 #ifdef HAVE_WIRELESS_PAIRING
1067 if (!client)
1068 return LOCKDOWN_E_INVALID_ARG;
1069
1070 if (!client->cu_key)
1071 return LOCKDOWN_E_NO_RUNNING_SESSION;
1072
1073 lockdownd_error_t ret = LOCKDOWN_E_UNKNOWN_ERROR;
1074
1075 plist_t request = plist_new_dict();
1076 if (domain) {
1077 plist_dict_set_item(request, "Domain", plist_new_string(domain));
1078 }
1079 if (key) {
1080 plist_dict_set_item(request, "Key", plist_new_string(key));
1081 }
1082
1083 plist_t reply = NULL;
1084 ret = lockdownd_cu_send_request_and_get_reply(client, "GetValueCU", request, &reply);
1085 plist_free(request);
1086 if (ret != LOCKDOWN_E_SUCCESS) {
1087 return ret;
1088 }
1089
1090 plist_t value_node = plist_dict_get_item(reply, "Value");
1091 if (value_node) {
1092 debug_info("has a value");
1093 *value = plist_copy(value_node);
1094 }
1095 plist_free(reply);
1096
1097 return ret;
1098 #else
1099 debug_info("not supported");
1100 return LOCKDOWN_E_UNKNOWN_ERROR;
1101 #endif
1102 }
1103
1104 lockdownd_error_t lockdownd_pair_cu(lockdownd_client_t client)
1105 {
1106 #ifdef HAVE_WIRELESS_PAIRING
1107 if (!client)
1108 return LOCKDOWN_E_INVALID_ARG;
1109
1110 if (!client->cu_key)
1111 return LOCKDOWN_E_NO_RUNNING_SESSION;
1112
1113 lockdownd_error_t ret;
1114
1115 plist_t wifi_mac = NULL;
1116 ret = lockdownd_get_value_cu(client, NULL, "WiFiAddress", &wifi_mac);
1117 if (ret != LOCKDOWN_E_SUCCESS) {
1118 return ret;
1119 }
1120
1121 plist_t pubkey = NULL;
1122 ret = lockdownd_get_value_cu(client, NULL, "DevicePublicKey", &pubkey);
1123 if (ret != LOCKDOWN_E_SUCCESS) {
1124 plist_free(wifi_mac);
1125 return ret;
1126 }
1127
1128 key_data_t public_key = { NULL, 0 };
1129 uint64_t data_len = 0;
1130 plist_get_data_val(pubkey, (char**)&public_key.data, &data_len);
1131 public_key.size = (unsigned int)data_len;
1132 plist_free(pubkey);
1133
1134 plist_t pair_record_plist = plist_new_dict();
1135 pair_record_generate_keys_and_certs(pair_record_plist, public_key, client->device->version);
1136
1137 char* host_id = NULL;
1138 char* system_buid = NULL;
1139
1140 /* set SystemBUID */
1141 userpref_read_system_buid(&system_buid);
1142 if (system_buid) {
1143 plist_dict_set_item(pair_record_plist, USERPREF_SYSTEM_BUID_KEY, plist_new_string(system_buid));
1144 free(system_buid);
1145 }
1146
1147 /* set HostID */
1148 host_id = generate_uuid();
1149 pair_record_set_host_id(pair_record_plist, host_id);
1150 free(host_id);
1151
1152 plist_t request_pair_record = plist_copy(pair_record_plist);
1153 /* remove stuff that is private */
1154 plist_dict_remove_item(request_pair_record, USERPREF_ROOT_PRIVATE_KEY_KEY);
1155 plist_dict_remove_item(request_pair_record, USERPREF_HOST_PRIVATE_KEY_KEY);
1156
1157 plist_t request = plist_new_dict();
1158 plist_dict_set_item(request, "PairRecord", request_pair_record);
1159 plist_t pairing_opts = plist_new_dict();
1160 plist_dict_set_item(pairing_opts, "ExtendedPairingErrors", plist_new_bool(1));
1161 plist_dict_set_item(request, "PairingOptions", pairing_opts);
1162
1163 plist_t reply = NULL;
1164 ret = lockdownd_cu_send_request_and_get_reply(client, "PairCU", request, &reply);
1165 plist_free(request);
1166 if (ret != LOCKDOWN_E_SUCCESS) {
1167 plist_free(wifi_mac);
1168 return ret;
1169 }
1170
1171 char *s_udid = NULL;
1172 plist_t p_udid = plist_dict_get_item(reply, "UDID");
1173 if (p_udid) {
1174 plist_get_string_val(p_udid, &s_udid);
1175 }
1176 plist_t ebag = plist_dict_get_item(reply, "EscrowBag");
1177 if (ebag) {
1178 plist_dict_set_item(pair_record_plist, USERPREF_ESCROW_BAG_KEY, plist_copy(ebag));
1179 }
1180 plist_dict_set_item(pair_record_plist, USERPREF_WIFI_MAC_ADDRESS_KEY, wifi_mac);
1181 plist_free(reply);
1182
1183 if (userpref_save_pair_record(s_udid, 0, pair_record_plist) != 0) {
1184 printf("Failed to save pair record for UDID %s\n", s_udid);
1185 }
1186 free(s_udid);
1187 s_udid = NULL;
1188 plist_free(pair_record_plist);
1189
1190 ret = LOCKDOWN_E_SUCCESS;
1191
1192 return ret;
1193 #else
1194 debug_info("not supported");
1195 return LOCKDOWN_E_UNKNOWN_ERROR;
1196 #endif
1197 }