chiark / gitweb /
rsa1: rsa_loadpriv_core: Introduce rsapriv_load_ctx
[secnet.git] / rsa.c
1 /*
2  * rsa.c: implementation of RSA with PKCS#1 padding
3  */
4 /*
5  * This file is Free Software.  It was originally written for secnet.
6  *
7  * Copyright 1995-2003 Stephen Early
8  * Copyright 2002-2014 Ian Jackson
9  * Copyright 2001      Simon Tatham
10  * Copyright 2013      Mark Wooding
11  *
12  * You may redistribute secnet as a whole and/or modify it under the
13  * terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3, or (at your option) any
15  * later version.
16  *
17  * You may redistribute this file and/or modify it under the terms of
18  * the GNU General Public License as published by the Free Software
19  * Foundation; either version 2, or (at your option) any later
20  * version.
21  *
22  * This software is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  * GNU General Public License for more details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with this software; if not, see
29  * https://www.gnu.org/licenses/gpl.html.
30  */
31
32
33 #include <stdio.h>
34 #include <string.h>
35 #include <gmp.h>
36 #include "secnet.h"
37 #include "util.h"
38 #include "unaligned.h"
39
40 #define AUTHFILE_ID_STRING "SSH PRIVATE KEY FILE FORMAT 1.1\n"
41
42 #define mpp(s,n) do { char *p = mpz_get_str(NULL,16,n); printf("%s 0x%sL\n", s, p); free(p); } while (0)
43
44 struct rsacommon {
45     uint8_t *hashbuf;
46 };
47
48 struct rsapriv {
49     closure_t cl;
50     struct sigprivkey_if ops;
51     struct cloc loc;
52     struct rsacommon common;
53     MP_INT n;
54     MP_INT p, dp;
55     MP_INT q, dq;
56     MP_INT w;
57 };
58 struct rsapub {
59     closure_t cl;
60     struct sigpubkey_if ops;
61     struct cloc loc;
62     struct rsacommon common;
63     MP_INT e;
64     MP_INT n;
65 };
66 /* Sign data. NB data must be smaller than modulus */
67
68 #define RSA_MAX_MODBYTES 2048
69 /* The largest modulus I've seen is 15360 bits, which works out at 1920
70  * bytes.  Using keys this big is quite implausible, but it doesn't cost us
71  * much to support them.
72  */
73
74 static const char *hexchars="0123456789abcdef";
75
76 static void rsa_sethash(struct rsacommon *c, struct hash_if *hash,
77                         const struct hash_if **in_ops)
78 {
79     free(c->hashbuf);
80     c->hashbuf=safe_malloc(hash->hlen, "generate_msg");
81     *in_ops=hash;
82 }
83 static void rsa_pub_sethash(void *sst, struct hash_if *hash)
84 {
85     struct rsapub *st=sst;
86     rsa_sethash(&st->common, hash, &st->ops.hash);
87 }
88 static void rsa_priv_sethash(void *sst, struct hash_if *hash)
89 {
90     struct rsapriv *st=sst;
91     rsa_sethash(&st->common, hash, &st->ops.hash);
92 }
93 static void rsacommon_dispose(struct rsacommon *c)
94 {
95     free(c->hashbuf);
96 }
97
98 static void emsa_pkcs1(MP_INT *n, MP_INT *m,
99                        const uint8_t *data, int32_t datalen)
100 {
101     char buff[2*RSA_MAX_MODBYTES + 1];
102     int msize, i;
103
104     /* RSA PKCS#1 v1.5 signature padding:
105      *
106      * <------------ msize hex digits ---------->
107      *
108      * 00 01 ff ff .... ff ff 00 vv vv vv .... vv
109      *
110      *                           <--- datalen -->
111      *                                 bytes
112      *                         = datalen*2 hex digits
113      *
114      * NB that according to PKCS#1 v1.5 we're supposed to include a
115      * hash function OID in the data.  We don't do that (because we
116      * don't have the hash function OID to hand here), thus violating
117      * the spec in a way that affects interop but not security.
118      *
119      * -iwj 17.9.2002
120      */
121
122     msize=mpz_sizeinbase(n, 16);
123
124     if (datalen*2+6>=msize) {
125         fatal("rsa: message too big");
126     }
127
128     strcpy(buff,"0001");
129
130     for (i=0; i<datalen; i++) {
131         buff[msize+(-datalen+i)*2]=hexchars[(data[i]&0xf0)>>4];
132         buff[msize+(-datalen+i)*2+1]=hexchars[data[i]&0xf];
133     }
134     
135     buff[msize-datalen*2-2]= '0';
136     buff[msize-datalen*2-1]= '0';
137  
138     for (i=4; i<msize-datalen*2-2; i++)
139        buff[i]='f';
140
141     buff[msize]=0;
142
143     mpz_set_str(m, buff, 16);
144 }
145
146 static bool_t rsa_sign(void *sst, uint8_t *data, int32_t datalen,
147                        struct buffer_if *msg)
148 {
149     struct rsapriv *st=sst;
150     MP_INT a, b, u, v, tmp, tmp2;
151     string_t signature = 0;
152     bool_t ok;
153
154     mpz_init(&a);
155     mpz_init(&b);
156
157     hash_hash(st->ops.hash,data,datalen,st->common.hashbuf);
158     /* Construct the message representative. */
159     emsa_pkcs1(&st->n, &a, st->common.hashbuf, st->ops.hash->hlen);
160
161     /*
162      * Produce an RSA signature (a^d mod n) using the Chinese
163      * Remainder Theorem. We compute:
164      * 
165      *   u = a^dp mod p    (== a^d mod p, since dp == d mod (p-1))
166      *   v = a^dq mod q    (== a^d mod q, similarly)
167      * 
168      * We also know w == iqmp * q, which has the property that w ==
169      * 0 mod q and w == 1 mod p. So (1-w) has the reverse property
170      * (congruent to 0 mod p and to 1 mod q). Hence we now compute
171      * 
172      *   b = w * u + (1-w) * v
173      *     = w * (u-v) + v
174      * 
175      * so that b is congruent to a^d both mod p and mod q. Hence b,
176      * reduced mod n, is the required signature.
177      */
178     mpz_init(&tmp);
179     mpz_init(&tmp2);
180     mpz_init(&u);
181     mpz_init(&v);
182
183     mpz_powm_sec(&u, &a, &st->dp, &st->p);
184     mpz_powm_sec(&v, &a, &st->dq, &st->q);
185     mpz_sub(&tmp, &u, &v);
186     mpz_mul(&tmp2, &tmp, &st->w);
187     mpz_add(&tmp, &tmp2, &v);
188     mpz_mod(&b, &tmp, &st->n);
189
190     mpz_clear(&tmp);
191     mpz_clear(&tmp2);
192     mpz_clear(&u);
193     mpz_clear(&v);
194
195     signature=write_mpstring(&b);
196
197     uint8_t *op = buf_append(msg,2);
198     if (!op) { ok=False; goto out; }
199     size_t l = strlen(signature);
200     assert(l < 65536);
201     put_uint16(op, l);
202     op = buf_append(msg,l);
203     if (!op) { ok=False; goto out; }
204     memcpy(op, signature, l);
205
206     ok = True;
207
208  out:
209     free(signature);
210     mpz_clear(&b);
211     mpz_clear(&a);
212     return ok;
213 }
214
215 static bool_t rsa_sig_unpick(void *sst, struct buffer_if *msg,
216                              struct alg_msg_data *sig)
217 {
218     uint8_t *lp = buf_unprepend(msg, 2);
219     if (!lp) return False;
220     sig->len = get_uint16(lp);
221     sig->start = buf_unprepend(msg, sig->len);
222     if (!sig->start) return False;
223
224     /* In `rsa_sig_check' below, we assume that we can write a nul
225      * terminator following the signature.  Make sure there's enough space.
226      */
227     if (msg->start >= msg->base + msg->alloclen)
228         return False;
229
230     return True;
231 }
232
233 static sig_checksig_fn rsa_sig_check;
234 static bool_t rsa_sig_check(void *sst, uint8_t *data, int32_t datalen,
235                             const struct alg_msg_data *sig)
236 {
237     struct rsapub *st=sst;
238     MP_INT a, b, c;
239     bool_t ok;
240
241     mpz_init(&a);
242     mpz_init(&b);
243     mpz_init(&c);
244
245     hash_hash(st->ops.hash,data,datalen,st->common.hashbuf);
246     emsa_pkcs1(&st->n, &a, st->common.hashbuf, st->ops.hash->hlen);
247
248     /* Terminate signature with a '0' - already checked that this will fit */
249     int save = sig->start[sig->len];
250     sig->start[sig->len] = 0;
251     mpz_set_str(&b, sig->start, 16);
252     sig->start[sig->len] = save;
253
254     mpz_powm(&c, &b, &st->e, &st->n);
255
256     ok=(mpz_cmp(&a, &c)==0);
257
258     mpz_clear(&c);
259     mpz_clear(&b);
260     mpz_clear(&a);
261
262     return ok;
263 }
264
265 static void rsapub_dispose(void *sst) {
266     struct rsapub *st=sst;
267
268     mpz_clear(&st->e);
269     mpz_clear(&st->n);
270     rsacommon_dispose(&st->common);
271     free(st);
272 }
273
274 static list_t *rsapub_apply(closure_t *self, struct cloc loc, dict_t *context,
275                             list_t *args)
276 {
277     struct rsapub *st;
278     item_t *i;
279     string_t e,n;
280
281     NEW(st);
282     st->cl.description="rsapub";
283     st->cl.type=CL_SIGPUBKEY;
284     st->cl.apply=NULL;
285     st->cl.interface=&st->ops;
286     st->ops.st=st;
287     st->ops.sethash=rsa_pub_sethash;
288     st->common.hashbuf=NULL;
289     st->ops.unpick=rsa_sig_unpick;
290     st->ops.check=rsa_sig_check;
291     st->ops.hash=0;
292     st->ops.dispose=rsapub_dispose;
293     st->loc=loc;
294
295     i=list_elem(args,0);
296     if (i) {
297         if (i->type!=t_string) {
298             cfgfatal(i->loc,"rsa-public","first argument must be a string\n");
299         }
300         e=i->data.string;
301         if (mpz_init_set_str(&st->e,e,10)!=0) {
302             cfgfatal(i->loc,"rsa-public","encryption key \"%s\" is not a "
303                      "decimal number string\n",e);
304         }
305     } else {
306         cfgfatal(loc,"rsa-public","you must provide an encryption key\n");
307     }
308     if (mpz_sizeinbase(&st->e, 256) > RSA_MAX_MODBYTES) {
309         cfgfatal(loc, "rsa-public", "implausibly large public exponent\n");
310     }
311     
312     i=list_elem(args,1);
313     if (i) {
314         if (i->type!=t_string) {
315             cfgfatal(i->loc,"rsa-public","second argument must be a string\n");
316         }
317         n=i->data.string;
318         if (mpz_init_set_str(&st->n,n,10)!=0) {
319             cfgfatal(i->loc,"rsa-public","modulus \"%s\" is not a decimal "
320                      "number string\n",n);
321         }
322     } else {
323         cfgfatal(loc,"rsa-public","you must provide a modulus\n");
324     }
325     if (mpz_sizeinbase(&st->n, 256) > RSA_MAX_MODBYTES) {
326         cfgfatal(loc, "rsa-public", "implausibly large modulus\n");
327     }
328     return new_closure(&st->cl);
329 }
330
331 struct rsapriv_load_ctx {
332     void (*verror)(struct rsapriv_load_ctx *l,
333                    FILE *maybe_f, bool_t unsup,
334                    const char *message, va_list args);
335     union {
336         struct {
337             struct cloc loc;
338         } apply;
339     } u;
340 };
341
342 #define LDFATAL(...)      ({ load_error(l,0,0,__VA_ARGS__); goto error_out; })
343 #define LDUNSUP(...)      ({ load_error(l,0,1,__VA_ARGS__); goto error_out; })
344 #define LDFATAL_FILE(...) ({ load_error(l,f,0,__VA_ARGS__); goto error_out; })
345 #define LDUNSUP_FILE(...) ({ load_error(l,f,1,__VA_ARGS__); goto error_out; })
346 #define FREE(b)                ({ free((b)); (b)=0; })
347
348 static uint32_t keyfile_get_int(struct cloc loc, FILE *f)
349 {
350     uint32_t r;
351     r=fgetc(f)<<24;
352     r|=fgetc(f)<<16;
353     r|=fgetc(f)<<8;
354     r|=fgetc(f);
355     cfgfile_postreadcheck(loc,f);
356     return r;
357 }
358
359 static uint16_t keyfile_get_short(struct cloc loc, FILE *f)
360 {
361     uint16_t r;
362     r=fgetc(f)<<8;
363     r|=fgetc(f);
364     cfgfile_postreadcheck(loc,f);
365     return r;
366 }
367
368 static void load_error(struct rsapriv_load_ctx *l, FILE *maybe_f,
369                        bool_t unsup, const char *fmt, ...)
370 {
371     va_list al;
372     va_start(al,fmt);
373     l->verror(l,maybe_f,unsup,fmt,al);
374     va_end(al);
375 }
376
377 static void rsapriv_dispose(void *sst)
378 {
379     struct rsapriv *st=sst;
380     mpz_clear(&st->n);
381     mpz_clear(&st->p); mpz_clear(&st->dp);
382     mpz_clear(&st->q); mpz_clear(&st->dq);
383     mpz_clear(&st->w);
384     rsacommon_dispose(&st->common);
385     free(st);
386 }
387
388 static struct rsapriv *rsa_loadpriv_core(struct rsapriv_load_ctx *l,
389                                          FILE *f, struct cloc loc,
390                                          bool_t do_validity_check,
391                                          const char *filename)
392 {
393     struct rsapriv *st=0;
394     long length;
395     uint8_t *b=0, *c=0;
396     int cipher_type;
397     MP_INT e,d,iqmp,tmp,tmp2,tmp3;
398     bool_t valid;
399
400     mpz_init(&e);
401     mpz_init(&d);
402     mpz_init(&iqmp);
403     mpz_init(&tmp);
404     mpz_init(&tmp2);
405     mpz_init(&tmp3);
406
407     NEW(st);
408     st->cl.description="rsapriv";
409     st->cl.type=CL_SIGPRIVKEY;
410     st->cl.apply=NULL;
411     st->cl.interface=&st->ops;
412     st->ops.st=st;
413     st->ops.sethash=rsa_priv_sethash;
414     st->common.hashbuf=NULL;
415     st->ops.sign=rsa_sign;
416     st->ops.hash=0;
417     st->ops.dispose=rsapriv_dispose;
418     st->loc=loc;
419     mpz_init(&st->n);
420     mpz_init(&st->q);
421     mpz_init(&st->p);
422     mpz_init(&st->dp);
423     mpz_init(&st->dq);
424     mpz_init(&st->w);
425
426     if (!f) {
427         assert(just_check_config);
428         goto assume_valid;
429     }
430
431     /* Check that the ID string is correct */
432     length=strlen(AUTHFILE_ID_STRING)+1;
433     b=safe_malloc(length,"rsapriv_apply");
434     if (fread(b,length,1,f)!=1 || memcmp(b,AUTHFILE_ID_STRING,length)!=0) {
435         LDUNSUP_FILE("failed to read magic ID"
436                            " string from SSH1 private keyfile \"%s\"\n",
437                            filename);
438     }
439     FREE(b);
440
441     cipher_type=fgetc(f);
442     keyfile_get_int(loc,f); /* "Reserved data" */
443     if (cipher_type != 0) {
444         LDUNSUP("we don't support encrypted keyfiles\n");
445     }
446
447     /* Read the public key */
448     keyfile_get_int(loc,f); /* Not sure what this is */
449     length=(keyfile_get_short(loc,f)+7)/8;
450     if (length>RSA_MAX_MODBYTES) {
451         LDFATAL("implausible length %ld for modulus\n",
452                  length);
453     }
454     b=safe_malloc(length,"rsapriv_apply");
455     if (fread(b,length,1,f) != 1) {
456         LDFATAL_FILE("error reading modulus\n");
457     }
458     read_mpbin(&st->n,b,length);
459     FREE(b);
460     length=(keyfile_get_short(loc,f)+7)/8;
461     if (length>RSA_MAX_MODBYTES) {
462         LDFATAL("implausible length %ld for e\n",length);
463     }
464     b=safe_malloc(length,"rsapriv_apply");
465     if (fread(b,length,1,f)!=1) {
466         LDFATAL_FILE("error reading e\n");
467     }
468     read_mpbin(&e,b,length);
469     FREE(b);
470     
471     length=keyfile_get_int(loc,f);
472     if (length>1024) {
473         LDFATAL("implausibly long (%ld) key comment\n",
474                  length);
475     }
476     c=safe_malloc(length+1,"rsapriv_apply");
477     if (fread(c,length,1,f)!=1) {
478         LDFATAL_FILE("error reading key comment\n");
479     }
480     c[length]=0;
481
482     /* Check that the next two pairs of characters are identical - the
483        keyfile is not encrypted, so they should be */
484
485     if (keyfile_get_short(loc,f) != keyfile_get_short(loc,f)) {
486         LDFATAL("corrupt keyfile\n");
487     }
488
489     /* Read d */
490     length=(keyfile_get_short(loc,f)+7)/8;
491     if (length>RSA_MAX_MODBYTES) {
492         LDFATAL("implausibly long (%ld) decryption key\n",
493                  length);
494     }
495     b=safe_malloc(length,"rsapriv_apply");
496     if (fread(b,length,1,f)!=1) {
497         LDFATAL_FILE("error reading decryption key\n");
498     }
499     read_mpbin(&d,b,length);
500     FREE(b);
501     /* Read iqmp (inverse of q mod p) */
502     length=(keyfile_get_short(loc,f)+7)/8;
503     if (length>RSA_MAX_MODBYTES) {
504         LDFATAL("implausibly long (%ld)"
505                  " iqmp auxiliary value\n", length);
506     }
507     b=safe_malloc(length,"rsapriv_apply");
508     if (fread(b,length,1,f)!=1) {
509         LDFATAL_FILE("error reading decryption key\n");
510     }
511     read_mpbin(&iqmp,b,length);
512     FREE(b);
513     /* Read q (the smaller of the two primes) */
514     length=(keyfile_get_short(loc,f)+7)/8;
515     if (length>RSA_MAX_MODBYTES) {
516         LDFATAL("implausibly long (%ld) q value\n",
517                  length);
518     }
519     b=safe_malloc(length,"rsapriv_apply");
520     if (fread(b,length,1,f)!=1) {
521         LDFATAL_FILE("error reading q value\n");
522     }
523     read_mpbin(&st->q,b,length);
524     FREE(b);
525     /* Read p (the larger of the two primes) */
526     length=(keyfile_get_short(loc,f)+7)/8;
527     if (length>RSA_MAX_MODBYTES) {
528         LDFATAL("implausibly long (%ld) p value\n",
529                  length);
530     }
531     b=safe_malloc(length,"rsapriv_apply");
532     if (fread(b,length,1,f)!=1) {
533         LDFATAL_FILE("error reading p value\n");
534     }
535     read_mpbin(&st->p,b,length);
536     FREE(b);
537     
538     if (ferror(f)) {
539         fatal_perror("rsa-private (%s:%d): ferror",loc.file,loc.line);
540     }
541
542     /*
543      * Now verify the validity of the key, and set up the auxiliary
544      * values for fast CRT signing.
545      */
546     valid=False;
547     if (do_validity_check) {
548         /* Verify that p*q is equal to n. */
549         mpz_mul(&tmp, &st->p, &st->q);
550         if (mpz_cmp(&tmp, &st->n) != 0)
551             goto done_checks;
552
553         /*
554          * Verify that d*e is congruent to 1 mod (p-1), and mod
555          * (q-1). This is equivalent to it being congruent to 1 mod
556          * lambda(n) = lcm(p-1,q-1).  The usual `textbook' condition,
557          * that d e == 1 (mod (p-1)(q-1)) is sufficient, but not
558          * actually necessary.
559          */
560         mpz_mul(&tmp, &d, &e);
561         mpz_sub_ui(&tmp2, &st->p, 1);
562         mpz_mod(&tmp3, &tmp, &tmp2);
563         if (mpz_cmp_si(&tmp3, 1) != 0)
564             goto done_checks;
565         mpz_sub_ui(&tmp2, &st->q, 1);
566         mpz_mod(&tmp3, &tmp, &tmp2);
567         if (mpz_cmp_si(&tmp3, 1) != 0)
568             goto done_checks;
569
570         /* Verify that q*iqmp is congruent to 1 mod p. */
571         mpz_mul(&tmp, &st->q, &iqmp);
572         mpz_mod(&tmp2, &tmp, &st->p);
573         if (mpz_cmp_si(&tmp2, 1) != 0)
574             goto done_checks;
575     }
576     /* Now we know the key is valid (or we don't care). */
577     valid = True;
578     
579     /*
580      * Now we compute auxiliary values dp, dq and w to allow us
581      * to use the CRT optimisation when signing.
582      * 
583      *   dp == d mod (p-1)      so that a^dp == a^d mod p, for all a
584      *   dq == d mod (q-1)      similarly mod q
585      *   w == iqmp * q          so that w == 0 mod q, and w == 1 mod p
586      */
587     mpz_sub_ui(&tmp, &st->p, 1);
588     mpz_mod(&st->dp, &d, &tmp);
589     mpz_sub_ui(&tmp, &st->q, 1);
590     mpz_mod(&st->dq, &d, &tmp);
591     mpz_mul(&st->w, &iqmp, &st->q);
592     
593 done_checks:
594     if (!valid) {
595         LDFATAL("file \"%s\" does not contain a "
596                  "valid RSA key!\n",filename);
597     }
598
599 assume_valid:
600 out:
601     mpz_clear(&tmp);
602     mpz_clear(&tmp2);
603     mpz_clear(&tmp3);
604
605     FREE(b);
606     FREE(c);
607     mpz_clear(&e);
608     mpz_clear(&d);
609     mpz_clear(&iqmp);
610
611     return st;
612
613 error_out:
614     if (st) rsapriv_dispose(st);
615     st=0;
616     goto out;
617 }
618
619 static void verror_cfgfatal(struct rsapriv_load_ctx *l,
620                             FILE *maybe_f, bool_t unsup,
621                             const char *message, va_list args)
622 {
623     vcfgfatal_maybefile(maybe_f,l->u.apply.loc,"rsa-private",message,args);
624 }
625
626 static list_t *rsapriv_apply(closure_t *self, struct cloc loc, dict_t *context,
627                              list_t *args)
628 {
629     struct rsapriv *st;
630     item_t *i;
631     cstring_t filename;
632     FILE *f;
633     struct rsapriv_load_ctx l[1];
634
635     l->verror=verror_cfgfatal;
636     l->u.apply.loc=loc;
637
638     /* Argument is filename pointing to SSH1 private key file */
639     i=list_elem(args,0);
640     if (i) {
641         if (i->type!=t_string) {
642             cfgfatal(i->loc,"rsa-private","first argument must be a string\n");
643         }
644         filename=i->data.string;
645     } else {
646         filename=NULL; /* Make compiler happy */
647         cfgfatal(i->loc,"rsa-private","you must provide a filename\n");
648     }
649
650     f=fopen(filename,"rb");
651     if (!f) {
652         if (just_check_config) {
653             Message(M_WARNING,"rsa-private (%s:%d): cannot open keyfile "
654                     "\"%s\"; assuming it's valid while we check the "
655                     "rest of the configuration\n",loc.file,loc.line,filename);
656         } else {
657             fatal_perror("rsa-private (%s:%d): cannot open file \"%s\"",
658                          loc.file,loc.line,filename);
659         }
660     }
661
662     bool_t do_validity_check=True;
663     i=list_elem(args,1);
664     if (i && i->type==t_bool && i->data.bool==False) {
665         Message(M_INFO,"rsa-private (%s:%d): skipping RSA key validity "
666                 "check\n",loc.file,loc.line);
667         do_validity_check=False;
668     }
669
670     st=rsa_loadpriv_core(l,f,loc,do_validity_check,filename);
671     fclose(f);
672     return new_closure(&st->cl);
673 }
674
675 void rsa_module(dict_t *dict)
676 {
677     add_closure(dict,"rsa-private",rsapriv_apply);
678     add_closure(dict,"rsa-public",rsapub_apply);
679 }