Merge changes from team/russell/issue_9520
[asterisk-bristuff.git] / res / res_crypto.c
blobeea8356afec8007756851d0d6e79e1a5e786db48
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>
26 /*** MODULEINFO
27 <depend>ssl</depend>
28 ***/
30 #include "asterisk.h"
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
34 #include <sys/types.h>
35 #include <openssl/ssl.h>
36 #include <openssl/err.h>
37 #include <stdio.h>
38 #include <dirent.h>
39 #include <string.h>
40 #include <errno.h>
41 #include <unistd.h>
42 #include <fcntl.h>
44 #include "asterisk/file.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/logger.h"
47 #include "asterisk/say.h"
48 #include "asterisk/module.h"
49 #include "asterisk/options.h"
50 #include "asterisk/crypto.h"
51 #include "asterisk/md5.h"
52 #include "asterisk/cli.h"
53 #include "asterisk/io.h"
54 #include "asterisk/lock.h"
55 #include "asterisk/utils.h"
58 * Asterisk uses RSA keys with SHA-1 message digests for its
59 * digital signatures. The choice of RSA is due to its higher
60 * throughput on verification, and the choice of SHA-1 based
61 * on the recently discovered collisions in MD5's compression
62 * algorithm and recommendations of avoiding MD5 in new schemes
63 * from various industry experts.
65 * We use OpenSSL to provide our crypto routines, although we never
66 * actually use full-up SSL
71 * XXX This module is not very thread-safe. It is for everyday stuff
72 * like reading keys and stuff, but there are all kinds of weird
73 * races with people running reload and key init at the same time
74 * for example
76 * XXXX
79 AST_MUTEX_DEFINE_STATIC(keylock);
81 #define KEY_NEEDS_PASSCODE (1 << 16)
83 struct ast_key {
84 /* Name of entity */
85 char name[80];
86 /* File name */
87 char fn[256];
88 /* Key type (AST_KEY_PUB or AST_KEY_PRIV, along with flags from above) */
89 int ktype;
90 /* RSA structure (if successfully loaded) */
91 RSA *rsa;
92 /* Whether we should be deleted */
93 int delme;
94 /* FD for input (or -1 if no input allowed, or -2 if we needed input) */
95 int infd;
96 /* FD for output */
97 int outfd;
98 /* Last MD5 Digest */
99 unsigned char digest[16];
100 struct ast_key *next;
103 static struct ast_key *keys = NULL;
106 #if 0
107 static int fdprint(int fd, char *s)
109 return write(fd, s, strlen(s) + 1);
111 #endif
112 static int pw_cb(char *buf, int size, int rwflag, void *userdata)
114 struct ast_key *key = (struct ast_key *)userdata;
115 char prompt[256];
116 int res;
117 int tmp;
118 if (key->infd > -1) {
119 snprintf(prompt, sizeof(prompt), ">>>> passcode for %s key '%s': ",
120 key->ktype == AST_KEY_PRIVATE ? "PRIVATE" : "PUBLIC", key->name);
121 write(key->outfd, prompt, strlen(prompt));
122 memset(buf, 0, sizeof(buf));
123 tmp = ast_hide_password(key->infd);
124 memset(buf, 0, size);
125 res = read(key->infd, buf, size);
126 ast_restore_tty(key->infd, tmp);
127 if (buf[strlen(buf) -1] == '\n')
128 buf[strlen(buf) - 1] = '\0';
129 return strlen(buf);
130 } else {
131 /* Note that we were at least called */
132 key->infd = -2;
134 return -1;
137 static struct ast_key *__ast_key_get(const char *kname, int ktype)
139 struct ast_key *key;
140 ast_mutex_lock(&keylock);
141 key = keys;
142 while(key) {
143 if (!strcmp(kname, key->name) &&
144 (ktype == key->ktype))
145 break;
146 key = key->next;
148 ast_mutex_unlock(&keylock);
149 return key;
152 static struct ast_key *try_load_key (char *dir, char *fname, int ifd, int ofd, int *not2)
154 int ktype = 0;
155 char *c = NULL;
156 char ffname[256];
157 unsigned char digest[16];
158 FILE *f;
159 struct MD5Context md5;
160 struct ast_key *key;
161 static int notice = 0;
162 int found = 0;
164 /* Make sure its name is a public or private key */
166 if ((c = strstr(fname, ".pub")) && !strcmp(c, ".pub")) {
167 ktype = AST_KEY_PUBLIC;
168 } else if ((c = strstr(fname, ".key")) && !strcmp(c, ".key")) {
169 ktype = AST_KEY_PRIVATE;
170 } else
171 return NULL;
173 /* Get actual filename */
174 snprintf(ffname, sizeof(ffname), "%s/%s", dir, fname);
176 ast_mutex_lock(&keylock);
177 key = keys;
178 while(key) {
179 /* Look for an existing version already */
180 if (!strcasecmp(key->fn, ffname))
181 break;
182 key = key->next;
184 ast_mutex_unlock(&keylock);
186 /* Open file */
187 f = fopen(ffname, "r");
188 if (!f) {
189 ast_log(LOG_WARNING, "Unable to open key file %s: %s\n", ffname, strerror(errno));
190 return NULL;
192 MD5Init(&md5);
193 while(!feof(f)) {
194 /* Calculate a "whatever" quality md5sum of the key */
195 char buf[256];
196 memset(buf, 0, 256);
197 fgets(buf, sizeof(buf), f);
198 if (!feof(f)) {
199 MD5Update(&md5, (unsigned char *) buf, strlen(buf));
202 MD5Final(digest, &md5);
203 if (key) {
204 /* If the MD5 sum is the same, and it isn't awaiting a passcode
205 then this is far enough */
206 if (!memcmp(digest, key->digest, 16) &&
207 !(key->ktype & KEY_NEEDS_PASSCODE)) {
208 fclose(f);
209 key->delme = 0;
210 return NULL;
211 } else {
212 /* Preserve keytype */
213 ktype = key->ktype;
214 /* Recycle the same structure */
215 found++;
219 /* Make fname just be the normal name now */
220 *c = '\0';
221 if (!key) {
222 if (!(key = ast_calloc(1, sizeof(*key)))) {
223 fclose(f);
224 return NULL;
227 /* At this point we have a key structure (old or new). Time to
228 fill it with what we know */
229 /* Gotta lock if this one already exists */
230 if (found)
231 ast_mutex_lock(&keylock);
232 /* First the filename */
233 ast_copy_string(key->fn, ffname, sizeof(key->fn));
234 /* Then the name */
235 ast_copy_string(key->name, fname, sizeof(key->name));
236 key->ktype = ktype;
237 /* Yes, assume we're going to be deleted */
238 key->delme = 1;
239 /* Keep the key type */
240 memcpy(key->digest, digest, 16);
241 /* Can I/O takes the FD we're given */
242 key->infd = ifd;
243 key->outfd = ofd;
244 /* Reset the file back to the beginning */
245 rewind(f);
246 /* Now load the key with the right method */
247 if (ktype == AST_KEY_PUBLIC)
248 key->rsa = PEM_read_RSA_PUBKEY(f, NULL, pw_cb, key);
249 else
250 key->rsa = PEM_read_RSAPrivateKey(f, NULL, pw_cb, key);
251 fclose(f);
252 if (key->rsa) {
253 if (RSA_size(key->rsa) == 128) {
254 /* Key loaded okay */
255 key->ktype &= ~KEY_NEEDS_PASSCODE;
256 if (option_verbose > 2)
257 ast_verbose(VERBOSE_PREFIX_3 "Loaded %s key '%s'\n", key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name);
258 if (option_debug)
259 ast_log(LOG_DEBUG, "Key '%s' loaded OK\n", key->name);
260 key->delme = 0;
261 } else
262 ast_log(LOG_NOTICE, "Key '%s' is not expected size.\n", key->name);
263 } else if (key->infd != -2) {
264 ast_log(LOG_WARNING, "Key load %s '%s' failed\n",key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name);
265 if (ofd > -1) {
266 ERR_print_errors_fp(stderr);
267 } else
268 ERR_print_errors_fp(stderr);
269 } else {
270 ast_log(LOG_NOTICE, "Key '%s' needs passcode.\n", key->name);
271 key->ktype |= KEY_NEEDS_PASSCODE;
272 if (!notice) {
273 if (!ast_opt_init_keys)
274 ast_log(LOG_NOTICE, "Add the '-i' flag to the asterisk command line if you want to automatically initialize passcodes at launch.\n");
275 notice++;
277 /* Keep it anyway */
278 key->delme = 0;
279 /* Print final notice about "init keys" when done */
280 *not2 = 1;
282 if (found)
283 ast_mutex_unlock(&keylock);
284 if (!found) {
285 ast_mutex_lock(&keylock);
286 key->next = keys;
287 keys = key;
288 ast_mutex_unlock(&keylock);
290 return key;
293 #if 0
295 static void dump(unsigned char *src, int len)
297 int x;
298 for (x=0;x<len;x++)
299 printf("%02x", *(src++));
300 printf("\n");
303 static char *binary(int y, int len)
305 static char res[80];
306 int x;
307 memset(res, 0, sizeof(res));
308 for (x=0;x<len;x++) {
309 if (y & (1 << x))
310 res[(len - x - 1)] = '1';
311 else
312 res[(len - x - 1)] = '0';
314 return res;
317 #endif
319 static int __ast_sign_bin(struct ast_key *key, const char *msg, int msglen, unsigned char *dsig)
321 unsigned char digest[20];
322 unsigned int siglen = 128;
323 int res;
325 if (key->ktype != AST_KEY_PRIVATE) {
326 ast_log(LOG_WARNING, "Cannot sign with a public key\n");
327 return -1;
330 /* Calculate digest of message */
331 SHA1((unsigned char *)msg, msglen, digest);
333 /* Verify signature */
334 res = RSA_sign(NID_sha1, digest, sizeof(digest), dsig, &siglen, key->rsa);
336 if (!res) {
337 ast_log(LOG_WARNING, "RSA Signature (key %s) failed\n", key->name);
338 return -1;
341 if (siglen != 128) {
342 ast_log(LOG_WARNING, "Unexpected signature length %d, expecting %d\n", (int)siglen, (int)128);
343 return -1;
346 return 0;
350 static int __ast_decrypt_bin(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
352 int res;
353 int pos = 0;
354 if (key->ktype != AST_KEY_PRIVATE) {
355 ast_log(LOG_WARNING, "Cannot decrypt with a public key\n");
356 return -1;
359 if (srclen % 128) {
360 ast_log(LOG_NOTICE, "Tried to decrypt something not a multiple of 128 bytes\n");
361 return -1;
363 while(srclen) {
364 /* Process chunks 128 bytes at a time */
365 res = RSA_private_decrypt(128, src, dst, key->rsa, RSA_PKCS1_OAEP_PADDING);
366 if (res < 0)
367 return -1;
368 pos += res;
369 src += 128;
370 srclen -= 128;
371 dst += res;
373 return pos;
376 static int __ast_encrypt_bin(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
378 int res;
379 int bytes;
380 int pos = 0;
381 if (key->ktype != AST_KEY_PUBLIC) {
382 ast_log(LOG_WARNING, "Cannot encrypt with a private key\n");
383 return -1;
386 while(srclen) {
387 bytes = srclen;
388 if (bytes > 128 - 41)
389 bytes = 128 - 41;
390 /* Process chunks 128-41 bytes at a time */
391 res = RSA_public_encrypt(bytes, src, dst, key->rsa, RSA_PKCS1_OAEP_PADDING);
392 if (res != 128) {
393 ast_log(LOG_NOTICE, "How odd, encrypted size is %d\n", res);
394 return -1;
396 src += bytes;
397 srclen -= bytes;
398 pos += res;
399 dst += res;
401 return pos;
404 static int __ast_sign(struct ast_key *key, char *msg, char *sig)
406 unsigned char dsig[128];
407 int siglen = sizeof(dsig);
408 int res;
409 res = ast_sign_bin(key, msg, strlen(msg), dsig);
410 if (!res)
411 /* Success -- encode (256 bytes max as documented) */
412 ast_base64encode(sig, dsig, siglen, 256);
413 return res;
417 static int __ast_check_signature_bin(struct ast_key *key, const char *msg, int msglen, const unsigned char *dsig)
419 unsigned char digest[20];
420 int res;
422 if (key->ktype != AST_KEY_PUBLIC) {
423 /* Okay, so of course you really *can* but for our purposes
424 we're going to say you can't */
425 ast_log(LOG_WARNING, "Cannot check message signature with a private key\n");
426 return -1;
429 /* Calculate digest of message */
430 SHA1((unsigned char *)msg, msglen, digest);
432 /* Verify signature */
433 res = RSA_verify(NID_sha1, digest, sizeof(digest), (unsigned char *)dsig, 128, key->rsa);
435 if (!res) {
436 ast_log(LOG_DEBUG, "Key failed verification: %s\n", key->name);
437 return -1;
439 /* Pass */
440 return 0;
443 static int __ast_check_signature(struct ast_key *key, const char *msg, const char *sig)
445 unsigned char dsig[128];
446 int res;
448 /* Decode signature */
449 res = ast_base64decode(dsig, sig, sizeof(dsig));
450 if (res != sizeof(dsig)) {
451 ast_log(LOG_WARNING, "Signature improper length (expect %d, got %d)\n", (int)sizeof(dsig), (int)res);
452 return -1;
454 res = ast_check_signature_bin(key, msg, strlen(msg), dsig);
455 return res;
458 static void crypto_load(int ifd, int ofd)
460 struct ast_key *key, *nkey, *last;
461 DIR *dir = NULL;
462 struct dirent *ent;
463 int note = 0;
464 /* Mark all keys for deletion */
465 ast_mutex_lock(&keylock);
466 key = keys;
467 while(key) {
468 key->delme = 1;
469 key = key->next;
471 ast_mutex_unlock(&keylock);
472 /* Load new keys */
473 dir = opendir((char *)ast_config_AST_KEY_DIR);
474 if (dir) {
475 while((ent = readdir(dir))) {
476 try_load_key((char *)ast_config_AST_KEY_DIR, ent->d_name, ifd, ofd, &note);
478 closedir(dir);
479 } else
480 ast_log(LOG_WARNING, "Unable to open key directory '%s'\n", (char *)ast_config_AST_KEY_DIR);
481 if (note) {
482 ast_log(LOG_NOTICE, "Please run the command 'init keys' to enter the passcodes for the keys\n");
484 ast_mutex_lock(&keylock);
485 key = keys;
486 last = NULL;
487 while(key) {
488 nkey = key->next;
489 if (key->delme) {
490 ast_log(LOG_DEBUG, "Deleting key %s type %d\n", key->name, key->ktype);
491 /* Do the delete */
492 if (last)
493 last->next = nkey;
494 else
495 keys = nkey;
496 if (key->rsa)
497 RSA_free(key->rsa);
498 free(key);
499 } else
500 last = key;
501 key = nkey;
503 ast_mutex_unlock(&keylock);
506 static void md52sum(char *sum, unsigned char *md5)
508 int x;
509 for (x=0;x<16;x++)
510 sum += sprintf(sum, "%02x", *(md5++));
513 static int show_keys(int fd, int argc, char *argv[])
515 struct ast_key *key;
516 char sum[16 * 2 + 1];
517 int count_keys = 0;
519 ast_mutex_lock(&keylock);
520 key = keys;
521 ast_cli(fd, "%-18s %-8s %-16s %-33s\n", "Key Name", "Type", "Status", "Sum");
522 while(key) {
523 md52sum(sum, key->digest);
524 ast_cli(fd, "%-18s %-8s %-16s %-33s\n", key->name,
525 (key->ktype & 0xf) == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE",
526 key->ktype & KEY_NEEDS_PASSCODE ? "[Needs Passcode]" : "[Loaded]", sum);
528 key = key->next;
529 count_keys++;
531 ast_mutex_unlock(&keylock);
532 ast_cli(fd, "%d known RSA keys.\n", count_keys);
533 return RESULT_SUCCESS;
536 static int init_keys(int fd, int argc, char *argv[])
538 struct ast_key *key;
539 int ign;
540 char *kn;
541 char tmp[256] = "";
543 key = keys;
544 while(key) {
545 /* Reload keys that need pass codes now */
546 if (key->ktype & KEY_NEEDS_PASSCODE) {
547 kn = key->fn + strlen(ast_config_AST_KEY_DIR) + 1;
548 ast_copy_string(tmp, kn, sizeof(tmp));
549 try_load_key((char *)ast_config_AST_KEY_DIR, tmp, fd, fd, &ign);
551 key = key->next;
553 return RESULT_SUCCESS;
556 static char show_key_usage[] =
557 "Usage: keys show\n"
558 " Displays information about RSA keys known by Asterisk\n";
560 static char init_keys_usage[] =
561 "Usage: keys init\n"
562 " Initializes private keys (by reading in pass code from the user)\n";
564 static struct ast_cli_entry cli_show_keys_deprecated = {
565 { "show", "keys", NULL },
566 show_keys, NULL,
567 NULL };
569 static struct ast_cli_entry cli_init_keys_deprecated = {
570 { "init", "keys", NULL },
571 init_keys, NULL,
572 NULL };
574 static struct ast_cli_entry cli_crypto[] = {
575 { { "keys", "show", NULL },
576 show_keys, "Displays RSA key information",
577 show_key_usage, NULL, &cli_show_keys_deprecated },
579 { { "keys", "init", NULL },
580 init_keys, "Initialize RSA key passcodes",
581 init_keys_usage, NULL, &cli_init_keys_deprecated },
584 static int crypto_init(void)
586 SSL_library_init();
587 ERR_load_crypto_strings();
588 ast_cli_register_multiple(cli_crypto, sizeof(cli_crypto) / sizeof(struct ast_cli_entry));
590 /* Install ourselves into stubs */
591 ast_key_get = __ast_key_get;
592 ast_check_signature = __ast_check_signature;
593 ast_check_signature_bin = __ast_check_signature_bin;
594 ast_sign = __ast_sign;
595 ast_sign_bin = __ast_sign_bin;
596 ast_encrypt_bin = __ast_encrypt_bin;
597 ast_decrypt_bin = __ast_decrypt_bin;
598 return 0;
601 static int reload(void)
603 crypto_load(-1, -1);
604 return 0;
607 static int load_module(void)
609 crypto_init();
610 if (ast_opt_init_keys)
611 crypto_load(STDIN_FILENO, STDOUT_FILENO);
612 else
613 crypto_load(-1, -1);
614 return 0;
617 static int unload_module(void)
619 /* Can't unload this once we're loaded */
620 return -1;
623 /* needs usecount semantics defined */
624 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Cryptographic Digital Signatures",
625 .load = load_module,
626 .unload = unload_module,
627 .reload = reload