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