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/
30 <depend>openssl</depend>
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
37 #include "asterisk/paths.h" /* use ast_config_AST_KEY_DIR */
38 #include <openssl/ssl.h>
39 #include <openssl/err.h>
42 #include "asterisk/module.h"
43 #include "asterisk/crypto.h"
44 #include "asterisk/md5.h"
45 #include "asterisk/cli.h"
46 #include "asterisk/io.h"
47 #include "asterisk/lock.h"
48 #include "asterisk/utils.h"
51 * Asterisk uses RSA keys with SHA-1 message digests for its
52 * digital signatures. The choice of RSA is due to its higher
53 * throughput on verification, and the choice of SHA-1 based
54 * on the recently discovered collisions in MD5's compression
55 * algorithm and recommendations of avoiding MD5 in new schemes
56 * from various industry experts.
58 * We use OpenSSL to provide our crypto routines, although we never
59 * actually use full-up SSL
63 #define KEY_NEEDS_PASSCODE (1 << 16)
70 /*! Key type (AST_KEY_PUB or AST_KEY_PRIV, along with flags from above) */
72 /*! RSA structure (if successfully loaded) */
74 /*! Whether we should be deleted */
76 /*! FD for input (or -1 if no input allowed, or -2 if we needed input) */
80 /*! Last MD5 Digest */
81 unsigned char digest[16];
82 AST_RWLIST_ENTRY(ast_key) list;
85 static AST_RWLIST_HEAD_STATIC(keys, ast_key);
88 * \brief setting of priv key
93 * \return length of string,-1 on failure
95 static int pw_cb(char *buf, int size, int rwflag, void *userdata)
97 struct ast_key *key = (struct ast_key *)userdata;
102 /* Note that we were at least called */
107 snprintf(prompt, sizeof(prompt), ">>>> passcode for %s key '%s': ",
108 key->ktype == AST_KEY_PRIVATE ? "PRIVATE" : "PUBLIC", key->name);
109 if (write(key->outfd, prompt, strlen(prompt)) < 0) {
110 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
114 memset(buf, 0, sizeof(buf));
115 tmp = ast_hide_password(key->infd);
116 memset(buf, 0, size);
117 res = read(key->infd, buf, size);
118 ast_restore_tty(key->infd, tmp);
119 if (buf[strlen(buf) -1] == '\n')
120 buf[strlen(buf) - 1] = '\0';
125 * \brief return the ast_key structure for name
128 static struct ast_key *__ast_key_get(const char *kname, int ktype)
132 AST_RWLIST_RDLOCK(&keys);
133 AST_RWLIST_TRAVERSE(&keys, key, list) {
134 if (!strcmp(kname, key->name) &&
135 (ktype == key->ktype))
138 AST_RWLIST_UNLOCK(&keys);
144 * \brief load RSA key from file
145 * \param dir directory string
146 * \param fname name of file
147 * \param ifd incoming file descriptor
148 * \param ofd outgoing file descriptor
150 * \retval key on success.
151 * \retval NULL on failure.
153 static struct ast_key *try_load_key(const char *dir, const char *fname, int ifd, int ofd, int *not2)
155 int ktype = 0, found = 0;
156 char *c = NULL, ffname[256];
157 unsigned char digest[16];
159 struct MD5Context md5;
161 static int notice = 0;
163 /* Make sure its name is a public or private key */
164 if ((c = strstr(fname, ".pub")) && !strcmp(c, ".pub"))
165 ktype = AST_KEY_PUBLIC;
166 else if ((c = strstr(fname, ".key")) && !strcmp(c, ".key"))
167 ktype = AST_KEY_PRIVATE;
171 /* Get actual filename */
172 snprintf(ffname, sizeof(ffname), "%s/%s", dir, fname);
175 if (!(f = fopen(ffname, "r"))) {
176 ast_log(LOG_WARNING, "Unable to open key file %s: %s\n", ffname, strerror(errno));
182 /* Calculate a "whatever" quality md5sum of the key */
184 if (!fgets(buf, sizeof(buf), f)) {
188 MD5Update(&md5, (unsigned char *) buf, strlen(buf));
190 MD5Final(digest, &md5);
192 /* Look for an existing key */
193 AST_RWLIST_TRAVERSE(&keys, key, list) {
194 if (!strcasecmp(key->fn, ffname))
199 /* If the MD5 sum is the same, and it isn't awaiting a passcode
200 then this is far enough */
201 if (!memcmp(digest, key->digest, 16) &&
202 !(key->ktype & KEY_NEEDS_PASSCODE)) {
207 /* Preserve keytype */
209 /* Recycle the same structure */
214 /* Make fname just be the normal name now */
217 if (!(key = ast_calloc(1, sizeof(*key)))) {
222 /* First the filename */
223 ast_copy_string(key->fn, ffname, sizeof(key->fn));
225 ast_copy_string(key->name, fname, sizeof(key->name));
227 /* Yes, assume we're going to be deleted */
229 /* Keep the key type */
230 memcpy(key->digest, digest, 16);
231 /* Can I/O takes the FD we're given */
234 /* Reset the file back to the beginning */
236 /* Now load the key with the right method */
237 if (ktype == AST_KEY_PUBLIC)
238 key->rsa = PEM_read_RSA_PUBKEY(f, NULL, pw_cb, key);
240 key->rsa = PEM_read_RSAPrivateKey(f, NULL, pw_cb, key);
243 if (RSA_size(key->rsa) == 128) {
244 /* Key loaded okay */
245 key->ktype &= ~KEY_NEEDS_PASSCODE;
246 ast_verb(3, "Loaded %s key '%s'\n", key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name);
247 ast_debug(1, "Key '%s' loaded OK\n", key->name);
250 ast_log(LOG_NOTICE, "Key '%s' is not expected size.\n", key->name);
251 } else if (key->infd != -2) {
252 ast_log(LOG_WARNING, "Key load %s '%s' failed\n",key->ktype == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE", key->name);
254 ERR_print_errors_fp(stderr);
256 ERR_print_errors_fp(stderr);
258 ast_log(LOG_NOTICE, "Key '%s' needs passcode.\n", key->name);
259 key->ktype |= KEY_NEEDS_PASSCODE;
261 if (!ast_opt_init_keys)
262 ast_log(LOG_NOTICE, "Add the '-i' flag to the asterisk command line if you want to automatically initialize passcodes at launch.\n");
267 /* Print final notice about "init keys" when done */
271 /* If this is a new key add it to the list */
273 AST_RWLIST_INSERT_TAIL(&keys, key, list);
279 * \brief signs outgoing message with public key
282 static int __ast_sign_bin(struct ast_key *key, const char *msg, int msglen, unsigned char *dsig)
284 unsigned char digest[20];
285 unsigned int siglen = 128;
288 if (key->ktype != AST_KEY_PRIVATE) {
289 ast_log(LOG_WARNING, "Cannot sign with a public key\n");
293 /* Calculate digest of message */
294 SHA1((unsigned char *)msg, msglen, digest);
296 /* Verify signature */
297 if (!(res = RSA_sign(NID_sha1, digest, sizeof(digest), dsig, &siglen, key->rsa))) {
298 ast_log(LOG_WARNING, "RSA Signature (key %s) failed\n", key->name);
303 ast_log(LOG_WARNING, "Unexpected signature length %d, expecting %d\n", (int)siglen, (int)128);
312 * \brief decrypt a message
313 * \see ast_decrypt_bin
315 static int __ast_decrypt_bin(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
319 if (key->ktype != AST_KEY_PRIVATE) {
320 ast_log(LOG_WARNING, "Cannot decrypt with a public key\n");
325 ast_log(LOG_NOTICE, "Tried to decrypt something not a multiple of 128 bytes\n");
330 /* Process chunks 128 bytes at a time */
331 if ((res = RSA_private_decrypt(128, src, dst, key->rsa, RSA_PKCS1_OAEP_PADDING)) < 0)
343 * \brief encrypt a message
344 * \see ast_encrypt_bin
346 static int __ast_encrypt_bin(unsigned char *dst, const unsigned char *src, int srclen, struct ast_key *key)
348 int res, bytes, pos = 0;
350 if (key->ktype != AST_KEY_PUBLIC) {
351 ast_log(LOG_WARNING, "Cannot encrypt with a private key\n");
357 if (bytes > 128 - 41)
359 /* Process chunks 128-41 bytes at a time */
360 if ((res = RSA_public_encrypt(bytes, src, dst, key->rsa, RSA_PKCS1_OAEP_PADDING)) != 128) {
361 ast_log(LOG_NOTICE, "How odd, encrypted size is %d\n", res);
373 * \brief wrapper for __ast_sign_bin then base64 encode it
376 static int __ast_sign(struct ast_key *key, char *msg, char *sig)
378 unsigned char dsig[128];
379 int siglen = sizeof(dsig), res;
381 if (!(res = ast_sign_bin(key, msg, strlen(msg), dsig)))
382 /* Success -- encode (256 bytes max as documented) */
383 ast_base64encode(sig, dsig, siglen, 256);
389 * \brief check signature of a message
390 * \see ast_check_signature_bin
392 static int __ast_check_signature_bin(struct ast_key *key, const char *msg, int msglen, const unsigned char *dsig)
394 unsigned char digest[20];
397 if (key->ktype != AST_KEY_PUBLIC) {
398 /* Okay, so of course you really *can* but for our purposes
399 we're going to say you can't */
400 ast_log(LOG_WARNING, "Cannot check message signature with a private key\n");
404 /* Calculate digest of message */
405 SHA1((unsigned char *)msg, msglen, digest);
407 /* Verify signature */
408 if (!(res = RSA_verify(NID_sha1, digest, sizeof(digest), (unsigned char *)dsig, 128, key->rsa))) {
409 ast_debug(1, "Key failed verification: %s\n", key->name);
418 * \brief base64 decode then sent to __ast_check_signature_bin
419 * \see ast_check_signature
421 static int __ast_check_signature(struct ast_key *key, const char *msg, const char *sig)
423 unsigned char dsig[128];
426 /* Decode signature */
427 if ((res = ast_base64decode(dsig, sig, sizeof(dsig))) != sizeof(dsig)) {
428 ast_log(LOG_WARNING, "Signature improper length (expect %d, got %d)\n", (int)sizeof(dsig), (int)res);
432 res = ast_check_signature_bin(key, msg, strlen(msg), dsig);
438 * \brief refresh RSA keys from file
439 * \param ifd file descriptor
440 * \param ofd file descriptor
443 static void crypto_load(int ifd, int ofd)
450 AST_RWLIST_WRLOCK(&keys);
452 /* Mark all keys for deletion */
453 AST_RWLIST_TRAVERSE(&keys, key, list) {
458 if ((dir = opendir(ast_config_AST_KEY_DIR))) {
459 while((ent = readdir(dir))) {
460 try_load_key(ast_config_AST_KEY_DIR, ent->d_name, ifd, ofd, ¬e);
464 ast_log(LOG_WARNING, "Unable to open key directory '%s'\n", ast_config_AST_KEY_DIR);
467 ast_log(LOG_NOTICE, "Please run the command 'init keys' to enter the passcodes for the keys\n");
469 /* Delete any keys that are no longer present */
470 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&keys, key, list) {
472 ast_debug(1, "Deleting key %s type %d\n", key->name, key->ktype);
473 AST_RWLIST_REMOVE_CURRENT(list);
479 AST_RWLIST_TRAVERSE_SAFE_END;
481 AST_RWLIST_UNLOCK(&keys);
484 static void md52sum(char *sum, unsigned char *md5)
487 for (x = 0; x < 16; x++)
488 sum += sprintf(sum, "%02x", *(md5++));
492 * \brief show the list of RSA keys
493 * \param e CLI command
495 * \param a list of CLI arguments
496 * \return CLI_SUCCESS
498 static char *handle_cli_keys_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
500 #define FORMAT "%-18s %-8s %-16s %-33s\n"
503 char sum[16 * 2 + 1];
508 e->command = "keys show";
511 " Displays information about RSA keys known by Asterisk\n";
517 ast_cli(a->fd, FORMAT, "Key Name", "Type", "Status", "Sum");
518 ast_cli(a->fd, FORMAT, "------------------", "--------", "----------------", "--------------------------------");
520 AST_RWLIST_RDLOCK(&keys);
521 AST_RWLIST_TRAVERSE(&keys, key, list) {
522 md52sum(sum, key->digest);
523 ast_cli(a->fd, FORMAT, key->name,
524 (key->ktype & 0xf) == AST_KEY_PUBLIC ? "PUBLIC" : "PRIVATE",
525 key->ktype & KEY_NEEDS_PASSCODE ? "[Needs Passcode]" : "[Loaded]", sum);
528 AST_RWLIST_UNLOCK(&keys);
530 ast_cli(a->fd, "\n%d known RSA keys.\n", count_keys);
538 * \brief initialize all RSA keys
539 * \param e CLI command
541 * \param a list of CLI arguments
542 * \return CLI_SUCCESS
544 static char *handle_cli_keys_init(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
548 char *kn, tmp[256] = "";
552 e->command = "keys init";
555 " Initializes private keys (by reading in pass code from\n"
563 return CLI_SHOWUSAGE;
565 AST_RWLIST_WRLOCK(&keys);
566 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&keys, key, list) {
567 /* Reload keys that need pass codes now */
568 if (key->ktype & KEY_NEEDS_PASSCODE) {
569 kn = key->fn + strlen(ast_config_AST_KEY_DIR) + 1;
570 ast_copy_string(tmp, kn, sizeof(tmp));
571 try_load_key(ast_config_AST_KEY_DIR, tmp, a->fd, a->fd, &ign);
574 AST_RWLIST_TRAVERSE_SAFE_END
575 AST_RWLIST_UNLOCK(&keys);
580 static struct ast_cli_entry cli_crypto[] = {
581 AST_CLI_DEFINE(handle_cli_keys_show, "Displays RSA key information"),
582 AST_CLI_DEFINE(handle_cli_keys_init, "Initialize RSA key passcodes")
585 /*! \brief initialise the res_crypto module */
586 static int crypto_init(void)
588 ast_cli_register_multiple(cli_crypto, ARRAY_LEN(cli_crypto));
590 /* Install ourselves into stubs */
591 ast_key_get = __ast_key_get;
592 ast_check_signature = __ast_check_signature;
593 ast_check_signature_bin = __ast_check_signature_bin;
594 ast_sign = __ast_sign;
595 ast_sign_bin = __ast_sign_bin;
596 ast_encrypt_bin = __ast_encrypt_bin;
597 ast_decrypt_bin = __ast_decrypt_bin;
601 static int reload(void)
607 static int load_module(void)
610 if (ast_opt_init_keys)
611 crypto_load(STDIN_FILENO, STDOUT_FILENO);
614 return AST_MODULE_LOAD_SUCCESS;
617 static int unload_module(void)
619 /* Can't unload this once we're loaded */
623 /* needs usecount semantics defined */
624 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Cryptographic Digital Signatures",
626 .unload = unload_module,