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 "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 write(key
->outfd
, prompt
, strlen(prompt
));
110 memset(buf
, 0, sizeof(buf
));
111 tmp
= ast_hide_password(key
->infd
);
112 memset(buf
, 0, size
);
113 res
= read(key
->infd
, buf
, size
);
114 ast_restore_tty(key
->infd
, tmp
);
115 if (buf
[strlen(buf
) -1] == '\n')
116 buf
[strlen(buf
) - 1] = '\0';
121 * \brief return the ast_key structure for name
124 static struct ast_key
*__ast_key_get(const char *kname
, int ktype
)
128 AST_RWLIST_RDLOCK(&keys
);
129 AST_RWLIST_TRAVERSE(&keys
, key
, list
) {
130 if (!strcmp(kname
, key
->name
) &&
131 (ktype
== key
->ktype
))
134 AST_RWLIST_UNLOCK(&keys
);
140 * \brief load RSA key from file
141 * \param dir directory string
142 * \param fname name of file
143 * \param ifd incoming file descriptor
144 * \param ofd outgoing file descriptor
146 * \retval key on success.
147 * \retval NULL on failure.
149 static struct ast_key
*try_load_key(const char *dir
, const char *fname
, int ifd
, int ofd
, int *not2
)
151 int ktype
= 0, found
= 0;
152 char *c
= NULL
, ffname
[256];
153 unsigned char digest
[16];
155 struct MD5Context md5
;
157 static int notice
= 0;
159 /* Make sure its name is a public or private key */
160 if ((c
= strstr(fname
, ".pub")) && !strcmp(c
, ".pub"))
161 ktype
= AST_KEY_PUBLIC
;
162 else if ((c
= strstr(fname
, ".key")) && !strcmp(c
, ".key"))
163 ktype
= AST_KEY_PRIVATE
;
167 /* Get actual filename */
168 snprintf(ffname
, sizeof(ffname
), "%s/%s", dir
, fname
);
171 if (!(f
= fopen(ffname
, "r"))) {
172 ast_log(LOG_WARNING
, "Unable to open key file %s: %s\n", ffname
, strerror(errno
));
178 /* Calculate a "whatever" quality md5sum of the key */
180 fgets(buf
, sizeof(buf
), f
);
182 MD5Update(&md5
, (unsigned char *) buf
, strlen(buf
));
184 MD5Final(digest
, &md5
);
186 /* Look for an existing key */
187 AST_RWLIST_TRAVERSE(&keys
, key
, list
) {
188 if (!strcasecmp(key
->fn
, ffname
))
193 /* If the MD5 sum is the same, and it isn't awaiting a passcode
194 then this is far enough */
195 if (!memcmp(digest
, key
->digest
, 16) &&
196 !(key
->ktype
& KEY_NEEDS_PASSCODE
)) {
201 /* Preserve keytype */
203 /* Recycle the same structure */
208 /* Make fname just be the normal name now */
211 if (!(key
= ast_calloc(1, sizeof(*key
)))) {
216 /* First the filename */
217 ast_copy_string(key
->fn
, ffname
, sizeof(key
->fn
));
219 ast_copy_string(key
->name
, fname
, sizeof(key
->name
));
221 /* Yes, assume we're going to be deleted */
223 /* Keep the key type */
224 memcpy(key
->digest
, digest
, 16);
225 /* Can I/O takes the FD we're given */
228 /* Reset the file back to the beginning */
230 /* Now load the key with the right method */
231 if (ktype
== AST_KEY_PUBLIC
)
232 key
->rsa
= PEM_read_RSA_PUBKEY(f
, NULL
, pw_cb
, key
);
234 key
->rsa
= PEM_read_RSAPrivateKey(f
, NULL
, pw_cb
, key
);
237 if (RSA_size(key
->rsa
) == 128) {
238 /* Key loaded okay */
239 key
->ktype
&= ~KEY_NEEDS_PASSCODE
;
240 ast_verb(3, "Loaded %s key '%s'\n", key
->ktype
== AST_KEY_PUBLIC
? "PUBLIC" : "PRIVATE", key
->name
);
241 ast_debug(1, "Key '%s' loaded OK\n", key
->name
);
244 ast_log(LOG_NOTICE
, "Key '%s' is not expected size.\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 (!ast_opt_init_keys
)
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 /* If this is a new key add it to the list */
267 AST_RWLIST_INSERT_TAIL(&keys
, key
, list
);
273 * \brief signs outgoing message with public key
276 static int __ast_sign_bin(struct ast_key
*key
, const char *msg
, int msglen
, unsigned char *dsig
)
278 unsigned char digest
[20];
279 unsigned int siglen
= 128;
282 if (key
->ktype
!= AST_KEY_PRIVATE
) {
283 ast_log(LOG_WARNING
, "Cannot sign with a public key\n");
287 /* Calculate digest of message */
288 SHA1((unsigned char *)msg
, msglen
, digest
);
290 /* Verify signature */
291 if (!(res
= RSA_sign(NID_sha1
, digest
, sizeof(digest
), dsig
, &siglen
, key
->rsa
))) {
292 ast_log(LOG_WARNING
, "RSA Signature (key %s) failed\n", key
->name
);
297 ast_log(LOG_WARNING
, "Unexpected signature length %d, expecting %d\n", (int)siglen
, (int)128);
306 * \brief decrypt a message
307 * \see ast_decrypt_bin
309 static int __ast_decrypt_bin(unsigned char *dst
, const unsigned char *src
, int srclen
, struct ast_key
*key
)
313 if (key
->ktype
!= AST_KEY_PRIVATE
) {
314 ast_log(LOG_WARNING
, "Cannot decrypt with a public key\n");
319 ast_log(LOG_NOTICE
, "Tried to decrypt something not a multiple of 128 bytes\n");
324 /* Process chunks 128 bytes at a time */
325 if ((res
= RSA_private_decrypt(128, src
, dst
, key
->rsa
, RSA_PKCS1_OAEP_PADDING
)) < 0)
337 * \brief encrypt a message
338 * \see ast_encrypt_bin
340 static int __ast_encrypt_bin(unsigned char *dst
, const unsigned char *src
, int srclen
, struct ast_key
*key
)
342 int res
, bytes
, pos
= 0;
344 if (key
->ktype
!= AST_KEY_PUBLIC
) {
345 ast_log(LOG_WARNING
, "Cannot encrypt with a private key\n");
351 if (bytes
> 128 - 41)
353 /* Process chunks 128-41 bytes at a time */
354 if ((res
= RSA_public_encrypt(bytes
, src
, dst
, key
->rsa
, RSA_PKCS1_OAEP_PADDING
)) != 128) {
355 ast_log(LOG_NOTICE
, "How odd, encrypted size is %d\n", res
);
367 * \brief wrapper for __ast_sign_bin then base64 encode it
370 static int __ast_sign(struct ast_key
*key
, char *msg
, char *sig
)
372 unsigned char dsig
[128];
373 int siglen
= sizeof(dsig
), res
;
375 if (!(res
= ast_sign_bin(key
, msg
, strlen(msg
), dsig
)))
376 /* Success -- encode (256 bytes max as documented) */
377 ast_base64encode(sig
, dsig
, siglen
, 256);
383 * \brief check signature of a message
384 * \see ast_check_signature_bin
386 static int __ast_check_signature_bin(struct ast_key
*key
, const char *msg
, int msglen
, const unsigned char *dsig
)
388 unsigned char digest
[20];
391 if (key
->ktype
!= AST_KEY_PUBLIC
) {
392 /* Okay, so of course you really *can* but for our purposes
393 we're going to say you can't */
394 ast_log(LOG_WARNING
, "Cannot check message signature with a private key\n");
398 /* Calculate digest of message */
399 SHA1((unsigned char *)msg
, msglen
, digest
);
401 /* Verify signature */
402 if (!(res
= RSA_verify(NID_sha1
, digest
, sizeof(digest
), (unsigned char *)dsig
, 128, key
->rsa
))) {
403 ast_debug(1, "Key failed verification: %s\n", key
->name
);
412 * \brief base64 decode then sent to __ast_check_signature_bin
413 * \see ast_check_signature
415 static int __ast_check_signature(struct ast_key
*key
, const char *msg
, const char *sig
)
417 unsigned char dsig
[128];
420 /* Decode signature */
421 if ((res
= ast_base64decode(dsig
, sig
, sizeof(dsig
))) != sizeof(dsig
)) {
422 ast_log(LOG_WARNING
, "Signature improper length (expect %d, got %d)\n", (int)sizeof(dsig
), (int)res
);
426 res
= ast_check_signature_bin(key
, msg
, strlen(msg
), dsig
);
432 * \brief refresh RSA keys from file
433 * \param ifd file descriptor
434 * \param ofd file descriptor
437 static void crypto_load(int ifd
, int ofd
)
444 AST_RWLIST_WRLOCK(&keys
);
446 /* Mark all keys for deletion */
447 AST_RWLIST_TRAVERSE(&keys
, key
, list
) {
452 if ((dir
= opendir(ast_config_AST_KEY_DIR
))) {
453 while((ent
= readdir(dir
))) {
454 try_load_key(ast_config_AST_KEY_DIR
, ent
->d_name
, ifd
, ofd
, ¬e
);
458 ast_log(LOG_WARNING
, "Unable to open key directory '%s'\n", ast_config_AST_KEY_DIR
);
461 ast_log(LOG_NOTICE
, "Please run the command 'init keys' to enter the passcodes for the keys\n");
463 /* Delete any keys that are no longer present */
464 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&keys
, key
, list
) {
466 ast_debug(1, "Deleting key %s type %d\n", key
->name
, key
->ktype
);
467 AST_RWLIST_REMOVE_CURRENT(list
);
473 AST_RWLIST_TRAVERSE_SAFE_END
;
475 AST_RWLIST_UNLOCK(&keys
);
478 static void md52sum(char *sum
, unsigned char *md5
)
481 for (x
= 0; x
< 16; x
++)
482 sum
+= sprintf(sum
, "%02x", *(md5
++));
486 * \brief show the list of RSA keys
487 * \param e CLI command
489 * \param a list of CLI arguments
490 * \return CLI_SUCCESS
492 static char *handle_cli_keys_show(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
494 #define FORMAT "%-18s %-8s %-16s %-33s\n"
497 char sum
[16 * 2 + 1];
502 e
->command
= "keys show";
505 " Displays information about RSA keys known by Asterisk\n";
511 ast_cli(a
->fd
, FORMAT
, "Key Name", "Type", "Status", "Sum");
512 ast_cli(a
->fd
, FORMAT
, "------------------", "--------", "----------------", "--------------------------------");
514 AST_RWLIST_RDLOCK(&keys
);
515 AST_RWLIST_TRAVERSE(&keys
, key
, list
) {
516 md52sum(sum
, key
->digest
);
517 ast_cli(a
->fd
, FORMAT
, key
->name
,
518 (key
->ktype
& 0xf) == AST_KEY_PUBLIC
? "PUBLIC" : "PRIVATE",
519 key
->ktype
& KEY_NEEDS_PASSCODE
? "[Needs Passcode]" : "[Loaded]", sum
);
522 AST_RWLIST_UNLOCK(&keys
);
524 ast_cli(a
->fd
, "\n%d known RSA keys.\n", count_keys
);
532 * \brief initialize all RSA keys
533 * \param e CLI command
535 * \param a list of CLI arguments
536 * \return CLI_SUCCESS
538 static char *handle_cli_keys_init(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
542 char *kn
, tmp
[256] = "";
546 e
->command
= "keys init";
549 " Initializes private keys (by reading in pass code from\n"
557 return CLI_SHOWUSAGE
;
559 AST_RWLIST_WRLOCK(&keys
);
560 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&keys
, key
, list
) {
561 /* Reload keys that need pass codes now */
562 if (key
->ktype
& KEY_NEEDS_PASSCODE
) {
563 kn
= key
->fn
+ strlen(ast_config_AST_KEY_DIR
) + 1;
564 ast_copy_string(tmp
, kn
, sizeof(tmp
));
565 try_load_key(ast_config_AST_KEY_DIR
, tmp
, a
->fd
, a
->fd
, &ign
);
568 AST_RWLIST_TRAVERSE_SAFE_END
569 AST_RWLIST_UNLOCK(&keys
);
574 static struct ast_cli_entry cli_crypto
[] = {
575 AST_CLI_DEFINE(handle_cli_keys_show
, "Displays RSA key information"),
576 AST_CLI_DEFINE(handle_cli_keys_init
, "Initialize RSA key passcodes")
579 /*! \brief initialise the res_crypto module */
580 static int crypto_init(void)
583 ERR_load_crypto_strings();
584 ast_cli_register_multiple(cli_crypto
, sizeof(cli_crypto
) / sizeof(struct ast_cli_entry
));
586 /* Install ourselves into stubs */
587 ast_key_get
= __ast_key_get
;
588 ast_check_signature
= __ast_check_signature
;
589 ast_check_signature_bin
= __ast_check_signature_bin
;
590 ast_sign
= __ast_sign
;
591 ast_sign_bin
= __ast_sign_bin
;
592 ast_encrypt_bin
= __ast_encrypt_bin
;
593 ast_decrypt_bin
= __ast_decrypt_bin
;
597 static int reload(void)
603 static int load_module(void)
606 if (ast_opt_init_keys
)
607 crypto_load(STDIN_FILENO
, STDOUT_FILENO
);
610 return AST_MODULE_LOAD_SUCCESS
;
613 static int unload_module(void)
615 /* Can't unload this once we're loaded */
619 /* needs usecount semantics defined */
620 AST_MODULE_INFO(ASTERISK_GPL_KEY
, AST_MODFLAG_DEFAULT
, "Cryptographic Digital Signatures",
622 .unload
= unload_module
,