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