userpref.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. /*
  2. * userpref.c
  3. * contains methods to access user specific certificates IDs and more.
  4. *
  5. * Copyright (c) 2013-2014 Martin Szulecki All Rights Reserved.
  6. * Copyright (c) 2008 Jonathan Beck All Rights Reserved.
  7. *
  8. * This library is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * This library is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with this library; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #ifdef HAVE_CONFIG_H
  23. #include <config.h>
  24. #endif
  25. #include <stdio.h>
  26. #include <stdint.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #ifdef HAVE_SYS_TYPES_H
  30. #include <sys/types.h>
  31. #endif
  32. #ifndef WIN32
  33. #include <pwd.h>
  34. #endif
  35. #include <unistd.h>
  36. #include <usbmuxd.h>
  37. #ifdef HAVE_OPENSSL
  38. #include <openssl/pem.h>
  39. #include <openssl/rsa.h>
  40. #include <openssl/x509.h>
  41. #include <openssl/x509v3.h>
  42. #else
  43. #include <gnutls/gnutls.h>
  44. #include <gnutls/crypto.h>
  45. #include <gnutls/x509.h>
  46. #include <gcrypt.h>
  47. #include <libtasn1.h>
  48. #endif
  49. #include <dirent.h>
  50. #include <libgen.h>
  51. #include <sys/stat.h>
  52. #include <errno.h>
  53. #ifdef WIN32
  54. #include <shlobj.h>
  55. #endif
  56. #include "userpref.h"
  57. #include "debug.h"
  58. #include "utils.h"
  59. #ifndef HAVE_OPENSSL
  60. const ASN1_ARRAY_TYPE pkcs1_asn1_tab[] = {
  61. {"PKCS1", 536872976, 0},
  62. {0, 1073741836, 0},
  63. {"RSAPublicKey", 536870917, 0},
  64. {"modulus", 1073741827, 0},
  65. {"publicExponent", 3, 0},
  66. {0, 0, 0}
  67. };
  68. #endif
  69. #ifdef WIN32
  70. #define DIR_SEP '\\'
  71. #define DIR_SEP_S "\\"
  72. #else
  73. #define DIR_SEP '/'
  74. #define DIR_SEP_S "/"
  75. #endif
  76. #define USERPREF_CONFIG_EXTENSION ".plist"
  77. #ifdef WIN32
  78. #define USERPREF_CONFIG_DIR "Apple"DIR_SEP_S"Lockdown"
  79. #else
  80. #define USERPREF_CONFIG_DIR "lockdown"
  81. #endif
  82. #define USERPREF_CONFIG_FILE "SystemConfiguration"USERPREF_CONFIG_EXTENSION
  83. static char *__config_dir = NULL;
  84. #ifdef WIN32
  85. static char *userpref_utf16_to_utf8(wchar_t *unistr, long len, long *items_read, long *items_written)
  86. {
  87. if (!unistr || (len <= 0)) return NULL;
  88. char *outbuf = (char*)malloc(3*(len+1));
  89. int p = 0;
  90. int i = 0;
  91. wchar_t wc;
  92. while (i < len) {
  93. wc = unistr[i++];
  94. if (wc >= 0x800) {
  95. outbuf[p++] = (char)(0xE0 + ((wc >> 12) & 0xF));
  96. outbuf[p++] = (char)(0x80 + ((wc >> 6) & 0x3F));
  97. outbuf[p++] = (char)(0x80 + (wc & 0x3F));
  98. } else if (wc >= 0x80) {
  99. outbuf[p++] = (char)(0xC0 + ((wc >> 6) & 0x1F));
  100. outbuf[p++] = (char)(0x80 + (wc & 0x3F));
  101. } else {
  102. outbuf[p++] = (char)(wc & 0x7F);
  103. }
  104. }
  105. if (items_read) {
  106. *items_read = i;
  107. }
  108. if (items_written) {
  109. *items_written = p;
  110. }
  111. outbuf[p] = 0;
  112. return outbuf;
  113. }
  114. #endif
  115. const char *userpref_get_config_dir()
  116. {
  117. char *base_config_dir = NULL;
  118. if (__config_dir)
  119. return __config_dir;
  120. #ifdef WIN32
  121. wchar_t path[MAX_PATH+1];
  122. HRESULT hr;
  123. LPITEMIDLIST pidl = NULL;
  124. BOOL b = FALSE;
  125. hr = SHGetSpecialFolderLocation (NULL, CSIDL_COMMON_APPDATA, &pidl);
  126. if (hr == S_OK) {
  127. b = SHGetPathFromIDListW (pidl, path);
  128. if (b) {
  129. base_config_dir = userpref_utf16_to_utf8 (path, wcslen(path), NULL, NULL);
  130. CoTaskMemFree (pidl);
  131. }
  132. }
  133. #else
  134. #ifdef __APPLE__
  135. base_config_dir = strdup("/var/db");
  136. #else
  137. base_config_dir = strdup("/var/lib");
  138. #endif
  139. #endif
  140. __config_dir = string_concat(base_config_dir, DIR_SEP_S, USERPREF_CONFIG_DIR, NULL);
  141. if (__config_dir) {
  142. int i = strlen(__config_dir)-1;
  143. while ((i > 0) && (__config_dir[i] == DIR_SEP)) {
  144. __config_dir[i--] = '\0';
  145. }
  146. }
  147. free(base_config_dir);
  148. debug_info("initialized config_dir to %s", __config_dir);
  149. return __config_dir;
  150. }
  151. /**
  152. * Reads the SystemBUID from a previously generated configuration file.
  153. *
  154. * @note It is the responsibility of the calling function to free the returned system_buid.
  155. * @param system_buid A pointer that will be set to a newly allocated string containing the
  156. * SystemBUID upon successful return.
  157. * @return 0 if the SystemBUID has been successfully retrieved or < 0 otherwise.
  158. */
  159. int userpref_read_system_buid(char **system_buid)
  160. {
  161. int res = usbmuxd_read_buid(system_buid);
  162. if (res == 0) {
  163. debug_info("using %s as %s", *system_buid, USERPREF_SYSTEM_BUID_KEY);
  164. } else {
  165. debug_info("could not read system buid, error %d", res);
  166. }
  167. return res;
  168. }
  169. /**
  170. * Determines whether this device has been connected to this system before.
  171. *
  172. * @param udid The device UDID as given by the device.
  173. *
  174. * @return 1 if the device has been connected previously to this configuration
  175. * or 0 otherwise.
  176. */
  177. int userpref_has_pair_record(const char *udid)
  178. {
  179. int ret = 0;
  180. const char *config_path = NULL;
  181. char *config_file = NULL;
  182. struct stat st;
  183. if (!udid) return 0;
  184. /* first get config file */
  185. config_path = userpref_get_config_dir();
  186. config_file = string_concat(config_path, DIR_SEP_S, udid, USERPREF_CONFIG_EXTENSION, NULL);
  187. if ((stat(config_file, &st) == 0) && S_ISREG(st.st_mode))
  188. ret = 1;
  189. free(config_file);
  190. return ret;
  191. }
  192. /**
  193. * Fills a list with UDIDs of devices that have been connected to this
  194. * system before, i.e. for which a public key file exists.
  195. *
  196. * @param list A pointer to a char** initially pointing to NULL that will
  197. * hold a newly allocated list of UDIDs upon successful return.
  198. * The caller is responsible for freeing the memory. Note that if
  199. * no public key file was found the list has to be freed too as it
  200. * points to a terminating NULL element.
  201. * @param count The number of UDIDs found. This parameter can be NULL if it
  202. * is not required.
  203. *
  204. * @return USERPREF_E_SUCCESS on success, or USERPREF_E_INVALID_ARG if the
  205. * list parameter is not pointing to NULL.
  206. */
  207. userpref_error_t userpref_get_paired_udids(char ***list, unsigned int *count)
  208. {
  209. struct slist_t {
  210. char *name;
  211. void *next;
  212. };
  213. DIR *config_dir;
  214. const char *config_path = NULL;
  215. struct slist_t *udids = NULL;
  216. unsigned int i;
  217. unsigned int found = 0;
  218. if (!list || (list && *list)) {
  219. debug_info("ERROR: The list parameter needs to point to NULL!");
  220. return USERPREF_E_INVALID_ARG;
  221. }
  222. if (count) {
  223. *count = 0;
  224. }
  225. config_path = userpref_get_config_dir();
  226. config_dir = opendir(config_path);
  227. if (config_dir) {
  228. struct dirent *entry;
  229. struct slist_t *listp = udids;
  230. while ((entry = readdir(config_dir))) {
  231. char *ext = strstr(entry->d_name, USERPREF_CONFIG_EXTENSION);
  232. if (ext && ((ext - entry->d_name) == 40) && (strlen(entry->d_name) == (40 + strlen(ext)))) {
  233. struct slist_t *ne = (struct slist_t*)malloc(sizeof(struct slist_t));
  234. ne->name = (char*)malloc(41);
  235. strncpy(ne->name, entry->d_name, 40);
  236. ne->name[40] = 0;
  237. ne->next = NULL;
  238. if (!listp) {
  239. listp = ne;
  240. udids = listp;
  241. } else {
  242. listp->next = ne;
  243. listp = listp->next;
  244. }
  245. found++;
  246. }
  247. }
  248. closedir(config_dir);
  249. }
  250. *list = (char**)malloc(sizeof(char*) * (found+1));
  251. i = 0;
  252. while (udids) {
  253. (*list)[i++] = udids->name;
  254. struct slist_t *old = udids;
  255. udids = udids->next;
  256. free(old);
  257. }
  258. (*list)[i] = NULL;
  259. if (count) {
  260. *count = found;
  261. }
  262. return USERPREF_E_SUCCESS;
  263. }
  264. /**
  265. * Save a pair record for a device.
  266. *
  267. * @param udid The device UDID as given by the device
  268. * @param pair_record The pair record to save
  269. *
  270. * @return 1 on success and 0 if no device record is given or if it has already
  271. * been saved previously.
  272. */
  273. userpref_error_t userpref_save_pair_record(const char *udid, plist_t pair_record)
  274. {
  275. char* record_data = NULL;
  276. uint32_t record_size = 0;
  277. plist_to_bin(pair_record, &record_data, &record_size);
  278. int res = usbmuxd_save_pair_record(udid, record_data, record_size);
  279. free(record_data);
  280. return res == 0 ? USERPREF_E_SUCCESS: USERPREF_E_UNKNOWN_ERROR;
  281. }
  282. /**
  283. * Read a pair record for a device.
  284. *
  285. * @param udid The device UDID as given by the device
  286. * @param pair_record The pair record to read
  287. *
  288. * @return 1 on success and 0 if no device record is given or if it has already
  289. * been saved previously.
  290. */
  291. userpref_error_t userpref_read_pair_record(const char *udid, plist_t *pair_record)
  292. {
  293. char* record_data = NULL;
  294. uint32_t record_size = 0;
  295. int res = usbmuxd_read_pair_record(udid, &record_data, &record_size);
  296. if (res < 0) {
  297. if (record_data)
  298. free(record_data);
  299. return USERPREF_E_INVALID_CONF;
  300. }
  301. *pair_record = NULL;
  302. if (memcmp(record_data, "bplist00", 8) == 0) {
  303. plist_from_bin(record_data, record_size, pair_record);
  304. } else {
  305. plist_from_xml(record_data, record_size, pair_record);
  306. }
  307. free(record_data);
  308. return res == 0 ? USERPREF_E_SUCCESS: USERPREF_E_UNKNOWN_ERROR;
  309. }
  310. /**
  311. * Remove the pairing record stored for a device from this host.
  312. *
  313. * @param udid The udid of the device
  314. *
  315. * @return USERPREF_E_SUCCESS on success.
  316. */
  317. userpref_error_t userpref_delete_pair_record(const char *udid)
  318. {
  319. int res = usbmuxd_delete_pair_record(udid);
  320. return res == 0 ? USERPREF_E_SUCCESS: USERPREF_E_UNKNOWN_ERROR;
  321. }
  322. #ifdef HAVE_OPENSSL
  323. static int X509_add_ext_helper(X509 *cert, int nid, char *value)
  324. {
  325. X509_EXTENSION *ex;
  326. X509V3_CTX ctx;
  327. /* No configuration database */
  328. X509V3_set_ctx_nodb(&ctx);
  329. X509V3_set_ctx(&ctx, NULL, cert, NULL, NULL, 0);
  330. ex = X509V3_EXT_conf_nid(NULL, &ctx, nid, value);
  331. if (!ex) {
  332. debug_info("ERROR: X509V3_EXT_conf_nid(%d, %s) failed", nid, value);
  333. return 0;
  334. }
  335. X509_add_ext(cert, ex, -1);
  336. X509_EXTENSION_free(ex);
  337. return 1;
  338. }
  339. #endif
  340. /**
  341. * Private function to generate required private keys and certificates.
  342. *
  343. * @param pair_record a #PLIST_DICT that will be filled with the keys
  344. * and certificates
  345. * @param public_key the public key to use (device public key)
  346. *
  347. * @return 1 if keys were successfully generated, 0 otherwise
  348. */
  349. userpref_error_t pair_record_generate_keys_and_certs(plist_t pair_record, key_data_t public_key)
  350. {
  351. userpref_error_t ret = USERPREF_E_SSL_ERROR;
  352. printf("##%s:%d\n", __func__, __LINE__);
  353. key_data_t dev_cert_pem = { NULL, 0 };
  354. key_data_t root_key_pem = { NULL, 0 };
  355. key_data_t root_cert_pem = { NULL, 0 };
  356. key_data_t host_key_pem = { NULL, 0 };
  357. key_data_t host_cert_pem = { NULL, 0 };
  358. if (!pair_record || !public_key.data)
  359. return USERPREF_E_INVALID_ARG;
  360. debug_info("Generating keys and certificates...");
  361. #ifdef HAVE_OPENSSL
  362. BIGNUM *e = BN_new();
  363. RSA* root_keypair = RSA_new();
  364. RSA* host_keypair = RSA_new();
  365. BN_set_word(e, 4097);
  366. RSA_generate_key_ex(root_keypair, 512, e, NULL);
  367. RSA_generate_key_ex(host_keypair, 512, e, NULL);
  368. BN_free(e);
  369. EVP_PKEY* root_pkey = EVP_PKEY_new();
  370. EVP_PKEY_assign_RSA(root_pkey, root_keypair);
  371. EVP_PKEY* host_pkey = EVP_PKEY_new();
  372. EVP_PKEY_assign_RSA(host_pkey, host_keypair);
  373. /* generate root certificate */
  374. X509* root_cert = X509_new();
  375. {
  376. /* set serial number */
  377. ASN1_INTEGER* sn = ASN1_INTEGER_new();
  378. ASN1_INTEGER_set(sn, 0);
  379. X509_set_serialNumber(root_cert, sn);
  380. ASN1_INTEGER_free(sn);
  381. /* set version */
  382. X509_set_version(root_cert, 2);
  383. /* set x509v3 basic constraints */
  384. X509_add_ext_helper(root_cert, NID_basic_constraints, (char*)"critical,CA:TRUE");
  385. /* set key validity */
  386. ASN1_TIME* asn1time = ASN1_TIME_new();
  387. ASN1_TIME_set(asn1time, time(NULL));
  388. X509_set_notBefore(root_cert, asn1time);
  389. ASN1_TIME_set(asn1time, time(NULL) + (60 * 60 * 24 * 365 * 10));
  390. X509_set_notAfter(root_cert, asn1time);
  391. ASN1_TIME_free(asn1time);
  392. /* use root public key for root cert */
  393. X509_set_pubkey(root_cert, root_pkey);
  394. /* sign root cert with root private key */
  395. printf("%s:%d\n", __func__, __LINE__);
  396. X509_sign(root_cert, root_pkey, EVP_sha1());
  397. printf("%s:%d\n", __func__, __LINE__);
  398. }
  399. /* create host certificate */
  400. X509* host_cert = X509_new();
  401. {
  402. /* set serial number */
  403. ASN1_INTEGER* sn = ASN1_INTEGER_new();
  404. ASN1_INTEGER_set(sn, 0);
  405. X509_set_serialNumber(host_cert, sn);
  406. ASN1_INTEGER_free(sn);
  407. /* set version */
  408. X509_set_version(host_cert, 2);
  409. /* set x509v3 basic constraints */
  410. X509_add_ext_helper(host_cert, NID_basic_constraints, (char*)"critical,CA:FALSE");
  411. /* set x509v3 key usage */
  412. X509_add_ext_helper(host_cert, NID_key_usage, (char*)"critical,digitalSignature,keyEncipherment");
  413. /* set key validity */
  414. ASN1_TIME* asn1time = ASN1_TIME_new();
  415. ASN1_TIME_set(asn1time, time(NULL));
  416. X509_set_notBefore(host_cert, asn1time);
  417. ASN1_TIME_set(asn1time, time(NULL) + (60 * 60 * 24 * 365 * 10));
  418. X509_set_notAfter(host_cert, asn1time);
  419. ASN1_TIME_free(asn1time);
  420. /* use host public key for host cert */
  421. X509_set_pubkey(host_cert, host_pkey);
  422. /* sign host cert with root private key */
  423. X509_sign(host_cert, root_pkey, EVP_sha1());
  424. }
  425. if (root_cert && root_pkey && host_cert && host_pkey) {
  426. BIO* membp;
  427. char *bdata;
  428. membp = BIO_new(BIO_s_mem());
  429. if (PEM_write_bio_X509(membp, root_cert) > 0) {
  430. root_cert_pem.size = BIO_get_mem_data(membp, &bdata);
  431. root_cert_pem.data = (unsigned char*)malloc(root_cert_pem.size);
  432. if (root_cert_pem.data) {
  433. memcpy(root_cert_pem.data, bdata, root_cert_pem.size);
  434. }
  435. BIO_free(membp);
  436. membp = NULL;
  437. }
  438. membp = BIO_new(BIO_s_mem());
  439. if (PEM_write_bio_PrivateKey(membp, root_pkey, NULL, NULL, 0, 0, NULL) > 0) {
  440. root_key_pem.size = BIO_get_mem_data(membp, &bdata);
  441. root_key_pem.data = (unsigned char*)malloc(root_key_pem.size);
  442. if (root_key_pem.data) {
  443. memcpy(root_key_pem.data, bdata, root_key_pem.size);
  444. }
  445. BIO_free(membp);
  446. membp = NULL;
  447. }
  448. membp = BIO_new(BIO_s_mem());
  449. if (PEM_write_bio_X509(membp, host_cert) > 0) {
  450. host_cert_pem.size = BIO_get_mem_data(membp, &bdata);
  451. host_cert_pem.data = (unsigned char*)malloc(host_cert_pem.size);
  452. if (host_cert_pem.data) {
  453. memcpy(host_cert_pem.data, bdata, host_cert_pem.size);
  454. }
  455. BIO_free(membp);
  456. membp = NULL;
  457. }
  458. membp = BIO_new(BIO_s_mem());
  459. if (PEM_write_bio_PrivateKey(membp, host_pkey, NULL, NULL, 0, 0, NULL) > 0) {
  460. host_key_pem.size = BIO_get_mem_data(membp, &bdata);
  461. host_key_pem.data = (unsigned char*)malloc(host_key_pem.size);
  462. if (host_key_pem.data) {
  463. memcpy(host_key_pem.data, bdata, host_key_pem.size);
  464. }
  465. BIO_free(membp);
  466. membp = NULL;
  467. }
  468. }
  469. RSA *pubkey = NULL;
  470. {
  471. BIO *membp = BIO_new_mem_buf(public_key.data, public_key.size);
  472. if (!PEM_read_bio_RSAPublicKey(membp, &pubkey, NULL, NULL)) {
  473. debug_info("WARNING: Could not read public key");
  474. }
  475. BIO_free(membp);
  476. }
  477. X509* dev_cert = X509_new();
  478. if (pubkey && dev_cert) {
  479. /* generate device certificate */
  480. ASN1_INTEGER* sn = ASN1_INTEGER_new();
  481. ASN1_INTEGER_set(sn, 0);
  482. X509_set_serialNumber(dev_cert, sn);
  483. ASN1_INTEGER_free(sn);
  484. X509_set_version(dev_cert, 2);
  485. X509_add_ext_helper(dev_cert, NID_basic_constraints, (char*)"critical,CA:FALSE");
  486. ASN1_TIME* asn1time = ASN1_TIME_new();
  487. ASN1_TIME_set(asn1time, time(NULL));
  488. X509_set_notBefore(dev_cert, asn1time);
  489. ASN1_TIME_set(asn1time, time(NULL) + (60 * 60 * 24 * 365 * 10));
  490. X509_set_notAfter(dev_cert, asn1time);
  491. ASN1_TIME_free(asn1time);
  492. EVP_PKEY* pkey = EVP_PKEY_new();
  493. EVP_PKEY_assign_RSA(pkey, pubkey);
  494. X509_set_pubkey(dev_cert, pkey);
  495. EVP_PKEY_free(pkey);
  496. X509_add_ext_helper(dev_cert, NID_subject_key_identifier, (char*)"hash");
  497. X509_add_ext_helper(dev_cert, NID_key_usage, (char*)"critical,digitalSignature,keyEncipherment");
  498. /* sign device certificate with root private key */
  499. if (X509_sign(dev_cert, root_pkey, EVP_sha1())) {
  500. /* if signing succeeded, export in PEM format */
  501. BIO* membp = BIO_new(BIO_s_mem());
  502. if (PEM_write_bio_X509(membp, dev_cert) > 0) {
  503. char *bdata = NULL;
  504. dev_cert_pem.size = BIO_get_mem_data(membp, &bdata);
  505. dev_cert_pem.data = (unsigned char*)malloc(dev_cert_pem.size);
  506. if (dev_cert_pem.data) {
  507. memcpy(dev_cert_pem.data, bdata, dev_cert_pem.size);
  508. }
  509. BIO_free(membp);
  510. membp = NULL;
  511. }
  512. } else {
  513. debug_info("ERROR: Signing device certificate with root private key failed!");
  514. }
  515. }
  516. X509V3_EXT_cleanup();
  517. X509_free(dev_cert);
  518. EVP_PKEY_free(root_pkey);
  519. EVP_PKEY_free(host_pkey);
  520. X509_free(host_cert);
  521. X509_free(root_cert);printf("%s:%d\n", __func__, __LINE__);
  522. #else
  523. gnutls_x509_privkey_t root_privkey;
  524. gnutls_x509_crt_t root_cert;
  525. gnutls_x509_privkey_t host_privkey;
  526. gnutls_x509_crt_t host_cert;
  527. /* use less secure random to speed up key generation */
  528. gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM);
  529. gnutls_x509_privkey_init(&root_privkey);
  530. gnutls_x509_privkey_init(&host_privkey);
  531. gnutls_x509_crt_init(&root_cert);
  532. gnutls_x509_crt_init(&host_cert);
  533. /* generate root key */
  534. gnutls_x509_privkey_generate(root_privkey, GNUTLS_PK_RSA, 2048, 0);
  535. gnutls_x509_privkey_generate(host_privkey, GNUTLS_PK_RSA, 2048, 0);
  536. /* generate certificates */
  537. gnutls_x509_crt_set_key(root_cert, root_privkey);
  538. gnutls_x509_crt_set_serial(root_cert, "\x00", 1);
  539. gnutls_x509_crt_set_version(root_cert, 3);
  540. gnutls_x509_crt_set_ca_status(root_cert, 1);
  541. gnutls_x509_crt_set_activation_time(root_cert, time(NULL));
  542. gnutls_x509_crt_set_expiration_time(root_cert, time(NULL) + (60 * 60 * 24 * 365 * 10));
  543. gnutls_x509_crt_sign(root_cert, root_cert, root_privkey);
  544. gnutls_x509_crt_set_key(host_cert, host_privkey);
  545. gnutls_x509_crt_set_serial(host_cert, "\x00", 1);
  546. gnutls_x509_crt_set_version(host_cert, 3);
  547. gnutls_x509_crt_set_ca_status(host_cert, 0);
  548. gnutls_x509_crt_set_key_usage(host_cert, GNUTLS_KEY_KEY_ENCIPHERMENT | GNUTLS_KEY_DIGITAL_SIGNATURE);
  549. gnutls_x509_crt_set_activation_time(host_cert, time(NULL));
  550. gnutls_x509_crt_set_expiration_time(host_cert, time(NULL) + (60 * 60 * 24 * 365 * 10));
  551. gnutls_x509_crt_sign(host_cert, root_cert, root_privkey);
  552. /* export to PEM format */
  553. size_t root_key_export_size = 0;
  554. size_t host_key_export_size = 0;
  555. gnutls_x509_privkey_export(root_privkey, GNUTLS_X509_FMT_PEM, NULL, &root_key_export_size);
  556. gnutls_x509_privkey_export(host_privkey, GNUTLS_X509_FMT_PEM, NULL, &host_key_export_size);
  557. root_key_pem.data = gnutls_malloc(root_key_export_size);
  558. host_key_pem.data = gnutls_malloc(host_key_export_size);
  559. gnutls_x509_privkey_export(root_privkey, GNUTLS_X509_FMT_PEM, root_key_pem.data, &root_key_export_size);
  560. root_key_pem.size = root_key_export_size;
  561. gnutls_x509_privkey_export(host_privkey, GNUTLS_X509_FMT_PEM, host_key_pem.data, &host_key_export_size);
  562. host_key_pem.size = host_key_export_size;
  563. size_t root_cert_export_size = 0;
  564. size_t host_cert_export_size = 0;
  565. gnutls_x509_crt_export(root_cert, GNUTLS_X509_FMT_PEM, NULL, &root_cert_export_size);
  566. gnutls_x509_crt_export(host_cert, GNUTLS_X509_FMT_PEM, NULL, &host_cert_export_size);
  567. root_cert_pem.data = gnutls_malloc(root_cert_export_size);
  568. host_cert_pem.data = gnutls_malloc(host_cert_export_size);
  569. gnutls_x509_crt_export(root_cert, GNUTLS_X509_FMT_PEM, root_cert_pem.data, &root_cert_export_size);
  570. root_cert_pem.size = root_cert_export_size;
  571. gnutls_x509_crt_export(host_cert, GNUTLS_X509_FMT_PEM, host_cert_pem.data, &host_cert_export_size);
  572. host_cert_pem.size = host_cert_export_size;
  573. ret = USERPREF_E_UNKNOWN_ERROR;
  574. gnutls_datum_t modulus = { NULL, 0 };
  575. gnutls_datum_t exponent = { NULL, 0 };
  576. /* now decode the PEM encoded key */
  577. gnutls_datum_t der_pub_key;
  578. if (GNUTLS_E_SUCCESS == gnutls_pem_base64_decode_alloc("RSA PUBLIC KEY", &public_key, &der_pub_key)) {
  579. /* initalize asn.1 parser */
  580. ASN1_TYPE pkcs1 = ASN1_TYPE_EMPTY;
  581. if (ASN1_SUCCESS == asn1_array2tree(pkcs1_asn1_tab, &pkcs1, NULL)) {
  582. ASN1_TYPE asn1_pub_key = ASN1_TYPE_EMPTY;
  583. asn1_create_element(pkcs1, "PKCS1.RSAPublicKey", &asn1_pub_key);
  584. if (ASN1_SUCCESS == asn1_der_decoding(&asn1_pub_key, der_pub_key.data, der_pub_key.size, NULL)) {
  585. /* get size to read */
  586. int ret1 = asn1_read_value(asn1_pub_key, "modulus", NULL, (int*)&modulus.size);
  587. int ret2 = asn1_read_value(asn1_pub_key, "publicExponent", NULL, (int*)&exponent.size);
  588. modulus.data = gnutls_malloc(modulus.size);
  589. exponent.data = gnutls_malloc(exponent.size);
  590. ret1 = asn1_read_value(asn1_pub_key, "modulus", modulus.data, (int*)&modulus.size);
  591. ret2 = asn1_read_value(asn1_pub_key, "publicExponent", exponent.data, (int*)&exponent.size);
  592. if (ASN1_SUCCESS == ret1 && ASN1_SUCCESS == ret2)
  593. ret = USERPREF_E_SUCCESS;
  594. }
  595. if (asn1_pub_key)
  596. asn1_delete_structure(&asn1_pub_key);
  597. }
  598. if (pkcs1)
  599. asn1_delete_structure(&pkcs1);
  600. } else {
  601. debug_info("WARNING: Could not read public key");
  602. }
  603. /* now generate certificates */
  604. if (USERPREF_E_SUCCESS == ret && 0 != modulus.size && 0 != exponent.size) {
  605. gnutls_datum_t essentially_null = { (unsigned char*)strdup("abababababababab"), strlen("abababababababab") };
  606. gnutls_x509_privkey_t fake_privkey;
  607. gnutls_x509_crt_t dev_cert;
  608. gnutls_x509_privkey_init(&fake_privkey);
  609. gnutls_x509_crt_init(&dev_cert);
  610. if (GNUTLS_E_SUCCESS == gnutls_x509_privkey_import_rsa_raw(fake_privkey, &modulus, &exponent, &essentially_null, &essentially_null, &essentially_null, &essentially_null)) {
  611. /* generate device certificate */
  612. gnutls_x509_crt_set_key(dev_cert, fake_privkey);
  613. gnutls_x509_crt_set_serial(dev_cert, "\x00", 1);
  614. gnutls_x509_crt_set_version(dev_cert, 3);
  615. gnutls_x509_crt_set_ca_status(dev_cert, 0);
  616. gnutls_x509_crt_set_activation_time(dev_cert, time(NULL));
  617. gnutls_x509_crt_set_expiration_time(dev_cert, time(NULL) + (60 * 60 * 24 * 365 * 10));
  618. /* use custom hash generation for compatibility with the "Apple ecosystem" */
  619. const gnutls_digest_algorithm_t dig_sha1 = GNUTLS_DIG_SHA1;
  620. size_t hash_size = gnutls_hash_get_len(dig_sha1);
  621. unsigned char hash[hash_size];
  622. if (gnutls_hash_fast(dig_sha1, der_pub_key.data, der_pub_key.size, (unsigned char*)&hash) < 0) {
  623. debug_info("ERROR: Failed to generate SHA1 for public key");
  624. } else {
  625. gnutls_x509_crt_set_subject_key_id(dev_cert, hash, hash_size);
  626. }
  627. gnutls_x509_crt_set_key_usage(dev_cert, GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT);
  628. gnutls_x509_crt_sign(dev_cert, root_cert, root_privkey);
  629. if (USERPREF_E_SUCCESS == ret) {
  630. /* if everything went well, export in PEM format */
  631. size_t export_size = 0;
  632. gnutls_x509_crt_export(dev_cert, GNUTLS_X509_FMT_PEM, NULL, &export_size);
  633. dev_cert_pem.data = gnutls_malloc(export_size);
  634. gnutls_x509_crt_export(dev_cert, GNUTLS_X509_FMT_PEM, dev_cert_pem.data, &export_size);
  635. dev_cert_pem.size = export_size;
  636. } else {
  637. debug_info("ERROR: Signing device certificate with root private key failed!");
  638. }
  639. }
  640. if (essentially_null.data)
  641. free(essentially_null.data);
  642. gnutls_x509_crt_deinit(dev_cert);
  643. gnutls_x509_privkey_deinit(fake_privkey);
  644. }
  645. gnutls_x509_crt_deinit(root_cert);
  646. gnutls_x509_crt_deinit(host_cert);
  647. gnutls_x509_privkey_deinit(root_privkey);
  648. gnutls_x509_privkey_deinit(host_privkey);
  649. gnutls_free(modulus.data);
  650. gnutls_free(exponent.data);
  651. gnutls_free(der_pub_key.data);
  652. #endif
  653. if (NULL != root_cert_pem.data && 0 != root_cert_pem.size &&
  654. NULL != host_cert_pem.data && 0 != host_cert_pem.size)
  655. ret = USERPREF_E_SUCCESS;
  656. /* now set keys and certificates */
  657. pair_record_set_item_from_key_data(pair_record, USERPREF_DEVICE_CERTIFICATE_KEY, &dev_cert_pem);
  658. pair_record_set_item_from_key_data(pair_record, USERPREF_HOST_PRIVATE_KEY_KEY, &host_key_pem);
  659. pair_record_set_item_from_key_data(pair_record, USERPREF_HOST_CERTIFICATE_KEY, &host_cert_pem);
  660. pair_record_set_item_from_key_data(pair_record, USERPREF_ROOT_PRIVATE_KEY_KEY, &root_key_pem);
  661. pair_record_set_item_from_key_data(pair_record, USERPREF_ROOT_CERTIFICATE_KEY, &root_cert_pem);
  662. if (dev_cert_pem.data)
  663. free(dev_cert_pem.data);
  664. if (root_key_pem.data)
  665. free(root_key_pem.data);
  666. if (root_cert_pem.data)
  667. free(root_cert_pem.data);
  668. if (host_key_pem.data)
  669. free(host_key_pem.data);
  670. if (host_cert_pem.data)
  671. free(host_cert_pem.data);
  672. return ret;
  673. }
  674. /**
  675. * Private function which import the given key into a gnutls structure.
  676. *
  677. * @param name The name of the private key to import.
  678. * @param key the gnutls key structure.
  679. *
  680. * @return 1 if the key was successfully imported.
  681. */
  682. #ifdef HAVE_OPENSSL
  683. userpref_error_t pair_record_import_key_with_name(plist_t pair_record, const char* name, key_data_t* key)
  684. #else
  685. userpref_error_t pair_record_import_key_with_name(plist_t pair_record, const char* name, gnutls_x509_privkey_t key)
  686. #endif
  687. {
  688. #ifdef HAVE_OPENSSL
  689. if (!key)
  690. return USERPREF_E_SUCCESS;
  691. #endif
  692. userpref_error_t ret = USERPREF_E_INVALID_CONF;
  693. #ifdef HAVE_OPENSSL
  694. ret = pair_record_get_item_as_key_data(pair_record, name, key);
  695. #else
  696. key_data_t pem = { NULL, 0 };
  697. ret = pair_record_get_item_as_key_data(pair_record, name, &pem);
  698. if (ret == USERPREF_E_SUCCESS && GNUTLS_E_SUCCESS == gnutls_x509_privkey_import(key, &pem, GNUTLS_X509_FMT_PEM))
  699. ret = USERPREF_E_SUCCESS;
  700. else
  701. ret = USERPREF_E_SSL_ERROR;
  702. if (pem.data)
  703. free(pem.data);
  704. #endif
  705. return ret;
  706. }
  707. /**
  708. * Private function which import the given certificate into a gnutls structure.
  709. *
  710. * @param name The name of the certificate to import.
  711. * @param cert the gnutls certificate structure.
  712. *
  713. * @return IDEVICE_E_SUCCESS if the certificate was successfully imported.
  714. */
  715. #ifdef HAVE_OPENSSL
  716. userpref_error_t pair_record_import_crt_with_name(plist_t pair_record, const char* name, key_data_t* cert)
  717. #else
  718. userpref_error_t pair_record_import_crt_with_name(plist_t pair_record, const char* name, gnutls_x509_crt_t cert)
  719. #endif
  720. {
  721. #ifdef HAVE_OPENSSL
  722. if (!cert)
  723. return USERPREF_E_SUCCESS;
  724. #endif
  725. userpref_error_t ret = USERPREF_E_INVALID_CONF;
  726. #ifdef HAVE_OPENSSL
  727. ret = pair_record_get_item_as_key_data(pair_record, name, cert);
  728. #else
  729. key_data_t pem = { NULL, 0 };
  730. ret = pair_record_get_item_as_key_data(pair_record, name, &pem);
  731. if (ret == USERPREF_E_SUCCESS && GNUTLS_E_SUCCESS == gnutls_x509_crt_import(cert, &pem, GNUTLS_X509_FMT_PEM))
  732. ret = USERPREF_E_SUCCESS;
  733. else
  734. ret = USERPREF_E_SSL_ERROR;
  735. if (pem.data)
  736. free(pem.data);
  737. #endif
  738. return ret;
  739. }
  740. userpref_error_t pair_record_get_host_id(plist_t pair_record, char** host_id)
  741. {
  742. plist_t node = plist_dict_get_item(pair_record, USERPREF_HOST_ID_KEY);
  743. if (node && plist_get_node_type(node) == PLIST_STRING) {
  744. plist_get_string_val(node, host_id);
  745. }
  746. return USERPREF_E_SUCCESS;
  747. }
  748. userpref_error_t pair_record_set_host_id(plist_t pair_record, const char* host_id)
  749. {
  750. plist_dict_set_item(pair_record, USERPREF_HOST_ID_KEY, plist_new_string(host_id));
  751. return USERPREF_E_SUCCESS;
  752. }
  753. userpref_error_t pair_record_get_item_as_key_data(plist_t pair_record, const char* name, key_data_t *value)
  754. {
  755. if (!pair_record || !value)
  756. return USERPREF_E_INVALID_ARG;
  757. userpref_error_t ret = USERPREF_E_SUCCESS;
  758. char* buffer = NULL;
  759. uint64_t length = 0;
  760. plist_t node = plist_dict_get_item(pair_record, name);
  761. if (node && plist_get_node_type(node) == PLIST_DATA) {
  762. plist_get_data_val(node, &buffer, &length);
  763. value->data = (unsigned char*)malloc(length);
  764. memcpy(value->data, buffer, length);
  765. value->size = length;
  766. free(buffer);
  767. buffer = NULL;
  768. } else {
  769. ret = USERPREF_E_INVALID_CONF;
  770. }
  771. if (buffer)
  772. free(buffer);
  773. return ret;
  774. }
  775. userpref_error_t pair_record_set_item_from_key_data(plist_t pair_record, const char* name, key_data_t *value)
  776. {
  777. userpref_error_t ret = USERPREF_E_SUCCESS;
  778. if (!pair_record || !value) {
  779. return USERPREF_E_INVALID_ARG;
  780. }
  781. /* set new item */
  782. plist_dict_set_item(pair_record, name, plist_new_data((char*)value->data, value->size));
  783. return ret;
  784. }