Imported Upstream version 3.0.21
[platform/upstream/gnutls.git] / lib / gnutls_cipher.c
1 /*
2  * Copyright (C) 2000-2012 Free Software Foundation, Inc.
3  *
4  * Author: Nikos Mavrogiannopoulos
5  *
6  * This file is part of GnuTLS.
7  *
8  * The GnuTLS is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public License
10  * as published by the Free Software Foundation; either version 3 of
11  * the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>
20  *
21  */
22
23 /* Some high level functions to be used in the record encryption are
24  * included here.
25  */
26
27 #include "gnutls_int.h"
28 #include "gnutls_errors.h"
29 #include "gnutls_compress.h"
30 #include "gnutls_cipher.h"
31 #include "algorithms.h"
32 #include "gnutls_hash_int.h"
33 #include "gnutls_cipher_int.h"
34 #include "debug.h"
35 #include "gnutls_num.h"
36 #include "gnutls_datum.h"
37 #include "gnutls_kx.h"
38 #include "gnutls_record.h"
39 #include "gnutls_constate.h"
40 #include <gnutls_state.h>
41 #include <random.h>
42
43 static int compressed_to_ciphertext (gnutls_session_t session,
44                                    uint8_t * cipher_data, int cipher_size,
45                                    gnutls_datum_t *compressed,
46                                    content_type_t _type, 
47                                    record_parameters_st * params);
48 static int ciphertext_to_compressed (gnutls_session_t session,
49                                    gnutls_datum_t *ciphertext, 
50                                    uint8_t * compress_data,
51                                    int compress_size,
52                                    uint8_t type,
53                                    record_parameters_st * params, uint64* sequence);
54
55 inline static int
56 is_write_comp_null (record_parameters_st * record_params)
57 {
58   if (record_params->compression_algorithm == GNUTLS_COMP_NULL)
59     return 0;
60
61   return 1;
62 }
63
64 inline static int
65 is_read_comp_null (record_parameters_st * record_params)
66 {
67   if (record_params->compression_algorithm == GNUTLS_COMP_NULL)
68     return 0;
69
70   return 1;
71 }
72
73
74 /* returns ciphertext which contains the headers too. This also
75  * calculates the size in the header field.
76  * 
77  * If random pad != 0 then the random pad data will be appended.
78  */
79 int
80 _gnutls_encrypt (gnutls_session_t session, const uint8_t * headers,
81                  size_t headers_size, const uint8_t * data,
82                  size_t data_size, uint8_t * ciphertext,
83                  size_t ciphertext_size, content_type_t type, 
84                  record_parameters_st * params)
85 {
86   gnutls_datum_t comp;
87   int free_comp = 0;
88   int ret;
89
90   if (data_size == 0 || is_write_comp_null (params) == 0)
91     {
92       comp.data = (uint8_t*)data;
93       comp.size = data_size;
94     }
95   else
96     {
97       /* Here comp is allocated and must be 
98        * freed.
99        */
100       free_comp = 1;
101       
102       comp.size = ciphertext_size - headers_size;
103       comp.data = gnutls_malloc(comp.size);
104       if (comp.data == NULL)
105         return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
106       
107       ret = _gnutls_compress( &params->write.compression_state, data, data_size, comp.data, comp.size);
108       if (ret < 0)
109         {
110           gnutls_free(comp.data);
111           return gnutls_assert_val(ret);
112         }
113       
114       comp.size = ret;
115     }
116
117   ret = compressed_to_ciphertext (session, &ciphertext[headers_size],
118                                        ciphertext_size - headers_size,
119                                        &comp, type, params);
120
121   if (free_comp)
122     gnutls_free(comp.data);
123
124   if (ret < 0)
125     return gnutls_assert_val(ret);
126
127   /* copy the headers */
128   memcpy (ciphertext, headers, headers_size);
129   
130   if(IS_DTLS(session))
131     _gnutls_write_uint16 (ret, &ciphertext[11]);
132   else
133     _gnutls_write_uint16 (ret, &ciphertext[3]);
134
135   return ret + headers_size;
136 }
137
138 /* Decrypts the given data.
139  * Returns the decrypted data length.
140  */
141 int
142 _gnutls_decrypt (gnutls_session_t session, uint8_t * ciphertext,
143                  size_t ciphertext_size, uint8_t * data,
144                  size_t max_data_size, content_type_t type,
145                  record_parameters_st * params, uint64 *sequence)
146 {
147   gnutls_datum_t gcipher;
148   int ret, data_size;
149
150   if (ciphertext_size == 0)
151     return 0;
152
153   gcipher.size = ciphertext_size;
154   gcipher.data = ciphertext;
155
156   if (is_read_comp_null (params) == 0)
157     {
158       ret =
159         ciphertext_to_compressed (session, &gcipher, data, max_data_size,
160                                    type, params, sequence);
161       if (ret < 0)
162         return gnutls_assert_val(ret);
163       
164       return ret;
165     }
166   else
167     {
168       uint8_t* tmp_data;
169       
170       tmp_data = gnutls_malloc(max_data_size);
171       if (tmp_data == NULL)
172         return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
173       
174       ret =
175         ciphertext_to_compressed (session, &gcipher, tmp_data, max_data_size,
176                                    type, params, sequence);
177       if (ret < 0)
178         goto leave;
179       
180       data_size = ret;
181         
182       if (ret != 0)
183         {
184           ret = _gnutls_decompress( &params->read.compression_state, tmp_data, data_size, data, max_data_size);
185           if (ret < 0)
186             goto leave;
187         }
188         
189 leave:
190       gnutls_free(tmp_data);
191       return ret;
192     }
193 }
194
195
196 inline static int
197 calc_enc_length (gnutls_session_t session, int data_size,
198                  int hash_size, uint8_t * pad, int random_pad,
199                  unsigned block_algo, unsigned auth_cipher, uint16_t blocksize)
200 {
201   uint8_t rnd;
202   unsigned int length;
203   int ret;
204
205   *pad = 0;
206
207   switch (block_algo)
208     {
209     case CIPHER_STREAM:
210       length = data_size + hash_size;
211       if (auth_cipher)
212         length += AEAD_EXPLICIT_DATA_SIZE;
213
214       break;
215     case CIPHER_BLOCK:
216       ret = _gnutls_rnd (GNUTLS_RND_NONCE, &rnd, 1);
217       if (ret < 0)
218         return gnutls_assert_val(ret);
219
220       /* make rnd a multiple of blocksize */
221       if (session->security_parameters.version == GNUTLS_SSL3 ||
222           random_pad == 0)
223         {
224           rnd = 0;
225         }
226       else
227         {
228           rnd = (rnd / blocksize) * blocksize;
229           /* added to avoid the case of pad calculated 0
230            * seen below for pad calculation.
231            */
232           if (rnd > blocksize)
233             rnd -= blocksize;
234         }
235
236       length = data_size + hash_size;
237
238       *pad = (uint8_t) (blocksize - (length % blocksize)) + rnd;
239
240       length += *pad;
241       if (_gnutls_version_has_explicit_iv
242           (session->security_parameters.version))
243         length += blocksize;    /* for the IV */
244
245       break;
246     default:
247       return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
248     }
249
250   return length;
251 }
252
253 #define MAX_PREAMBLE_SIZE 16
254
255 /* generates the authentication data (data to be hashed only
256  * and are not to be sent). Returns their size.
257  */
258 static inline int
259 make_preamble (uint8_t * uint64_data, uint8_t type, unsigned int length,
260                uint8_t ver, uint8_t * preamble)
261 {
262   uint8_t minor = _gnutls_version_get_minor (ver);
263   uint8_t major = _gnutls_version_get_major (ver);
264   uint8_t *p = preamble;
265   uint16_t c_length;
266
267   c_length = _gnutls_conv_uint16 (length);
268
269   memcpy (p, uint64_data, 8);
270   p += 8;
271   *p = type;
272   p++;
273   if (ver != GNUTLS_SSL3)
274     { /* TLS protocols */
275       *p = major;
276       p++;
277       *p = minor;
278       p++;
279     }
280   memcpy (p, &c_length, 2);
281   p += 2;
282   return p - preamble;
283 }
284
285 /* This is the actual encryption 
286  * Encrypts the given compressed datum, and puts the result to cipher_data,
287  * which has cipher_size size.
288  * return the actual encrypted data length.
289  */
290 static int
291 compressed_to_ciphertext (gnutls_session_t session,
292                                uint8_t * cipher_data, int cipher_size,
293                                gnutls_datum_t *compressed,
294                                content_type_t type, 
295                                record_parameters_st * params)
296 {
297   uint8_t * tag_ptr = NULL;
298   uint8_t pad;
299   int length, length_to_encrypt, ret;
300   uint8_t preamble[MAX_PREAMBLE_SIZE];
301   int preamble_size;
302   int tag_size = _gnutls_auth_cipher_tag_len (&params->write.cipher_state);
303   int blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm);
304   unsigned block_algo =
305     _gnutls_cipher_is_block (params->cipher_algorithm);
306   uint8_t *data_ptr;
307   int ver = gnutls_protocol_get_version (session);
308   int explicit_iv = _gnutls_version_has_explicit_iv (session->security_parameters.version);
309   int auth_cipher = _gnutls_auth_cipher_is_aead(&params->write.cipher_state);
310   int random_pad;
311   
312   /* We don't use long padding if requested or if we are in DTLS.
313    */
314   if (session->internals.priorities.no_padding == 0 && (!IS_DTLS(session)))
315     random_pad = 1;
316   else
317     random_pad = 0;
318   
319   _gnutls_hard_log("ENC[%p]: cipher: %s, MAC: %s, Epoch: %u\n",
320     session, gnutls_cipher_get_name(params->cipher_algorithm), gnutls_mac_get_name(params->mac_algorithm),
321     (unsigned int)params->epoch);
322
323   preamble_size =
324     make_preamble (UINT64DATA
325                    (params->write.sequence_number),
326                    type, compressed->size, ver, preamble);
327
328   /* Calculate the encrypted length (padding etc.)
329    */
330   length_to_encrypt = length =
331     calc_enc_length (session, compressed->size, tag_size, &pad,
332                      random_pad, block_algo, auth_cipher, blocksize);
333   if (length < 0)
334     {
335       return gnutls_assert_val(length);
336     }
337
338   /* copy the encrypted data to cipher_data.
339    */
340   if (cipher_size < length)
341     {
342       return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
343     }
344
345   data_ptr = cipher_data;
346
347   if (explicit_iv)
348     {
349
350       if (block_algo == CIPHER_BLOCK)
351         {
352           /* copy the random IV.
353            */
354           ret = _gnutls_rnd (GNUTLS_RND_NONCE, data_ptr, blocksize);
355           if (ret < 0)
356             return gnutls_assert_val(ret);
357  
358           _gnutls_auth_cipher_setiv(&params->write.cipher_state, data_ptr, blocksize);
359
360           data_ptr += blocksize;
361           cipher_data += blocksize;
362           length_to_encrypt -= blocksize;
363         }
364       else if (auth_cipher)
365         {
366           uint8_t nonce[blocksize];
367
368           /* Values in AEAD are pretty fixed in TLS 1.2 for 128-bit block
369            */
370           if (params->write.IV.data == NULL || params->write.IV.size != AEAD_IMPLICIT_DATA_SIZE)
371             return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
372
373           /* Instead of generating a new nonce on every packet, we use the
374            * write.sequence_number (It is a MAY on RFC 5288).
375            */
376           memcpy(nonce, params->write.IV.data, params->write.IV.size);
377           memcpy(&nonce[AEAD_IMPLICIT_DATA_SIZE], UINT64DATA(params->write.sequence_number), 8);
378
379           _gnutls_auth_cipher_setiv(&params->write.cipher_state, nonce, AEAD_IMPLICIT_DATA_SIZE+AEAD_EXPLICIT_DATA_SIZE);
380
381           /* copy the explicit part */
382           memcpy(data_ptr, &nonce[AEAD_IMPLICIT_DATA_SIZE], AEAD_EXPLICIT_DATA_SIZE);
383
384           data_ptr += AEAD_EXPLICIT_DATA_SIZE;
385           cipher_data += AEAD_EXPLICIT_DATA_SIZE;
386           /* In AEAD ciphers we don't encrypt the tag 
387            */
388           length_to_encrypt -= AEAD_EXPLICIT_DATA_SIZE + tag_size;
389         }
390     }
391   else
392     {
393       /* AEAD ciphers have an explicit IV. Shouldn't be used otherwise.
394        */
395       if (auth_cipher) return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
396     }
397
398   memcpy (data_ptr, compressed->data, compressed->size);
399   data_ptr += compressed->size;
400
401   if (tag_size > 0)
402     {
403       tag_ptr = data_ptr;
404       data_ptr += tag_size;
405     }
406   if (block_algo == CIPHER_BLOCK && pad > 0)
407     {
408       memset (data_ptr, pad - 1, pad);
409     }
410
411   /* add the authenticate data */
412   ret = _gnutls_auth_cipher_add_auth(&params->write.cipher_state, preamble, preamble_size);
413   if (ret < 0)
414     return gnutls_assert_val(ret);
415
416   /* Actual encryption (inplace).
417    */
418   ret =
419     _gnutls_auth_cipher_encrypt2_tag (&params->write.cipher_state,
420         cipher_data, length_to_encrypt, 
421         cipher_data, cipher_size,
422         tag_ptr, tag_size, compressed->size);
423   if (ret < 0)
424     return gnutls_assert_val(ret);
425
426   return length;
427 }
428
429
430 /* Deciphers the ciphertext packet, and puts the result to compress_data, of compress_size.
431  * Returns the actual compressed packet size.
432  */
433 static int
434 ciphertext_to_compressed (gnutls_session_t session,
435                           gnutls_datum_t *ciphertext, 
436                           uint8_t * compress_data,
437                           int compress_size,
438                           uint8_t type, record_parameters_st * params, 
439                           uint64* sequence)
440 {
441   uint8_t tag[MAX_HASH_SIZE];
442   uint8_t pad;
443   int length, length_to_decrypt;
444   uint16_t blocksize;
445   int ret, i, pad_failed = 0;
446   uint8_t preamble[MAX_PREAMBLE_SIZE];
447   unsigned int preamble_size;
448   unsigned int ver = gnutls_protocol_get_version (session);
449   unsigned int tag_size = _gnutls_auth_cipher_tag_len (&params->read.cipher_state);
450   unsigned int explicit_iv = _gnutls_version_has_explicit_iv (session->security_parameters.version);
451
452   blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm);
453
454   /* actual decryption (inplace)
455    */
456   switch (_gnutls_cipher_is_block (params->cipher_algorithm))
457     {
458     case CIPHER_STREAM:
459       /* The way AEAD ciphers are defined in RFC5246, it allows
460        * only stream ciphers.
461        */
462       if (explicit_iv && _gnutls_auth_cipher_is_aead(&params->read.cipher_state))
463         {
464           uint8_t nonce[blocksize];
465           /* Values in AEAD are pretty fixed in TLS 1.2 for 128-bit block
466            */
467           if (params->read.IV.data == NULL || params->read.IV.size != 4)
468             return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
469           
470           if (ciphertext->size < tag_size+AEAD_EXPLICIT_DATA_SIZE)
471             return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
472
473           memcpy(nonce, params->read.IV.data, AEAD_IMPLICIT_DATA_SIZE);
474           memcpy(&nonce[AEAD_IMPLICIT_DATA_SIZE], ciphertext->data, AEAD_EXPLICIT_DATA_SIZE);
475           
476           _gnutls_auth_cipher_setiv(&params->read.cipher_state, nonce, AEAD_EXPLICIT_DATA_SIZE+AEAD_IMPLICIT_DATA_SIZE);
477
478           ciphertext->data += AEAD_EXPLICIT_DATA_SIZE;
479           ciphertext->size -= AEAD_EXPLICIT_DATA_SIZE;
480           
481           length_to_decrypt = ciphertext->size - tag_size;
482         }
483       else
484         {
485           if (ciphertext->size < tag_size)
486             return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
487   
488           length_to_decrypt = ciphertext->size;
489         }
490
491       length = ciphertext->size - tag_size;
492
493       /* Pass the type, version, length and compressed through
494        * MAC.
495        */
496       preamble_size =
497         make_preamble (UINT64DATA(*sequence), type,
498                        length, ver, preamble);
499
500       ret = _gnutls_auth_cipher_add_auth (&params->read.cipher_state, preamble, preamble_size);
501       if (ret < 0)
502         return gnutls_assert_val(ret);
503
504       if ((ret =
505            _gnutls_auth_cipher_decrypt2 (&params->read.cipher_state,
506              ciphertext->data, length_to_decrypt,
507              ciphertext->data, ciphertext->size)) < 0)
508         return gnutls_assert_val(ret);
509
510       break;
511     case CIPHER_BLOCK:
512       if (ciphertext->size < blocksize || (ciphertext->size % blocksize != 0))
513         return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
514
515       /* ignore the IV in TLS 1.1+
516        */
517       if (explicit_iv)
518         {
519           _gnutls_auth_cipher_setiv(&params->read.cipher_state,
520             ciphertext->data, blocksize);
521
522           ciphertext->size -= blocksize;
523           ciphertext->data += blocksize;
524         }
525
526       if (ciphertext->size < tag_size)
527         return gnutls_assert_val(GNUTLS_E_DECRYPTION_FAILED);
528
529       /* we don't use the auth_cipher interface here, since
530        * TLS with block ciphers is impossible to be used under such
531        * an API. (the length of plaintext is required to calculate
532        * auth_data, but it is not available before decryption).
533        */
534       if ((ret =
535            _gnutls_cipher_decrypt (&params->read.cipher_state.cipher,
536              ciphertext->data, ciphertext->size)) < 0)
537         return gnutls_assert_val(ret);
538
539       pad = ciphertext->data[ciphertext->size - 1] + 1;   /* pad */
540
541
542       if ((int) pad > (int) ciphertext->size - tag_size)
543         {
544           gnutls_assert ();
545           _gnutls_record_log
546             ("REC[%p]: Short record length %d > %d - %d (under attack?)\n",
547              session, pad, ciphertext->size, tag_size);
548           /* We do not fail here. We check below for the
549            * the pad_failed. If zero means success.
550            */
551           pad_failed = GNUTLS_E_DECRYPTION_FAILED;
552           pad %= blocksize;
553         }
554
555       length = ciphertext->size - tag_size - pad;
556
557       /* Check the pading bytes (TLS 1.x)
558        */
559       if (ver != GNUTLS_SSL3)
560         for (i = 2; i < pad; i++)
561           {
562             if (ciphertext->data[ciphertext->size - i] !=
563                 ciphertext->data[ciphertext->size - 1])
564               pad_failed = GNUTLS_E_DECRYPTION_FAILED;
565           }
566
567       if (length < 0)
568         {
569           /* Setting a proper length to prevent timing differences in
570            * processing of records with invalid encryption.
571            */
572           length = ciphertext->size - tag_size;
573         }
574
575       /* Pass the type, version, length and compressed through
576        * MAC.
577        */
578       preamble_size =
579         make_preamble (UINT64DATA(*sequence), type,
580                        length, ver, preamble);
581       ret = _gnutls_auth_cipher_add_auth (&params->read.cipher_state, preamble, preamble_size);
582       if (ret < 0)
583         return gnutls_assert_val(ret);
584
585       ret = _gnutls_auth_cipher_add_auth (&params->read.cipher_state, ciphertext->data, length);
586       if (ret < 0)
587         return gnutls_assert_val(ret);
588
589       break;
590     default:
591       return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
592     }
593
594   ret = _gnutls_auth_cipher_tag(&params->read.cipher_state, tag, tag_size);
595   if (ret < 0)
596     return gnutls_assert_val(ret);
597
598   /* This one was introduced to avoid a timing attack against the TLS
599    * 1.0 protocol.
600    */
601   /* HMAC was not the same. 
602    */
603   if (memcmp (tag, &ciphertext->data[length], tag_size) != 0 || pad_failed != 0)
604     return gnutls_assert_val(GNUTLS_E_DECRYPTION_FAILED);
605
606   /* copy the decrypted stuff to compress_data.
607    */
608   if (compress_size < length)
609     return gnutls_assert_val(GNUTLS_E_DECOMPRESSION_FAILED);
610
611   if (compress_data != ciphertext->data)
612     memcpy (compress_data, ciphertext->data, length);
613
614   return length;
615 }