Parse PEM RSA keys ourself, and use libgcrypt to do RSA encryption and decryption.
[tinc] / src / rsa.c
1 /*
2     rsa.c -- RSA key handling
3     Copyright (C) 2007 Guus Sliepen <guus@tinc-vpn.org>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19     $Id$
20 */
21
22 #include "system.h"
23
24 #include <gcrypt.h>
25
26 #include "logger.h"
27 #include "rsa.h"
28
29 // Base64 encoding/decoding tables
30
31 static const uint8_t b64d[128] = {
32   0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
33   0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
34   0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
35   0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
36   0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
37   0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
38   0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
39   0xff, 0x3e, 0xff, 0xff, 0xff, 0x3f,
40   0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
41   0x3a, 0x3b, 0x3c, 0x3d, 0xff, 0xff,
42   0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
43   0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
44   0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
45   0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12,
46   0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
47   0x19, 0xff, 0xff, 0xff, 0xff, 0xff,
48   0xff, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e,
49   0x1f, 0x20, 0x21, 0x22, 0x23, 0x24,
50   0x25, 0x26, 0x27, 0x28, 0x29, 0x2a,
51   0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
52   0x31, 0x32, 0x33, 0xff, 0xff, 0xff,
53   0xff, 0xff
54 };
55
56 static const char b64e[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
57
58 // PEM encoding/decoding functions
59
60 static bool pem_decode(FILE *fp, const char *header, uint8_t *buf, size_t size, size_t *outsize) {
61         bool decode = false;
62         char line[1024];
63         uint16_t word = 0;
64         int shift = 10;
65         size_t i, j = 0;
66
67         while(!feof(fp)) {
68                 if(!fgets(line, sizeof line, fp))
69                         return false;
70
71                 if(!decode && !strncmp(line, "-----BEGIN ", 11)) {
72                         if(!strncmp(line + 11, header, strlen(header)))
73                                 decode = true;
74                         continue;
75                 }
76
77                 if(decode && !strncmp(line, "-----END", 8)) {
78                         break;
79                 }
80
81                 if(!decode)
82                         continue;
83
84                 for(i = 0; line[i] >= ' '; i++) {
85                         if(line[i] >= 128 || line[i] < 0 || b64d[(int)line[i]] == 0xff)
86                                 break;
87                         word |= b64d[(int)line[i]] << shift;
88                         shift -= 6;
89                         if(shift <= 2) {
90                                 if(j > size) {
91                                         errno = ENOMEM;
92                                         return false;
93                                 }
94
95                                 buf[j++] = word >> 8;
96                                 word <<= 8;
97                                 shift += 8;
98                         }
99                 }
100         }
101
102         if(outsize)
103                 *outsize = j;
104         return true;
105 }
106
107
108 // BER decoding functions
109
110 static int ber_read_id(unsigned char **p, size_t *buflen) {
111         if(*buflen <= 0)
112                 return -1;
113
114         if((**p & 0x1f) == 0x1f) {
115                 int id = 0;
116                 bool more;
117                 while(*buflen > 0) {
118                         id <<= 7;
119                         id |= **p & 0x7f;
120                         more = *(*p)++ & 0x80;
121                         (*buflen)--;
122                         if(!more)
123                                 break;
124                 }
125                 return id;
126         } else {
127                 (*buflen)--;
128                 return *(*p)++ & 0x1f;
129         }
130 }
131
132 static size_t ber_read_len(unsigned char **p, size_t *buflen) {
133         if(*buflen <= 0)
134                 return -1;
135
136         if(**p & 0x80) {
137                 size_t result = 0;
138                 int len = *(*p)++ & 0x7f;
139                 (*buflen)--;
140                 if(len > *buflen)
141                         return 0;
142
143                 while(len--) {
144                         result <<= 8;
145                         result |= *(*p)++;
146                         (*buflen)--;
147                 }
148
149                 return result;
150         } else {
151                 (*buflen)--;
152                 return *(*p)++;
153         }
154 }
155         
156
157 static bool ber_read_sequence(unsigned char **p, size_t *buflen, size_t *result) {
158         int tag = ber_read_id(p, buflen);
159         size_t len = ber_read_len(p, buflen);
160
161         if(tag == 0x10) {
162                 if(result)
163                         *result = len;
164                 return true;
165         } else {
166                 return false;
167         }
168 }
169
170 static bool ber_read_mpi(unsigned char **p, size_t *buflen, gcry_mpi_t *mpi) {
171         int tag = ber_read_id(p, buflen);
172         size_t len = ber_read_len(p, buflen);
173         gcry_error_t err = 0;
174
175         if(tag != 0x02 || len > *buflen)
176                 return false;
177
178         if(mpi)
179                 err = gcry_mpi_scan(mpi, GCRYMPI_FMT_USG, *p, len, NULL);
180         
181         *p += len;
182         *buflen -= len;
183
184         return mpi ? !err : true;
185 }
186
187 // Read PEM RSA keys
188
189 bool read_pem_rsa_public_key(FILE *fp, rsa_key_t *key) {
190         uint8_t derbuf[8096], *derp = derbuf;
191         size_t derlen;
192
193         if(!pem_decode(fp, "RSA PUBLIC KEY", derbuf, sizeof derbuf, &derlen)) {
194                 logger(LOG_ERR, _("Unable to read RSA public key: %s"), strerror(errno));
195                 return NULL;
196         }
197
198         if(!ber_read_sequence(&derp, &derlen, NULL)
199                         || !ber_read_mpi(&derp, &derlen, &key->n)
200                         || !ber_read_mpi(&derp, &derlen, &key->e)
201                         || derlen) {
202                 logger(LOG_ERR, _("Error while decoding RSA public key"));
203                 return NULL;
204         }
205
206         return true;
207 }
208
209 bool read_pem_rsa_private_key(FILE *fp, rsa_key_t *key) {
210         uint8_t derbuf[8096], *derp = derbuf;
211         size_t derlen;
212
213         if(!pem_decode(fp, "RSA PRIVATE KEY", derbuf, sizeof derbuf, &derlen)) {
214                 logger(LOG_ERR, _("Unable to read RSA private key: %s"), strerror(errno));
215                 return NULL;
216         }
217
218         if(!ber_read_sequence(&derp, &derlen, NULL)
219                         || !ber_read_mpi(&derp, &derlen, NULL)
220                         || !ber_read_mpi(&derp, &derlen, &key->n)
221                         || !ber_read_mpi(&derp, &derlen, &key->e)
222                         || !ber_read_mpi(&derp, &derlen, &key->d)
223                         || !ber_read_mpi(&derp, &derlen, NULL) // p
224                         || !ber_read_mpi(&derp, &derlen, NULL) // q
225                         || !ber_read_mpi(&derp, &derlen, NULL)
226                         || !ber_read_mpi(&derp, &derlen, NULL)
227                         || !ber_read_mpi(&derp, &derlen, NULL) // u
228                         || derlen) {
229                 logger(LOG_ERR, _("Error while decoding RSA private key"));
230                 return NULL;
231         }
232
233         return true;
234 }
235
236 unsigned int get_rsa_size(rsa_key_t *key) {
237         return (gcry_mpi_get_nbits(key->n) + 7) / 8;
238 }
239
240 /* Well, libgcrypt has functions to handle RSA keys, but they suck.
241  * So we just use libgcrypt's mpi functions, and do the math ourselves.
242  */
243
244 // TODO: get rid of this macro, properly clean up gcry_ structures after use
245 #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; }}
246
247 bool rsa_public_encrypt(size_t len, void *in, void *out, rsa_key_t *key) {
248         gcry_mpi_t inmpi;
249         check(gcry_mpi_scan(&inmpi, GCRYMPI_FMT_USG, in, len, NULL));
250
251         gcry_mpi_t outmpi = gcry_mpi_new(len * 8);
252         gcry_mpi_powm(outmpi, inmpi, key->e, key->n);
253
254         check(gcry_mpi_print(GCRYMPI_FMT_USG, out,len, NULL, outmpi));
255
256         return true;
257 }
258
259 bool rsa_private_decrypt(size_t len, void *in, void *out, rsa_key_t *key) {
260         gcry_mpi_t inmpi;
261         check(gcry_mpi_scan(&inmpi, GCRYMPI_FMT_USG, in, len, NULL));
262
263         gcry_mpi_t outmpi = gcry_mpi_new(len * 8);
264         gcry_mpi_powm(outmpi, inmpi, key->d, key->n);
265
266         check(gcry_mpi_print(GCRYMPI_FMT_USG, out,len, NULL, outmpi));
267
268         return true;
269 }