Reformat all code using astyle.
[tinc] / src / gcrypt / rsa.c
1 /*
2     rsa.c -- RSA key handling
3     Copyright (C) 2007-2012 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 along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #include <gcrypt.h>
23
24 #include "logger.h"
25 #include "rsa.h"
26
27 // Base64 decoding table
28
29 static const uint8_t b64d[128] = {
30         0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
31         0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
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, 0x3e, 0xff, 0xff, 0xff, 0x3f,
38         0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
39         0x3a, 0x3b, 0x3c, 0x3d, 0xff, 0xff,
40         0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
41         0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
42         0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
43         0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12,
44         0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
45         0x19, 0xff, 0xff, 0xff, 0xff, 0xff,
46         0xff, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e,
47         0x1f, 0x20, 0x21, 0x22, 0x23, 0x24,
48         0x25, 0x26, 0x27, 0x28, 0x29, 0x2a,
49         0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
50         0x31, 0x32, 0x33, 0xff, 0xff, 0xff,
51         0xff, 0xff
52 };
53
54 // PEM encoding/decoding functions
55
56 static bool pem_decode(FILE *fp, const char *header, uint8_t *buf, size_t size, size_t *outsize) {
57         bool decode = false;
58         char line[1024];
59         uint16_t word = 0;
60         int shift = 10;
61         size_t i, j = 0;
62
63         while(!feof(fp)) {
64                 if(!fgets(line, sizeof(line), fp)) {
65                         return false;
66                 }
67
68                 if(!decode && !strncmp(line, "-----BEGIN ", 11)) {
69                         if(!strncmp(line + 11, header, strlen(header))) {
70                                 decode = true;
71                         }
72
73                         continue;
74                 }
75
76                 if(decode && !strncmp(line, "-----END", 8)) {
77                         break;
78                 }
79
80                 if(!decode) {
81                         continue;
82                 }
83
84                 for(i = 0; line[i] >= ' '; i++) {
85                         if((signed char)line[i] < 0 || b64d[(int)line[i]] == 0xff) {
86                                 break;
87                         }
88
89                         word |= b64d[(int)line[i]] << shift;
90                         shift -= 6;
91
92                         if(shift <= 2) {
93                                 if(j > size) {
94                                         errno = ENOMEM;
95                                         return false;
96                                 }
97
98                                 buf[j++] = word >> 8;
99                                 word <<= 8;
100                                 shift += 8;
101                         }
102                 }
103         }
104
105         if(outsize) {
106                 *outsize = j;
107         }
108
109         return true;
110 }
111
112
113 // BER decoding functions
114
115 static int ber_read_id(unsigned char **p, size_t *buflen) {
116         if(*buflen <= 0) {
117                 return -1;
118         }
119
120         if((**p & 0x1f) == 0x1f) {
121                 int id = 0;
122                 bool more;
123
124                 while(*buflen > 0) {
125                         id <<= 7;
126                         id |= **p & 0x7f;
127                         more = *(*p)++ & 0x80;
128                         (*buflen)--;
129
130                         if(!more) {
131                                 break;
132                         }
133                 }
134
135                 return id;
136         } else {
137                 (*buflen)--;
138                 return *(*p)++ & 0x1f;
139         }
140 }
141
142 static size_t ber_read_len(unsigned char **p, size_t *buflen) {
143         if(*buflen <= 0) {
144                 return -1;
145         }
146
147         if(**p & 0x80) {
148                 size_t result = 0;
149                 int len = *(*p)++ & 0x7f;
150                 (*buflen)--;
151
152                 if(len > *buflen) {
153                         return 0;
154                 }
155
156                 while(len--) {
157                         result <<= 8;
158                         result |= *(*p)++;
159                         (*buflen)--;
160                 }
161
162                 return result;
163         } else {
164                 (*buflen)--;
165                 return *(*p)++;
166         }
167 }
168
169
170 static bool ber_read_sequence(unsigned char **p, size_t *buflen, size_t *result) {
171         int tag = ber_read_id(p, buflen);
172         size_t len = ber_read_len(p, buflen);
173
174         if(tag == 0x10) {
175                 if(result) {
176                         *result = len;
177                 }
178
179                 return true;
180         } else {
181                 return false;
182         }
183 }
184
185 static bool ber_read_mpi(unsigned char **p, size_t *buflen, gcry_mpi_t *mpi) {
186         int tag = ber_read_id(p, buflen);
187         size_t len = ber_read_len(p, buflen);
188         gcry_error_t err = 0;
189
190         if(tag != 0x02 || len > *buflen) {
191                 return false;
192         }
193
194         if(mpi) {
195                 err = gcry_mpi_scan(mpi, GCRYMPI_FMT_USG, *p, len, NULL);
196         }
197
198         *p += len;
199         *buflen -= len;
200
201         return mpi ? !err : true;
202 }
203
204 bool rsa_set_hex_public_key(rsa_t *rsa, char *n, char *e) {
205         gcry_error_t err = 0;
206
207         err = gcry_mpi_scan(&rsa->n, GCRYMPI_FMT_HEX, n, 0, NULL)
208               ? : gcry_mpi_scan(&rsa->e, GCRYMPI_FMT_HEX, e, 0, NULL);
209
210         if(err) {
211                 logger(DEBUG_ALWAYS, LOG_ERR, "Error while reading RSA public key: %s", gcry_strerror(errno));
212                 return false;
213         }
214
215         return true;
216 }
217
218 bool rsa_set_hex_private_key(rsa_t *rsa, char *n, char *e, char *d) {
219         gcry_error_t err = 0;
220
221         err = gcry_mpi_scan(&rsa->n, GCRYMPI_FMT_HEX, n, 0, NULL)
222               ? : gcry_mpi_scan(&rsa->e, GCRYMPI_FMT_HEX, e, 0, NULL)
223               ? : gcry_mpi_scan(&rsa->d, GCRYMPI_FMT_HEX, d, 0, NULL);
224
225         if(err) {
226                 logger(DEBUG_ALWAYS, LOG_ERR, "Error while reading RSA public key: %s", gcry_strerror(errno));
227                 return false;
228         }
229
230         return true;
231 }
232
233 // Read PEM RSA keys
234
235 bool rsa_read_pem_public_key(rsa_t *rsa, FILE *fp) {
236         uint8_t derbuf[8096], *derp = derbuf;
237         size_t derlen;
238
239         if(!pem_decode(fp, "RSA PUBLIC KEY", derbuf, sizeof(derbuf), &derlen)) {
240                 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to read RSA public key: %s", strerror(errno));
241                 return NULL;
242         }
243
244         if(!ber_read_sequence(&derp, &derlen, NULL)
245                         || !ber_read_mpi(&derp, &derlen, &rsa->n)
246                         || !ber_read_mpi(&derp, &derlen, &rsa->e)
247                         || derlen) {
248                 logger(DEBUG_ALWAYS, LOG_ERR, "Error while decoding RSA public key");
249                 return NULL;
250         }
251
252         return true;
253 }
254
255 bool rsa_read_pem_private_key(rsa_t *rsa, FILE *fp) {
256         uint8_t derbuf[8096], *derp = derbuf;
257         size_t derlen;
258
259         if(!pem_decode(fp, "RSA PRIVATE KEY", derbuf, sizeof(derbuf), &derlen)) {
260                 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to read RSA private key: %s", strerror(errno));
261                 return NULL;
262         }
263
264         if(!ber_read_sequence(&derp, &derlen, NULL)
265                         || !ber_read_mpi(&derp, &derlen, NULL)
266                         || !ber_read_mpi(&derp, &derlen, &rsa->n)
267                         || !ber_read_mpi(&derp, &derlen, &rsa->e)
268                         || !ber_read_mpi(&derp, &derlen, &rsa->d)
269                         || !ber_read_mpi(&derp, &derlen, NULL) // p
270                         || !ber_read_mpi(&derp, &derlen, NULL) // q
271                         || !ber_read_mpi(&derp, &derlen, NULL)
272                         || !ber_read_mpi(&derp, &derlen, NULL)
273                         || !ber_read_mpi(&derp, &derlen, NULL) // u
274                         || derlen) {
275                 logger(DEBUG_ALWAYS, LOG_ERR, "Error while decoding RSA private key");
276                 return NULL;
277         }
278
279         return true;
280 }
281
282 size_t rsa_size(rsa_t *rsa) {
283         return (gcry_mpi_get_nbits(rsa->n) + 7) / 8;
284 }
285
286 /* Well, libgcrypt has functions to handle RSA keys, but they suck.
287  * So we just use libgcrypt's mpi functions, and do the math ourselves.
288  */
289
290 // TODO: get rid of this macro, properly clean up gcry_ structures after use
291 #define check(foo) { gcry_error_t err = (foo); if(err) {logger(DEBUG_ALWAYS, LOG_ERR, "gcrypt error %s/%s at %s:%d", gcry_strsource(err), gcry_strerror(err), __FILE__, __LINE__); return false; }}
292
293 bool rsa_public_encrypt(rsa_t *rsa, void *in, size_t len, void *out) {
294         gcry_mpi_t inmpi;
295         check(gcry_mpi_scan(&inmpi, GCRYMPI_FMT_USG, in, len, NULL));
296
297         gcry_mpi_t outmpi = gcry_mpi_new(len * 8);
298         gcry_mpi_powm(outmpi, inmpi, rsa->e, rsa->n);
299
300         int pad = len - (gcry_mpi_get_nbits(outmpi) + 7) / 8;
301
302         while(pad--) {
303                 *(char *)out++ = 0;
304         }
305
306         check(gcry_mpi_print(GCRYMPI_FMT_USG, out, len, NULL, outmpi));
307
308         return true;
309 }
310
311 bool rsa_private_decrypt(rsa_t *rsa, void *in, size_t len, void *out) {
312         gcry_mpi_t inmpi;
313         check(gcry_mpi_scan(&inmpi, GCRYMPI_FMT_USG, in, len, NULL));
314
315         gcry_mpi_t outmpi = gcry_mpi_new(len * 8);
316         gcry_mpi_powm(outmpi, inmpi, rsa->d, rsa->n);
317
318         int pad = len - (gcry_mpi_get_nbits(outmpi) + 7) / 8;
319
320         while(pad--) {
321                 *(char *)out++ = 0;
322         }
323
324         check(gcry_mpi_print(GCRYMPI_FMT_USG, out, len, NULL, outmpi));
325
326         return true;
327 }