Merged revisions 140169 via svnmerge from
[asterisk-bristuff.git] / res / res_crypto.c
blobf1a2234fd40367514132c797fef82122368db7a3
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
19 /*! \file
21 * \brief Provide Cryptographic Signature capability
23 * \author Mark Spencer <markster@digium.com>
25 * \extref Uses the OpenSSL library, available at
26 * http://www.openssl.org/
29 /*** MODULEINFO
30 <depend>ssl</depend>
31 ***/
33 #include "asterisk.h"
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37 #include "asterisk/paths.h" /* use ast_config_AST_KEY_DIR */
38 #include <openssl/ssl.h>
39 #include <openssl/err.h>
40 #include <dirent.h>
42 #include "asterisk/module.h"
43 #include "asterisk/crypto.h"
44 #include "asterisk/md5.h"
45 #include "asterisk/cli.h"
46 #include "asterisk/io.h"
47 #include "asterisk/lock.h"
48 #include "asterisk/utils.h"
51 * Asterisk uses RSA keys with SHA-1 message digests for its
52 * digital signatures. The choice of RSA is due to its higher
53 * throughput on verification, and the choice of SHA-1 based
54 * on the recently discovered collisions in MD5's compression
55 * algorithm and recommendations of avoiding MD5 in new schemes
56 * from various industry experts.
58 * We use OpenSSL to provide our crypto routines, although we never
59 * actually use full-up SSL
63 #define KEY_NEEDS_PASSCODE (1 << 16)
65 struct ast_key {
66 /*! Name of entity */
67 char name[80];
68 /*! File name */
69 char fn[256];
70 /*! Key type (AST_KEY_PUB or AST_KEY_PRIV, along with flags from above) */
71 int ktype;
72 /*! RSA structure (if successfully loaded) */
73 RSA *rsa;
74 /*! Whether we should be deleted */
75 int delme;
76 /*! FD for input (or -1 if no input allowed, or -2 if we needed input) */
77 int infd;
78 /*! FD for output */
79 int outfd;
80 /*! Last MD5 Digest */
81 unsigned char digest[16];
82 AST_RWLIST_ENTRY(ast_key) list;
85 static AST_RWLIST_HEAD_STATIC(keys, ast_key);
87 /*!
88 * \brief setting of priv key
89 * \param buf
90 * \param size
91 * \param rwflag
92 * \param userdata
93 * \return length of string,-1 on failure
95 static int pw_cb(char *buf, int size, int rwflag, void *userdata)
97 struct ast_key *key = (struct ast_key *)userdata;
98 char prompt[256];
99 int res, tmp;
101 if (key->infd < 0) {
102 /* Note that we were at least called */
103 key->infd = -2;
104 return -1;
107 snprintf(prompt, sizeof(prompt), ">>>> passcode for %s key '%s': ",
108 key->ktype == AST_KEY_PRIVATE ? "PRIVATE" : "PUBLIC", key->name);
109 write(key->outfd, prompt, strlen(prompt));
110 memset(buf, 0, sizeof(buf));
111 tmp = ast_hide_password(key->infd);
112 memset(buf, 0, size);
113 res = read(key->infd, buf, size);
114 ast_restore_tty(key->infd, tmp);
115 if (buf[strlen(buf) -1] == '\n')
116 buf[strlen(buf) - 1] = '\0';
117 return strlen(buf);
121 * \brief return the ast_key structure for name
122 * \see ast_key_get
124 static struct ast_key *__ast_key_get(const char *kname, int ktype)
126 struct ast_key *key;
128 AST_RWLIST_RDLOCK(&keys);
129 AST_RWLIST_TRAVERSE(&keys, key, list) {
130 if (!strcmp(kname, key->name) &&
131 (ktype == key->ktype))
132 break;
134 AST_RWLIST_UNLOCK(&keys);
136 return key;
140 * \brief load RSA key from file
141 * \param dir directory string
142 * \param fname name of file
143 * \param ifd incoming file descriptor
144 * \param ofd outgoing file descriptor
145 * \param not2
146 * \retval key on success.
147 * \retval NULL on failure.
149 static struct ast_key *try_load_key(const char *dir, const char *fname, int ifd, int ofd, int *not2)
151 int ktype = 0, found = 0;
152 char *c = NULL, ffname[256];
153 unsigned char digest[16];
154 FILE *f;
155 struct MD5Context md5;
156 struct ast_key *key;
157 static int notice = 0;
159 /* Make sure its name is a public or private key */
160 if ((c = strstr(fname, ".pub")) && !strcmp(c, ".pub"))
161 ktype = AST_KEY_PUBLIC;
162 else if ((c = strstr(fname, ".key")) && !strcmp(c, ".key"))
163 ktype = AST_KEY_PRIVATE;
164 else
165 return NULL;
167 /* Get actual filename */
168 snprintf(ffname, sizeof(ffname), "%s/%s", dir, fname);
170 /* Open file */
171 if (!(f = fopen(ffname, "r"))) {
172 ast_log(LOG_WARNING, "Unable to open key file %s: %s\n", ffname, strerror(errno));
173 return NULL;
176 MD5Init(&md5);
177 while(!feof(f)) {
178 /* Calculate a "whatever" quality md5sum of the key */
179 char buf[256] = "";
180 fgets(buf, sizeof(buf), f);
181 if (!feof(f))
182 MD5Update(&md5, (unsigned char *) buf, strlen(buf));
184 MD5Final(digest, &md5);
186 /* Look for an existing key */
187 AST_RWLIST_TRAVERSE(&keys, key, list) {
188 if (!strcasecmp(key->fn, ffname))
189 break;
192 if (key) {
193 /* If the MD5 sum is the same, and it isn't awaiting a passcode
194 then this is far enough */
195 if (!memcmp(digest, key->digest, 16) &&
196 !(key->ktype & KEY_NEEDS_PASSCODE)) {
197 fclose(f);
198 key->delme = 0;
199 return NULL;
200 } else {
201 /* Preserve keytype */
202 ktype = key->ktype;
203 /* Recycle the same structure */
204 found++;
208 /* Make fname just be the normal name now */
209 *c = '\0';
210 if (!key) {
211 if (!(key = ast_calloc(1, sizeof(*key)))) {
212 fclose(f);
213 return NULL;
216 /* First the filename */
217 ast_copy_string(key->fn, ffname, sizeof(key->fn));
218 /* Then the name */
219 ast_copy_string(key->name, fname, sizeof(key->name));
220 key->ktype = ktype;
221 /* Yes, assume we're going to be deleted */
222 key->delme = 1;
223 /* Keep the key type */
224 memcpy(key->digest, digest, 16);
225 /* Can I/O takes the FD we're given */
226 key->infd = ifd;
227 key->outfd = ofd;
228 /* Reset the file back to the beginning */
229 rewind(f);
230 /* Now load the key with the right method */
231 if (ktype == AST_KEY_PUBLIC)
232 key->rsa = PEM_read_RSA_PUBKEY(f, NULL, pw_cb, key);
233 else
234 key->rsa = PEM_read_RSAPrivateKey(f, NULL, pw_cb, key);
235 fclose(f);
236 if (key->rsa) {
237 if (RSA_size(key->rsa) == 128) {
238 /* Key loaded okay */
239 key->ktype &= ~KEY_NEEDS_PASSCODE;
240 ast_verb(3, "Loaded %s key '%s'\n", key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name);
241 ast_debug(1, "Key '%s' loaded OK\n", key->name);
242 key->delme = 0;
243 } else
244 ast_log(LOG_NOTICE, "Key '%s' is not expected size.\n", key->name);
245 } else if (key->infd != -2) {
246 ast_log(LOG_WARNING, "Key load %s '%s' failed\n",key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name);
247 if (ofd > -1)
248 ERR_print_errors_fp(stderr);
249 else
250 ERR_print_errors_fp(stderr);
251 } else {
252 ast_log(LOG_NOTICE, "Key '%s' needs passcode.\n", key->name);
253 key->ktype |= KEY_NEEDS_PASSCODE;
254 if (!notice) {
255 if (!ast_opt_init_keys)
256 ast_log(LOG_NOTICE, "Add the '-i' flag to the asterisk command line if you want to automatically initialize passcodes at launch.\n");
257 notice++;
259 /* Keep it anyway */
260 key->delme = 0;
261 /* Print final notice about "init keys" when done */
262 *not2 = 1;
265 /* If this is a new key add it to the list */
266 if (!found)
267 AST_RWLIST_INSERT_TAIL(&keys, key, list);
269 return key;
273 * \brief signs outgoing message with public key
274 * \see ast_sign_bin
276 static int __ast_sign_bin(struct ast_key *key, const char *msg, int msglen, unsigned char *dsig)
278 unsigned char digest[20];
279 unsigned int siglen = 128;
280 int res;
282 if (key->ktype != AST_KEY_PRIVATE) {
283 ast_log(LOG_WARNING, "Cannot sign with a public key\n");
284 return -1;
287 /* Calculate digest of message */
288 SHA1((unsigned char *)msg, msglen, digest);
290 /* Verify signature */
291 if (!(res = RSA_sign(NID_sha1, digest, sizeof(digest), dsig, &siglen, key->rsa))) {
292 ast_log(LOG_WARNING, "RSA Signature (key %s) failed\n", key->name);
293 return -1;
296 if (siglen != 128) {
297 ast_log(LOG_WARNING, "Unexpected signature length %d, expecting %d\n", (int)siglen, (int)128);
298 return -1;
301 return 0;
306 * \brief decrypt a message
307 * \see ast_decrypt_bin
309 static int __ast_decrypt_bin(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
311 int res, pos = 0;
313 if (key->ktype != AST_KEY_PRIVATE) {
314 ast_log(LOG_WARNING, "Cannot decrypt with a public key\n");
315 return -1;
318 if (srclen % 128) {
319 ast_log(LOG_NOTICE, "Tried to decrypt something not a multiple of 128 bytes\n");
320 return -1;
323 while(srclen) {
324 /* Process chunks 128 bytes at a time */
325 if ((res = RSA_private_decrypt(128, src, dst, key->rsa, RSA_PKCS1_OAEP_PADDING)) < 0)
326 return -1;
327 pos += res;
328 src += 128;
329 srclen -= 128;
330 dst += res;
333 return pos;
337 * \brief encrypt a message
338 * \see ast_encrypt_bin
340 static int __ast_encrypt_bin(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
342 int res, bytes, pos = 0;
344 if (key->ktype != AST_KEY_PUBLIC) {
345 ast_log(LOG_WARNING, "Cannot encrypt with a private key\n");
346 return -1;
349 while(srclen) {
350 bytes = srclen;
351 if (bytes > 128 - 41)
352 bytes = 128 - 41;
353 /* Process chunks 128-41 bytes at a time */
354 if ((res = RSA_public_encrypt(bytes, src, dst, key->rsa, RSA_PKCS1_OAEP_PADDING)) != 128) {
355 ast_log(LOG_NOTICE, "How odd, encrypted size is %d\n", res);
356 return -1;
358 src += bytes;
359 srclen -= bytes;
360 pos += res;
361 dst += res;
363 return pos;
367 * \brief wrapper for __ast_sign_bin then base64 encode it
368 * \see ast_sign
370 static int __ast_sign(struct ast_key *key, char *msg, char *sig)
372 unsigned char dsig[128];
373 int siglen = sizeof(dsig), res;
375 if (!(res = ast_sign_bin(key, msg, strlen(msg), dsig)))
376 /* Success -- encode (256 bytes max as documented) */
377 ast_base64encode(sig, dsig, siglen, 256);
379 return res;
383 * \brief check signature of a message
384 * \see ast_check_signature_bin
386 static int __ast_check_signature_bin(struct ast_key *key, const char *msg, int msglen, const unsigned char *dsig)
388 unsigned char digest[20];
389 int res;
391 if (key->ktype != AST_KEY_PUBLIC) {
392 /* Okay, so of course you really *can* but for our purposes
393 we're going to say you can't */
394 ast_log(LOG_WARNING, "Cannot check message signature with a private key\n");
395 return -1;
398 /* Calculate digest of message */
399 SHA1((unsigned char *)msg, msglen, digest);
401 /* Verify signature */
402 if (!(res = RSA_verify(NID_sha1, digest, sizeof(digest), (unsigned char *)dsig, 128, key->rsa))) {
403 ast_debug(1, "Key failed verification: %s\n", key->name);
404 return -1;
407 /* Pass */
408 return 0;
412 * \brief base64 decode then sent to __ast_check_signature_bin
413 * \see ast_check_signature
415 static int __ast_check_signature(struct ast_key *key, const char *msg, const char *sig)
417 unsigned char dsig[128];
418 int res;
420 /* Decode signature */
421 if ((res = ast_base64decode(dsig, sig, sizeof(dsig))) != sizeof(dsig)) {
422 ast_log(LOG_WARNING, "Signature improper length (expect %d, got %d)\n", (int)sizeof(dsig), (int)res);
423 return -1;
426 res = ast_check_signature_bin(key, msg, strlen(msg), dsig);
428 return res;
432 * \brief refresh RSA keys from file
433 * \param ifd file descriptor
434 * \param ofd file descriptor
435 * \return void
437 static void crypto_load(int ifd, int ofd)
439 struct ast_key *key;
440 DIR *dir = NULL;
441 struct dirent *ent;
442 int note = 0;
444 AST_RWLIST_WRLOCK(&keys);
446 /* Mark all keys for deletion */
447 AST_RWLIST_TRAVERSE(&keys, key, list) {
448 key->delme = 1;
451 /* Load new keys */
452 if ((dir = opendir(ast_config_AST_KEY_DIR))) {
453 while((ent = readdir(dir))) {
454 try_load_key(ast_config_AST_KEY_DIR, ent->d_name, ifd, ofd, &note);
456 closedir(dir);
457 } else
458 ast_log(LOG_WARNING, "Unable to open key directory '%s'\n", ast_config_AST_KEY_DIR);
460 if (note)
461 ast_log(LOG_NOTICE, "Please run the command 'init keys' to enter the passcodes for the keys\n");
463 /* Delete any keys that are no longer present */
464 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&keys, key, list) {
465 if (key->delme) {
466 ast_debug(1, "Deleting key %s type %d\n", key->name, key->ktype);
467 AST_RWLIST_REMOVE_CURRENT(list);
468 if (key->rsa)
469 RSA_free(key->rsa);
470 ast_free(key);
473 AST_RWLIST_TRAVERSE_SAFE_END;
475 AST_RWLIST_UNLOCK(&keys);
478 static void md52sum(char *sum, unsigned char *md5)
480 int x;
481 for (x = 0; x < 16; x++)
482 sum += sprintf(sum, "%02x", *(md5++));
485 /*!
486 * \brief show the list of RSA keys
487 * \param e CLI command
488 * \param cmd
489 * \param a list of CLI arguments
490 * \return CLI_SUCCESS
492 static char *handle_cli_keys_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
494 #define FORMAT "%-18s %-8s %-16s %-33s\n"
496 struct ast_key *key;
497 char sum[16 * 2 + 1];
498 int count_keys = 0;
500 switch (cmd) {
501 case CLI_INIT:
502 e->command = "keys show";
503 e->usage =
504 "Usage: keys show\n"
505 " Displays information about RSA keys known by Asterisk\n";
506 return NULL;
507 case CLI_GENERATE:
508 return NULL;
511 ast_cli(a->fd, FORMAT, "Key Name", "Type", "Status", "Sum");
512 ast_cli(a->fd, FORMAT, "------------------", "--------", "----------------", "--------------------------------");
514 AST_RWLIST_RDLOCK(&keys);
515 AST_RWLIST_TRAVERSE(&keys, key, list) {
516 md52sum(sum, key->digest);
517 ast_cli(a->fd, FORMAT, key->name,
518 (key->ktype & 0xf) == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE",
519 key->ktype & KEY_NEEDS_PASSCODE ? "[Needs Passcode]" : "[Loaded]", sum);
520 count_keys++;
522 AST_RWLIST_UNLOCK(&keys);
524 ast_cli(a->fd, "\n%d known RSA keys.\n", count_keys);
526 return CLI_SUCCESS;
528 #undef FORMAT
531 /*!
532 * \brief initialize all RSA keys
533 * \param e CLI command
534 * \param cmd
535 * \param a list of CLI arguments
536 * \return CLI_SUCCESS
538 static char *handle_cli_keys_init(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
540 struct ast_key *key;
541 int ign;
542 char *kn, tmp[256] = "";
544 switch (cmd) {
545 case CLI_INIT:
546 e->command = "keys init";
547 e->usage =
548 "Usage: keys init\n"
549 " Initializes private keys (by reading in pass code from\n"
550 " the user)\n";
551 return NULL;
552 case CLI_GENERATE:
553 return NULL;
556 if (a->argc != 2)
557 return CLI_SHOWUSAGE;
559 AST_RWLIST_WRLOCK(&keys);
560 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&keys, key, list) {
561 /* Reload keys that need pass codes now */
562 if (key->ktype & KEY_NEEDS_PASSCODE) {
563 kn = key->fn + strlen(ast_config_AST_KEY_DIR) + 1;
564 ast_copy_string(tmp, kn, sizeof(tmp));
565 try_load_key(ast_config_AST_KEY_DIR, tmp, a->fd, a->fd, &ign);
568 AST_RWLIST_TRAVERSE_SAFE_END
569 AST_RWLIST_UNLOCK(&keys);
571 return CLI_SUCCESS;
574 static struct ast_cli_entry cli_crypto[] = {
575 AST_CLI_DEFINE(handle_cli_keys_show, "Displays RSA key information"),
576 AST_CLI_DEFINE(handle_cli_keys_init, "Initialize RSA key passcodes")
579 /*! \brief initialise the res_crypto module */
580 static int crypto_init(void)
582 SSL_library_init();
583 ERR_load_crypto_strings();
584 ast_cli_register_multiple(cli_crypto, sizeof(cli_crypto) / sizeof(struct ast_cli_entry));
586 /* Install ourselves into stubs */
587 ast_key_get = __ast_key_get;
588 ast_check_signature = __ast_check_signature;
589 ast_check_signature_bin = __ast_check_signature_bin;
590 ast_sign = __ast_sign;
591 ast_sign_bin = __ast_sign_bin;
592 ast_encrypt_bin = __ast_encrypt_bin;
593 ast_decrypt_bin = __ast_decrypt_bin;
594 return 0;
597 static int reload(void)
599 crypto_load(-1, -1);
600 return 0;
603 static int load_module(void)
605 crypto_init();
606 if (ast_opt_init_keys)
607 crypto_load(STDIN_FILENO, STDOUT_FILENO);
608 else
609 crypto_load(-1, -1);
610 return AST_MODULE_LOAD_SUCCESS;
613 static int unload_module(void)
615 /* Can't unload this once we're loaded */
616 return -1;
619 /* needs usecount semantics defined */
620 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Cryptographic Digital Signatures",
621 .load = load_module,
622 .unload = unload_module,
623 .reload = reload