2 * Asterisk -- A telephony toolkit for Linux.
4 * Provide Cryptographic Signature capability
6 * Copyright (C) 1999, Mark Spencer
8 * Mark Spencer <markster@linux-support.net>
10 * This program is free software, distributed under the terms of
11 * the GNU General Public License
14 #include <sys/types.h>
15 #include <asterisk/file.h>
16 #include <asterisk/channel.h>
17 #include <asterisk/logger.h>
18 #include <asterisk/say.h>
19 #include <asterisk/module.h>
20 #include <asterisk/options.h>
21 #include <asterisk/crypto.h>
22 #include <asterisk/md5.h>
23 #include <asterisk/cli.h>
24 #include <asterisk/io.h>
25 #include <asterisk/lock.h>
26 #include <openssl/ssl.h>
27 #include <openssl/err.h>
34 #include "../asterisk.h"
35 #include "../astconf.h"
38 * Asterisk uses RSA keys with SHA-1 message digests for its
39 * digital signatures. The choice of RSA is due to its higher
40 * throughput on verification, and the choice of SHA-1 based
41 * on the recently discovered collisions in MD5's compression
42 * algorithm and recommendations of avoiding MD5 in new schemes
43 * from various industry experts.
45 * We use OpenSSL to provide our crypto routines, although we never
46 * actually use full-up SSL
51 * XXX This module is not very thread-safe. It is for everyday stuff
52 * like reading keys and stuff, but there are all kinds of weird
53 * races with people running reload and key init at the same time
59 static char base64[64];
62 AST_MUTEX_DEFINE_STATIC(keylock);
64 #define KEY_NEEDS_PASSCODE (1 << 16)
71 /* Key type (AST_KEY_PUB or AST_KEY_PRIV, along with flags from above) */
73 /* RSA structure (if successfully loaded) */
75 /* Whether we should be deleted */
77 /* FD for input (or -1 if no input allowed, or -2 if we needed input) */
82 unsigned char digest[16];
86 static struct ast_key *keys = NULL;
90 static int fdprint(int fd, char *s)
92 return write(fd, s, strlen(s) + 1);
95 static int pw_cb(char *buf, int size, int rwflag, void *userdata)
97 struct ast_key *key = (struct ast_key *)userdata;
101 if (key->infd > -1) {
102 snprintf(prompt, sizeof(prompt), ">>>> passcode for %s key '%s': ",
103 key->ktype == AST_KEY_PRIVATE ? "PRIVATE" : "PUBLIC", key->name);
104 write(key->outfd, prompt, strlen(prompt));
105 memset(buf, 0, sizeof(buf));
106 tmp = ast_hide_password(key->infd);
107 memset(buf, 0, size);
108 res = read(key->infd, buf, size);
109 ast_restore_tty(key->infd, tmp);
110 if (buf[strlen(buf) -1] == '\n')
111 buf[strlen(buf) - 1] = '\0';
114 /* Note that we were at least called */
120 struct ast_key *ast_key_get(char *kname, int ktype)
123 ast_mutex_lock(&keylock);
126 if (!strcmp(kname, key->name) &&
127 (ktype == key->ktype))
131 ast_mutex_unlock(&keylock);
135 static struct ast_key *try_load_key (char *dir, char *fname, int ifd, int ofd, int *not2)
142 struct MD5Context md5;
144 static int notice = 0;
147 /* Make sure its name is a public or private key */
149 if ((c = strstr(fname, ".pub")) && !strcmp(c, ".pub")) {
150 ktype = AST_KEY_PUBLIC;
151 } else if ((c = strstr(fname, ".key")) && !strcmp(c, ".key")) {
152 ktype = AST_KEY_PRIVATE;
156 /* Get actual filename */
157 snprintf(ffname, sizeof(ffname), "%s/%s", dir, fname);
159 ast_mutex_lock(&keylock);
162 /* Look for an existing version already */
163 if (!strcasecmp(key->fn, ffname))
167 ast_mutex_unlock(&keylock);
170 f = fopen(ffname, "r");
172 ast_log(LOG_WARNING, "Unable to open key file %s: %s\n", ffname, strerror(errno));
177 /* Calculate a "whatever" quality md5sum of the key */
179 fgets(buf, sizeof(buf), f);
181 MD5Update(&md5, buf, strlen(buf));
184 MD5Final(digest, &md5);
186 /* If the MD5 sum is the same, and it isn't awaiting a passcode
187 then this is far enough */
188 if (!memcmp(digest, key->digest, 16) &&
189 !(key->ktype & KEY_NEEDS_PASSCODE)) {
194 /* Preserve keytype */
196 /* Recycle the same structure */
201 /* Make fname just be the normal name now */
204 key = (struct ast_key *)malloc(sizeof(struct ast_key));
206 ast_log(LOG_WARNING, "Out of memory\n");
210 memset(key, 0, sizeof(struct ast_key));
212 /* At this point we have a key structure (old or new). Time to
213 fill it with what we know */
214 /* Gotta lock if this one already exists */
216 ast_mutex_lock(&keylock);
217 /* First the filename */
218 strncpy(key->fn, ffname, sizeof(key->fn));
220 strncpy(key->name, fname, sizeof(key->name));
222 /* Yes, assume we're going to be deleted */
224 /* Keep the key type */
225 memcpy(key->digest, digest, 16);
226 /* Can I/O takes the FD we're given */
229 /* Reset the file back to the beginning */
231 /* Now load the key with the right method */
232 if (ktype == AST_KEY_PUBLIC)
233 key->rsa = PEM_read_RSA_PUBKEY(f, NULL, pw_cb, key);
235 key->rsa = PEM_read_RSAPrivateKey(f, NULL, pw_cb, key);
238 /* Key loaded okay */
239 key->ktype &= ~KEY_NEEDS_PASSCODE;
240 if (option_verbose > 2)
241 ast_verbose(VERBOSE_PREFIX_3 "Loaded %s key '%s'\n", key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name);
243 ast_log(LOG_DEBUG, "Key '%s' loaded OK\n", key->name);
245 } else if (key->infd != -2) {
246 ast_log(LOG_WARNING, "Key load %s '%s' failed\n",key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name);
248 ERR_print_errors_fp(stderr);
250 ERR_print_errors_fp(stderr);
252 ast_log(LOG_NOTICE, "Key '%s' needs passcode.\n", key->name);
253 key->ktype |= KEY_NEEDS_PASSCODE;
255 if (!option_initcrypto)
256 ast_log(LOG_NOTICE, "Add the '-i' flag to the asterisk command line if you want to automatically initialize passcodes at launch.\n");
261 /* Print final notice about "init keys" when done */
265 ast_mutex_unlock(&keylock);
267 ast_mutex_lock(&keylock);
270 ast_mutex_unlock(&keylock);
277 static void dump(unsigned char *src, int len)
281 printf("%02x", *(src++));
285 static char *binary(int y, int len)
289 memset(res, 0, sizeof(res));
290 for (x=0;x<len;x++) {
292 res[(len - x - 1)] = '1';
294 res[(len - x - 1)] = '0';
301 static int base64decode(unsigned char *dst, char *src, int max)
304 unsigned int byte = 0;
305 unsigned int bits = 0;
308 unsigned char *odst = dst;
310 while(*src && (cnt < max)) {
311 /* Shift in 6 bits of input */
313 byte |= (b2a[(int)(*src)]) & 0x3f;
316 printf("Add: %c %s\n", *src, binary(b2a[(int)(*src)] & 0x3f, 6));
320 /* If we have at least 8 bits left over, take that character
324 *dst = (byte >> bits) & 0xff;
326 printf("Remove: %02x %s\n", *dst, binary(*dst, 8));
335 /* Dont worry about left over bits, they're extra anyway */
339 static int base64encode(char *dst, unsigned char *src, int srclen, int max)
342 unsigned int byte = 0;
350 /* Reserve one bit for end */
352 while((cntin < srclen) && (cnt < max)) {
355 printf("Add: %02x %s\n", *src, binary(*src, 8));
360 while((bits >= 6) && (cnt < max)) {
362 /* We want only the top */
363 index = (byte >> bits) & 0x3f;
364 *dst = base64[index];
366 printf("Remove: %c %s\n", *dst, binary(index, 6));
372 if (bits && (cnt < max)) {
373 /* Add one last character for the remaining bits,
374 padding the rest with 0 */
376 index = (byte) & 0x3f;
377 *(dst++) = base64[index];
384 int ast_sign(struct ast_key *key, char *msg, char *sig)
386 unsigned char digest[20];
387 unsigned char dsig[128];
388 int siglen = sizeof(dsig);
391 if (key->ktype != AST_KEY_PRIVATE) {
392 ast_log(LOG_WARNING, "Cannot sign with a private key\n");
396 /* Calculate digest of message */
397 SHA1((unsigned char *)msg, strlen(msg), digest);
399 /* Verify signature */
400 res = RSA_sign(NID_sha1, digest, sizeof(digest), dsig, &siglen, key->rsa);
403 ast_log(LOG_WARNING, "RSA Signature (key %s) failed\n", key->name);
407 if (siglen != sizeof(dsig)) {
408 ast_log(LOG_WARNING, "Unexpected signature length %d, expecting %d\n", (int)siglen, (int)sizeof(dsig));
412 /* Success -- encode (256 bytes max as documented) */
413 base64encode(sig, dsig, siglen, 256);
418 int ast_check_signature(struct ast_key *key, char *msg, char *sig)
420 unsigned char digest[20];
421 unsigned char dsig[128];
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 /* Decode signature */
432 res = base64decode(dsig, sig, sizeof(dsig));
433 if (res != sizeof(dsig)) {
434 ast_log(LOG_WARNING, "Signature improper length (expect %d, got %d)\n", (int)sizeof(dsig), (int)res);
438 /* Calculate digest of message */
439 SHA1((unsigned char *)msg, strlen(msg), digest);
441 /* Verify signature */
442 res = RSA_verify(NID_sha1, digest, sizeof(digest), dsig, sizeof(dsig), key->rsa);
445 ast_log(LOG_DEBUG, "Key failed verification\n");
452 static void crypto_load(int ifd, int ofd)
454 struct ast_key *key, *nkey, *last;
458 /* Mark all keys for deletion */
459 ast_mutex_lock(&keylock);
465 ast_mutex_unlock(&keylock);
467 dir = opendir((char *)ast_config_AST_KEY_DIR);
469 while((ent = readdir(dir))) {
470 try_load_key((char *)ast_config_AST_KEY_DIR, ent->d_name, ifd, ofd, ¬e);
474 ast_log(LOG_WARNING, "Unable to open key directory '%s'\n", (char *)ast_config_AST_KEY_DIR);
476 ast_log(LOG_NOTICE, "Please run the command 'init keys' to enter the passcodes for the keys\n");
478 ast_mutex_lock(&keylock);
484 ast_log(LOG_DEBUG, "Deleting key %s type %d\n", key->name, key->ktype);
497 ast_mutex_unlock(&keylock);
500 static void md52sum(char *sum, unsigned char *md5)
504 sum += sprintf(sum, "%02x", *(md5++));
507 static int show_keys(int fd, int argc, char *argv[])
510 char sum[16 * 2 + 1];
512 ast_mutex_lock(&keylock);
514 ast_cli(fd, "%-18s %-8s %-16s %-33s\n", "Key Name", "Type", "Status", "Sum");
516 md52sum(sum, key->digest);
517 ast_cli(fd, "%-18s %-8s %-16s %-33s\n", key->name,
518 (key->ktype & 0xf) == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE",
519 key->ktype & KEY_NEEDS_PASSCODE ? "[Needs Passcode]" : "[Loaded]", sum);
523 ast_mutex_unlock(&keylock);
524 return RESULT_SUCCESS;
527 static int init_keys(int fd, int argc, char *argv[])
536 /* Reload keys that need pass codes now */
537 if (key->ktype & KEY_NEEDS_PASSCODE) {
538 kn = key->fn + strlen(ast_config_AST_KEY_DIR) + 1;
539 strncpy(tmp, kn, sizeof(tmp));
540 try_load_key((char *)ast_config_AST_KEY_DIR, tmp, fd, fd, &ign);
544 return RESULT_SUCCESS;
547 static char show_key_usage[] =
549 " Displays information about RSA keys known by Asterisk\n";
551 static char init_keys_usage[] =
553 " Initializes private keys (by reading in pass code from the user)\n";
555 static struct ast_cli_entry cli_show_keys =
556 { { "show", "keys", NULL }, show_keys, "Displays RSA key information", show_key_usage };
558 static struct ast_cli_entry cli_init_keys =
559 { { "init", "keys", NULL }, init_keys, "Initialize RSA key passcodes", init_keys_usage };
561 static void base64_init(void)
564 memset(b2a, -1, sizeof(b2a));
565 /* Initialize base-64 Conversion table */
571 base64[x + 26] = 'a' + x;
572 b2a['a' + x] = x + 26;
575 base64[x + 52] = '0' + x;
576 b2a['0' + x] = x + 52;
585 if (b2a[(int)base64[x]] != x) {
586 fprintf(stderr, "!!! %d failed\n", x);
588 fprintf(stderr, "--- %d passed\n", x);
593 static int crypto_init(void)
597 ERR_load_crypto_strings();
598 ast_cli_register(&cli_show_keys);
599 ast_cli_register(&cli_init_keys);
609 int load_module(void)
612 if (option_initcrypto)
613 crypto_load(STDIN_FILENO, STDOUT_FILENO);
619 int unload_module(void)
621 /* Can't unload this once we're loaded */
625 char *description(void)
627 return "Cryptographic Digital Signatures";
632 /* We should never be unloaded */
638 return ASTERISK_GPL_KEY;