See ChangeLog: Thu Jan 27 18:00:44 CET 2000 Werner Koch
[gnupg.git] / g10 / seckey-cert.c
1 /* seckey-cert.c -  secret key certificate packet handling
2  *      Copyright (C) 1998, 1999 Free Software Foundation, Inc.
3  *
4  * This file is part of GnuPG.
5  *
6  * GnuPG is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * GnuPG is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
19  */
20
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <assert.h>
26
27 #include <gcrypt.h>
28 #include "util.h"
29 #include "packet.h"
30 #include "keydb.h"
31 #include "main.h"
32 #include "options.h"
33 #include "i18n.h"
34 #include "status.h"
35
36 /****************
37  * Emulate our old PK interface here - sometime in the future we might
38  * change the internal design to directly fit to libgcrypt.
39  */
40 static int
41 pk_check_secret_key( int algo, MPI *skey )
42 {
43     GCRY_SEXP s_skey;
44     int rc;
45
46     /* make a sexp from skey */
47     if( algo == GCRY_PK_DSA ) {
48         s_skey = SEXP_CONS( SEXP_NEW( "private-key", 0 ),
49                           gcry_sexp_vlist( SEXP_NEW( "dsa", 0 ),
50                           gcry_sexp_new_name_mpi( "p", skey[0] ),
51                           gcry_sexp_new_name_mpi( "q", skey[1] ),
52                           gcry_sexp_new_name_mpi( "g", skey[2] ),
53                           gcry_sexp_new_name_mpi( "y", skey[3] ),
54                           gcry_sexp_new_name_mpi( "x", skey[4] ),
55                           NULL ));
56     }
57     else if( algo == GCRY_PK_ELG || algo == GCRY_PK_ELG_E ) {
58         s_skey = SEXP_CONS( SEXP_NEW( "private-key", 0 ),
59                           gcry_sexp_vlist( SEXP_NEW( "elg", 0 ),
60                           gcry_sexp_new_name_mpi( "p", skey[0] ),
61                           gcry_sexp_new_name_mpi( "g", skey[1] ),
62                           gcry_sexp_new_name_mpi( "y", skey[2] ),
63                           gcry_sexp_new_name_mpi( "x", skey[3] ),
64                           NULL ));
65     }
66     else if( algo == GCRY_PK_RSA ) {
67         s_skey = SEXP_CONS( SEXP_NEW( "private-key", 0 ),
68                           gcry_sexp_vlist( SEXP_NEW( "rsa", 0 ),
69                           gcry_sexp_new_name_mpi( "n", skey[0] ),
70                           gcry_sexp_new_name_mpi( "e", skey[1] ),
71                           gcry_sexp_new_name_mpi( "d", skey[2] ),
72                           gcry_sexp_new_name_mpi( "p", skey[3] ),
73                           gcry_sexp_new_name_mpi( "q", skey[4] ),
74                           gcry_sexp_new_name_mpi( "u", skey[5] ),
75                           NULL ));
76     }
77     else
78         return GPGERR_PUBKEY_ALGO;
79
80     rc = gcry_pk_testkey( s_skey );
81     gcry_sexp_release( s_skey );
82     return rc;
83 }
84
85 static int
86 do_check( PKT_secret_key *sk )
87 {
88     u16 csum=0;
89     int i, res;
90     unsigned nbytes;
91
92     if( sk->is_protected ) { /* remove the protection */
93         DEK *dek = NULL;
94         u32 keyid[4]; /* 4! because we need two of them */
95         GCRY_CIPHER_HD cipher_hd=NULL;
96         PKT_secret_key *save_sk;
97
98         if( sk->protect.algo == GCRY_CIPHER_NONE )
99             BUG();
100         if( openpgp_cipher_test_algo( sk->protect.algo ) ) {
101             log_info(_("protection algorithm %d is not supported\n"),
102                         sk->protect.algo );
103             return GPGERR_CIPHER_ALGO;
104         }
105         keyid_from_sk( sk, keyid );
106         keyid[2] = keyid[3] = 0;
107         if( !sk->is_primary ) {
108             PKT_secret_key *sk2 = gcry_xcalloc( 1, sizeof *sk2 );
109             if( !get_primary_seckey( sk2, keyid ) )
110                 keyid_from_sk( sk2, keyid+2 );
111             free_secret_key( sk2 );
112         }
113         dek = passphrase_to_dek( keyid, sk->pubkey_algo, sk->protect.algo,
114                                  &sk->protect.s2k, 0 );
115         if( !(cipher_hd = gcry_cipher_open( sk->protect.algo,
116                                       GCRY_CIPHER_MODE_CFB,
117                                       GCRY_CIPHER_SECURE
118                                       | (sk->protect.algo >= 100 ?
119                                            0 : GCRY_CIPHER_ENABLE_SYNC) ) )
120                                     ) {
121             BUG();
122         }
123
124         if( gcry_cipher_setkey( cipher_hd, dek->key, dek->keylen ) )
125             log_fatal("set key failed: %s\n", gcry_strerror(-1) );
126         gcry_free(dek);
127         save_sk = copy_secret_key( NULL, sk );
128         if( gcry_cipher_setiv( cipher_hd, sk->protect.iv, sk->protect.ivlen ))
129             log_fatal("set IV failed: %s\n", gcry_strerror(-1) );
130         csum = 0;
131         if( sk->version >= 4 ) {
132             size_t ndata;
133             unsigned int ndatabits;
134             byte *p, *data;
135
136             i = pubkey_get_npkey(sk->pubkey_algo);
137             assert( gcry_mpi_get_flag( sk->skey[i], GCRYMPI_FLAG_OPAQUE ) );
138             p = gcry_mpi_get_opaque( sk->skey[i], &ndatabits );
139             ndata = (ndatabits+7)/8;
140             data = gcry_xmalloc_secure( ndata );
141             gcry_cipher_decrypt( cipher_hd, data, ndata, p, ndata );
142             mpi_release( sk->skey[i] ); sk->skey[i] = NULL ;
143             p = data;
144             if( ndata < 2 ) {
145                 log_error("not enough bytes for checksum\n");
146                 sk->csum = 0;
147                 csum = 1;
148             }
149             else {
150                 csum = checksum( data, ndata-2);
151                 sk->csum = data[ndata-2] << 8 | data[ndata-1];
152             }
153             /* must check it here otherwise the mpi_read_xx would fail
154              * because the length may have an arbitrary value */
155             if( sk->csum == csum ) {
156                 for( ; i < pubkey_get_nskey(sk->pubkey_algo); i++ ) {
157                     nbytes = ndata;
158                     assert( gcry_is_secure( p ) );
159                     res = gcry_mpi_scan( &sk->skey[i], GCRYMPI_FMT_PGP,
160                                                              p, &nbytes);
161                     if( res )
162                         log_bug("gcry_mpi_scan failed in do_check: rc=%d\n", res);
163
164                     ndata -= nbytes;
165                     p += nbytes;
166                 }
167             }
168             gcry_free(data);
169         }
170         else {
171             for(i=pubkey_get_npkey(sk->pubkey_algo);
172                     i < pubkey_get_nskey(sk->pubkey_algo); i++ ) {
173                 size_t ndata;
174                 unsigned int ndatabits;
175                 byte *p, *data;
176
177                 assert( gcry_mpi_get_flag( sk->skey[i], GCRYMPI_FLAG_OPAQUE ) );
178                 p = gcry_mpi_get_opaque( sk->skey[i], &ndatabits );
179                 ndata = (ndatabits+7)/8;
180                 data = gcry_xmalloc_secure( ndata );
181                 gcry_cipher_sync( cipher_hd );
182                 gcry_cipher_decrypt( cipher_hd, data, ndata, p, ndata );
183                 mpi_release( sk->skey[i] ); sk->skey[i] = NULL ;
184
185                 res = gcry_mpi_scan( &sk->skey[i], GCRYMPI_FMT_USG,
186                                      data, &ndata );
187                 if( res )
188                     log_bug("gcry_mpi_scan failed in do_check: rc=%d\n", res);
189
190                 csum += checksum_mpi( sk->skey[i] );
191                 gcry_free( data );
192             }
193         }
194         gcry_cipher_close( cipher_hd );
195         /* now let's see whether we have used the right passphrase */
196         if( csum != sk->csum ) {
197             copy_secret_key( sk, save_sk );
198             free_secret_key( save_sk );
199             return GPGERR_BAD_PASS;
200         }
201         /* the checksum may fail, so we also check the key itself */
202         res = pk_check_secret_key( sk->pubkey_algo, sk->skey );
203         if( res ) {
204             copy_secret_key( sk, save_sk );
205             free_secret_key( save_sk );
206             return GPGERR_BAD_PASS;
207         }
208         free_secret_key( save_sk );
209         sk->is_protected = 0;
210     }
211     else { /* not protected, assume it is okay if the checksum is okay */
212         csum = 0;
213         for(i=pubkey_get_npkey(sk->pubkey_algo);
214                 i < pubkey_get_nskey(sk->pubkey_algo); i++ ) {
215             assert( !gcry_mpi_get_flag( sk->skey[i], GCRYMPI_FLAG_OPAQUE ) );
216             csum += checksum_mpi( sk->skey[i] );
217         }
218         if( csum != sk->csum )
219             return GPGERR_CHECKSUM;
220     }
221
222     return 0;
223 }
224
225
226
227 /****************
228  * Check the secret key
229  * Ask up to 3 (or n) times for a correct passphrase
230  */
231 int
232 check_secret_key( PKT_secret_key *sk, int n )
233 {
234     int rc = GPGERR_BAD_PASS;
235     int i;
236
237     if( n < 1 )
238         n = opt.batch? 1 : 3; /* use the default value */
239
240     for(i=0; i < n && rc == GPGERR_BAD_PASS; i++ ) {
241         if( i )
242             log_info(_("Invalid passphrase; please try again ...\n"));
243         rc = do_check( sk );
244         if( rc == GPGERR_BAD_PASS && is_status_enabled() ) {
245             u32 kid[2];
246             char buf[50];
247
248             keyid_from_sk( sk, kid );
249             sprintf(buf, "%08lX%08lX", (ulong)kid[0], (ulong)kid[1]);
250             write_status_text( STATUS_BAD_PASSPHRASE, buf );
251         }
252         if( have_static_passphrase() )
253             break;
254     }
255
256     if( !rc )
257         write_status( STATUS_GOOD_PASSPHRASE );
258
259     return rc;
260 }
261
262 /****************
263  * check whether the secret key is protected.
264  * Returns: 0 not protected, -1 on error or the protection algorithm
265  */
266 int
267 is_secret_key_protected( PKT_secret_key *sk )
268 {
269     return sk->is_protected? sk->protect.algo : 0;
270 }
271
272
273
274 /****************
275  * Protect the secret key with the passphrase from DEK
276  */
277 int
278 protect_secret_key( PKT_secret_key *sk, DEK *dek )
279 {
280     int i,j, rc = 0;
281     byte *buffer;
282     unsigned nbytes;
283     u16 csum;
284
285     if( !dek )
286         return 0;
287
288     if( !sk->is_protected ) { /* okay, apply the protection */
289         GCRY_CIPHER_HD cipher_hd=NULL;
290
291         if( openpgp_cipher_test_algo( sk->protect.algo ) )
292             rc = GPGERR_CIPHER_ALGO; /* unsupport protection algorithm */
293         else {
294             print_cipher_algo_note( sk->protect.algo );
295             if( !(cipher_hd = gcry_cipher_open( sk->protect.algo,
296                                           GCRY_CIPHER_MODE_CFB,
297                                           GCRY_CIPHER_SECURE
298                                           | (sk->protect.algo >= 100 ?
299                                               0 : GCRY_CIPHER_ENABLE_SYNC) ))
300                                          ) {
301                 BUG();
302             }
303
304
305             rc = gcry_cipher_setkey( cipher_hd, dek->key, dek->keylen );
306             if( rc == GCRYERR_WEAK_KEY ) {
307                 log_info(_("WARNING: Weak key detected"
308                            " - please change passphrase again.\n"));
309                 rc = 0;
310             }
311             else if( rc )
312                 BUG();
313
314             /* set the IV length */
315             {   int blocksize = gcry_cipher_get_algo_blklen( sk->protect.algo );
316                 if( blocksize != 8 && blocksize != 16 )
317                     log_fatal("unsupported blocksize %d\n", blocksize );
318                 sk->protect.ivlen = blocksize;
319             }
320
321             assert( sk->protect.ivlen <= DIM(sk->protect.iv) );
322             gcry_randomize(sk->protect.iv, sk->protect.ivlen,
323                                                         GCRY_STRONG_RANDOM);
324             gcry_cipher_setiv( cipher_hd, sk->protect.iv, sk->protect.ivlen );
325             #warning FIXME: replace set/get buffer
326             if( sk->version >= 4 ) {
327               #define NMPIS (GNUPG_MAX_NSKEY - GNUPG_MAX_NPKEY)
328                 byte *bufarr[NMPIS];
329                 unsigned narr[NMPIS];
330                 unsigned nbits[NMPIS];
331                 int ndata=0;
332                 byte *p, *data;
333
334                 for(j=0, i = pubkey_get_npkey(sk->pubkey_algo);
335                         i < pubkey_get_nskey(sk->pubkey_algo); i++, j++ ) {
336                     assert( !gcry_mpi_get_flag( sk->skey[i], GCRYMPI_FLAG_OPAQUE ) );
337
338                     if( gcry_mpi_aprint( GCRYMPI_FMT_USG, (char*)bufarr+j,
339                                                           narr+j, sk->skey[i]))
340                         BUG();
341
342                     nbits[j]  = gcry_mpi_get_nbits( sk->skey[i] );
343                     ndata += narr[j] + 2;
344                 }
345                 for( ; j < NMPIS; j++ )
346                     bufarr[j] = NULL;
347                 ndata += 2; /* for checksum */
348
349                 data = gcry_xmalloc_secure( ndata );
350                 p = data;
351                 for(j=0; j < NMPIS && bufarr[j]; j++ ) {
352                     p[0] = nbits[j] >> 8 ;
353                     p[1] = nbits[j];
354                     p += 2;
355                     memcpy(p, bufarr[j], narr[j] );
356                     p += narr[j];
357                     gcry_free(bufarr[j]);
358                 }
359               #undef NMPIS
360                 csum = checksum( data, ndata-2);
361                 sk->csum = csum;
362                 *p++ =  csum >> 8;
363                 *p++ =  csum;
364                 assert( p == data+ndata );
365                 gcry_cipher_encrypt( cipher_hd, data, ndata, NULL, 0 );
366                 for(i = pubkey_get_npkey(sk->pubkey_algo);
367                         i < pubkey_get_nskey(sk->pubkey_algo); i++ ) {
368                     mpi_release( sk->skey[i] );
369                     sk->skey[i] = NULL;
370                 }
371                 i = pubkey_get_npkey(sk->pubkey_algo);
372                 sk->skey[i] = gcry_mpi_set_opaque(NULL, data, ndata*8 );
373             }
374             else {
375                 /* NOTE: we always recalculate the checksum because there
376                  * are some test releases which calculated it wrong */
377                #warning FIXME:  Replace this code
378                 csum = 0;
379                 for(i=pubkey_get_npkey(sk->pubkey_algo);
380                         i < pubkey_get_nskey(sk->pubkey_algo); i++ ) {
381                     csum += checksum_mpi( sk->skey[i] );
382
383                     if( gcry_mpi_aprint( GCRYMPI_FMT_USG,
384                                          &buffer, &nbytes, sk->skey[i] ) )
385                         BUG();
386
387                     gcry_cipher_sync( cipher_hd );
388                     assert( !gcry_mpi_get_flag( sk->skey[i], GCRYMPI_FLAG_OPAQUE ) );
389                     gcry_cipher_encrypt( cipher_hd, buffer, nbytes, NULL, 0 );
390                     gcry_mpi_release( sk->skey[i] );
391                     if( gcry_mpi_scan( &sk->skey[i], GCRYMPI_FMT_USG,
392                                        buffer,&nbytes ) )
393                         BUG();
394
395                     gcry_free( buffer );
396                 }
397                 sk->csum = csum;
398             }
399             sk->is_protected = 1;
400             gcry_cipher_close( cipher_hd );
401         }
402     }
403     return rc;
404 }
405