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.
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/
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37 #include <sys/types.h>
38 #include <openssl/ssl.h>
39 #include <openssl/err.h>
47 #include "asterisk/file.h"
48 #include "asterisk/channel.h"
49 #include "asterisk/logger.h"
50 #include "asterisk/say.h"
51 #include "asterisk/module.h"
52 #include "asterisk/options.h"
53 #include "asterisk/crypto.h"
54 #include "asterisk/md5.h"
55 #include "asterisk/cli.h"
56 #include "asterisk/io.h"
57 #include "asterisk/lock.h"
58 #include "asterisk/utils.h"
61 * Asterisk uses RSA keys with SHA-1 message digests for its
62 * digital signatures. The choice of RSA is due to its higher
63 * throughput on verification, and the choice of SHA-1 based
64 * on the recently discovered collisions in MD5's compression
65 * algorithm and recommendations of avoiding MD5 in new schemes
66 * from various industry experts.
68 * We use OpenSSL to provide our crypto routines, although we never
69 * actually use full-up SSL
74 * XXX This module is not very thread-safe. It is for everyday stuff
75 * like reading keys and stuff, but there are all kinds of weird
76 * races with people running reload and key init at the same time
82 AST_MUTEX_DEFINE_STATIC(keylock);
84 #define KEY_NEEDS_PASSCODE (1 << 16)
91 /* Key type (AST_KEY_PUB or AST_KEY_PRIV, along with flags from above) */
93 /* RSA structure (if successfully loaded) */
95 /* Whether we should be deleted */
97 /* FD for input (or -1 if no input allowed, or -2 if we needed input) */
101 /* Last MD5 Digest */
102 unsigned char digest[16];
103 struct ast_key *next;
106 static struct ast_key *keys = NULL;
110 static int fdprint(int fd, char *s)
112 return write(fd, s, strlen(s) + 1);
115 static int pw_cb(char *buf, int size, int rwflag, void *userdata)
117 struct ast_key *key = (struct ast_key *)userdata;
121 if (key->infd > -1) {
122 snprintf(prompt, sizeof(prompt), ">>>> passcode for %s key '%s': ",
123 key->ktype == AST_KEY_PRIVATE ? "PRIVATE" : "PUBLIC", key->name);
124 write(key->outfd, prompt, strlen(prompt));
125 memset(buf, 0, sizeof(buf));
126 tmp = ast_hide_password(key->infd);
127 memset(buf, 0, size);
128 res = read(key->infd, buf, size);
129 ast_restore_tty(key->infd, tmp);
130 if (buf[strlen(buf) -1] == '\n')
131 buf[strlen(buf) - 1] = '\0';
134 /* Note that we were at least called */
140 static struct ast_key *__ast_key_get(const char *kname, int ktype)
143 ast_mutex_lock(&keylock);
146 if (!strcmp(kname, key->name) &&
147 (ktype == key->ktype))
151 ast_mutex_unlock(&keylock);
155 static struct ast_key *try_load_key (char *dir, char *fname, int ifd, int ofd, int *not2)
160 unsigned char digest[16];
162 struct MD5Context md5;
164 static int notice = 0;
167 /* Make sure its name is a public or private key */
169 if ((c = strstr(fname, ".pub")) && !strcmp(c, ".pub")) {
170 ktype = AST_KEY_PUBLIC;
171 } else if ((c = strstr(fname, ".key")) && !strcmp(c, ".key")) {
172 ktype = AST_KEY_PRIVATE;
176 /* Get actual filename */
177 snprintf(ffname, sizeof(ffname), "%s/%s", dir, fname);
179 ast_mutex_lock(&keylock);
182 /* Look for an existing version already */
183 if (!strcasecmp(key->fn, ffname))
187 ast_mutex_unlock(&keylock);
190 f = fopen(ffname, "r");
192 ast_log(LOG_WARNING, "Unable to open key file %s: %s\n", ffname, strerror(errno));
197 /* Calculate a "whatever" quality md5sum of the key */
200 fgets(buf, sizeof(buf), f);
202 MD5Update(&md5, (unsigned char *) buf, strlen(buf));
205 MD5Final(digest, &md5);
207 /* If the MD5 sum is the same, and it isn't awaiting a passcode
208 then this is far enough */
209 if (!memcmp(digest, key->digest, 16) &&
210 !(key->ktype & KEY_NEEDS_PASSCODE)) {
215 /* Preserve keytype */
217 /* Recycle the same structure */
222 /* Make fname just be the normal name now */
225 if (!(key = ast_calloc(1, sizeof(*key)))) {
230 /* At this point we have a key structure (old or new). Time to
231 fill it with what we know */
232 /* Gotta lock if this one already exists */
234 ast_mutex_lock(&keylock);
235 /* First the filename */
236 ast_copy_string(key->fn, ffname, sizeof(key->fn));
238 ast_copy_string(key->name, fname, sizeof(key->name));
240 /* Yes, assume we're going to be deleted */
242 /* Keep the key type */
243 memcpy(key->digest, digest, 16);
244 /* Can I/O takes the FD we're given */
247 /* Reset the file back to the beginning */
249 /* Now load the key with the right method */
250 if (ktype == AST_KEY_PUBLIC)
251 key->rsa = PEM_read_RSA_PUBKEY(f, NULL, pw_cb, key);
253 key->rsa = PEM_read_RSAPrivateKey(f, NULL, pw_cb, key);
256 if (RSA_size(key->rsa) == 128) {
257 /* Key loaded okay */
258 key->ktype &= ~KEY_NEEDS_PASSCODE;
259 if (option_verbose > 2)
260 ast_verbose(VERBOSE_PREFIX_3 "Loaded %s key '%s'\n", key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name);
261 ast_debug(1, "Key '%s' loaded OK\n", key->name);
264 ast_log(LOG_NOTICE, "Key '%s' is not expected size.\n", key->name);
265 } else if (key->infd != -2) {
266 ast_log(LOG_WARNING, "Key load %s '%s' failed\n",key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name);
268 ERR_print_errors_fp(stderr);
270 ERR_print_errors_fp(stderr);
272 ast_log(LOG_NOTICE, "Key '%s' needs passcode.\n", key->name);
273 key->ktype |= KEY_NEEDS_PASSCODE;
275 if (!ast_opt_init_keys)
276 ast_log(LOG_NOTICE, "Add the '-i' flag to the asterisk command line if you want to automatically initialize passcodes at launch.\n");
281 /* Print final notice about "init keys" when done */
285 ast_mutex_unlock(&keylock);
287 ast_mutex_lock(&keylock);
290 ast_mutex_unlock(&keylock);
297 static void dump(unsigned char *src, int len)
301 printf("%02x", *(src++));
305 static char *binary(int y, int len)
309 memset(res, 0, sizeof(res));
310 for (x=0;x<len;x++) {
312 res[(len - x - 1)] = '1';
314 res[(len - x - 1)] = '0';
321 static int __ast_sign_bin(struct ast_key *key, const char *msg, int msglen, unsigned char *dsig)
323 unsigned char digest[20];
324 unsigned int siglen = 128;
327 if (key->ktype != AST_KEY_PRIVATE) {
328 ast_log(LOG_WARNING, "Cannot sign with a public key\n");
332 /* Calculate digest of message */
333 SHA1((unsigned char *)msg, msglen, digest);
335 /* Verify signature */
336 res = RSA_sign(NID_sha1, digest, sizeof(digest), dsig, &siglen, key->rsa);
339 ast_log(LOG_WARNING, "RSA Signature (key %s) failed\n", key->name);
344 ast_log(LOG_WARNING, "Unexpected signature length %d, expecting %d\n", (int)siglen, (int)128);
352 static int __ast_decrypt_bin(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
356 if (key->ktype != AST_KEY_PRIVATE) {
357 ast_log(LOG_WARNING, "Cannot decrypt with a public key\n");
362 ast_log(LOG_NOTICE, "Tried to decrypt something not a multiple of 128 bytes\n");
366 /* Process chunks 128 bytes at a time */
367 res = RSA_private_decrypt(128, src, dst, key->rsa, RSA_PKCS1_OAEP_PADDING);
378 static int __ast_encrypt_bin(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
383 if (key->ktype != AST_KEY_PUBLIC) {
384 ast_log(LOG_WARNING, "Cannot encrypt with a private key\n");
390 if (bytes > 128 - 41)
392 /* Process chunks 128-41 bytes at a time */
393 res = RSA_public_encrypt(bytes, src, dst, key->rsa, RSA_PKCS1_OAEP_PADDING);
395 ast_log(LOG_NOTICE, "How odd, encrypted size is %d\n", res);
406 static int __ast_sign(struct ast_key *key, char *msg, char *sig)
408 unsigned char dsig[128];
409 int siglen = sizeof(dsig);
411 res = ast_sign_bin(key, msg, strlen(msg), dsig);
413 /* Success -- encode (256 bytes max as documented) */
414 ast_base64encode(sig, dsig, siglen, 256);
419 static int __ast_check_signature_bin(struct ast_key *key, const char *msg, int msglen, const unsigned char *dsig)
421 unsigned char digest[20];
424 if (key->ktype != AST_KEY_PUBLIC) {
425 /* Okay, so of course you really *can* but for our purposes
426 we're going to say you can't */
427 ast_log(LOG_WARNING, "Cannot check message signature with a private key\n");
431 /* Calculate digest of message */
432 SHA1((unsigned char *)msg, msglen, digest);
434 /* Verify signature */
435 res = RSA_verify(NID_sha1, digest, sizeof(digest), (unsigned char *)dsig, 128, key->rsa);
438 ast_debug(1, "Key failed verification: %s\n", key->name);
445 static int __ast_check_signature(struct ast_key *key, const char *msg, const char *sig)
447 unsigned char dsig[128];
450 /* Decode signature */
451 res = ast_base64decode(dsig, sig, sizeof(dsig));
452 if (res != sizeof(dsig)) {
453 ast_log(LOG_WARNING, "Signature improper length (expect %d, got %d)\n", (int)sizeof(dsig), (int)res);
456 res = ast_check_signature_bin(key, msg, strlen(msg), dsig);
460 static void crypto_load(int ifd, int ofd)
462 struct ast_key *key, *nkey, *last;
466 /* Mark all keys for deletion */
467 ast_mutex_lock(&keylock);
473 ast_mutex_unlock(&keylock);
475 dir = opendir((char *)ast_config_AST_KEY_DIR);
477 while((ent = readdir(dir))) {
478 try_load_key((char *)ast_config_AST_KEY_DIR, ent->d_name, ifd, ofd, ¬e);
482 ast_log(LOG_WARNING, "Unable to open key directory '%s'\n", (char *)ast_config_AST_KEY_DIR);
484 ast_log(LOG_NOTICE, "Please run the command 'init keys' to enter the passcodes for the keys\n");
486 ast_mutex_lock(&keylock);
492 ast_debug(1, "Deleting key %s type %d\n", key->name, key->ktype);
505 ast_mutex_unlock(&keylock);
508 static void md52sum(char *sum, unsigned char *md5)
512 sum += sprintf(sum, "%02x", *(md5++));
515 static int show_keys(int fd, int argc, char *argv[])
518 char sum[16 * 2 + 1];
521 ast_mutex_lock(&keylock);
523 ast_cli(fd, "%-18s %-8s %-16s %-33s\n", "Key Name", "Type", "Status", "Sum");
525 md52sum(sum, key->digest);
526 ast_cli(fd, "%-18s %-8s %-16s %-33s\n", key->name,
527 (key->ktype & 0xf) == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE",
528 key->ktype & KEY_NEEDS_PASSCODE ? "[Needs Passcode]" : "[Loaded]", sum);
533 ast_mutex_unlock(&keylock);
534 ast_cli(fd, "%d known RSA keys.\n", count_keys);
535 return RESULT_SUCCESS;
538 static int init_keys(int fd, int argc, char *argv[])
547 /* Reload keys that need pass codes now */
548 if (key->ktype & KEY_NEEDS_PASSCODE) {
549 kn = key->fn + strlen(ast_config_AST_KEY_DIR) + 1;
550 ast_copy_string(tmp, kn, sizeof(tmp));
551 try_load_key((char *)ast_config_AST_KEY_DIR, tmp, fd, fd, &ign);
555 return RESULT_SUCCESS;
558 static const char show_key_usage[] =
560 " Displays information about RSA keys known by Asterisk\n";
562 static const char init_keys_usage[] =
564 " Initializes private keys (by reading in pass code from the user)\n";
566 static struct ast_cli_entry cli_crypto[] = {
567 { { "keys", "show", NULL },
568 show_keys, "Displays RSA key information",
571 { { "keys", "init", NULL },
572 init_keys, "Initialize RSA key passcodes",
576 static int crypto_init(void)
579 ERR_load_crypto_strings();
580 ast_cli_register_multiple(cli_crypto, sizeof(cli_crypto) / sizeof(struct ast_cli_entry));
582 /* Install ourselves into stubs */
583 ast_key_get = __ast_key_get;
584 ast_check_signature = __ast_check_signature;
585 ast_check_signature_bin = __ast_check_signature_bin;
586 ast_sign = __ast_sign;
587 ast_sign_bin = __ast_sign_bin;
588 ast_encrypt_bin = __ast_encrypt_bin;
589 ast_decrypt_bin = __ast_decrypt_bin;
593 static int reload(void)
599 static int load_module(void)
602 if (ast_opt_init_keys)
603 crypto_load(STDIN_FILENO, STDOUT_FILENO);
609 static int unload_module(void)
611 /* Can't unload this once we're loaded */
615 /* needs usecount semantics defined */
616 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Cryptographic Digital Signatures",
618 .unload = unload_module,