2 * rsa.c: implementation of RSA with PKCS#1 padding
5 * This file is Free Software. It was originally written for secnet.
7 * Copyright 1995-2003 Stephen Early
8 * Copyright 2002-2014 Ian Jackson
9 * Copyright 2001 Simon Tatham
10 * Copyright 2013 Mark Wooding
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
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
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.
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.
38 #include "unaligned.h"
40 #define AUTHFILE_ID_STRING "SSH PRIVATE KEY FILE FORMAT 1.1\n"
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)
49 void (*verror)(struct load_ctx *l,
50 FILE *maybe_f, bool_t unsup,
51 const char *message, va_list args);
52 bool_t (*postreadcheck)(struct load_ctx *l, FILE *f);
63 static void verror_tryload(struct load_ctx *l,
64 FILE *maybe_f, bool_t unsup,
65 const char *message, va_list args)
67 int class=unsup ? M_DEBUG : M_ERR;
68 slilog_part(l->u.tryload.log,class,"%s: ",l->what);
69 vslilog(l->u.tryload.log,class,message,args);
72 static void verror_cfgfatal(struct load_ctx *l,
73 FILE *maybe_f, bool_t unsup,
74 const char *message, va_list args)
76 vcfgfatal_maybefile(maybe_f,*l->loc,l->what,message,args);
81 struct sigprivkey_if ops;
83 struct rsacommon common;
91 struct sigpubkey_if ops;
93 struct rsacommon common;
97 /* Sign data. NB data must be smaller than modulus */
99 #define RSA_MAX_MODBYTES 2048
100 /* The largest modulus I've seen is 15360 bits, which works out at 1920
101 * bytes. Using keys this big is quite implausible, but it doesn't cost us
102 * much to support them.
105 static const char *hexchars="0123456789abcdef";
107 static void rsa_sethash(struct rsacommon *c, struct hash_if *hash,
108 const struct hash_if **in_ops)
111 c->hashbuf=safe_malloc(hash->hlen, "generate_msg");
114 static void rsa_pub_sethash(void *sst, struct hash_if *hash)
116 struct rsapub *st=sst;
117 rsa_sethash(&st->common, hash, &st->ops.hash);
119 static void rsa_priv_sethash(void *sst, struct hash_if *hash)
121 struct rsapriv *st=sst;
122 rsa_sethash(&st->common, hash, &st->ops.hash);
124 static void rsacommon_dispose(struct rsacommon *c)
129 static void emsa_pkcs1(MP_INT *n, MP_INT *m,
130 const uint8_t *data, int32_t datalen)
132 char buff[2*RSA_MAX_MODBYTES + 1];
135 /* RSA PKCS#1 v1.5 signature padding:
137 * <------------ msize hex digits ---------->
139 * 00 01 ff ff .... ff ff 00 vv vv vv .... vv
143 * = datalen*2 hex digits
145 * NB that according to PKCS#1 v1.5 we're supposed to include a
146 * hash function OID in the data. We don't do that (because we
147 * don't have the hash function OID to hand here), thus violating
148 * the spec in a way that affects interop but not security.
153 msize=mpz_sizeinbase(n, 16);
155 if (datalen*2+6>=msize) {
156 fatal("rsa: message too big");
161 for (i=0; i<datalen; i++) {
162 buff[msize+(-datalen+i)*2]=hexchars[(data[i]&0xf0)>>4];
163 buff[msize+(-datalen+i)*2+1]=hexchars[data[i]&0xf];
166 buff[msize-datalen*2-2]= '0';
167 buff[msize-datalen*2-1]= '0';
169 for (i=4; i<msize-datalen*2-2; i++)
174 mpz_set_str(m, buff, 16);
177 static bool_t rsa_sign(void *sst, uint8_t *data, int32_t datalen,
178 struct buffer_if *msg)
180 struct rsapriv *st=sst;
181 MP_INT a, b, u, v, tmp, tmp2;
182 string_t signature = 0;
188 hash_hash(st->ops.hash,data,datalen,st->common.hashbuf);
189 /* Construct the message representative. */
190 emsa_pkcs1(&st->n, &a, st->common.hashbuf, st->ops.hash->hlen);
193 * Produce an RSA signature (a^d mod n) using the Chinese
194 * Remainder Theorem. We compute:
196 * u = a^dp mod p (== a^d mod p, since dp == d mod (p-1))
197 * v = a^dq mod q (== a^d mod q, similarly)
199 * We also know w == iqmp * q, which has the property that w ==
200 * 0 mod q and w == 1 mod p. So (1-w) has the reverse property
201 * (congruent to 0 mod p and to 1 mod q). Hence we now compute
203 * b = w * u + (1-w) * v
206 * so that b is congruent to a^d both mod p and mod q. Hence b,
207 * reduced mod n, is the required signature.
214 mpz_powm_sec(&u, &a, &st->dp, &st->p);
215 mpz_powm_sec(&v, &a, &st->dq, &st->q);
216 mpz_sub(&tmp, &u, &v);
217 mpz_mul(&tmp2, &tmp, &st->w);
218 mpz_add(&tmp, &tmp2, &v);
219 mpz_mod(&b, &tmp, &st->n);
226 signature=write_mpstring(&b);
228 uint8_t *op = buf_append(msg,2);
229 if (!op) { ok=False; goto out; }
230 size_t l = strlen(signature);
233 op = buf_append(msg,l);
234 if (!op) { ok=False; goto out; }
235 memcpy(op, signature, l);
246 static bool_t rsa_sig_unpick(void *sst, struct buffer_if *msg,
247 struct alg_msg_data *sig)
249 uint8_t *lp = buf_unprepend(msg, 2);
250 if (!lp) return False;
251 sig->len = get_uint16(lp);
252 sig->start = buf_unprepend(msg, sig->len);
253 if (!sig->start) return False;
255 /* In `rsa_sig_check' below, we assume that we can write a nul
256 * terminator following the signature. Make sure there's enough space.
258 if (msg->start >= msg->base + msg->alloclen)
264 static sig_checksig_fn rsa_sig_check;
265 static bool_t rsa_sig_check(void *sst, uint8_t *data, int32_t datalen,
266 const struct alg_msg_data *sig)
268 struct rsapub *st=sst;
276 hash_hash(st->ops.hash,data,datalen,st->common.hashbuf);
277 emsa_pkcs1(&st->n, &a, st->common.hashbuf, st->ops.hash->hlen);
279 /* Terminate signature with a '0' - already checked that this will fit */
280 int save = sig->start[sig->len];
281 sig->start[sig->len] = 0;
282 mpz_set_str(&b, sig->start, 16);
283 sig->start[sig->len] = save;
285 mpz_powm(&c, &b, &st->e, &st->n);
287 ok=(mpz_cmp(&a, &c)==0);
296 static void rsapub_dispose(void *sst) {
297 struct rsapub *st=sst;
301 rsacommon_dispose(&st->common);
305 static list_t *rsapub_apply(closure_t *self, struct cloc loc, dict_t *context,
313 st->cl.description="rsapub";
314 st->cl.type=CL_SIGPUBKEY;
316 st->cl.interface=&st->ops;
318 st->ops.sethash=rsa_pub_sethash;
319 st->common.hashbuf=NULL;
320 st->ops.unpick=rsa_sig_unpick;
321 st->ops.check=rsa_sig_check;
323 st->ops.dispose=rsapub_dispose;
328 if (i->type!=t_string) {
329 cfgfatal(i->loc,"rsa-public","first argument must be a string\n");
332 if (mpz_init_set_str(&st->e,e,10)!=0) {
333 cfgfatal(i->loc,"rsa-public","encryption key \"%s\" is not a "
334 "decimal number string\n",e);
337 cfgfatal(loc,"rsa-public","you must provide an encryption key\n");
339 if (mpz_sizeinbase(&st->e, 256) > RSA_MAX_MODBYTES) {
340 cfgfatal(loc, "rsa-public", "implausibly large public exponent\n");
345 if (i->type!=t_string) {
346 cfgfatal(i->loc,"rsa-public","second argument must be a string\n");
349 if (mpz_init_set_str(&st->n,n,10)!=0) {
350 cfgfatal(i->loc,"rsa-public","modulus \"%s\" is not a decimal "
351 "number string\n",n);
354 cfgfatal(loc,"rsa-public","you must provide a modulus\n");
356 if (mpz_sizeinbase(&st->n, 256) > RSA_MAX_MODBYTES) {
357 cfgfatal(loc, "rsa-public", "implausibly large modulus\n");
359 return new_closure(&st->cl);
362 static void load_error(struct load_ctx *l, FILE *maybe_f,
363 bool_t unsup, const char *fmt, ...)
367 l->verror(l,maybe_f,unsup,fmt,al);
371 #define LDFATAL(...) ({ load_error(l,0,0,__VA_ARGS__); goto error_out; })
372 #define LDUNSUP(...) ({ load_error(l,0,1,__VA_ARGS__); goto error_out; })
373 #define LDFATAL_FILE(...) ({ load_error(l,f,0,__VA_ARGS__); goto error_out; })
374 #define LDUNSUP_FILE(...) ({ load_error(l,f,1,__VA_ARGS__); goto error_out; })
375 #define FREE(b) ({ free((b)); (b)=0; })
376 #define KEYFILE_GET(is) ({ \
377 uint##is##_t keyfile_get_tmp=keyfile_get_##is(l,f); \
378 if (!l->postreadcheck(l,f)) goto error_out; \
382 static uint32_t keyfile_get_32(struct load_ctx *l, FILE *f)
392 static uint16_t keyfile_get_16(struct load_ctx *l, FILE *f)
400 static void rsapriv_dispose(void *sst)
402 struct rsapriv *st=sst;
404 mpz_clear(&st->p); mpz_clear(&st->dp);
405 mpz_clear(&st->q); mpz_clear(&st->dq);
407 rsacommon_dispose(&st->common);
411 static struct rsapriv *rsa_loadpriv_core(struct load_ctx *l,
412 FILE *f, struct cloc loc,
413 bool_t do_validity_check)
415 struct rsapriv *st=0;
419 MP_INT e,d,iqmp,tmp,tmp2,tmp3;
430 st->cl.description="rsapriv";
431 st->cl.type=CL_SIGPRIVKEY;
433 st->cl.interface=&st->ops;
435 st->ops.sethash=rsa_priv_sethash;
436 st->common.hashbuf=NULL;
437 st->ops.sign=rsa_sign;
439 st->ops.dispose=rsapriv_dispose;
449 assert(just_check_config);
453 /* Check that the ID string is correct */
454 length=strlen(AUTHFILE_ID_STRING)+1;
455 b=safe_malloc(length,"rsapriv_apply");
456 if (fread(b,length,1,f)!=1 || memcmp(b,AUTHFILE_ID_STRING,length)!=0) {
457 LDUNSUP_FILE("failed to read magic ID"
458 " string from SSH1 private keyfile\n");
462 cipher_type=fgetc(f);
463 KEYFILE_GET(32); /* "Reserved data" */
464 if (cipher_type != 0) {
465 LDUNSUP("we don't support encrypted keyfiles\n");
468 /* Read the public key */
469 KEYFILE_GET(32); /* Not sure what this is */
470 length=(KEYFILE_GET(16)+7)/8;
471 if (length>RSA_MAX_MODBYTES) {
472 LDFATAL("implausible length %ld for modulus\n",
475 b=safe_malloc(length,"rsapriv_apply");
476 if (fread(b,length,1,f) != 1) {
477 LDFATAL_FILE("error reading modulus\n");
479 read_mpbin(&st->n,b,length);
481 length=(KEYFILE_GET(16)+7)/8;
482 if (length>RSA_MAX_MODBYTES) {
483 LDFATAL("implausible length %ld for e\n",length);
485 b=safe_malloc(length,"rsapriv_apply");
486 if (fread(b,length,1,f)!=1) {
487 LDFATAL_FILE("error reading e\n");
489 read_mpbin(&e,b,length);
492 length=KEYFILE_GET(32);
494 LDFATAL("implausibly long (%ld) key comment\n",
497 c=safe_malloc(length+1,"rsapriv_apply");
498 if (fread(c,length,1,f)!=1) {
499 LDFATAL_FILE("error reading key comment\n");
503 /* Check that the next two pairs of characters are identical - the
504 keyfile is not encrypted, so they should be */
506 if (KEYFILE_GET(16) != KEYFILE_GET(16)) {
507 LDFATAL("corrupt keyfile\n");
511 length=(KEYFILE_GET(16)+7)/8;
512 if (length>RSA_MAX_MODBYTES) {
513 LDFATAL("implausibly long (%ld) decryption key\n",
516 b=safe_malloc(length,"rsapriv_apply");
517 if (fread(b,length,1,f)!=1) {
518 LDFATAL_FILE("error reading decryption key\n");
520 read_mpbin(&d,b,length);
522 /* Read iqmp (inverse of q mod p) */
523 length=(KEYFILE_GET(16)+7)/8;
524 if (length>RSA_MAX_MODBYTES) {
525 LDFATAL("implausibly long (%ld)"
526 " iqmp auxiliary value\n", length);
528 b=safe_malloc(length,"rsapriv_apply");
529 if (fread(b,length,1,f)!=1) {
530 LDFATAL_FILE("error reading decryption key\n");
532 read_mpbin(&iqmp,b,length);
534 /* Read q (the smaller of the two primes) */
535 length=(KEYFILE_GET(16)+7)/8;
536 if (length>RSA_MAX_MODBYTES) {
537 LDFATAL("implausibly long (%ld) q value\n",
540 b=safe_malloc(length,"rsapriv_apply");
541 if (fread(b,length,1,f)!=1) {
542 LDFATAL_FILE("error reading q value\n");
544 read_mpbin(&st->q,b,length);
546 /* Read p (the larger of the two primes) */
547 length=(KEYFILE_GET(16)+7)/8;
548 if (length>RSA_MAX_MODBYTES) {
549 LDFATAL("implausibly long (%ld) p value\n",
552 b=safe_malloc(length,"rsapriv_apply");
553 if (fread(b,length,1,f)!=1) {
554 LDFATAL_FILE("error reading p value\n");
556 read_mpbin(&st->p,b,length);
560 fatal_perror("rsa-private (%s:%d): ferror",loc.file,loc.line);
564 * Now verify the validity of the key, and set up the auxiliary
565 * values for fast CRT signing.
568 if (do_validity_check) {
569 /* Verify that p*q is equal to n. */
570 mpz_mul(&tmp, &st->p, &st->q);
571 if (mpz_cmp(&tmp, &st->n) != 0)
575 * Verify that d*e is congruent to 1 mod (p-1), and mod
576 * (q-1). This is equivalent to it being congruent to 1 mod
577 * lambda(n) = lcm(p-1,q-1). The usual `textbook' condition,
578 * that d e == 1 (mod (p-1)(q-1)) is sufficient, but not
579 * actually necessary.
581 mpz_mul(&tmp, &d, &e);
582 mpz_sub_ui(&tmp2, &st->p, 1);
583 mpz_mod(&tmp3, &tmp, &tmp2);
584 if (mpz_cmp_si(&tmp3, 1) != 0)
586 mpz_sub_ui(&tmp2, &st->q, 1);
587 mpz_mod(&tmp3, &tmp, &tmp2);
588 if (mpz_cmp_si(&tmp3, 1) != 0)
591 /* Verify that q*iqmp is congruent to 1 mod p. */
592 mpz_mul(&tmp, &st->q, &iqmp);
593 mpz_mod(&tmp2, &tmp, &st->p);
594 if (mpz_cmp_si(&tmp2, 1) != 0)
597 /* Now we know the key is valid (or we don't care). */
601 * Now we compute auxiliary values dp, dq and w to allow us
602 * to use the CRT optimisation when signing.
604 * dp == d mod (p-1) so that a^dp == a^d mod p, for all a
605 * dq == d mod (q-1) similarly mod q
606 * w == iqmp * q so that w == 0 mod q, and w == 1 mod p
608 mpz_sub_ui(&tmp, &st->p, 1);
609 mpz_mod(&st->dp, &d, &tmp);
610 mpz_sub_ui(&tmp, &st->q, 1);
611 mpz_mod(&st->dq, &d, &tmp);
612 mpz_mul(&st->w, &iqmp, &st->q);
616 LDFATAL("file does not contain a "
635 if (st) rsapriv_dispose(st);
640 static bool_t postreadcheck_tryload(struct load_ctx *l, FILE *f)
643 if (feof(f)) { load_error(l,0,0,"eof mid-integer"); return False; }
647 bool_t rsa1_loadpriv(const struct sigscheme_info *algo,
648 struct buffer_if *privkeydata,
649 struct sigprivkey_if **sigpriv_r,
650 struct log_if *log, struct cloc loc)
653 struct rsapriv *st=0;
655 f=fmemopen(privkeydata->start,privkeydata->size,"r");
657 slilog(log,M_ERR,"failed to fmemopen private key file\n");
661 struct load_ctx l[1];
662 l->what="rsa1priv load";
663 l->verror=verror_tryload;
664 l->postreadcheck=postreadcheck_tryload;
666 l->u.tryload.log=log;
668 st=rsa_loadpriv_core(l,f,loc,False);
669 if (!st) goto error_out;
673 if (st) { free(st); st=0; }
676 if (!st) return False;
681 static bool_t postreadcheck_apply(struct load_ctx *l, FILE *f)
683 cfgfile_postreadcheck(*l->loc,f);
687 static list_t *rsapriv_apply(closure_t *self, struct cloc loc, dict_t *context,
694 struct load_ctx l[1];
696 l->what="rsa-private";
697 l->verror=verror_cfgfatal;
698 l->postreadcheck=postreadcheck_apply;
701 /* Argument is filename pointing to SSH1 private key file */
704 if (i->type!=t_string) {
705 cfgfatal(i->loc,"rsa-private","first argument must be a string\n");
707 filename=i->data.string;
709 filename=NULL; /* Make compiler happy */
710 cfgfatal(i->loc,"rsa-private","you must provide a filename\n");
713 f=fopen(filename,"rb");
715 if (just_check_config) {
716 Message(M_WARNING,"rsa-private (%s:%d): cannot open keyfile "
717 "\"%s\"; assuming it's valid while we check the "
718 "rest of the configuration\n",loc.file,loc.line,filename);
720 fatal_perror("rsa-private (%s:%d): cannot open file \"%s\"",
721 loc.file,loc.line,filename);
725 bool_t do_validity_check=True;
727 if (i && i->type==t_bool && i->data.bool==False) {
728 Message(M_INFO,"rsa-private (%s:%d): skipping RSA key validity "
729 "check\n",loc.file,loc.line);
730 do_validity_check=False;
733 st=rsa_loadpriv_core(l,f,loc,do_validity_check);
735 return new_closure(&st->cl);
738 void rsa_module(dict_t *dict)
740 add_closure(dict,"rsa-private",rsapriv_apply);
741 add_closure(dict,"rsa-public",rsapub_apply);