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);
118 * \brief setting of priv key
123 * \return length of string,-1 on failure
125 static int pw_cb(char *buf, int size, int rwflag, void *userdata)
127 struct ast_key *key = (struct ast_key *)userdata;
131 if (key->infd > -1) {
132 snprintf(prompt, sizeof(prompt), ">>>> passcode for %s key '%s': ",
133 key->ktype == AST_KEY_PRIVATE ? "PRIVATE" : "PUBLIC", key->name);
134 write(key->outfd, prompt, strlen(prompt));
135 memset(buf, 0, sizeof(buf));
136 tmp = ast_hide_password(key->infd);
137 memset(buf, 0, size);
138 res = read(key->infd, buf, size);
139 ast_restore_tty(key->infd, tmp);
140 if (buf[strlen(buf) -1] == '\n')
141 buf[strlen(buf) - 1] = '\0';
144 /* Note that we were at least called */
151 * \brief return the ast_key structure for name
154 static struct ast_key *__ast_key_get(const char *kname, int ktype)
157 ast_mutex_lock(&keylock);
160 if (!strcmp(kname, key->name) &&
161 (ktype == key->ktype))
165 ast_mutex_unlock(&keylock);
170 * \brief load RSA key from file
171 * \param dir directory string
172 * \param fname name of file
173 * \param ifd incoming file descriptor
174 * \param ofd outgoing file descriptor
176 * \retval key on success.
177 * \retval NULL on failure.
179 static struct ast_key *try_load_key (char *dir, char *fname, int ifd, int ofd, int *not2)
184 unsigned char digest[16];
186 struct MD5Context md5;
188 static int notice = 0;
191 /* Make sure its name is a public or private key */
193 if ((c = strstr(fname, ".pub")) && !strcmp(c, ".pub")) {
194 ktype = AST_KEY_PUBLIC;
195 } else if ((c = strstr(fname, ".key")) && !strcmp(c, ".key")) {
196 ktype = AST_KEY_PRIVATE;
200 /* Get actual filename */
201 snprintf(ffname, sizeof(ffname), "%s/%s", dir, fname);
203 ast_mutex_lock(&keylock);
206 /* Look for an existing version already */
207 if (!strcasecmp(key->fn, ffname))
211 ast_mutex_unlock(&keylock);
214 f = fopen(ffname, "r");
216 ast_log(LOG_WARNING, "Unable to open key file %s: %s\n", ffname, strerror(errno));
221 /* Calculate a "whatever" quality md5sum of the key */
224 fgets(buf, sizeof(buf), f);
226 MD5Update(&md5, (unsigned char *) buf, strlen(buf));
229 MD5Final(digest, &md5);
231 /* If the MD5 sum is the same, and it isn't awaiting a passcode
232 then this is far enough */
233 if (!memcmp(digest, key->digest, 16) &&
234 !(key->ktype & KEY_NEEDS_PASSCODE)) {
239 /* Preserve keytype */
241 /* Recycle the same structure */
246 /* Make fname just be the normal name now */
249 if (!(key = ast_calloc(1, sizeof(*key)))) {
254 /* At this point we have a key structure (old or new). Time to
255 fill it with what we know */
256 /* Gotta lock if this one already exists */
258 ast_mutex_lock(&keylock);
259 /* First the filename */
260 ast_copy_string(key->fn, ffname, sizeof(key->fn));
262 ast_copy_string(key->name, fname, sizeof(key->name));
264 /* Yes, assume we're going to be deleted */
266 /* Keep the key type */
267 memcpy(key->digest, digest, 16);
268 /* Can I/O takes the FD we're given */
271 /* Reset the file back to the beginning */
273 /* Now load the key with the right method */
274 if (ktype == AST_KEY_PUBLIC)
275 key->rsa = PEM_read_RSA_PUBKEY(f, NULL, pw_cb, key);
277 key->rsa = PEM_read_RSAPrivateKey(f, NULL, pw_cb, key);
280 if (RSA_size(key->rsa) == 128) {
281 /* Key loaded okay */
282 key->ktype &= ~KEY_NEEDS_PASSCODE;
283 if (option_verbose > 2)
284 ast_verbose(VERBOSE_PREFIX_3 "Loaded %s key '%s'\n", key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name);
285 ast_debug(1, "Key '%s' loaded OK\n", key->name);
288 ast_log(LOG_NOTICE, "Key '%s' is not expected size.\n", key->name);
289 } else if (key->infd != -2) {
290 ast_log(LOG_WARNING, "Key load %s '%s' failed\n",key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name);
292 ERR_print_errors_fp(stderr);
294 ERR_print_errors_fp(stderr);
296 ast_log(LOG_NOTICE, "Key '%s' needs passcode.\n", key->name);
297 key->ktype |= KEY_NEEDS_PASSCODE;
299 if (!ast_opt_init_keys)
300 ast_log(LOG_NOTICE, "Add the '-i' flag to the asterisk command line if you want to automatically initialize passcodes at launch.\n");
305 /* Print final notice about "init keys" when done */
309 ast_mutex_unlock(&keylock);
311 ast_mutex_lock(&keylock);
314 ast_mutex_unlock(&keylock);
321 static void dump(unsigned char *src, int len)
325 printf("%02x", *(src++));
329 static char *binary(int y, int len)
333 memset(res, 0, sizeof(res));
334 for (x=0;x<len;x++) {
336 res[(len - x - 1)] = '1';
338 res[(len - x - 1)] = '0';
346 * \brief signs outgoing message with public key
349 static int __ast_sign_bin(struct ast_key *key, const char *msg, int msglen, unsigned char *dsig)
351 unsigned char digest[20];
352 unsigned int siglen = 128;
355 if (key->ktype != AST_KEY_PRIVATE) {
356 ast_log(LOG_WARNING, "Cannot sign with a public key\n");
360 /* Calculate digest of message */
361 SHA1((unsigned char *)msg, msglen, digest);
363 /* Verify signature */
364 res = RSA_sign(NID_sha1, digest, sizeof(digest), dsig, &siglen, key->rsa);
367 ast_log(LOG_WARNING, "RSA Signature (key %s) failed\n", key->name);
372 ast_log(LOG_WARNING, "Unexpected signature length %d, expecting %d\n", (int)siglen, (int)128);
381 * \brief decrypt a message
382 * \see ast_decrypt_bin
384 static int __ast_decrypt_bin(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
388 if (key->ktype != AST_KEY_PRIVATE) {
389 ast_log(LOG_WARNING, "Cannot decrypt with a public key\n");
394 ast_log(LOG_NOTICE, "Tried to decrypt something not a multiple of 128 bytes\n");
398 /* Process chunks 128 bytes at a time */
399 res = RSA_private_decrypt(128, src, dst, key->rsa, RSA_PKCS1_OAEP_PADDING);
411 * \brief encrypt a message
412 * \see ast_encrypt_bin
414 static int __ast_encrypt_bin(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
419 if (key->ktype != AST_KEY_PUBLIC) {
420 ast_log(LOG_WARNING, "Cannot encrypt with a private key\n");
426 if (bytes > 128 - 41)
428 /* Process chunks 128-41 bytes at a time */
429 res = RSA_public_encrypt(bytes, src, dst, key->rsa, RSA_PKCS1_OAEP_PADDING);
431 ast_log(LOG_NOTICE, "How odd, encrypted size is %d\n", res);
443 * \brief wrapper for __ast_sign_bin then base64 encode it
446 static int __ast_sign(struct ast_key *key, char *msg, char *sig)
448 unsigned char dsig[128];
449 int siglen = sizeof(dsig);
451 res = ast_sign_bin(key, msg, strlen(msg), dsig);
453 /* Success -- encode (256 bytes max as documented) */
454 ast_base64encode(sig, dsig, siglen, 256);
460 * \brief check signature of a message
461 * \see ast_check_signature_bin
463 static int __ast_check_signature_bin(struct ast_key *key, const char *msg, int msglen, const unsigned char *dsig)
465 unsigned char digest[20];
468 if (key->ktype != AST_KEY_PUBLIC) {
469 /* Okay, so of course you really *can* but for our purposes
470 we're going to say you can't */
471 ast_log(LOG_WARNING, "Cannot check message signature with a private key\n");
475 /* Calculate digest of message */
476 SHA1((unsigned char *)msg, msglen, digest);
478 /* Verify signature */
479 res = RSA_verify(NID_sha1, digest, sizeof(digest), (unsigned char *)dsig, 128, key->rsa);
482 ast_debug(1, "Key failed verification: %s\n", key->name);
490 * \brief base64 decode then sent to __ast_check_signature_bin
491 * \see ast_check_signature
493 static int __ast_check_signature(struct ast_key *key, const char *msg, const char *sig)
495 unsigned char dsig[128];
498 /* Decode signature */
499 res = ast_base64decode(dsig, sig, sizeof(dsig));
500 if (res != sizeof(dsig)) {
501 ast_log(LOG_WARNING, "Signature improper length (expect %d, got %d)\n", (int)sizeof(dsig), (int)res);
504 res = ast_check_signature_bin(key, msg, strlen(msg), dsig);
509 * \brief refresh RSA keys from file
510 * \param ifd file descriptor
511 * \param ofd file descriptor
514 static void crypto_load(int ifd, int ofd)
516 struct ast_key *key, *nkey, *last;
520 /* Mark all keys for deletion */
521 ast_mutex_lock(&keylock);
527 ast_mutex_unlock(&keylock);
529 dir = opendir((char *)ast_config_AST_KEY_DIR);
531 while((ent = readdir(dir))) {
532 try_load_key((char *)ast_config_AST_KEY_DIR, ent->d_name, ifd, ofd, ¬e);
536 ast_log(LOG_WARNING, "Unable to open key directory '%s'\n", (char *)ast_config_AST_KEY_DIR);
538 ast_log(LOG_NOTICE, "Please run the command 'init keys' to enter the passcodes for the keys\n");
540 ast_mutex_lock(&keylock);
546 ast_debug(1, "Deleting key %s type %d\n", key->name, key->ktype);
559 ast_mutex_unlock(&keylock);
562 static void md52sum(char *sum, unsigned char *md5)
566 sum += sprintf(sum, "%02x", *(md5++));
570 * \brief show the list of RSA keys
571 * \param fd file descriptor
572 * \param argc no of arguements
573 * \param argv list of arguements
574 * \return RESULT_SUCCESS
576 static int show_keys(int fd, int argc, char *argv[])
579 char sum[16 * 2 + 1];
582 ast_mutex_lock(&keylock);
584 ast_cli(fd, "%-18s %-8s %-16s %-33s\n", "Key Name", "Type", "Status", "Sum");
586 md52sum(sum, key->digest);
587 ast_cli(fd, "%-18s %-8s %-16s %-33s\n", key->name,
588 (key->ktype & 0xf) == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE",
589 key->ktype & KEY_NEEDS_PASSCODE ? "[Needs Passcode]" : "[Loaded]", sum);
594 ast_mutex_unlock(&keylock);
595 ast_cli(fd, "%d known RSA keys.\n", count_keys);
596 return RESULT_SUCCESS;
600 * \brief initialize all RSA keys
601 * \param fd file descriptor
602 * \param argc no of arguements
603 * \param argv list of arguements
604 * \return RESULT_SUCCESS
606 static int init_keys(int fd, int argc, char *argv[])
615 /* Reload keys that need pass codes now */
616 if (key->ktype & KEY_NEEDS_PASSCODE) {
617 kn = key->fn + strlen(ast_config_AST_KEY_DIR) + 1;
618 ast_copy_string(tmp, kn, sizeof(tmp));
619 try_load_key((char *)ast_config_AST_KEY_DIR, tmp, fd, fd, &ign);
623 return RESULT_SUCCESS;
626 static const char show_key_usage[] =
628 " Displays information about RSA keys known by Asterisk\n";
630 static const char init_keys_usage[] =
632 " Initializes private keys (by reading in pass code from the user)\n";
634 static struct ast_cli_entry cli_crypto[] = {
635 { { "keys", "show", NULL },
636 show_keys, "Displays RSA key information",
639 { { "keys", "init", NULL },
640 init_keys, "Initialize RSA key passcodes",
644 /*! \brief initialise the res_crypto module */
645 static int crypto_init(void)
648 ERR_load_crypto_strings();
649 ast_cli_register_multiple(cli_crypto, sizeof(cli_crypto) / sizeof(struct ast_cli_entry));
651 /* Install ourselves into stubs */
652 ast_key_get = __ast_key_get;
653 ast_check_signature = __ast_check_signature;
654 ast_check_signature_bin = __ast_check_signature_bin;
655 ast_sign = __ast_sign;
656 ast_sign_bin = __ast_sign_bin;
657 ast_encrypt_bin = __ast_encrypt_bin;
658 ast_decrypt_bin = __ast_decrypt_bin;
662 static int reload(void)
668 static int load_module(void)
671 if (ast_opt_init_keys)
672 crypto_load(STDIN_FILENO, STDOUT_FILENO);
678 static int unload_module(void)
680 /* Can't unload this once we're loaded */
684 /* needs usecount semantics defined */
685 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Cryptographic Digital Signatures",
687 .unload = unload_module,