res_crypto.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2006, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*! \file
  19. *
  20. * \brief Provide Cryptographic Signature capability
  21. *
  22. * \author Mark Spencer <markster@digium.com>
  23. *
  24. * Uses the OpenSSL library, available at
  25. * http://www.openssl.org/
  26. */
  27. /*** MODULEINFO
  28. <depend>openssl</depend>
  29. <support_level>core</support_level>
  30. ***/
  31. #include "asterisk.h"
  32. #include <dirent.h> /* for closedir, opendir, readdir, DIR */
  33. #include <sys/stat.h> /* for fstat */
  34. #include <openssl/err.h> /* for ERR_print_errors_fp */
  35. #include <openssl/ssl.h> /* for NID_sha1, RSA */
  36. #include <openssl/evp.h> /* for EVP_PKEY, EVP_sha1(), ... */
  37. #include <openssl/md5.h> /* for MD5_DIGEST_LENGTH */
  38. #include <openssl/sha.h> /* for SHA_DIGEST_LENGTH */
  39. #include "asterisk/cli.h" /* for ast_cli, ast_cli_args, ast_cli_entry */
  40. #include "asterisk/compat.h" /* for strcasecmp */
  41. #include "asterisk/io.h" /* for ast_hide_password, ast_restore_tty */
  42. #include "asterisk/linkedlists.h" /* for AST_RWLIST_TRAVERSE, AST_RWLIST_U... */
  43. #include "asterisk/logger.h" /* for ast_log, LOG_WARNING, LOG_NOTICE */
  44. #include "asterisk/md5.h" /* for MD5Final, MD5Init, MD5Update, MD5... */
  45. #include "asterisk/module.h" /* for ast_module_flags::AST_MODFLAG_GLO... */
  46. #include "asterisk/options.h" /* for ast_opt_init_keys */
  47. #include "asterisk/paths.h" /* for ast_config_AST_KEY_DIR */
  48. #include "asterisk/utils.h" /* for ast_copy_string, ast_base64decode */
  49. #include "asterisk/file.h" /* for ast_file_read_dirs */
  50. #define AST_API_MODULE
  51. #include "asterisk/crypto.h" /* for AST_KEY_PUBLIC, AST_KEY_PRIVATE */
  52. /*
  53. * Asterisk uses RSA keys with SHA-1 message digests for its
  54. * digital signatures. The choice of RSA is due to its higher
  55. * throughput on verification, and the choice of SHA-1 based
  56. * on the recently discovered collisions in MD5's compression
  57. * algorithm and recommendations of avoiding MD5 in new schemes
  58. * from various industry experts.
  59. *
  60. * We use OpenSSL to provide our crypto routines, although we never
  61. * actually use full-up SSL
  62. *
  63. */
  64. #define KEY_NEEDS_PASSCODE (1 << 16)
  65. /* From RFC-2437, section 9.1.1 the padding size is 1+2*hLen, where
  66. * the hLen for SHA-1 is 20 bytes (or 160 bits).
  67. */
  68. #define RSA_PKCS1_OAEP_PADDING_SIZE (1 + 2 * SHA_DIGEST_LENGTH)
  69. struct ast_key {
  70. /*! Name of entity */
  71. char name[80];
  72. /*! File name */
  73. char fn[256];
  74. /*! Key type (AST_KEY_PUB or AST_KEY_PRIV, along with flags from above) */
  75. int ktype;
  76. /*! RSA key structure (if successfully loaded) */
  77. EVP_PKEY *pkey;
  78. /*! Whether we should be deleted */
  79. int delme;
  80. /*! FD for input (or -1 if no input allowed, or -2 if we needed input) */
  81. int infd;
  82. /*! FD for output */
  83. int outfd;
  84. /*! Last MD5 Digest */
  85. unsigned char digest[MD5_DIGEST_LENGTH];
  86. AST_RWLIST_ENTRY(ast_key) list;
  87. };
  88. static AST_RWLIST_HEAD_STATIC(keys, ast_key);
  89. static void crypto_load(int ifd, int ofd);
  90. /*!
  91. * \brief setting of priv key
  92. * \param buf
  93. * \param size
  94. * \param rwflag
  95. * \param userdata
  96. * \return length of string,-1 on failure
  97. */
  98. static int pw_cb(char *buf, int size, int rwflag, void *userdata)
  99. {
  100. struct ast_key *key = (struct ast_key *)userdata;
  101. char prompt[256];
  102. int tmp;
  103. int res;
  104. if (key->infd < 0) {
  105. /* Note that we were at least called */
  106. key->infd = -2;
  107. return -1;
  108. }
  109. snprintf(prompt, sizeof(prompt), ">>>> passcode for %s key '%s': ",
  110. key->ktype == AST_KEY_PRIVATE ? "PRIVATE" : "PUBLIC", key->name);
  111. if (write(key->outfd, prompt, strlen(prompt)) < 0) {
  112. ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
  113. key->infd = -2;
  114. return -1;
  115. }
  116. tmp = ast_hide_password(key->infd);
  117. memset(buf, 0, size);
  118. res = read(key->infd, buf, size);
  119. if (res == -1) {
  120. ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
  121. }
  122. ast_restore_tty(key->infd, tmp);
  123. if (buf[strlen(buf) -1] == '\n') {
  124. buf[strlen(buf) - 1] = '\0';
  125. }
  126. return strlen(buf);
  127. }
  128. /*!
  129. * \brief return the ast_key structure for name
  130. * \see ast_key_get
  131. */
  132. struct ast_key * AST_OPTIONAL_API_NAME(ast_key_get)(const char *kname, int ktype)
  133. {
  134. struct ast_key *key;
  135. AST_RWLIST_RDLOCK(&keys);
  136. AST_RWLIST_TRAVERSE(&keys, key, list) {
  137. if (!strcmp(kname, key->name) &&
  138. (ktype == key->ktype)) {
  139. break;
  140. }
  141. }
  142. AST_RWLIST_UNLOCK(&keys);
  143. return key;
  144. }
  145. /*!
  146. * \brief load RSA key from file
  147. * \param dir directory string
  148. * \param fname name of file
  149. * \param ifd incoming file descriptor
  150. * \param ofd outgoing file descriptor
  151. * \param not2
  152. * \return key on success.
  153. * \retval NULL on failure.
  154. */
  155. static struct ast_key *try_load_key(const char *dir, const char *fname, int ifd, int ofd, int *not2)
  156. {
  157. int n, ktype = 0, found = 0;
  158. const char *c = NULL;
  159. char ffname[256];
  160. unsigned char digest[MD5_DIGEST_LENGTH];
  161. unsigned digestlen;
  162. FILE *f;
  163. EVP_MD_CTX *ctx = NULL;
  164. struct ast_key *key;
  165. static int notice = 0;
  166. struct stat st;
  167. size_t fnamelen = strlen(fname);
  168. /* Make sure its name is a public or private key */
  169. if (fnamelen > 4 && !strcmp((c = &fname[fnamelen - 4]), ".pub")) {
  170. ktype = AST_KEY_PUBLIC;
  171. } else if (fnamelen > 4 && !strcmp((c = &fname[fnamelen - 4]), ".key")) {
  172. ktype = AST_KEY_PRIVATE;
  173. } else {
  174. return NULL;
  175. }
  176. /* Get actual filename */
  177. n = snprintf(ffname, sizeof(ffname), "%s/%s", dir, fname);
  178. if (n >= sizeof(ffname)) {
  179. ast_log(LOG_WARNING,
  180. "Key filenames can be up to %zu bytes long, but the filename for the"
  181. " key we are currently trying to load (%s/%s) is %d bytes long.",
  182. sizeof(ffname) - 1, dir, fname, n);
  183. return NULL;
  184. }
  185. /* Open file */
  186. if (!(f = fopen(ffname, "r"))) {
  187. ast_log(LOG_WARNING, "Unable to open key file %s: %s\n", ffname, strerror(errno));
  188. return NULL;
  189. }
  190. n = fstat(fileno(f), &st);
  191. if (n != 0) {
  192. ast_log(LOG_ERROR, "Unable to stat key file: %s: %s\n", ffname, strerror(errno));
  193. fclose(f);
  194. return NULL;
  195. }
  196. if (!S_ISREG(st.st_mode)) {
  197. ast_log(LOG_ERROR, "Key file is not a regular file: %s\n", ffname);
  198. fclose(f);
  199. return NULL;
  200. }
  201. /* FILE_MODE_BITS is a bitwise OR of all possible file mode bits encoded in
  202. * the `st_mode` member of `struct stat`. For POSIX compatible systems this
  203. * will be 07777. */
  204. #define FILE_MODE_BITS (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO)
  205. /* only user read or read/write modes allowed */
  206. if (ktype == AST_KEY_PRIVATE &&
  207. ((st.st_mode & FILE_MODE_BITS) & ~(S_IRUSR | S_IWUSR)) != 0) {
  208. ast_log(LOG_ERROR, "Private key file has bad permissions: %s: %#4o\n", ffname, st.st_mode & FILE_MODE_BITS);
  209. fclose(f);
  210. return NULL;
  211. }
  212. ctx = EVP_MD_CTX_create();
  213. if (ctx == NULL) {
  214. ast_log(LOG_ERROR, "Out of memory\n");
  215. fclose(f);
  216. return NULL;
  217. }
  218. EVP_DigestInit(ctx, EVP_md5());
  219. while (!feof(f)) {
  220. /* Calculate a "whatever" quality md5sum of the key */
  221. char buf[256] = "";
  222. if (!fgets(buf, sizeof(buf), f)) {
  223. continue;
  224. }
  225. if (!feof(f)) {
  226. EVP_DigestUpdate(ctx, (unsigned char *)buf, strlen(buf));
  227. }
  228. }
  229. EVP_DigestFinal(ctx, digest, &digestlen);
  230. EVP_MD_CTX_destroy(ctx);
  231. /* Look for an existing key */
  232. AST_RWLIST_TRAVERSE(&keys, key, list) {
  233. if (!strcasecmp(key->fn, ffname)) {
  234. break;
  235. }
  236. }
  237. if (key) {
  238. /* If the MD5 sum is the same, and it isn't awaiting a passcode
  239. then this is far enough */
  240. if (!memcmp(digest, key->digest, sizeof(digest)) &&
  241. !(key->ktype & KEY_NEEDS_PASSCODE)) {
  242. fclose(f);
  243. key->delme = 0;
  244. return NULL;
  245. } else {
  246. /* Preserve keytype */
  247. ktype = key->ktype;
  248. /* Recycle the same structure */
  249. found++;
  250. }
  251. }
  252. if (!key) {
  253. if (!(key = ast_calloc(1, sizeof(*key)))) {
  254. fclose(f);
  255. return NULL;
  256. }
  257. }
  258. /* First the filename */
  259. ast_copy_string(key->fn, ffname, sizeof(key->fn));
  260. /* Then the name minus the suffix */
  261. snprintf(key->name, sizeof(key->name), "%.*s", (int)(c - fname), fname);
  262. key->ktype = ktype;
  263. /* Yes, assume we're going to be deleted */
  264. key->delme = 1;
  265. /* Keep the key type */
  266. memcpy(key->digest, digest, sizeof(key->digest));
  267. /* Can I/O takes the FD we're given */
  268. key->infd = ifd;
  269. key->outfd = ofd;
  270. /* Reset the file back to the beginning */
  271. rewind(f);
  272. /* Now load the key with the right method */
  273. if (ktype == AST_KEY_PUBLIC) {
  274. PEM_read_PUBKEY(f, &key->pkey, pw_cb, key);
  275. } else {
  276. PEM_read_PrivateKey(f, &key->pkey, pw_cb, key);
  277. }
  278. fclose(f);
  279. if (key->pkey) {
  280. if (EVP_PKEY_size(key->pkey) == (AST_CRYPTO_RSA_KEY_BITS / 8)) {
  281. /* Key loaded okay */
  282. key->ktype &= ~KEY_NEEDS_PASSCODE;
  283. ast_verb(3, "Loaded %s key '%s'\n", key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name);
  284. ast_debug(1, "Key '%s' loaded OK\n", key->name);
  285. key->delme = 0;
  286. } else {
  287. ast_log(LOG_NOTICE, "Key '%s' is not expected size.\n", key->name);
  288. }
  289. } else if (key->infd != -2) {
  290. ast_log(LOG_WARNING, "Key load %s '%s' failed\n", key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name);
  291. if (ofd > -1) {
  292. ERR_print_errors_fp(stderr);
  293. } else {
  294. ERR_print_errors_fp(stderr);
  295. }
  296. } else {
  297. ast_log(LOG_NOTICE, "Key '%s' needs passcode.\n", key->name);
  298. key->ktype |= KEY_NEEDS_PASSCODE;
  299. if (!notice) {
  300. if (!ast_opt_init_keys) {
  301. ast_log(LOG_NOTICE, "Add the '-i' flag to the asterisk command line if you want to automatically initialize passcodes at launch.\n");
  302. }
  303. notice++;
  304. }
  305. /* Keep it anyway */
  306. key->delme = 0;
  307. /* Print final notice about "keys init" when done */
  308. *not2 = 1;
  309. }
  310. /* If this is a new key add it to the list */
  311. if (!found) {
  312. AST_RWLIST_INSERT_TAIL(&keys, key, list);
  313. }
  314. return key;
  315. }
  316. static int evp_pkey_sign(EVP_PKEY *pkey, const unsigned char *in, unsigned inlen, unsigned char *sig, unsigned *siglen, unsigned padding)
  317. {
  318. EVP_PKEY_CTX *ctx = NULL;
  319. int res = -1;
  320. size_t _siglen;
  321. if (*siglen < EVP_PKEY_size(pkey)) {
  322. return -1;
  323. }
  324. if ((ctx = EVP_PKEY_CTX_new(pkey, NULL)) == NULL) {
  325. return -1;
  326. }
  327. do {
  328. if ((res = EVP_PKEY_sign_init(ctx)) <= 0) {
  329. break;
  330. }
  331. if ((res = EVP_PKEY_CTX_set_rsa_padding(ctx, padding)) <= 0) {
  332. break;
  333. }
  334. if ((res = EVP_PKEY_CTX_set_signature_md(ctx, EVP_sha1())) <= 0) {
  335. break;
  336. }
  337. _siglen = *siglen;
  338. if ((res = EVP_PKEY_sign(ctx, sig, &_siglen, in, inlen)) <= 0) {
  339. break;
  340. }
  341. *siglen = _siglen;
  342. } while (0);
  343. EVP_PKEY_CTX_free(ctx);
  344. return res;
  345. }
  346. /*!
  347. * \brief signs outgoing message with public key
  348. * \see ast_sign_bin
  349. */
  350. int AST_OPTIONAL_API_NAME(ast_sign_bin)(struct ast_key *key, const char *msg, int msglen, unsigned char *dsig)
  351. {
  352. unsigned char digest[SHA_DIGEST_LENGTH];
  353. unsigned digestlen, siglen = 128;
  354. int res;
  355. EVP_MD_CTX *ctx = NULL;
  356. if (key->ktype != AST_KEY_PRIVATE) {
  357. ast_log(LOG_WARNING, "Cannot sign with a public key\n");
  358. return -1;
  359. }
  360. if (siglen < EVP_PKEY_size(key->pkey)) {
  361. ast_log(LOG_WARNING, "Signature buffer too small\n");
  362. return -1;
  363. }
  364. /* Calculate digest of message */
  365. ctx = EVP_MD_CTX_create();
  366. if (ctx == NULL) {
  367. ast_log(LOG_ERROR, "Out of memory\n");
  368. return -1;
  369. }
  370. EVP_DigestInit(ctx, EVP_sha1());
  371. EVP_DigestUpdate(ctx, msg, msglen);
  372. EVP_DigestFinal(ctx, digest, &digestlen);
  373. EVP_MD_CTX_destroy(ctx);
  374. /* Verify signature */
  375. if ((res = evp_pkey_sign(key->pkey, digest, sizeof(digest), dsig, &siglen, RSA_PKCS1_PADDING)) <= 0) {
  376. ast_log(LOG_WARNING, "RSA Signature (key %s) failed %d\n", key->name, res);
  377. return -1;
  378. }
  379. if (siglen != EVP_PKEY_size(key->pkey)) {
  380. ast_log(LOG_WARNING, "Unexpected signature length %u, expecting %d\n", siglen, EVP_PKEY_size(key->pkey));
  381. return -1;
  382. }
  383. return 0;
  384. }
  385. static int evp_pkey_decrypt(EVP_PKEY *pkey, const unsigned char *in, unsigned inlen, unsigned char *out, unsigned *outlen, unsigned padding)
  386. {
  387. EVP_PKEY_CTX *ctx = NULL;
  388. int res = -1;
  389. size_t _outlen;
  390. if (*outlen < EVP_PKEY_size(pkey)) {
  391. return -1;
  392. }
  393. if (inlen != EVP_PKEY_size(pkey)) {
  394. return -1;
  395. }
  396. if ((ctx = EVP_PKEY_CTX_new(pkey, NULL)) == NULL) {
  397. return -1;
  398. }
  399. do {
  400. if ((res = EVP_PKEY_decrypt_init(ctx)) <= 0) {
  401. break;
  402. }
  403. if ((res = EVP_PKEY_CTX_set_rsa_padding(ctx, padding)) <= 0) {
  404. break;
  405. }
  406. _outlen = *outlen;
  407. if ((res = EVP_PKEY_decrypt(ctx, out, &_outlen, in, inlen)) <= 0) {
  408. break;
  409. }
  410. res = *outlen = _outlen;
  411. } while (0);
  412. EVP_PKEY_CTX_free(ctx);
  413. return res;
  414. }
  415. /*!
  416. * \brief decrypt a message
  417. * \see ast_decrypt_bin
  418. */
  419. int AST_OPTIONAL_API_NAME(ast_decrypt_bin)(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
  420. {
  421. int res;
  422. unsigned pos = 0, dstlen, blocksize;
  423. if (key->ktype != AST_KEY_PRIVATE) {
  424. ast_log(LOG_WARNING, "Cannot decrypt with a public key\n");
  425. return -1;
  426. }
  427. blocksize = EVP_PKEY_size(key->pkey);
  428. if (srclen % blocksize) {
  429. ast_log(LOG_NOTICE, "Tried to decrypt something not a multiple of %u bytes\n", blocksize);
  430. return -1;
  431. }
  432. while (srclen > 0) {
  433. /* Process chunks 128 bytes at a time */
  434. dstlen = blocksize;
  435. if ((res = evp_pkey_decrypt(key->pkey, src, blocksize, dst, &dstlen, RSA_PKCS1_OAEP_PADDING)) <= 0) {
  436. return -1;
  437. }
  438. pos += dstlen;
  439. src += blocksize;
  440. srclen -= blocksize;
  441. dst += dstlen;
  442. }
  443. return pos;
  444. }
  445. static int evp_pkey_encrypt(EVP_PKEY *pkey, const unsigned char *in, unsigned inlen, unsigned char *out, unsigned *outlen, unsigned padding)
  446. {
  447. EVP_PKEY_CTX *ctx = NULL;
  448. int res = -1;
  449. size_t _outlen;
  450. if (padding != RSA_PKCS1_OAEP_PADDING) {
  451. ast_log(LOG_WARNING, "Only OAEP padding is supported for now\n");
  452. return -1;
  453. }
  454. if (inlen > EVP_PKEY_size(pkey) - RSA_PKCS1_OAEP_PADDING_SIZE) {
  455. return -1;
  456. }
  457. if (*outlen < EVP_PKEY_size(pkey)) {
  458. return -1;
  459. }
  460. do {
  461. if ((ctx = EVP_PKEY_CTX_new(pkey, NULL)) == NULL) {
  462. break;
  463. }
  464. if ((res = EVP_PKEY_encrypt_init(ctx)) <= 0) {
  465. break;
  466. }
  467. if ((res = EVP_PKEY_CTX_set_rsa_padding(ctx, padding)) <= 0) {
  468. break;
  469. }
  470. _outlen = *outlen;
  471. if ((res = EVP_PKEY_encrypt(ctx, out, &_outlen, in, inlen)) <= 0) {
  472. break;
  473. }
  474. res = *outlen = _outlen;
  475. } while (0);
  476. EVP_PKEY_CTX_free(ctx);
  477. return res;
  478. }
  479. /*!
  480. * \brief encrypt a message
  481. * \see ast_encrypt_bin
  482. */
  483. int AST_OPTIONAL_API_NAME(ast_encrypt_bin)(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
  484. {
  485. unsigned bytes, pos = 0, dstlen, blocksize;
  486. int res;
  487. if (key->ktype != AST_KEY_PUBLIC) {
  488. ast_log(LOG_WARNING, "Cannot encrypt with a private key\n");
  489. return -1;
  490. }
  491. blocksize = EVP_PKEY_size(key->pkey);
  492. while (srclen) {
  493. bytes = srclen;
  494. if (bytes > blocksize - RSA_PKCS1_OAEP_PADDING_SIZE) {
  495. bytes = blocksize - RSA_PKCS1_OAEP_PADDING_SIZE;
  496. }
  497. /* Process chunks 128-41 bytes at a time */
  498. dstlen = blocksize;
  499. if ((res = evp_pkey_encrypt(key->pkey, src, bytes, dst, &dstlen, RSA_PKCS1_OAEP_PADDING)) != blocksize) {
  500. ast_log(LOG_NOTICE, "How odd, encrypted size is %d\n", res);
  501. return -1;
  502. }
  503. src += bytes;
  504. srclen -= bytes;
  505. pos += dstlen;
  506. dst += dstlen;
  507. }
  508. return pos;
  509. }
  510. /*!
  511. * \brief wrapper for __ast_sign_bin then base64 encode it
  512. * \see ast_sign
  513. */
  514. int AST_OPTIONAL_API_NAME(ast_sign)(struct ast_key *key, char *msg, char *sig)
  515. {
  516. /* assumes 1024 bit RSA key size */
  517. unsigned char dsig[128];
  518. int siglen = sizeof(dsig), res;
  519. if (!(res = ast_sign_bin(key, msg, strlen(msg), dsig))) {
  520. /* Success -- encode (256 bytes max as documented) */
  521. ast_base64encode(sig, dsig, siglen, 256);
  522. }
  523. return res;
  524. }
  525. static int evp_pkey_verify(EVP_PKEY *pkey, const unsigned char *in, unsigned inlen, const unsigned char *sig, unsigned siglen, unsigned padding)
  526. {
  527. EVP_PKEY_CTX *ctx = NULL;
  528. int res = -1;
  529. if (siglen < EVP_PKEY_size(pkey)) {
  530. return -1;
  531. }
  532. if ((ctx = EVP_PKEY_CTX_new(pkey, NULL)) == NULL) {
  533. return -1;
  534. }
  535. do {
  536. if ((res = EVP_PKEY_verify_init(ctx)) <= 0) {
  537. break;
  538. }
  539. if ((res = EVP_PKEY_CTX_set_rsa_padding(ctx, padding)) <= 0) {
  540. break;
  541. }
  542. if ((res = EVP_PKEY_CTX_set_signature_md(ctx, EVP_sha1())) <= 0) {
  543. break;
  544. }
  545. if ((res = EVP_PKEY_verify(ctx, sig, siglen, in, inlen)) <= 0) {
  546. break;
  547. }
  548. } while (0);
  549. EVP_PKEY_CTX_free(ctx);
  550. return res;
  551. }
  552. /*!
  553. * \brief check signature of a message
  554. * \see ast_check_signature_bin
  555. */
  556. int AST_OPTIONAL_API_NAME(ast_check_signature_bin)(struct ast_key *key, const char *msg, int msglen, const unsigned char *dsig)
  557. {
  558. unsigned char digest[SHA_DIGEST_LENGTH];
  559. unsigned digestlen;
  560. int res;
  561. EVP_MD_CTX *ctx = NULL;
  562. if (key->ktype != AST_KEY_PUBLIC) {
  563. /* Okay, so of course you really *can* but for our purposes
  564. we're going to say you can't */
  565. ast_log(LOG_WARNING, "Cannot check message signature with a private key\n");
  566. return -1;
  567. }
  568. /* Calculate digest of message */
  569. ctx = EVP_MD_CTX_create();
  570. if (ctx == NULL) {
  571. ast_log(LOG_ERROR, "Out of memory\n");
  572. return -1;
  573. }
  574. EVP_DigestInit(ctx, EVP_sha1());
  575. EVP_DigestUpdate(ctx, msg, msglen);
  576. EVP_DigestFinal(ctx, digest, &digestlen);
  577. EVP_MD_CTX_destroy(ctx);
  578. /* Verify signature */
  579. if (!(res = evp_pkey_verify(key->pkey, (const unsigned char *)digest, sizeof(digest), (unsigned char *)dsig, 128, RSA_PKCS1_PADDING))) {
  580. ast_debug(1, "Key failed verification: %s\n", key->name);
  581. return -1;
  582. }
  583. /* Pass */
  584. return 0;
  585. }
  586. /*!
  587. * \brief base64 decode then sent to __ast_check_signature_bin
  588. * \see ast_check_signature
  589. */
  590. int AST_OPTIONAL_API_NAME(ast_check_signature)(struct ast_key *key, const char *msg, const char *sig)
  591. {
  592. unsigned char dsig[128];
  593. int res;
  594. /* Decode signature */
  595. if ((res = ast_base64decode(dsig, sig, sizeof(dsig))) != sizeof(dsig)) {
  596. ast_log(LOG_WARNING, "Signature improper length (expect %d, got %d)\n", (int)sizeof(dsig), (int)res);
  597. return -1;
  598. }
  599. res = ast_check_signature_bin(key, msg, strlen(msg), dsig);
  600. return res;
  601. }
  602. int AST_OPTIONAL_API_NAME(ast_crypto_loaded)(void)
  603. {
  604. return 1;
  605. }
  606. int AST_OPTIONAL_API_NAME(ast_crypto_reload)(void)
  607. {
  608. crypto_load(-1, -1);
  609. return 1;
  610. }
  611. int AST_OPTIONAL_API_NAME(ast_aes_set_encrypt_key)(const unsigned char *key, ast_aes_encrypt_key *ctx)
  612. {
  613. if (key == NULL || ctx == NULL) {
  614. return -1;
  615. }
  616. memcpy(ctx->raw, key, AST_CRYPTO_AES_BLOCKSIZE / 8);
  617. return 0;
  618. }
  619. int AST_OPTIONAL_API_NAME(ast_aes_set_decrypt_key)(const unsigned char *key, ast_aes_decrypt_key *ctx)
  620. {
  621. if (key == NULL || ctx == NULL) {
  622. return -1;
  623. }
  624. memcpy(ctx->raw, key, AST_CRYPTO_AES_BLOCKSIZE / 8);
  625. return 0;
  626. }
  627. static int evp_cipher_aes_encrypt(const unsigned char *in, unsigned char *out, unsigned inlen, const ast_aes_encrypt_key *key)
  628. {
  629. EVP_CIPHER_CTX *ctx = NULL;
  630. int res, outlen, finallen;
  631. unsigned char final[AST_CRYPTO_AES_BLOCKSIZE / 8];
  632. if ((ctx = EVP_CIPHER_CTX_new()) == NULL) {
  633. return -1;
  634. }
  635. do {
  636. if ((res = EVP_CipherInit(ctx, EVP_aes_128_ecb(), key->raw, NULL, 1)) <= 0) {
  637. break;
  638. }
  639. EVP_CIPHER_CTX_set_padding(ctx, 0);
  640. if ((res = EVP_CipherUpdate(ctx, out, &outlen, in, inlen)) <= 0) {
  641. break;
  642. }
  643. /* for ECB, this is a no-op */
  644. if ((res = EVP_CipherFinal(ctx, final, &finallen)) <= 0) {
  645. break;
  646. }
  647. res = outlen;
  648. } while (0);
  649. EVP_CIPHER_CTX_free(ctx);
  650. return res;
  651. }
  652. int AST_OPTIONAL_API_NAME(ast_aes_encrypt)(const unsigned char *in, unsigned char *out, const ast_aes_encrypt_key *key)
  653. {
  654. int res;
  655. if ((res = evp_cipher_aes_encrypt(in, out, AST_CRYPTO_AES_BLOCKSIZE / 8, key)) <= 0) {
  656. ast_log(LOG_ERROR, "AES encryption failed\n");
  657. }
  658. return res;
  659. }
  660. static int evp_cipher_aes_decrypt(const unsigned char *in, unsigned char *out, unsigned inlen, const ast_aes_decrypt_key *key)
  661. {
  662. EVP_CIPHER_CTX *ctx = NULL;
  663. int res, outlen, finallen;
  664. unsigned char final[AST_CRYPTO_AES_BLOCKSIZE / 8];
  665. if ((ctx = EVP_CIPHER_CTX_new()) == NULL) {
  666. return -1;
  667. }
  668. do {
  669. if ((res = EVP_CipherInit(ctx, EVP_aes_128_ecb(), key->raw, NULL, 0)) <= 0) {
  670. break;
  671. }
  672. EVP_CIPHER_CTX_set_padding(ctx, 0);
  673. if ((res = EVP_CipherUpdate(ctx, out, &outlen, in, inlen)) <= 0) {
  674. break;
  675. }
  676. /* for ECB, this is a no-op */
  677. if ((res = EVP_CipherFinal(ctx, final, &finallen)) <= 0) {
  678. break;
  679. }
  680. res = outlen;
  681. } while (0);
  682. EVP_CIPHER_CTX_free(ctx);
  683. return res;
  684. }
  685. int AST_OPTIONAL_API_NAME(ast_aes_decrypt)(const unsigned char *in, unsigned char *out, const ast_aes_decrypt_key *key)
  686. {
  687. int res;
  688. if ((res = evp_cipher_aes_decrypt(in, out, AST_CRYPTO_AES_BLOCKSIZE / 8, key)) <= 0) {
  689. ast_log(LOG_ERROR, "AES decryption failed\n");
  690. }
  691. return res;
  692. }
  693. struct crypto_load_on_file {
  694. int ifd;
  695. int ofd;
  696. int note;
  697. };
  698. static int crypto_load_cb(const char *directory, const char *file, void *obj)
  699. {
  700. struct crypto_load_on_file *on_file = obj;
  701. try_load_key(directory, file, on_file->ifd, on_file->ofd, &on_file->note);
  702. return 0;
  703. }
  704. /*!
  705. * \brief refresh RSA keys from file
  706. * \param ifd file descriptor
  707. * \param ofd file descriptor
  708. */
  709. static void crypto_load(int ifd, int ofd)
  710. {
  711. struct ast_key *key;
  712. struct crypto_load_on_file on_file = { ifd, ofd, 0 };
  713. AST_RWLIST_WRLOCK(&keys);
  714. /* Mark all keys for deletion */
  715. AST_RWLIST_TRAVERSE(&keys, key, list) {
  716. key->delme = 1;
  717. }
  718. if (ast_file_read_dirs(ast_config_AST_KEY_DIR, crypto_load_cb, &on_file, 1) == -1) {
  719. ast_log(LOG_WARNING, "Unable to open key directory '%s'\n", ast_config_AST_KEY_DIR);
  720. }
  721. if (on_file.note) {
  722. ast_log(LOG_NOTICE, "Please run the command 'keys init' to enter the passcodes for the keys\n");
  723. }
  724. /* Delete any keys that are no longer present */
  725. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&keys, key, list) {
  726. if (key->delme) {
  727. ast_debug(1, "Deleting key %s type %d\n", key->name, key->ktype);
  728. AST_RWLIST_REMOVE_CURRENT(list);
  729. if (key->pkey) {
  730. EVP_PKEY_free(key->pkey);
  731. }
  732. ast_free(key);
  733. }
  734. }
  735. AST_RWLIST_TRAVERSE_SAFE_END;
  736. AST_RWLIST_UNLOCK(&keys);
  737. }
  738. static void md52sum(char *sum, unsigned char *md5)
  739. {
  740. int x;
  741. for (x = 0; x < MD5_DIGEST_LENGTH; x++) {
  742. sum += sprintf(sum, "%02hhx", *(md5++));
  743. }
  744. }
  745. /*!
  746. * \brief show the list of RSA keys
  747. * \param e CLI command
  748. * \param cmd
  749. * \param a list of CLI arguments
  750. * \retval CLI_SUCCESS
  751. */
  752. static char *handle_cli_keys_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  753. {
  754. #define FORMAT "%-18s %-8s %-16s %-33s\n"
  755. struct ast_key *key;
  756. char sum[MD5_DIGEST_LENGTH * 2 + 1];
  757. int count_keys = 0;
  758. switch (cmd) {
  759. case CLI_INIT:
  760. e->command = "keys show";
  761. e->usage =
  762. "Usage: keys show\n"
  763. " Displays information about RSA keys known by Asterisk\n";
  764. return NULL;
  765. case CLI_GENERATE:
  766. return NULL;
  767. }
  768. ast_cli(a->fd, FORMAT, "Key Name", "Type", "Status", "Sum");
  769. ast_cli(a->fd, FORMAT, "------------------", "--------", "----------------", "--------------------------------");
  770. AST_RWLIST_RDLOCK(&keys);
  771. AST_RWLIST_TRAVERSE(&keys, key, list) {
  772. md52sum(sum, key->digest);
  773. ast_cli(a->fd, FORMAT, key->name,
  774. (key->ktype & 0xf) == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE",
  775. key->ktype & KEY_NEEDS_PASSCODE ? "[Needs Passcode]" : "[Loaded]", sum);
  776. count_keys++;
  777. }
  778. AST_RWLIST_UNLOCK(&keys);
  779. ast_cli(a->fd, "\n%d known RSA keys.\n", count_keys);
  780. return CLI_SUCCESS;
  781. #undef FORMAT
  782. }
  783. /*!
  784. * \brief initialize all RSA keys
  785. * \param e CLI command
  786. * \param cmd
  787. * \param a list of CLI arguments
  788. * \retval CLI_SUCCESS
  789. */
  790. static char *handle_cli_keys_init(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  791. {
  792. struct ast_key *key;
  793. int ign;
  794. char *kn, tmp[256] = "";
  795. switch (cmd) {
  796. case CLI_INIT:
  797. e->command = "keys init";
  798. e->usage =
  799. "Usage: keys init\n"
  800. " Initializes private keys (by reading in pass code from\n"
  801. " the user)\n";
  802. return NULL;
  803. case CLI_GENERATE:
  804. return NULL;
  805. }
  806. if (a->argc != 2) {
  807. return CLI_SHOWUSAGE;
  808. }
  809. AST_RWLIST_WRLOCK(&keys);
  810. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&keys, key, list) {
  811. /* Reload keys that need pass codes now */
  812. if (key->ktype & KEY_NEEDS_PASSCODE) {
  813. kn = key->fn + strlen(ast_config_AST_KEY_DIR) + 1;
  814. ast_copy_string(tmp, kn, sizeof(tmp));
  815. try_load_key(ast_config_AST_KEY_DIR, tmp, a->fd, a->fd, &ign);
  816. }
  817. }
  818. AST_RWLIST_TRAVERSE_SAFE_END
  819. AST_RWLIST_UNLOCK(&keys);
  820. return CLI_SUCCESS;
  821. }
  822. static struct ast_cli_entry cli_crypto[] = {
  823. AST_CLI_DEFINE(handle_cli_keys_show, "Displays RSA key information"),
  824. AST_CLI_DEFINE(handle_cli_keys_init, "Initialize RSA key passcodes")
  825. };
  826. /*! \brief initialise the res_crypto module */
  827. static int crypto_init(void)
  828. {
  829. ast_cli_register_multiple(cli_crypto, ARRAY_LEN(cli_crypto));
  830. return 0;
  831. }
  832. static int reload(void)
  833. {
  834. crypto_load(-1, -1);
  835. return 0;
  836. }
  837. static int load_module(void)
  838. {
  839. crypto_init();
  840. if (ast_opt_init_keys) {
  841. crypto_load(STDIN_FILENO, STDOUT_FILENO);
  842. } else {
  843. crypto_load(-1, -1);
  844. }
  845. return AST_MODULE_LOAD_SUCCESS;
  846. }
  847. static int unload_module(void)
  848. {
  849. ast_cli_unregister_multiple(cli_crypto, ARRAY_LEN(cli_crypto));
  850. return 0;
  851. }
  852. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Cryptographic Digital Signatures",
  853. .support_level = AST_MODULE_SUPPORT_CORE,
  854. .load = load_module,
  855. .unload = unload_module,
  856. .reload = reload,
  857. .load_pri = AST_MODPRI_CHANNEL_DEPEND, /*!< Since we don't have a config file, we could move up to REALTIME_DEPEND, if necessary */
  858. );