]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - sshdss.c
Const-correctness in public-key functions.
[PuTTY.git] / sshdss.c
1 /*
2  * Digital Signature Standard implementation for PuTTY.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <assert.h>
8
9 #include "ssh.h"
10 #include "misc.h"
11
12 static void sha_mpint(SHA_State * s, Bignum b)
13 {
14     unsigned char lenbuf[4];
15     int len;
16     len = (bignum_bitcount(b) + 8) / 8;
17     PUT_32BIT(lenbuf, len);
18     SHA_Bytes(s, lenbuf, 4);
19     while (len-- > 0) {
20         lenbuf[0] = bignum_byte(b, len);
21         SHA_Bytes(s, lenbuf, 1);
22     }
23     smemclr(lenbuf, sizeof(lenbuf));
24 }
25
26 static void sha512_mpint(SHA512_State * s, Bignum b)
27 {
28     unsigned char lenbuf[4];
29     int len;
30     len = (bignum_bitcount(b) + 8) / 8;
31     PUT_32BIT(lenbuf, len);
32     SHA512_Bytes(s, lenbuf, 4);
33     while (len-- > 0) {
34         lenbuf[0] = bignum_byte(b, len);
35         SHA512_Bytes(s, lenbuf, 1);
36     }
37     smemclr(lenbuf, sizeof(lenbuf));
38 }
39
40 static void getstring(const char **data, int *datalen,
41                       const char **p, int *length)
42 {
43     *p = NULL;
44     if (*datalen < 4)
45         return;
46     *length = toint(GET_32BIT(*data));
47     if (*length < 0)
48         return;
49     *datalen -= 4;
50     *data += 4;
51     if (*datalen < *length)
52         return;
53     *p = *data;
54     *data += *length;
55     *datalen -= *length;
56 }
57 static Bignum getmp(const char **data, int *datalen)
58 {
59     const char *p;
60     int length;
61     Bignum b;
62
63     getstring(data, datalen, &p, &length);
64     if (!p)
65         return NULL;
66     if (p[0] & 0x80)
67         return NULL;                   /* negative mp */
68     b = bignum_from_bytes((const unsigned char *)p, length);
69     return b;
70 }
71
72 static Bignum get160(const char **data, int *datalen)
73 {
74     Bignum b;
75
76     if (*datalen < 20)
77         return NULL;
78
79     b = bignum_from_bytes((const unsigned char *)*data, 20);
80     *data += 20;
81     *datalen -= 20;
82
83     return b;
84 }
85
86 static void dss_freekey(void *key);    /* forward reference */
87
88 static void *dss_newkey(const char *data, int len)
89 {
90     const char *p;
91     int slen;
92     struct dss_key *dss;
93
94     dss = snew(struct dss_key);
95     getstring(&data, &len, &p, &slen);
96
97 #ifdef DEBUG_DSS
98     {
99         int i;
100         printf("key:");
101         for (i = 0; i < len; i++)
102             printf("  %02x", (unsigned char) (data[i]));
103         printf("\n");
104     }
105 #endif
106
107     if (!p || slen != 7 || memcmp(p, "ssh-dss", 7)) {
108         sfree(dss);
109         return NULL;
110     }
111     dss->p = getmp(&data, &len);
112     dss->q = getmp(&data, &len);
113     dss->g = getmp(&data, &len);
114     dss->y = getmp(&data, &len);
115     dss->x = NULL;
116
117     if (!dss->p || !dss->q || !dss->g || !dss->y ||
118         !bignum_cmp(dss->q, Zero) || !bignum_cmp(dss->p, Zero)) {
119         /* Invalid key. */
120         dss_freekey(dss);
121         return NULL;
122     }
123
124     return dss;
125 }
126
127 static void dss_freekey(void *key)
128 {
129     struct dss_key *dss = (struct dss_key *) key;
130     if (dss->p)
131         freebn(dss->p);
132     if (dss->q)
133         freebn(dss->q);
134     if (dss->g)
135         freebn(dss->g);
136     if (dss->y)
137         freebn(dss->y);
138     if (dss->x)
139         freebn(dss->x);
140     sfree(dss);
141 }
142
143 static char *dss_fmtkey(void *key)
144 {
145     struct dss_key *dss = (struct dss_key *) key;
146     char *p;
147     int len, i, pos, nibbles;
148     static const char hex[] = "0123456789abcdef";
149     if (!dss->p)
150         return NULL;
151     len = 8 + 4 + 1;                   /* 4 x "0x", punctuation, \0 */
152     len += 4 * (bignum_bitcount(dss->p) + 15) / 16;
153     len += 4 * (bignum_bitcount(dss->q) + 15) / 16;
154     len += 4 * (bignum_bitcount(dss->g) + 15) / 16;
155     len += 4 * (bignum_bitcount(dss->y) + 15) / 16;
156     p = snewn(len, char);
157     if (!p)
158         return NULL;
159
160     pos = 0;
161     pos += sprintf(p + pos, "0x");
162     nibbles = (3 + bignum_bitcount(dss->p)) / 4;
163     if (nibbles < 1)
164         nibbles = 1;
165     for (i = nibbles; i--;)
166         p[pos++] =
167             hex[(bignum_byte(dss->p, i / 2) >> (4 * (i % 2))) & 0xF];
168     pos += sprintf(p + pos, ",0x");
169     nibbles = (3 + bignum_bitcount(dss->q)) / 4;
170     if (nibbles < 1)
171         nibbles = 1;
172     for (i = nibbles; i--;)
173         p[pos++] =
174             hex[(bignum_byte(dss->q, i / 2) >> (4 * (i % 2))) & 0xF];
175     pos += sprintf(p + pos, ",0x");
176     nibbles = (3 + bignum_bitcount(dss->g)) / 4;
177     if (nibbles < 1)
178         nibbles = 1;
179     for (i = nibbles; i--;)
180         p[pos++] =
181             hex[(bignum_byte(dss->g, i / 2) >> (4 * (i % 2))) & 0xF];
182     pos += sprintf(p + pos, ",0x");
183     nibbles = (3 + bignum_bitcount(dss->y)) / 4;
184     if (nibbles < 1)
185         nibbles = 1;
186     for (i = nibbles; i--;)
187         p[pos++] =
188             hex[(bignum_byte(dss->y, i / 2) >> (4 * (i % 2))) & 0xF];
189     p[pos] = '\0';
190     return p;
191 }
192
193 static char *dss_fingerprint(void *key)
194 {
195     struct dss_key *dss = (struct dss_key *) key;
196     struct MD5Context md5c;
197     unsigned char digest[16], lenbuf[4];
198     char buffer[16 * 3 + 40];
199     char *ret;
200     int numlen, i;
201
202     MD5Init(&md5c);
203     MD5Update(&md5c, (unsigned char *)"\0\0\0\7ssh-dss", 11);
204
205 #define ADD_BIGNUM(bignum) \
206     numlen = (bignum_bitcount(bignum)+8)/8; \
207     PUT_32BIT(lenbuf, numlen); MD5Update(&md5c, lenbuf, 4); \
208     for (i = numlen; i-- ;) { \
209         unsigned char c = bignum_byte(bignum, i); \
210         MD5Update(&md5c, &c, 1); \
211     }
212     ADD_BIGNUM(dss->p);
213     ADD_BIGNUM(dss->q);
214     ADD_BIGNUM(dss->g);
215     ADD_BIGNUM(dss->y);
216 #undef ADD_BIGNUM
217
218     MD5Final(digest, &md5c);
219
220     sprintf(buffer, "ssh-dss %d ", bignum_bitcount(dss->p));
221     for (i = 0; i < 16; i++)
222         sprintf(buffer + strlen(buffer), "%s%02x", i ? ":" : "",
223                 digest[i]);
224     ret = snewn(strlen(buffer) + 1, char);
225     if (ret)
226         strcpy(ret, buffer);
227     return ret;
228 }
229
230 static int dss_verifysig(void *key, const char *sig, int siglen,
231                          const char *data, int datalen)
232 {
233     struct dss_key *dss = (struct dss_key *) key;
234     const char *p;
235     int slen;
236     char hash[20];
237     Bignum r, s, w, gu1p, yu2p, gu1yu2p, u1, u2, sha, v;
238     int ret;
239
240     if (!dss->p)
241         return 0;
242
243 #ifdef DEBUG_DSS
244     {
245         int i;
246         printf("sig:");
247         for (i = 0; i < siglen; i++)
248             printf("  %02x", (unsigned char) (sig[i]));
249         printf("\n");
250     }
251 #endif
252     /*
253      * Commercial SSH (2.0.13) and OpenSSH disagree over the format
254      * of a DSA signature. OpenSSH is in line with RFC 4253:
255      * it uses a string "ssh-dss", followed by a 40-byte string
256      * containing two 160-bit integers end-to-end. Commercial SSH
257      * can't be bothered with the header bit, and considers a DSA
258      * signature blob to be _just_ the 40-byte string containing
259      * the two 160-bit integers. We tell them apart by measuring
260      * the length: length 40 means the commercial-SSH bug, anything
261      * else is assumed to be RFC-compliant.
262      */
263     if (siglen != 40) {                /* bug not present; read admin fields */
264         getstring(&sig, &siglen, &p, &slen);
265         if (!p || slen != 7 || memcmp(p, "ssh-dss", 7)) {
266             return 0;
267         }
268         sig += 4, siglen -= 4;         /* skip yet another length field */
269     }
270     r = get160(&sig, &siglen);
271     s = get160(&sig, &siglen);
272     if (!r || !s) {
273         if (r)
274             freebn(r);
275         if (s)
276             freebn(s);
277         return 0;
278     }
279
280     if (!bignum_cmp(s, Zero)) {
281         freebn(r);
282         freebn(s);
283         return 0;
284     }
285
286     /*
287      * Step 1. w <- s^-1 mod q.
288      */
289     w = modinv(s, dss->q);
290     if (!w) {
291         freebn(r);
292         freebn(s);
293         return 0;
294     }
295
296     /*
297      * Step 2. u1 <- SHA(message) * w mod q.
298      */
299     SHA_Simple(data, datalen, (unsigned char *)hash);
300     p = hash;
301     slen = 20;
302     sha = get160(&p, &slen);
303     u1 = modmul(sha, w, dss->q);
304
305     /*
306      * Step 3. u2 <- r * w mod q.
307      */
308     u2 = modmul(r, w, dss->q);
309
310     /*
311      * Step 4. v <- (g^u1 * y^u2 mod p) mod q.
312      */
313     gu1p = modpow(dss->g, u1, dss->p);
314     yu2p = modpow(dss->y, u2, dss->p);
315     gu1yu2p = modmul(gu1p, yu2p, dss->p);
316     v = modmul(gu1yu2p, One, dss->q);
317
318     /*
319      * Step 5. v should now be equal to r.
320      */
321
322     ret = !bignum_cmp(v, r);
323
324     freebn(w);
325     freebn(sha);
326     freebn(u1);
327     freebn(u2);
328     freebn(gu1p);
329     freebn(yu2p);
330     freebn(gu1yu2p);
331     freebn(v);
332     freebn(r);
333     freebn(s);
334
335     return ret;
336 }
337
338 static unsigned char *dss_public_blob(void *key, int *len)
339 {
340     struct dss_key *dss = (struct dss_key *) key;
341     int plen, qlen, glen, ylen, bloblen;
342     int i;
343     unsigned char *blob, *p;
344
345     plen = (bignum_bitcount(dss->p) + 8) / 8;
346     qlen = (bignum_bitcount(dss->q) + 8) / 8;
347     glen = (bignum_bitcount(dss->g) + 8) / 8;
348     ylen = (bignum_bitcount(dss->y) + 8) / 8;
349
350     /*
351      * string "ssh-dss", mpint p, mpint q, mpint g, mpint y. Total
352      * 27 + sum of lengths. (five length fields, 20+7=27).
353      */
354     bloblen = 27 + plen + qlen + glen + ylen;
355     blob = snewn(bloblen, unsigned char);
356     p = blob;
357     PUT_32BIT(p, 7);
358     p += 4;
359     memcpy(p, "ssh-dss", 7);
360     p += 7;
361     PUT_32BIT(p, plen);
362     p += 4;
363     for (i = plen; i--;)
364         *p++ = bignum_byte(dss->p, i);
365     PUT_32BIT(p, qlen);
366     p += 4;
367     for (i = qlen; i--;)
368         *p++ = bignum_byte(dss->q, i);
369     PUT_32BIT(p, glen);
370     p += 4;
371     for (i = glen; i--;)
372         *p++ = bignum_byte(dss->g, i);
373     PUT_32BIT(p, ylen);
374     p += 4;
375     for (i = ylen; i--;)
376         *p++ = bignum_byte(dss->y, i);
377     assert(p == blob + bloblen);
378     *len = bloblen;
379     return blob;
380 }
381
382 static unsigned char *dss_private_blob(void *key, int *len)
383 {
384     struct dss_key *dss = (struct dss_key *) key;
385     int xlen, bloblen;
386     int i;
387     unsigned char *blob, *p;
388
389     xlen = (bignum_bitcount(dss->x) + 8) / 8;
390
391     /*
392      * mpint x, string[20] the SHA of p||q||g. Total 4 + xlen.
393      */
394     bloblen = 4 + xlen;
395     blob = snewn(bloblen, unsigned char);
396     p = blob;
397     PUT_32BIT(p, xlen);
398     p += 4;
399     for (i = xlen; i--;)
400         *p++ = bignum_byte(dss->x, i);
401     assert(p == blob + bloblen);
402     *len = bloblen;
403     return blob;
404 }
405
406 static void *dss_createkey(const unsigned char *pub_blob, int pub_len,
407                            const unsigned char *priv_blob, int priv_len)
408 {
409     struct dss_key *dss;
410     const char *pb = (const char *) priv_blob;
411     const char *hash;
412     int hashlen;
413     SHA_State s;
414     unsigned char digest[20];
415     Bignum ytest;
416
417     dss = dss_newkey((char *) pub_blob, pub_len);
418     if (!dss)
419         return NULL;
420     dss->x = getmp(&pb, &priv_len);
421     if (!dss->x) {
422         dss_freekey(dss);
423         return NULL;
424     }
425
426     /*
427      * Check the obsolete hash in the old DSS key format.
428      */
429     hashlen = -1;
430     getstring(&pb, &priv_len, &hash, &hashlen);
431     if (hashlen == 20) {
432         SHA_Init(&s);
433         sha_mpint(&s, dss->p);
434         sha_mpint(&s, dss->q);
435         sha_mpint(&s, dss->g);
436         SHA_Final(&s, digest);
437         if (0 != memcmp(hash, digest, 20)) {
438             dss_freekey(dss);
439             return NULL;
440         }
441     }
442
443     /*
444      * Now ensure g^x mod p really is y.
445      */
446     ytest = modpow(dss->g, dss->x, dss->p);
447     if (0 != bignum_cmp(ytest, dss->y)) {
448         dss_freekey(dss);
449         freebn(ytest);
450         return NULL;
451     }
452     freebn(ytest);
453
454     return dss;
455 }
456
457 static void *dss_openssh_createkey(const unsigned char **blob, int *len)
458 {
459     const char **b = (const char **) blob;
460     struct dss_key *dss;
461
462     dss = snew(struct dss_key);
463
464     dss->p = getmp(b, len);
465     dss->q = getmp(b, len);
466     dss->g = getmp(b, len);
467     dss->y = getmp(b, len);
468     dss->x = getmp(b, len);
469
470     if (!dss->p || !dss->q || !dss->g || !dss->y || !dss->x ||
471         !bignum_cmp(dss->q, Zero) || !bignum_cmp(dss->p, Zero)) {
472         /* Invalid key. */
473         dss_freekey(dss);
474         return NULL;
475     }
476
477     return dss;
478 }
479
480 static int dss_openssh_fmtkey(void *key, unsigned char *blob, int len)
481 {
482     struct dss_key *dss = (struct dss_key *) key;
483     int bloblen, i;
484
485     bloblen =
486         ssh2_bignum_length(dss->p) +
487         ssh2_bignum_length(dss->q) +
488         ssh2_bignum_length(dss->g) +
489         ssh2_bignum_length(dss->y) +
490         ssh2_bignum_length(dss->x);
491
492     if (bloblen > len)
493         return bloblen;
494
495     bloblen = 0;
496 #define ENC(x) \
497     PUT_32BIT(blob+bloblen, ssh2_bignum_length((x))-4); bloblen += 4; \
498     for (i = ssh2_bignum_length((x))-4; i-- ;) blob[bloblen++]=bignum_byte((x),i);
499     ENC(dss->p);
500     ENC(dss->q);
501     ENC(dss->g);
502     ENC(dss->y);
503     ENC(dss->x);
504
505     return bloblen;
506 }
507
508 static int dss_pubkey_bits(const void *blob, int len)
509 {
510     struct dss_key *dss;
511     int ret;
512
513     dss = dss_newkey((const char *) blob, len);
514     if (!dss)
515         return -1;
516     ret = bignum_bitcount(dss->p);
517     dss_freekey(dss);
518
519     return ret;
520 }
521
522 Bignum *dss_gen_k(const char *id_string, Bignum modulus, Bignum private_key,
523                   unsigned char *digest, int digest_len)
524 {
525     /*
526      * The basic DSS signing algorithm is:
527      * 
528      *  - invent a random k between 1 and q-1 (exclusive).
529      *  - Compute r = (g^k mod p) mod q.
530      *  - Compute s = k^-1 * (hash + x*r) mod q.
531      * 
532      * This has the dangerous properties that:
533      * 
534      *  - if an attacker in possession of the public key _and_ the
535      *    signature (for example, the host you just authenticated
536      *    to) can guess your k, he can reverse the computation of s
537      *    and work out x = r^-1 * (s*k - hash) mod q. That is, he
538      *    can deduce the private half of your key, and masquerade
539      *    as you for as long as the key is still valid.
540      * 
541      *  - since r is a function purely of k and the public key, if
542      *    the attacker only has a _range of possibilities_ for k
543      *    it's easy for him to work through them all and check each
544      *    one against r; he'll never be unsure of whether he's got
545      *    the right one.
546      * 
547      *  - if you ever sign two different hashes with the same k, it
548      *    will be immediately obvious because the two signatures
549      *    will have the same r, and moreover an attacker in
550      *    possession of both signatures (and the public key of
551      *    course) can compute k = (hash1-hash2) * (s1-s2)^-1 mod q,
552      *    and from there deduce x as before.
553      * 
554      *  - the Bleichenbacher attack on DSA makes use of methods of
555      *    generating k which are significantly non-uniformly
556      *    distributed; in particular, generating a 160-bit random
557      *    number and reducing it mod q is right out.
558      * 
559      * For this reason we must be pretty careful about how we
560      * generate our k. Since this code runs on Windows, with no
561      * particularly good system entropy sources, we can't trust our
562      * RNG itself to produce properly unpredictable data. Hence, we
563      * use a totally different scheme instead.
564      * 
565      * What we do is to take a SHA-512 (_big_) hash of the private
566      * key x, and then feed this into another SHA-512 hash that
567      * also includes the message hash being signed. That is:
568      * 
569      *   proto_k = SHA512 ( SHA512(x) || SHA160(message) )
570      * 
571      * This number is 512 bits long, so reducing it mod q won't be
572      * noticeably non-uniform. So
573      * 
574      *   k = proto_k mod q
575      * 
576      * This has the interesting property that it's _deterministic_:
577      * signing the same hash twice with the same key yields the
578      * same signature.
579      * 
580      * Despite this determinism, it's still not predictable to an
581      * attacker, because in order to repeat the SHA-512
582      * construction that created it, the attacker would have to
583      * know the private key value x - and by assumption he doesn't,
584      * because if he knew that he wouldn't be attacking k!
585      *
586      * (This trick doesn't, _per se_, protect against reuse of k.
587      * Reuse of k is left to chance; all it does is prevent
588      * _excessively high_ chances of reuse of k due to entropy
589      * problems.)
590      * 
591      * Thanks to Colin Plumb for the general idea of using x to
592      * ensure k is hard to guess, and to the Cambridge University
593      * Computer Security Group for helping to argue out all the
594      * fine details.
595      */
596     SHA512_State ss;
597     unsigned char digest512[64];
598     Bignum proto_k, k;
599
600     /*
601      * Hash some identifying text plus x.
602      */
603     SHA512_Init(&ss);
604     SHA512_Bytes(&ss, id_string, strlen(id_string) + 1);
605     sha512_mpint(&ss, private_key);
606     SHA512_Final(&ss, digest512);
607
608     /*
609      * Now hash that digest plus the message hash.
610      */
611     SHA512_Init(&ss);
612     SHA512_Bytes(&ss, digest512, sizeof(digest512));
613     SHA512_Bytes(&ss, digest, digest_len);
614
615     while (1) {
616         SHA512_State ss2 = ss;         /* structure copy */
617         SHA512_Final(&ss2, digest512);
618
619         smemclr(&ss2, sizeof(ss2));
620
621         /*
622          * Now convert the result into a bignum, and reduce it mod q.
623          */
624         proto_k = bignum_from_bytes(digest512, 64);
625         k = bigmod(proto_k, modulus);
626         freebn(proto_k);
627
628         if (bignum_cmp(k, One) != 0 && bignum_cmp(k, Zero) != 0) {
629             smemclr(&ss, sizeof(ss));
630             smemclr(digest512, sizeof(digest512));
631             return k;
632         }
633
634         /* Very unlikely we get here, but if so, k was unsuitable. */
635         freebn(k);
636         /* Perturb the hash to think of a different k. */
637         SHA512_Bytes(&ss, "x", 1);
638         /* Go round and try again. */
639     }
640 }
641
642 static unsigned char *dss_sign(void *key, const char *data, int datalen,
643                                int *siglen)
644 {
645     struct dss_key *dss = (struct dss_key *) key;
646     Bignum k, gkp, hash, kinv, hxr, r, s;
647     unsigned char digest[20];
648     unsigned char *bytes;
649     int nbytes, i;
650
651     SHA_Simple(data, datalen, digest);
652
653     k = dss_gen_k("DSA deterministic k generator", dss->q, dss->x,
654                   digest, sizeof(digest));
655     kinv = modinv(k, dss->q);          /* k^-1 mod q */
656     assert(kinv);
657
658     /*
659      * Now we have k, so just go ahead and compute the signature.
660      */
661     gkp = modpow(dss->g, k, dss->p);   /* g^k mod p */
662     r = bigmod(gkp, dss->q);           /* r = (g^k mod p) mod q */
663     freebn(gkp);
664
665     hash = bignum_from_bytes(digest, 20);
666     hxr = bigmuladd(dss->x, r, hash);  /* hash + x*r */
667     s = modmul(kinv, hxr, dss->q);     /* s = k^-1 * (hash + x*r) mod q */
668     freebn(hxr);
669     freebn(kinv);
670     freebn(k);
671     freebn(hash);
672
673     /*
674      * Signature blob is
675      * 
676      *   string  "ssh-dss"
677      *   string  two 20-byte numbers r and s, end to end
678      * 
679      * i.e. 4+7 + 4+40 bytes.
680      */
681     nbytes = 4 + 7 + 4 + 40;
682     bytes = snewn(nbytes, unsigned char);
683     PUT_32BIT(bytes, 7);
684     memcpy(bytes + 4, "ssh-dss", 7);
685     PUT_32BIT(bytes + 4 + 7, 40);
686     for (i = 0; i < 20; i++) {
687         bytes[4 + 7 + 4 + i] = bignum_byte(r, 19 - i);
688         bytes[4 + 7 + 4 + 20 + i] = bignum_byte(s, 19 - i);
689     }
690     freebn(r);
691     freebn(s);
692
693     *siglen = nbytes;
694     return bytes;
695 }
696
697 const struct ssh_signkey ssh_dss = {
698     dss_newkey,
699     dss_freekey,
700     dss_fmtkey,
701     dss_public_blob,
702     dss_private_blob,
703     dss_createkey,
704     dss_openssh_createkey,
705     dss_openssh_fmtkey,
706     5 /* p,q,g,y,x */,
707     dss_pubkey_bits,
708     dss_fingerprint,
709     dss_verifysig,
710     dss_sign,
711     "ssh-dss",
712     "dss"
713 };