From 465837dd7f7b727d489b354e4b75489dd49fd6e3 Mon Sep 17 00:00:00 2001 From: Guus Sliepen Date: Sun, 20 May 2007 22:28:49 +0000 Subject: [PATCH] Parse PEM RSA keys ourself, and use libgcrypt to do RSA encryption and decryption. --- configure.in | 1 + src/Makefile.am | 8 +- src/connection.h | 6 +- src/net_setup.c | 138 ++++------------------- src/protocol_auth.c | 22 ++-- src/rsa.c | 269 ++++++++++++++++++++++++++++++++++++++++++++ src/rsa.h | 40 +++++++ 7 files changed, 355 insertions(+), 129 deletions(-) create mode 100644 src/rsa.c create mode 100644 src/rsa.h diff --git a/configure.in b/configure.in index 99f28ed7..cbf6bf23 100644 --- a/configure.in +++ b/configure.in @@ -145,6 +145,7 @@ AC_CACHE_SAVE dnl These are defined in files in m4/ +AM_PATH_LIBGCRYPT([], [], [AC_MSG_ERROR([Libgcrypt not found.]); break]) tinc_OPENSSL tinc_ZLIB tinc_LZO diff --git a/src/Makefile.am b/src/Makefile.am index 41b25980..5259ff7a 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -7,7 +7,7 @@ EXTRA_DIST = linux/device.c bsd/device.c solaris/device.c cygwin/device.c mingw/ tincd_SOURCES = conf.c connection.c control.c edge.c graph.c logger.c meta.c net.c net_packet.c net_setup.c \ net_socket.c netutl.c node.c process.c protocol.c protocol_auth.c protocol_edge.c protocol_misc.c \ - protocol_key.c protocol_subnet.c route.c subnet.c tincd.c + protocol_key.c protocol_subnet.c route.c rsa.c subnet.c tincd.c tincctl_SOURCES = tincctl.c @@ -18,12 +18,13 @@ DEFAULT_INCLUDES = INCLUDES = @INCLUDES@ -I$(top_builddir) -I$(top_srcdir)/lib noinst_HEADERS = conf.h connection.h control.h device.h edge.h graph.h logger.h meta.h net.h netutl.h node.h process.h \ - protocol.h route.h subnet.h + protocol.h route.h rsa.h subnet.h LIBS = @LIBS@ @LIBINTL@ tincd_LDADD = \ - $(top_builddir)/lib/libvpn.a + $(top_builddir)/lib/libvpn.a \ + $(LIBGCRYPT_LIBS) tincctl_LDADD = \ $(top_builddir)/lib/libvpn.a @@ -31,6 +32,7 @@ tincctl_LDADD = \ localedir = $(datadir)/locale AM_CFLAGS = @CFLAGS@ -DCONFDIR=\"$(sysconfdir)\" -DLOCALEDIR=\"$(localedir)\" -DLOCALSTATEDIR=\"$(localstatedir)\" +tinc_CPPFLAGS = $(LIBGCRYPT_CFLAGS) dist-hook: rm -f `find . -type l` diff --git a/src/connection.h b/src/connection.h index 2426a220..e5cd6895 100644 --- a/src/connection.h +++ b/src/connection.h @@ -23,11 +23,12 @@ #ifndef __TINC_CONNECTION_H__ #define __TINC_CONNECTION_H__ -#include +//#include #include #include +#include "rsa.h" #include "splay_tree.h" #define OPTION_INDIRECT 0x0001 @@ -72,7 +73,8 @@ typedef struct connection_t { struct node_t *node; /* node associated with the other end */ struct edge_t *edge; /* edge associated with this connection */ - RSA *rsa_key; /* his public/private key */ + //RSA *rsa_key; /* his public/private key */ + struct rsa_key_t rsa_key; /* his public/private key */ const EVP_CIPHER *incipher; /* Cipher he will use to send data to us */ const EVP_CIPHER *outcipher; /* Cipher we will use to send data to him */ EVP_CIPHER_CTX *inctx; /* Context of encrypted meta data that will come from him to us */ diff --git a/src/net_setup.c b/src/net_setup.c index b8fb4f02..94e39872 100644 --- a/src/net_setup.c +++ b/src/net_setup.c @@ -22,6 +22,8 @@ #include "system.h" +#include + #include #include #include @@ -40,6 +42,7 @@ #include "process.h" #include "protocol.h" #include "route.h" +#include "rsa.h" #include "subnet.h" #include "utils.h" #include "xalloc.h" @@ -50,125 +53,38 @@ static struct event device_ev; bool read_rsa_public_key(connection_t *c) { FILE *fp; char *fname; - char *key; + bool result; cp(); - if(!c->rsa_key) { - c->rsa_key = RSA_new(); -// RSA_blinding_on(c->rsa_key, NULL); - } + if(!get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname)) + asprintf(&fname, "%s/hosts/%s", confbase, c->name); - /* First, check for simple PublicKey statement */ + fp = fopen(fname, "r"); - if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &key)) { - BN_hex2bn(&c->rsa_key->n, key); - BN_hex2bn(&c->rsa_key->e, "FFFF"); - free(key); - return true; - } - - /* Else, check for PublicKeyFile statement and read it */ - - if(get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname)) { - fp = fopen(fname, "r"); - - if(!fp) { - logger(LOG_ERR, _("Error reading RSA public key file `%s': %s"), - fname, strerror(errno)); - free(fname); - return false; - } - - free(fname); - c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL); - fclose(fp); - - if(c->rsa_key) - return true; /* Woohoo. */ - - /* If it fails, try PEM_read_RSA_PUBKEY. */ - fp = fopen(fname, "r"); - - if(!fp) { - logger(LOG_ERR, _("Error reading RSA public key file `%s': %s"), - fname, strerror(errno)); - free(fname); - return false; - } - - free(fname); - c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL); - fclose(fp); - - if(c->rsa_key) { -// RSA_blinding_on(c->rsa_key, NULL); - return true; - } - - logger(LOG_ERR, _("Reading RSA public key file `%s' failed: %s"), + if(!fp) { + logger(LOG_ERR, _("Error reading RSA public key file `%s': %s"), fname, strerror(errno)); + free(fname); return false; } - /* Else, check if a harnessed public key is in the config file */ - - asprintf(&fname, "%s/hosts/%s", confbase, c->name); - fp = fopen(fname, "r"); - - if(fp) { - c->rsa_key = PEM_read_RSAPublicKey(fp, &c->rsa_key, NULL, NULL); - fclose(fp); - } + result = read_pem_rsa_public_key(fp, &c->rsa_key); + fclose(fp); + if(!result) + logger(LOG_ERR, _("Reading RSA public key file `%s' failed: %s"), fname, strerror(errno)); free(fname); - - if(c->rsa_key) - return true; - - /* Try again with PEM_read_RSA_PUBKEY. */ - - asprintf(&fname, "%s/hosts/%s", confbase, c->name); - fp = fopen(fname, "r"); - - if(fp) { - c->rsa_key = PEM_read_RSA_PUBKEY(fp, &c->rsa_key, NULL, NULL); -// RSA_blinding_on(c->rsa_key, NULL); - fclose(fp); - } - - free(fname); - - if(c->rsa_key) - return true; - - logger(LOG_ERR, _("No public key for %s specified!"), c->name); - - return false; + return result; } -bool read_rsa_private_key(void) { +bool read_rsa_private_key() { FILE *fp; - char *fname, *key, *pubkey; - struct stat s; + char *fname; + bool result; cp(); - if(get_config_string(lookup_config(config_tree, "PrivateKey"), &key)) { - if(!get_config_string(lookup_config(myself->connection->config_tree, "PublicKey"), &pubkey)) { - logger(LOG_ERR, _("PrivateKey used but no PublicKey found!")); - return false; - } - myself->connection->rsa_key = RSA_new(); -// RSA_blinding_on(myself->connection->rsa_key, NULL); - BN_hex2bn(&myself->connection->rsa_key->d, key); - BN_hex2bn(&myself->connection->rsa_key->n, pubkey); - BN_hex2bn(&myself->connection->rsa_key->e, "FFFF"); - free(key); - free(pubkey); - return true; - } - if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname)) asprintf(&fname, "%s/rsa_key.priv", confbase); @@ -182,9 +98,10 @@ bool read_rsa_private_key(void) { } #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN) + struct stat s; + if(fstat(fileno(fp), &s)) { - logger(LOG_ERR, _("Could not stat RSA private key file `%s': %s'"), - fname, strerror(errno)); + logger(LOG_ERR, _("Could not stat RSA private key file `%s': %s'"), fname, strerror(errno)); free(fname); return false; } @@ -193,18 +110,13 @@ bool read_rsa_private_key(void) { logger(LOG_WARNING, _("Warning: insecure file permissions for RSA private key file `%s'!"), fname); #endif - myself->connection->rsa_key = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL); + result = read_pem_rsa_private_key(fp, &myself->connection->rsa_key); fclose(fp); - if(!myself->connection->rsa_key) { - logger(LOG_ERR, _("Reading RSA private key file `%s' failed: %s"), - fname, strerror(errno)); - free(fname); - return false; - } - + if(!result) + logger(LOG_ERR, _("Reading RSA private key file `%s' failed: %s"), fname, strerror(errno)); free(fname); - return true; + return result; } static struct event keyexpire_event; diff --git a/src/protocol_auth.c b/src/protocol_auth.c index 31dae675..499e6869 100644 --- a/src/protocol_auth.c +++ b/src/protocol_auth.c @@ -37,6 +37,7 @@ #include "netutl.h" #include "node.h" #include "protocol.h" +#include "rsa.h" #include "utils.h" #include "xalloc.h" @@ -116,12 +117,12 @@ bool id_h(connection_t *c, char *request) { bool send_metakey(connection_t *c) { char *buffer; - int len; + unsigned int len; bool x; cp(); - len = RSA_size(c->rsa_key); + len = get_rsa_size(&c->rsa_key); /* Allocate buffers for the meta key */ @@ -163,7 +164,7 @@ bool send_metakey(connection_t *c) { with a length equal to that of the modulus of the RSA key. */ - if(RSA_public_encrypt(len, (unsigned char *)c->outkey, (unsigned char *)buffer, c->rsa_key, RSA_NO_PADDING) != len) { + if(!rsa_public_encrypt(len, (unsigned char *)c->outkey, (unsigned char *)buffer, &c->rsa_key)) { logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"), c->name, c->hostname); return false; @@ -212,7 +213,7 @@ bool metakey_h(connection_t *c, char *request) { return false; } - len = RSA_size(myself->connection->rsa_key); + len = get_rsa_size(&myself->connection->rsa_key); /* Check if the length of the meta key is all right */ @@ -235,9 +236,8 @@ bool metakey_h(connection_t *c, char *request) { /* Decrypt the meta key */ - if(RSA_private_decrypt(len, (unsigned char *)buffer, (unsigned char *)c->inkey, myself->connection->rsa_key, RSA_NO_PADDING) != len) { /* See challenge() */ - logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"), - c->name, c->hostname); + if(!rsa_private_decrypt(len, (unsigned char *)buffer, (unsigned char *)c->inkey, &myself->connection->rsa_key)) { + logger(LOG_ERR, _("Error during encryption of meta key for %s (%s)"), c->name, c->hostname); return false; } @@ -306,7 +306,7 @@ bool send_challenge(connection_t *c) { /* CHECKME: what is most reasonable value for len? */ - len = RSA_size(c->rsa_key); + len = get_rsa_size(&c->rsa_key); /* Allocate buffers for the challenge */ @@ -341,7 +341,7 @@ bool challenge_h(connection_t *c, char *request) { return false; } - len = RSA_size(myself->connection->rsa_key); + len = get_rsa_size(&myself->connection->rsa_key); /* Check if the length of the challenge is all right */ @@ -376,7 +376,7 @@ bool send_chal_reply(connection_t *c) { /* Calculate the hash from the challenge we received */ if(!EVP_DigestInit(&ctx, c->indigest) - || !EVP_DigestUpdate(&ctx, c->mychallenge, RSA_size(myself->connection->rsa_key)) + || !EVP_DigestUpdate(&ctx, c->mychallenge, get_rsa_size(&myself->connection->rsa_key)) || !EVP_DigestFinal(&ctx, (unsigned char *)hash, NULL)) { logger(LOG_ERR, _("Error during calculation of response for %s (%s): %s"), c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL)); @@ -421,7 +421,7 @@ bool chal_reply_h(connection_t *c, char *request) { /* Calculate the hash from the challenge we sent */ if(!EVP_DigestInit(&ctx, c->outdigest) - || !EVP_DigestUpdate(&ctx, c->hischallenge, RSA_size(c->rsa_key)) + || !EVP_DigestUpdate(&ctx, c->hischallenge, get_rsa_size(&c->rsa_key)) || !EVP_DigestFinal(&ctx, (unsigned char *)myhash, NULL)) { logger(LOG_ERR, _("Error during calculation of response from %s (%s): %s"), c->name, c->hostname, ERR_error_string(ERR_get_error(), NULL)); diff --git a/src/rsa.c b/src/rsa.c new file mode 100644 index 00000000..486f354c --- /dev/null +++ b/src/rsa.c @@ -0,0 +1,269 @@ +/* + rsa.c -- RSA key handling + Copyright (C) 2007 Guus Sliepen + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + $Id$ +*/ + +#include "system.h" + +#include + +#include "logger.h" +#include "rsa.h" + +// Base64 encoding/decoding tables + +static const uint8_t b64d[128] = { + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0x3e, 0xff, 0xff, 0xff, 0x3f, + 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, + 0x3a, 0x3b, 0x3c, 0x3d, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, + 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, + 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, + 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x19, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, + 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, + 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, + 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, + 0x31, 0x32, 0x33, 0xff, 0xff, 0xff, + 0xff, 0xff +}; + +static const char b64e[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +// PEM encoding/decoding functions + +static bool pem_decode(FILE *fp, const char *header, uint8_t *buf, size_t size, size_t *outsize) { + bool decode = false; + char line[1024]; + uint16_t word = 0; + int shift = 10; + size_t i, j = 0; + + while(!feof(fp)) { + if(!fgets(line, sizeof line, fp)) + return false; + + if(!decode && !strncmp(line, "-----BEGIN ", 11)) { + if(!strncmp(line + 11, header, strlen(header))) + decode = true; + continue; + } + + if(decode && !strncmp(line, "-----END", 8)) { + break; + } + + if(!decode) + continue; + + for(i = 0; line[i] >= ' '; i++) { + if(line[i] >= 128 || line[i] < 0 || b64d[(int)line[i]] == 0xff) + break; + word |= b64d[(int)line[i]] << shift; + shift -= 6; + if(shift <= 2) { + if(j > size) { + errno = ENOMEM; + return false; + } + + buf[j++] = word >> 8; + word <<= 8; + shift += 8; + } + } + } + + if(outsize) + *outsize = j; + return true; +} + + +// BER decoding functions + +static int ber_read_id(unsigned char **p, size_t *buflen) { + if(*buflen <= 0) + return -1; + + if((**p & 0x1f) == 0x1f) { + int id = 0; + bool more; + while(*buflen > 0) { + id <<= 7; + id |= **p & 0x7f; + more = *(*p)++ & 0x80; + (*buflen)--; + if(!more) + break; + } + return id; + } else { + (*buflen)--; + return *(*p)++ & 0x1f; + } +} + +static size_t ber_read_len(unsigned char **p, size_t *buflen) { + if(*buflen <= 0) + return -1; + + if(**p & 0x80) { + size_t result = 0; + int len = *(*p)++ & 0x7f; + (*buflen)--; + if(len > *buflen) + return 0; + + while(len--) { + result <<= 8; + result |= *(*p)++; + (*buflen)--; + } + + return result; + } else { + (*buflen)--; + return *(*p)++; + } +} + + +static bool ber_read_sequence(unsigned char **p, size_t *buflen, size_t *result) { + int tag = ber_read_id(p, buflen); + size_t len = ber_read_len(p, buflen); + + if(tag == 0x10) { + if(result) + *result = len; + return true; + } else { + return false; + } +} + +static bool ber_read_mpi(unsigned char **p, size_t *buflen, gcry_mpi_t *mpi) { + int tag = ber_read_id(p, buflen); + size_t len = ber_read_len(p, buflen); + gcry_error_t err = 0; + + if(tag != 0x02 || len > *buflen) + return false; + + if(mpi) + err = gcry_mpi_scan(mpi, GCRYMPI_FMT_USG, *p, len, NULL); + + *p += len; + *buflen -= len; + + return mpi ? !err : true; +} + +// Read PEM RSA keys + +bool read_pem_rsa_public_key(FILE *fp, rsa_key_t *key) { + uint8_t derbuf[8096], *derp = derbuf; + size_t derlen; + + if(!pem_decode(fp, "RSA PUBLIC KEY", derbuf, sizeof derbuf, &derlen)) { + logger(LOG_ERR, _("Unable to read RSA public key: %s"), strerror(errno)); + return NULL; + } + + if(!ber_read_sequence(&derp, &derlen, NULL) + || !ber_read_mpi(&derp, &derlen, &key->n) + || !ber_read_mpi(&derp, &derlen, &key->e) + || derlen) { + logger(LOG_ERR, _("Error while decoding RSA public key")); + return NULL; + } + + return true; +} + +bool read_pem_rsa_private_key(FILE *fp, rsa_key_t *key) { + uint8_t derbuf[8096], *derp = derbuf; + size_t derlen; + + if(!pem_decode(fp, "RSA PRIVATE KEY", derbuf, sizeof derbuf, &derlen)) { + logger(LOG_ERR, _("Unable to read RSA private key: %s"), strerror(errno)); + return NULL; + } + + if(!ber_read_sequence(&derp, &derlen, NULL) + || !ber_read_mpi(&derp, &derlen, NULL) + || !ber_read_mpi(&derp, &derlen, &key->n) + || !ber_read_mpi(&derp, &derlen, &key->e) + || !ber_read_mpi(&derp, &derlen, &key->d) + || !ber_read_mpi(&derp, &derlen, NULL) // p + || !ber_read_mpi(&derp, &derlen, NULL) // q + || !ber_read_mpi(&derp, &derlen, NULL) + || !ber_read_mpi(&derp, &derlen, NULL) + || !ber_read_mpi(&derp, &derlen, NULL) // u + || derlen) { + logger(LOG_ERR, _("Error while decoding RSA private key")); + return NULL; + } + + return true; +} + +unsigned int get_rsa_size(rsa_key_t *key) { + return (gcry_mpi_get_nbits(key->n) + 7) / 8; +} + +/* Well, libgcrypt has functions to handle RSA keys, but they suck. + * So we just use libgcrypt's mpi functions, and do the math ourselves. + */ + +// TODO: get rid of this macro, properly clean up gcry_ structures after use +#define check(foo) { gcry_error_t err = (foo); if(err) {logger(LOG_ERR, "gcrypt error %s/%s at %s:%d\n", gcry_strsource(err), gcry_strerror(err), __FILE__, __LINE__); return false; }} + +bool rsa_public_encrypt(size_t len, void *in, void *out, rsa_key_t *key) { + gcry_mpi_t inmpi; + check(gcry_mpi_scan(&inmpi, GCRYMPI_FMT_USG, in, len, NULL)); + + gcry_mpi_t outmpi = gcry_mpi_new(len * 8); + gcry_mpi_powm(outmpi, inmpi, key->e, key->n); + + check(gcry_mpi_print(GCRYMPI_FMT_USG, out,len, NULL, outmpi)); + + return true; +} + +bool rsa_private_decrypt(size_t len, void *in, void *out, rsa_key_t *key) { + gcry_mpi_t inmpi; + check(gcry_mpi_scan(&inmpi, GCRYMPI_FMT_USG, in, len, NULL)); + + gcry_mpi_t outmpi = gcry_mpi_new(len * 8); + gcry_mpi_powm(outmpi, inmpi, key->d, key->n); + + check(gcry_mpi_print(GCRYMPI_FMT_USG, out,len, NULL, outmpi)); + + return true; +} diff --git a/src/rsa.h b/src/rsa.h new file mode 100644 index 00000000..bcb795e0 --- /dev/null +++ b/src/rsa.h @@ -0,0 +1,40 @@ +/* + rsa.h -- RSA key handling + Copyright (C) 2007 Guus Sliepen + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + + $Id$ +*/ + +#ifndef __TINC_RSA_H__ +#define __TINC_RSA_H__ + +#include + +typedef struct rsa_key_t { + gcry_mpi_t n; + gcry_mpi_t e; + gcry_mpi_t d; +} rsa_key_t; + +extern bool read_pem_rsa_public_key(FILE *fp, struct rsa_key_t *key); +extern bool read_pem_rsa_private_key(FILE *fp, struct rsa_key_t *key); +extern unsigned int get_rsa_size(struct rsa_key_t *key); +extern bool rsa_public_encrypt(size_t len, void *in, void *out, struct rsa_key_t *key); +extern bool rsa_private_decrypt(size_t len, void *in, void *out, struct rsa_key_t *key); + + +#endif