accabd16b5fa636c1d72d07c4bf51e3faf706375
[asterisk/asterisk.git] / res / res_crypto.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
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.
13  *
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.
17  */
18
19 /*! \file
20  *
21  * \brief Provide Cryptographic Signature capability
22  *
23  * \author Mark Spencer <markster@digium.com> 
24  */
25
26 #include <sys/types.h>
27 #include <openssl/ssl.h>
28 #include <openssl/err.h>
29 #include <stdio.h>
30 #include <dirent.h>
31 #include <string.h>
32 #include <errno.h>
33 #include <unistd.h>
34 #include <fcntl.h>
35
36 #include "asterisk.h"
37
38 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
39
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"
52
53 /*
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.
60  *
61  * We use OpenSSL to provide our crypto routines, although we never
62  * actually use full-up SSL
63  *
64  */
65
66 /*
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
70  *     for example
71  *
72  * XXXX
73  */
74
75 AST_MUTEX_DEFINE_STATIC(keylock);
76
77 #define KEY_NEEDS_PASSCODE (1 << 16)
78
79 struct ast_key {
80         /* Name of entity */
81         char name[80];
82         /* File name */
83         char fn[256];
84         /* Key type (AST_KEY_PUB or AST_KEY_PRIV, along with flags from above) */
85         int ktype;
86         /* RSA structure (if successfully loaded) */
87         RSA *rsa;
88         /* Whether we should be deleted */
89         int delme;
90         /* FD for input (or -1 if no input allowed, or -2 if we needed input) */
91         int infd;
92         /* FD for output */
93         int outfd;
94         /* Last MD5 Digest */
95         unsigned char digest[16];
96         struct ast_key *next;
97 };
98
99 static struct ast_key *keys = NULL;
100
101
102 #if 0
103 static int fdprint(int fd, char *s)
104 {
105         return write(fd, s, strlen(s) + 1);
106 }
107 #endif
108 static int pw_cb(char *buf, int size, int rwflag, void *userdata)
109 {
110         struct ast_key *key = (struct ast_key *)userdata;
111         char prompt[256];
112         int res;
113         int tmp;
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';
125                 return strlen(buf);
126         } else {
127                 /* Note that we were at least called */
128                 key->infd = -2;
129         }
130         return -1;
131 }
132
133 static struct ast_key *__ast_key_get(const char *kname, int ktype)
134 {
135         struct ast_key *key;
136         ast_mutex_lock(&keylock);
137         key = keys;
138         while(key) {
139                 if (!strcmp(kname, key->name) &&
140                     (ktype == key->ktype))
141                         break;
142                 key = key->next;
143         }
144         ast_mutex_unlock(&keylock);
145         return key;
146 }
147
148 static struct ast_key *try_load_key (char *dir, char *fname, int ifd, int ofd, int *not2)
149 {
150         int ktype = 0;
151         char *c = NULL;
152         char ffname[256];
153         unsigned char digest[16];
154         FILE *f;
155         struct MD5Context md5;
156         struct ast_key *key;
157         static int notice = 0;
158         int found = 0;
159
160         /* Make sure its name is a public or private key */
161
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;
166         } else
167                 return NULL;
168
169         /* Get actual filename */
170         snprintf(ffname, sizeof(ffname), "%s/%s", dir, fname);
171
172         ast_mutex_lock(&keylock);
173         key = keys;
174         while(key) {
175                 /* Look for an existing version already */
176                 if (!strcasecmp(key->fn, ffname)) 
177                         break;
178                 key = key->next;
179         }
180         ast_mutex_unlock(&keylock);
181
182         /* Open file */
183         f = fopen(ffname, "r");
184         if (!f) {
185                 ast_log(LOG_WARNING, "Unable to open key file %s: %s\n", ffname, strerror(errno));
186                 return NULL;
187         }
188         MD5Init(&md5);
189         while(!feof(f)) {
190                 /* Calculate a "whatever" quality md5sum of the key */
191                 char buf[256];
192                 memset(buf, 0, 256);
193                 fgets(buf, sizeof(buf), f);
194                 if (!feof(f)) {
195                         MD5Update(&md5, (unsigned char *) buf, strlen(buf));
196                 }
197         }
198         MD5Final(digest, &md5);
199         if (key) {
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)) {
204                         fclose(f);
205                         key->delme = 0;
206                         return NULL;
207                 } else {
208                         /* Preserve keytype */
209                         ktype = key->ktype;
210                         /* Recycle the same structure */
211                         found++;
212                 }
213         }
214
215         /* Make fname just be the normal name now */
216         *c = '\0';
217         if (!key) {
218                 if (!(key = ast_calloc(1, sizeof(*key)))) {
219                         fclose(f);
220                         return NULL;
221                 }
222         }
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 */
226         if (found)
227                 ast_mutex_lock(&keylock);
228         /* First the filename */
229         ast_copy_string(key->fn, ffname, sizeof(key->fn));
230         /* Then the name */
231         ast_copy_string(key->name, fname, sizeof(key->name));
232         key->ktype = ktype;
233         /* Yes, assume we're going to be deleted */
234         key->delme = 1;
235         /* Keep the key type */
236         memcpy(key->digest, digest, 16);
237         /* Can I/O takes the FD we're given */
238         key->infd = ifd;
239         key->outfd = ofd;
240         /* Reset the file back to the beginning */
241         rewind(f);
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);
245         else
246                 key->rsa = PEM_read_RSAPrivateKey(f, NULL, pw_cb, key);
247         fclose(f);
248         if (key->rsa) {
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);
254                         if (option_debug)
255                                 ast_log(LOG_DEBUG, "Key '%s' loaded OK\n", key->name);
256                         key->delme = 0;
257                 } else
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);
261                 if (ofd > -1) {
262                         ERR_print_errors_fp(stderr);
263                 } else
264                         ERR_print_errors_fp(stderr);
265         } else {
266                 ast_log(LOG_NOTICE, "Key '%s' needs passcode.\n", key->name);
267                 key->ktype |= KEY_NEEDS_PASSCODE;
268                 if (!notice) {
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");
271                         notice++;
272                 }
273                 /* Keep it anyway */
274                 key->delme = 0;
275                 /* Print final notice about "init keys" when done */
276                 *not2 = 1;
277         }
278         if (found)
279                 ast_mutex_unlock(&keylock);
280         if (!found) {
281                 ast_mutex_lock(&keylock);
282                 key->next = keys;
283                 keys = key;
284                 ast_mutex_unlock(&keylock);
285         }
286         return key;
287 }
288
289 #if 0
290
291 static void dump(unsigned char *src, int len)
292 {
293         int x; 
294         for (x=0;x<len;x++)
295                 printf("%02x", *(src++));
296         printf("\n");
297 }
298
299 static char *binary(int y, int len)
300 {
301         static char res[80];
302         int x;
303         memset(res, 0, sizeof(res));
304         for (x=0;x<len;x++) {
305                 if (y & (1 << x))
306                         res[(len - x - 1)] = '1';
307                 else
308                         res[(len - x - 1)] = '0';
309         }
310         return res;
311 }
312
313 #endif
314
315 static int __ast_sign_bin(struct ast_key *key, const char *msg, int msglen, unsigned char *dsig)
316 {
317         unsigned char digest[20];
318         unsigned int siglen = 128;
319         int res;
320
321         if (key->ktype != AST_KEY_PRIVATE) {
322                 ast_log(LOG_WARNING, "Cannot sign with a public key\n");
323                 return -1;
324         }
325
326         /* Calculate digest of message */
327         SHA1((unsigned char *)msg, msglen, digest);
328
329         /* Verify signature */
330         res = RSA_sign(NID_sha1, digest, sizeof(digest), dsig, &siglen, key->rsa);
331         
332         if (!res) {
333                 ast_log(LOG_WARNING, "RSA Signature (key %s) failed\n", key->name);
334                 return -1;
335         }
336
337         if (siglen != 128) {
338                 ast_log(LOG_WARNING, "Unexpected signature length %d, expecting %d\n", (int)siglen, (int)128);
339                 return -1;
340         }
341
342         return 0;
343         
344 }
345
346 static int __ast_decrypt_bin(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
347 {
348         int res;
349         int pos = 0;
350         if (key->ktype != AST_KEY_PRIVATE) {
351                 ast_log(LOG_WARNING, "Cannot decrypt with a public key\n");
352                 return -1;
353         }
354
355         if (srclen % 128) {
356                 ast_log(LOG_NOTICE, "Tried to decrypt something not a multiple of 128 bytes\n");
357                 return -1;
358         }
359         while(srclen) {
360                 /* Process chunks 128 bytes at a time */
361                 res = RSA_private_decrypt(128, src, dst, key->rsa, RSA_PKCS1_OAEP_PADDING);
362                 if (res < 0)
363                         return -1;
364                 pos += res;
365                 src += 128;
366                 srclen -= 128;
367                 dst += res;
368         }
369         return pos;
370 }
371
372 static int __ast_encrypt_bin(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
373 {
374         int res;
375         int bytes;
376         int pos = 0;
377         if (key->ktype != AST_KEY_PUBLIC) {
378                 ast_log(LOG_WARNING, "Cannot encrypt with a private key\n");
379                 return -1;
380         }
381         
382         while(srclen) {
383                 bytes = srclen;
384                 if (bytes > 128 - 41)
385                         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);
388                 if (res != 128) {
389                         ast_log(LOG_NOTICE, "How odd, encrypted size is %d\n", res);
390                         return -1;
391                 }
392                 src += bytes;
393                 srclen -= bytes;
394                 pos += res;
395                 dst += res;
396         }
397         return pos;
398 }
399
400 static int __ast_sign(struct ast_key *key, char *msg, char *sig)
401 {
402         unsigned char dsig[128];
403         int siglen = sizeof(dsig);
404         int res;
405         res = ast_sign_bin(key, msg, strlen(msg), dsig);
406         if (!res)
407                 /* Success -- encode (256 bytes max as documented) */
408                 ast_base64encode(sig, dsig, siglen, 256);
409         return res;
410         
411 }
412
413 static int __ast_check_signature_bin(struct ast_key *key, const char *msg, int msglen, const unsigned char *dsig)
414 {
415         unsigned char digest[20];
416         int res;
417
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");
422                 return -1;
423         }
424
425         /* Calculate digest of message */
426         SHA1((unsigned char *)msg, msglen, digest);
427
428         /* Verify signature */
429         res = RSA_verify(NID_sha1, digest, sizeof(digest), (unsigned char *)dsig, 128, key->rsa);
430         
431         if (!res) {
432                 ast_log(LOG_DEBUG, "Key failed verification: %s\n", key->name);
433                 return -1;
434         }
435         /* Pass */
436         return 0;
437 }
438
439 static int __ast_check_signature(struct ast_key *key, const char *msg, const char *sig)
440 {
441         unsigned char dsig[128];
442         int res;
443
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);
448                 return -1;
449         }
450         res = ast_check_signature_bin(key, msg, strlen(msg), dsig);
451         return res;
452 }
453
454 static void crypto_load(int ifd, int ofd)
455 {
456         struct ast_key *key, *nkey, *last;
457         DIR *dir = NULL;
458         struct dirent *ent;
459         int note = 0;
460         /* Mark all keys for deletion */
461         ast_mutex_lock(&keylock);
462         key = keys;
463         while(key) {
464                 key->delme = 1;
465                 key = key->next;
466         }
467         ast_mutex_unlock(&keylock);
468         /* Load new keys */
469         dir = opendir((char *)ast_config_AST_KEY_DIR);
470         if (dir) {
471                 while((ent = readdir(dir))) {
472                         try_load_key((char *)ast_config_AST_KEY_DIR, ent->d_name, ifd, ofd, &note);
473                 }
474                 closedir(dir);
475         } else
476                 ast_log(LOG_WARNING, "Unable to open key directory '%s'\n", (char *)ast_config_AST_KEY_DIR);
477         if (note) {
478                 ast_log(LOG_NOTICE, "Please run the command 'init keys' to enter the passcodes for the keys\n");
479         }
480         ast_mutex_lock(&keylock);
481         key = keys;
482         last = NULL;
483         while(key) {
484                 nkey = key->next;
485                 if (key->delme) {
486                         ast_log(LOG_DEBUG, "Deleting key %s type %d\n", key->name, key->ktype);
487                         /* Do the delete */
488                         if (last)
489                                 last->next = nkey;
490                         else
491                                 keys = nkey;
492                         if (key->rsa)
493                                 RSA_free(key->rsa);
494                         free(key);
495                 } else 
496                         last = key;
497                 key = nkey;
498         }
499         ast_mutex_unlock(&keylock);
500 }
501
502 static void md52sum(char *sum, unsigned char *md5)
503 {
504         int x;
505         for (x=0;x<16;x++) 
506                 sum += sprintf(sum, "%02x", *(md5++));
507 }
508
509 static int show_keys(int fd, int argc, char *argv[])
510 {
511         struct ast_key *key;
512         char sum[16 * 2 + 1];
513         int count_keys = 0;
514
515         ast_mutex_lock(&keylock);
516         key = keys;
517         ast_cli(fd, "%-18s %-8s %-16s %-33s\n", "Key Name", "Type", "Status", "Sum");
518         while(key) {
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);
523                                 
524                 key = key->next;
525                 count_keys++;
526         }
527         ast_mutex_unlock(&keylock);
528         ast_cli(fd, "%d known RSA keys.\n", count_keys);
529         return RESULT_SUCCESS;
530 }
531
532 static int init_keys(int fd, int argc, char *argv[])
533 {
534         struct ast_key *key;
535         int ign;
536         char *kn;
537         char tmp[256] = "";
538
539         key = keys;
540         while(key) {
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);
546                 }
547                 key = key->next;
548         }
549         return RESULT_SUCCESS;
550 }
551
552 static char show_key_usage[] =
553 "Usage: show keys\n"
554 "       Displays information about RSA keys known by Asterisk\n";
555
556 static char init_keys_usage[] =
557 "Usage: init keys\n"
558 "       Initializes private keys (by reading in pass code from the user)\n";
559
560 static struct ast_cli_entry cli_show_keys = 
561 { { "show", "keys", NULL }, show_keys, "Displays RSA key information", show_key_usage };
562
563 static struct ast_cli_entry cli_init_keys = 
564 { { "init", "keys", NULL }, init_keys, "Initialize RSA key passcodes", init_keys_usage };
565
566 static int crypto_init(void)
567 {
568         SSL_library_init();
569         ERR_load_crypto_strings();
570         ast_cli_register(&cli_show_keys);
571         ast_cli_register(&cli_init_keys);
572
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;
581         return 0;
582 }
583
584 int reload(void)
585 {
586         crypto_load(-1, -1);
587         return 0;
588 }
589
590 int load_module(void)
591 {
592         crypto_init();
593         if (ast_opt_init_keys)
594                 crypto_load(STDIN_FILENO, STDOUT_FILENO);
595         else
596                 crypto_load(-1, -1);
597         return 0;
598 }
599
600 int unload_module(void)
601 {
602         /* Can't unload this once we're loaded */
603         return -1;
604 }
605
606 const char *description(void)
607 {
608         return "Cryptographic Digital Signatures";
609 }
610
611 int usecount(void)
612 {
613         /* We should never be unloaded */
614         return 1;
615 }
616
617 const char *key()
618 {
619         return ASTERISK_GPL_KEY;
620 }