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>
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
34 #include <sys/types.h>
35 #include <openssl/ssl.h>
36 #include <openssl/err.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
79 AST_MUTEX_DEFINE_STATIC(keylock);
81 #define KEY_NEEDS_PASSCODE (1 << 16)
88 /* Key type (AST_KEY_PUB or AST_KEY_PRIV, along with flags from above) */
90 /* RSA structure (if successfully loaded) */
92 /* Whether we should be deleted */
94 /* FD for input (or -1 if no input allowed, or -2 if we needed input) */
99 unsigned char digest[16];
100 struct ast_key *next;
103 static struct ast_key *keys = NULL;
107 static int fdprint(int fd, char *s)
109 return write(fd, s, strlen(s) + 1);
112 static int pw_cb(char *buf, int size, int rwflag, void *userdata)
114 struct ast_key *key = (struct ast_key *)userdata;
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';
131 /* Note that we were at least called */
137 static struct ast_key *__ast_key_get(const char *kname, int ktype)
140 ast_mutex_lock(&keylock);
143 if (!strcmp(kname, key->name) &&
144 (ktype == key->ktype))
148 ast_mutex_unlock(&keylock);
152 static struct ast_key *try_load_key (char *dir, char *fname, int ifd, int ofd, int *not2)
157 unsigned char digest[16];
159 struct MD5Context md5;
161 static int notice = 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;
173 /* Get actual filename */
174 snprintf(ffname, sizeof(ffname), "%s/%s", dir, fname);
176 ast_mutex_lock(&keylock);
179 /* Look for an existing version already */
180 if (!strcasecmp(key->fn, ffname))
184 ast_mutex_unlock(&keylock);
187 f = fopen(ffname, "r");
189 ast_log(LOG_WARNING, "Unable to open key file %s: %s\n", ffname, strerror(errno));
194 /* Calculate a "whatever" quality md5sum of the key */
197 fgets(buf, sizeof(buf), f);
199 MD5Update(&md5, (unsigned char *) buf, strlen(buf));
202 MD5Final(digest, &md5);
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)) {
212 /* Preserve keytype */
214 /* Recycle the same structure */
219 /* Make fname just be the normal name now */
222 if (!(key = ast_calloc(1, sizeof(*key)))) {
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 */
231 ast_mutex_lock(&keylock);
232 /* First the filename */
233 ast_copy_string(key->fn, ffname, sizeof(key->fn));
235 ast_copy_string(key->name, fname, sizeof(key->name));
237 /* Yes, assume we're going to be deleted */
239 /* Keep the key type */
240 memcpy(key->digest, digest, 16);
241 /* Can I/O takes the FD we're given */
244 /* Reset the file back to the beginning */
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);
250 key->rsa = PEM_read_RSAPrivateKey(f, NULL, pw_cb, key);
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);
259 ast_log(LOG_DEBUG, "Key '%s' loaded OK\n", key->name);
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);
266 ERR_print_errors_fp(stderr);
268 ERR_print_errors_fp(stderr);
270 ast_log(LOG_NOTICE, "Key '%s' needs passcode.\n", key->name);
271 key->ktype |= KEY_NEEDS_PASSCODE;
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");
279 /* Print final notice about "init keys" when done */
283 ast_mutex_unlock(&keylock);
285 ast_mutex_lock(&keylock);
288 ast_mutex_unlock(&keylock);
295 static void dump(unsigned char *src, int len)
299 printf("%02x", *(src++));
303 static char *binary(int y, int len)
307 memset(res, 0, sizeof(res));
308 for (x=0;x<len;x++) {
310 res[(len - x - 1)] = '1';
312 res[(len - x - 1)] = '0';
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;
325 if (key->ktype != AST_KEY_PRIVATE) {
326 ast_log(LOG_WARNING, "Cannot sign with a public key\n");
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);
337 ast_log(LOG_WARNING, "RSA Signature (key %s) failed\n", key->name);
342 ast_log(LOG_WARNING, "Unexpected signature length %d, expecting %d\n", (int)siglen, (int)128);
350 static int __ast_decrypt_bin(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
354 if (key->ktype != AST_KEY_PRIVATE) {
355 ast_log(LOG_WARNING, "Cannot decrypt with a public key\n");
360 ast_log(LOG_NOTICE, "Tried to decrypt something not a multiple of 128 bytes\n");
364 /* Process chunks 128 bytes at a time */
365 res = RSA_private_decrypt(128, src, dst, key->rsa, RSA_PKCS1_OAEP_PADDING);
376 static int __ast_encrypt_bin(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
381 if (key->ktype != AST_KEY_PUBLIC) {
382 ast_log(LOG_WARNING, "Cannot encrypt with a private key\n");
388 if (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);
393 ast_log(LOG_NOTICE, "How odd, encrypted size is %d\n", res);
404 static int __ast_sign(struct ast_key *key, char *msg, char *sig)
406 unsigned char dsig[128];
407 int siglen = sizeof(dsig);
409 res = ast_sign_bin(key, msg, strlen(msg), dsig);
411 /* Success -- encode (256 bytes max as documented) */
412 ast_base64encode(sig, dsig, siglen, 256);
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];
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");
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);
436 ast_log(LOG_DEBUG, "Key failed verification: %s\n", key->name);
443 static int __ast_check_signature(struct ast_key *key, const char *msg, const char *sig)
445 unsigned char dsig[128];
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);
454 res = ast_check_signature_bin(key, msg, strlen(msg), dsig);
458 static void crypto_load(int ifd, int ofd)
460 struct ast_key *key, *nkey, *last;
464 /* Mark all keys for deletion */
465 ast_mutex_lock(&keylock);
471 ast_mutex_unlock(&keylock);
473 dir = opendir((char *)ast_config_AST_KEY_DIR);
475 while((ent = readdir(dir))) {
476 try_load_key((char *)ast_config_AST_KEY_DIR, ent->d_name, ifd, ofd, ¬e);
480 ast_log(LOG_WARNING, "Unable to open key directory '%s'\n", (char *)ast_config_AST_KEY_DIR);
482 ast_log(LOG_NOTICE, "Please run the command 'init keys' to enter the passcodes for the keys\n");
484 ast_mutex_lock(&keylock);
490 ast_log(LOG_DEBUG, "Deleting key %s type %d\n", key->name, key->ktype);
503 ast_mutex_unlock(&keylock);
506 static void md52sum(char *sum, unsigned char *md5)
510 sum += sprintf(sum, "%02x", *(md5++));
513 static int show_keys(int fd, int argc, char *argv[])
516 char sum[16 * 2 + 1];
519 ast_mutex_lock(&keylock);
521 ast_cli(fd, "%-18s %-8s %-16s %-33s\n", "Key Name", "Type", "Status", "Sum");
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);
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[])
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);
553 return RESULT_SUCCESS;
556 static char show_key_usage[] =
558 " Displays information about RSA keys known by Asterisk\n";
560 static char init_keys_usage[] =
562 " Initializes private keys (by reading in pass code from the user)\n";
564 static struct ast_cli_entry cli_show_keys =
565 { { "show", "keys", NULL }, show_keys, "Displays RSA key information", show_key_usage };
567 static struct ast_cli_entry cli_init_keys =
568 { { "init", "keys", NULL }, init_keys, "Initialize RSA key passcodes", init_keys_usage };
570 static int crypto_init(void)
573 ERR_load_crypto_strings();
574 ast_cli_register(&cli_show_keys);
575 ast_cli_register(&cli_init_keys);
577 /* Install ourselves into stubs */
578 ast_key_get = __ast_key_get;
579 ast_check_signature = __ast_check_signature;
580 ast_check_signature_bin = __ast_check_signature_bin;
581 ast_sign = __ast_sign;
582 ast_sign_bin = __ast_sign_bin;
583 ast_encrypt_bin = __ast_encrypt_bin;
584 ast_decrypt_bin = __ast_decrypt_bin;
588 static int reload(void)
594 static int load_module(void)
597 if (ast_opt_init_keys)
598 crypto_load(STDIN_FILENO, STDOUT_FILENO);
604 static int unload_module(void)
606 /* Can't unload this once we're loaded */
610 /* needs usecount semantics defined */
611 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Cryptographic Digital Signatures",
613 .unload = unload_module,