2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2005, 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>
26 #include <sys/types.h>
27 #include <openssl/ssl.h>
28 #include <openssl/err.h>
38 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
40 #include "asterisk/file.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/logger.h"
43 #include "asterisk/say.h"
44 #include "asterisk/module.h"
45 #include "asterisk/options.h"
46 #include "asterisk/crypto.h"
47 #include "asterisk/md5.h"
48 #include "asterisk/cli.h"
49 #include "asterisk/io.h"
50 #include "asterisk/lock.h"
51 #include "asterisk/utils.h"
54 * Asterisk uses RSA keys with SHA-1 message digests for its
55 * digital signatures. The choice of RSA is due to its higher
56 * throughput on verification, and the choice of SHA-1 based
57 * on the recently discovered collisions in MD5's compression
58 * algorithm and recommendations of avoiding MD5 in new schemes
59 * from various industry experts.
61 * We use OpenSSL to provide our crypto routines, although we never
62 * actually use full-up SSL
67 * XXX This module is not very thread-safe. It is for everyday stuff
68 * like reading keys and stuff, but there are all kinds of weird
69 * races with people running reload and key init at the same time
75 AST_MUTEX_DEFINE_STATIC(keylock);
77 #define KEY_NEEDS_PASSCODE (1 << 16)
84 /* Key type (AST_KEY_PUB or AST_KEY_PRIV, along with flags from above) */
86 /* RSA structure (if successfully loaded) */
88 /* Whether we should be deleted */
90 /* FD for input (or -1 if no input allowed, or -2 if we needed input) */
95 unsigned char digest[16];
99 static struct ast_key *keys = NULL;
103 static int fdprint(int fd, char *s)
105 return write(fd, s, strlen(s) + 1);
108 static int pw_cb(char *buf, int size, int rwflag, void *userdata)
110 struct ast_key *key = (struct ast_key *)userdata;
114 if (key->infd > -1) {
115 snprintf(prompt, sizeof(prompt), ">>>> passcode for %s key '%s': ",
116 key->ktype == AST_KEY_PRIVATE ? "PRIVATE" : "PUBLIC", key->name);
117 write(key->outfd, prompt, strlen(prompt));
118 memset(buf, 0, sizeof(buf));
119 tmp = ast_hide_password(key->infd);
120 memset(buf, 0, size);
121 res = read(key->infd, buf, size);
122 ast_restore_tty(key->infd, tmp);
123 if (buf[strlen(buf) -1] == '\n')
124 buf[strlen(buf) - 1] = '\0';
127 /* Note that we were at least called */
133 static struct ast_key *__ast_key_get(const char *kname, int ktype)
136 ast_mutex_lock(&keylock);
139 if (!strcmp(kname, key->name) &&
140 (ktype == key->ktype))
144 ast_mutex_unlock(&keylock);
148 static struct ast_key *try_load_key (char *dir, char *fname, int ifd, int ofd, int *not2)
153 unsigned char digest[16];
155 struct MD5Context md5;
157 static int notice = 0;
160 /* Make sure its name is a public or private key */
162 if ((c = strstr(fname, ".pub")) && !strcmp(c, ".pub")) {
163 ktype = AST_KEY_PUBLIC;
164 } else if ((c = strstr(fname, ".key")) && !strcmp(c, ".key")) {
165 ktype = AST_KEY_PRIVATE;
169 /* Get actual filename */
170 snprintf(ffname, sizeof(ffname), "%s/%s", dir, fname);
172 ast_mutex_lock(&keylock);
175 /* Look for an existing version already */
176 if (!strcasecmp(key->fn, ffname))
180 ast_mutex_unlock(&keylock);
183 f = fopen(ffname, "r");
185 ast_log(LOG_WARNING, "Unable to open key file %s: %s\n", ffname, strerror(errno));
190 /* Calculate a "whatever" quality md5sum of the key */
193 fgets(buf, sizeof(buf), f);
195 MD5Update(&md5, (unsigned char *) buf, strlen(buf));
198 MD5Final(digest, &md5);
200 /* If the MD5 sum is the same, and it isn't awaiting a passcode
201 then this is far enough */
202 if (!memcmp(digest, key->digest, 16) &&
203 !(key->ktype & KEY_NEEDS_PASSCODE)) {
208 /* Preserve keytype */
210 /* Recycle the same structure */
215 /* Make fname just be the normal name now */
218 if (!(key = ast_calloc(1, sizeof(*key)))) {
223 /* At this point we have a key structure (old or new). Time to
224 fill it with what we know */
225 /* Gotta lock if this one already exists */
227 ast_mutex_lock(&keylock);
228 /* First the filename */
229 ast_copy_string(key->fn, ffname, sizeof(key->fn));
231 ast_copy_string(key->name, fname, sizeof(key->name));
233 /* Yes, assume we're going to be deleted */
235 /* Keep the key type */
236 memcpy(key->digest, digest, 16);
237 /* Can I/O takes the FD we're given */
240 /* Reset the file back to the beginning */
242 /* Now load the key with the right method */
243 if (ktype == AST_KEY_PUBLIC)
244 key->rsa = PEM_read_RSA_PUBKEY(f, NULL, pw_cb, key);
246 key->rsa = PEM_read_RSAPrivateKey(f, NULL, pw_cb, key);
249 if (RSA_size(key->rsa) == 128) {
250 /* Key loaded okay */
251 key->ktype &= ~KEY_NEEDS_PASSCODE;
252 if (option_verbose > 2)
253 ast_verbose(VERBOSE_PREFIX_3 "Loaded %s key '%s'\n", key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name);
255 ast_log(LOG_DEBUG, "Key '%s' loaded OK\n", key->name);
258 ast_log(LOG_NOTICE, "Key '%s' is not expected size.\n", key->name);
259 } else if (key->infd != -2) {
260 ast_log(LOG_WARNING, "Key load %s '%s' failed\n",key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name);
262 ERR_print_errors_fp(stderr);
264 ERR_print_errors_fp(stderr);
266 ast_log(LOG_NOTICE, "Key '%s' needs passcode.\n", key->name);
267 key->ktype |= KEY_NEEDS_PASSCODE;
269 if (!ast_opt_init_keys)
270 ast_log(LOG_NOTICE, "Add the '-i' flag to the asterisk command line if you want to automatically initialize passcodes at launch.\n");
275 /* Print final notice about "init keys" when done */
279 ast_mutex_unlock(&keylock);
281 ast_mutex_lock(&keylock);
284 ast_mutex_unlock(&keylock);
291 static void dump(unsigned char *src, int len)
295 printf("%02x", *(src++));
299 static char *binary(int y, int len)
303 memset(res, 0, sizeof(res));
304 for (x=0;x<len;x++) {
306 res[(len - x - 1)] = '1';
308 res[(len - x - 1)] = '0';
315 static int __ast_sign_bin(struct ast_key *key, const char *msg, int msglen, unsigned char *dsig)
317 unsigned char digest[20];
318 unsigned int siglen = 128;
321 if (key->ktype != AST_KEY_PRIVATE) {
322 ast_log(LOG_WARNING, "Cannot sign with a public key\n");
326 /* Calculate digest of message */
327 SHA1((unsigned char *)msg, msglen, digest);
329 /* Verify signature */
330 res = RSA_sign(NID_sha1, digest, sizeof(digest), dsig, &siglen, key->rsa);
333 ast_log(LOG_WARNING, "RSA Signature (key %s) failed\n", key->name);
338 ast_log(LOG_WARNING, "Unexpected signature length %d, expecting %d\n", (int)siglen, (int)128);
346 static int __ast_decrypt_bin(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
350 if (key->ktype != AST_KEY_PRIVATE) {
351 ast_log(LOG_WARNING, "Cannot decrypt with a public key\n");
356 ast_log(LOG_NOTICE, "Tried to decrypt something not a multiple of 128 bytes\n");
360 /* Process chunks 128 bytes at a time */
361 res = RSA_private_decrypt(128, src, dst, key->rsa, RSA_PKCS1_OAEP_PADDING);
372 static int __ast_encrypt_bin(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
377 if (key->ktype != AST_KEY_PUBLIC) {
378 ast_log(LOG_WARNING, "Cannot encrypt with a private key\n");
384 if (bytes > 128 - 41)
386 /* Process chunks 128-41 bytes at a time */
387 res = RSA_public_encrypt(bytes, src, dst, key->rsa, RSA_PKCS1_OAEP_PADDING);
389 ast_log(LOG_NOTICE, "How odd, encrypted size is %d\n", res);
400 static int __ast_sign(struct ast_key *key, char *msg, char *sig)
402 unsigned char dsig[128];
403 int siglen = sizeof(dsig);
405 res = ast_sign_bin(key, msg, strlen(msg), dsig);
407 /* Success -- encode (256 bytes max as documented) */
408 ast_base64encode(sig, dsig, siglen, 256);
413 static int __ast_check_signature_bin(struct ast_key *key, const char *msg, int msglen, const unsigned char *dsig)
415 unsigned char digest[20];
418 if (key->ktype != AST_KEY_PUBLIC) {
419 /* Okay, so of course you really *can* but for our purposes
420 we're going to say you can't */
421 ast_log(LOG_WARNING, "Cannot check message signature with a private key\n");
425 /* Calculate digest of message */
426 SHA1((unsigned char *)msg, msglen, digest);
428 /* Verify signature */
429 res = RSA_verify(NID_sha1, digest, sizeof(digest), (unsigned char *)dsig, 128, key->rsa);
432 ast_log(LOG_DEBUG, "Key failed verification: %s\n", key->name);
439 static int __ast_check_signature(struct ast_key *key, const char *msg, const char *sig)
441 unsigned char dsig[128];
444 /* Decode signature */
445 res = ast_base64decode(dsig, sig, sizeof(dsig));
446 if (res != sizeof(dsig)) {
447 ast_log(LOG_WARNING, "Signature improper length (expect %d, got %d)\n", (int)sizeof(dsig), (int)res);
450 res = ast_check_signature_bin(key, msg, strlen(msg), dsig);
454 static void crypto_load(int ifd, int ofd)
456 struct ast_key *key, *nkey, *last;
460 /* Mark all keys for deletion */
461 ast_mutex_lock(&keylock);
467 ast_mutex_unlock(&keylock);
469 dir = opendir((char *)ast_config_AST_KEY_DIR);
471 while((ent = readdir(dir))) {
472 try_load_key((char *)ast_config_AST_KEY_DIR, ent->d_name, ifd, ofd, ¬e);
476 ast_log(LOG_WARNING, "Unable to open key directory '%s'\n", (char *)ast_config_AST_KEY_DIR);
478 ast_log(LOG_NOTICE, "Please run the command 'init keys' to enter the passcodes for the keys\n");
480 ast_mutex_lock(&keylock);
486 ast_log(LOG_DEBUG, "Deleting key %s type %d\n", key->name, key->ktype);
499 ast_mutex_unlock(&keylock);
502 static void md52sum(char *sum, unsigned char *md5)
506 sum += sprintf(sum, "%02x", *(md5++));
509 static int show_keys(int fd, int argc, char *argv[])
512 char sum[16 * 2 + 1];
515 ast_mutex_lock(&keylock);
517 ast_cli(fd, "%-18s %-8s %-16s %-33s\n", "Key Name", "Type", "Status", "Sum");
519 md52sum(sum, key->digest);
520 ast_cli(fd, "%-18s %-8s %-16s %-33s\n", key->name,
521 (key->ktype & 0xf) == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE",
522 key->ktype & KEY_NEEDS_PASSCODE ? "[Needs Passcode]" : "[Loaded]", sum);
527 ast_mutex_unlock(&keylock);
528 ast_cli(fd, "%d known RSA keys.\n", count_keys);
529 return RESULT_SUCCESS;
532 static int init_keys(int fd, int argc, char *argv[])
541 /* Reload keys that need pass codes now */
542 if (key->ktype & KEY_NEEDS_PASSCODE) {
543 kn = key->fn + strlen(ast_config_AST_KEY_DIR) + 1;
544 ast_copy_string(tmp, kn, sizeof(tmp));
545 try_load_key((char *)ast_config_AST_KEY_DIR, tmp, fd, fd, &ign);
549 return RESULT_SUCCESS;
552 static char show_key_usage[] =
554 " Displays information about RSA keys known by Asterisk\n";
556 static char init_keys_usage[] =
558 " Initializes private keys (by reading in pass code from the user)\n";
560 static struct ast_cli_entry cli_show_keys =
561 { { "show", "keys", NULL }, show_keys, "Displays RSA key information", show_key_usage };
563 static struct ast_cli_entry cli_init_keys =
564 { { "init", "keys", NULL }, init_keys, "Initialize RSA key passcodes", init_keys_usage };
566 static int crypto_init(void)
569 ERR_load_crypto_strings();
570 ast_cli_register(&cli_show_keys);
571 ast_cli_register(&cli_init_keys);
573 /* Install ourselves into stubs */
574 ast_key_get = __ast_key_get;
575 ast_check_signature = __ast_check_signature;
576 ast_check_signature_bin = __ast_check_signature_bin;
577 ast_sign = __ast_sign;
578 ast_sign_bin = __ast_sign_bin;
579 ast_encrypt_bin = __ast_encrypt_bin;
580 ast_decrypt_bin = __ast_decrypt_bin;
590 int load_module(void)
593 if (ast_opt_init_keys)
594 crypto_load(STDIN_FILENO, STDOUT_FILENO);
600 int unload_module(void)
602 /* Can't unload this once we're loaded */
606 const char *description(void)
608 return "Cryptographic Digital Signatures";
613 /* We should never be unloaded */
619 return ASTERISK_GPL_KEY;