forked from voipmonitor/sniffer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssl.cpp
More file actions
3322 lines (2857 loc) · 98.6 KB
/
Copy pathssl.cpp
File metadata and controls
3322 lines (2857 loc) · 98.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "config.h"
#ifdef HAVE_LIBGNUTLS
#include <stdlib.h>
#include <stdio.h>
#include <glib.h>
#include <vector>
#include <map>
#include <string>
#include <iostream>
#include <unistd.h>
#include "tools.h"
#include "ssl.h"
#include "ssl-test.h"
using namespace std;
//TODO: overit ssl_decrypted_data_avail thread safe
static gint ssl_decrypted_data_avail = 0;
static StringInfo ssl_decrypted_data = {NULL, 0};
static StringInfo ssl_compressed_data = {NULL, 0};
static GHashTable *ssl_key_hash = NULL;
static ssl_master_key_map_t ssl_master_key_map = {NULL, NULL, NULL};
static ssl_common_options_t ssl_options = { NULL, NULL};
extern map<d_u_int32_t, string> ssl_ipport;
struct session_t {
SslDecryptSessionC *session;
time_t created_at;
};
map<string, session_t*> sessions;
map<string, session_t*>::iterator sessions_it;
gboolean ssl_ignore_mac_failed = FALSE;
struct ssl_keys_t {
unsigned int ip;
int port;
string filename;
};
std::vector<ssl_keys_t*> ssl_keys;
string
find_ssl_keys(unsigned int ip1, int port1, unsigned int ip2, int port2) {
for(std::vector<ssl_keys_t*>::iterator it = ssl_keys.begin(); it != ssl_keys.end(); ++it) {
if((port1 == (*it)->port && ip1 == (*it)->ip) || (port2 == (*it)->port && ip2 == (*it)->ip)) {
return (*it)->filename;
}
}
return "";
}
/* we keep this internal to packet-ssl-utils, as there should be
no need to access it any other way.
This also allows us to hide the dependency on zlib.
*/
struct _SslDecompress {
gint compression;
z_stream istream;
};
static const gchar *ciphers[]={
"DES",
"3DES",
"ARCFOUR", /* libgcrypt does not support rc4, but this should be 100% compatible*/
"RFC2268_128", /* libgcrypt name for RC2 with a 128-bit key */
"IDEA",
"AES",
"AES256",
"CAMELLIA128",
"CAMELLIA256",
"SEED",
"*UNKNOWN*"
};
static const SslDigestAlgo digests[]={
{"MD5", 16},
{"SHA1", 20},
{"SHA256", 32},
{"SHA384", 48},
{"Not Applicable", 0},
};
/* stream cipher abstraction layer*/
static gint
ssl_cipher_init(gcry_cipher_hd_t *cipher, gint algo, guchar* sk,
guchar* iv, gint mode)
{
gint gcry_modes[]={GCRY_CIPHER_MODE_STREAM,GCRY_CIPHER_MODE_CBC,GCRY_CIPHER_MODE_CTR,GCRY_CIPHER_MODE_CTR,GCRY_CIPHER_MODE_CTR};
gint err;
if (algo == -1) {
/* NULL mode */
*(cipher) = (gcry_cipher_hd_t)-1;
return 0;
}
err = gcry_cipher_open(cipher, algo, gcry_modes[mode], 0);
if (err !=0)
return -1;
err = gcry_cipher_setkey(*(cipher), sk, gcry_cipher_get_algo_keylen (algo));
if (err != 0)
return -1;
err = gcry_cipher_setiv(*(cipher), iv, gcry_cipher_get_algo_blklen (algo));
if (err != 0)
return -1;
return 0;
}
static inline gint
ssl_get_digest_by_name(const gchar*name)
{
return gcry_md_map_name(name);
}
static inline gint
ssl_get_cipher_by_name(const gchar* name)
{
return gcry_cipher_map_name(name);
}
static inline void
ssl_cipher_cleanup(gcry_cipher_hd_t *cipher)
{
if ((*cipher) != (gcry_cipher_hd_t)-1)
gcry_cipher_close(*cipher);
*cipher = NULL;
}
static inline gint
ssl_cipher_decrypt(gcry_cipher_hd_t *cipher, guchar * out, gint outl,
const guchar * in, gint inl)
{
if ((*cipher) == (gcry_cipher_hd_t)-1)
{
if (in && inl)
memcpy(out, in, outl < inl ? outl : inl);
return 0;
}
return gcry_cipher_decrypt ( *(cipher), out, outl, in, inl);
}
#define SSL_MD gcry_md_hd_t
static inline gint
ssl_md_init(SSL_MD* md, gint algo)
{
gcry_error_t err;
const char *err_str, *err_src;
err = gcry_md_open(md,algo, 0);
if (err != 0) {
err_str = gcry_strerror(err);
err_src = gcry_strsource(err);
if (debug) printf("ssl_md_init(): gcry_md_open failed %s/%s", err_str, err_src);
return -1;
}
return 0;
}
static inline void
ssl_md_update(SSL_MD* md, guchar* data, gint len)
{
gcry_md_write(*(md), data, len);
}
static inline void
ssl_md_final(SSL_MD* md, guchar* data, guint* datalen)
{
gint algo;
gint len;
algo = gcry_md_get_algo (*(md));
len = gcry_md_get_algo_dlen (algo);
memcpy(data, gcry_md_read(*(md), algo), len);
*datalen = len;
}
static inline void
ssl_md_cleanup(SSL_MD* md)
{
gcry_md_close(*(md));
}
/* memory allocation functions for zlib initialization */
static void* ssl_zalloc(void* opaque, unsigned int no, unsigned int size)
{
return g_malloc0(no*size);
}
static void ssl_zfree(void* opaque, void* addr)
{
g_free(addr);
}
static SslDecompress*
ssl_create_decompressor(gint compression)
{
SslDecompress *decomp;
int err;
if (compression == 0) return NULL;
if (debug) printf("ssl_create_decompressor: compression method %d\n", compression);
decomp = (SslDecompress *)calloc(1, sizeof(SslDecompress));
decomp->compression = compression;
switch (decomp->compression) {
case 1: /* DEFLATE */
decomp->istream.zalloc = ssl_zalloc;
decomp->istream.zfree = ssl_zfree;
decomp->istream.opaque = Z_NULL;
decomp->istream.next_in = Z_NULL;
decomp->istream.next_out = Z_NULL;
decomp->istream.avail_in = 0;
decomp->istream.avail_out = 0;
err = inflateInit_(&decomp->istream, ZLIB_VERSION, sizeof(z_stream));
if (err != Z_OK) {
if (debug) printf("ssl_create_decompressor: inflateInit_() failed - %d\n", err);
return NULL;
}
break;
default:
if (debug) printf("ssl_create_decompressor: unsupported compression method %d\n", decomp->compression);
return NULL;
}
return decomp;
}
#define DIGEST_MAX_SIZE 48
/* get index digest index */
static const SslDigestAlgo *
ssl_cipher_suite_dig(SslCipherSuite *cs) {
return &digests[cs->dig - DIG_MD5];
}
/* convert network byte order 32 byte number to right-aligned host byte order *
* 8 bytes buffer */
static gint fmt_seq(guint32 num, guint8* buf)
{
guint32 netnum;
memset(buf,0,8);
netnum=g_htonl(num);
memcpy(buf+4,&netnum,4);
return(0);
}
static int
ssl3_check_mac(SslDecoder*decoder,int ct,guint8* data,
guint32 datalen, guint8* mac)
{
SSL_MD mc;
gint md;
guint32 len;
guint8 buf[64],dgst[20];
gint pad_ct;
gint16 temp;
pad_ct=(decoder->cipher_suite->dig==DIG_SHA)?40:48;
/* get cipher used for digest comptuation */
md=ssl_get_digest_by_name(ssl_cipher_suite_dig(decoder->cipher_suite)->name);
if (ssl_md_init(&mc,md) !=0)
return -1;
/* do hash computation on data && padding */
ssl_md_update(&mc,decoder->mac_key.data,decoder->mac_key.data_len);
/* hash padding*/
memset(buf,0x36,pad_ct);
ssl_md_update(&mc,buf,pad_ct);
/* hash sequence number */
fmt_seq(decoder->seq,buf);
decoder->seq++;
ssl_md_update(&mc,buf,8);
/* hash content type */
buf[0]=ct;
ssl_md_update(&mc,buf,1);
/* hash data length in network byte order and data*/
/* *((gint16* )buf) = g_htons(datalen); */
temp = g_htons(datalen);
memcpy(buf, &temp, 2);
ssl_md_update(&mc,buf,2);
ssl_md_update(&mc,data,datalen);
/* get partial digest */
ssl_md_final(&mc,dgst,&len);
ssl_md_cleanup(&mc);
ssl_md_init(&mc,md);
/* hash mac key */
ssl_md_update(&mc,decoder->mac_key.data,decoder->mac_key.data_len);
/* hash padding and partial digest*/
memset(buf,0x5c,pad_ct);
ssl_md_update(&mc,buf,pad_ct);
ssl_md_update(&mc,dgst,len);
ssl_md_final(&mc,dgst,&len);
ssl_md_cleanup(&mc);
if(memcmp(mac,dgst,len))
return -1;
return(0);
}
int
ssl_packet_from_server(SslDecryptSessionC *ssl, packet_info *pinfo)
{
gint ret = 0;
if (ssl && (ssl->srv_ptype != PT_NONE)) {
ret = (ssl->srv_ptype == pinfo->ptype) && (ssl->srv_port == pinfo->srcport) && (ssl->srv_addr2 == pinfo->src2);
} else {
for(std::vector<ssl_keys_t*>::iterator it = ssl_keys.begin(); it != ssl_keys.end(); ++it) {
if(pinfo->srcport == (*it)->port && pinfo->src2 == (*it)->ip) {
ret = 1;
break;
}
}
}
if(debug) printf("packet_from_server: is from server - %s [srcport:%u]\n", (ret)?"TRUE":"FALSE", pinfo->srcport);
return ret;
}
/* get ssl data for this session. if no ssl data is found allocate a new one*/
void
ssl_session_init(SslDecryptSession* ssl_session)
{
if(debug) printf("ssl_session_init: initializing ptr %p size %" "u\n",
(void *)ssl_session, sizeof(SslDecryptSession));
/* data_len is the part that is meaningful, not the allocated length */
ssl_session->master_secret.data_len = 0;
ssl_session->master_secret.data = ssl_session->_master_secret;
ssl_session->session_id.data_len = 0;
ssl_session->session_id.data = ssl_session->_session_id;
ssl_session->client_random.data_len = 0;
ssl_session->client_random.data = ssl_session->_client_random;
ssl_session->server_random.data_len = 0;
ssl_session->server_random.data = ssl_session->_server_random;
ssl_session->session_ticket.data_len = 0;
ssl_session->session_ticket.data = NULL; /* will be re-alloced as needed */
ssl_session->server_data_for_iv.data_len = 0;
ssl_session->server_data_for_iv.data = ssl_session->_server_data_for_iv;
ssl_session->client_data_for_iv.data_len = 0;
ssl_session->client_data_for_iv.data = ssl_session->_client_data_for_iv;
ssl_session->app_data_segment.data = NULL;
ssl_session->app_data_segment.data_len = 0;
//SET_ADDRESS(&ssl_session->srv_addr, AT_NONE, 0, NULL);
ssl_session->srv_addr2 = 0;
ssl_session->srv_ptype = PT_NONE;
ssl_session->srv_port = 0;
ssl_session->state = 0;
ssl_session->private_key = NULL;
ssl_session->private_key_c = NULL;
ssl_session->server = NULL;
ssl_session->client = NULL;
// ssl_session->cipher = 0;
}
bool
ssl_is_valid_content_type(uint8_t type)
{
switch ((ContentType) type) {
case SSL_ID_CHG_CIPHER_SPEC:
case SSL_ID_ALERT:
case SSL_ID_HANDSHAKE:
case SSL_ID_APP_DATA:
case SSL_ID_HEARTBEAT:
return true;
}
return false;
}
/* this applies a heuristic to determine whether
* or not the data beginning at offset looks like a
* valid sslv3 record. this is somewhat more reliable
* than sslv2 due to the structure of the v3 protocol
*/
static gint
ssl_looks_like_sslv3(char *data, const guint32 offset)
{
/* have to have a valid content type followed by a valid
* protocol version
*/
guint8 byte;
guint16 version;
/* see if the first byte is a valid content type */
byte = (guint8)*(data + offset);
if (!ssl_is_valid_content_type(byte))
{
return 0;
}
/* now check to see if the version byte appears valid */
version = pntoh16(data + offset + 1);
switch (version) {
case SSLV3_VERSION:
case TLSV1_VERSION:
case TLSV1DOT1_VERSION:
case TLSV1DOT2_VERSION:
return 1;
}
return 0;
}
gboolean
ssl_is_valid_handshake_type(guint8 hs_type, gboolean is_dtls)
{
switch ((HandshakeType) hs_type) {
case SSL_HND_HELLO_VERIFY_REQUEST:
/* hello_verify_request is DTLS-only */
return is_dtls;
case SSL_HND_HELLO_REQUEST:
case SSL_HND_CLIENT_HELLO:
case SSL_HND_SERVER_HELLO:
case SSL_HND_NEWSESSION_TICKET:
case SSL_HND_CERTIFICATE:
case SSL_HND_SERVER_KEY_EXCHG:
case SSL_HND_CERT_REQUEST:
case SSL_HND_SVR_HELLO_DONE:
case SSL_HND_CERT_VERIFY:
case SSL_HND_CLIENT_KEY_EXCHG:
case SSL_HND_FINISHED:
case SSL_HND_CERT_URL:
case SSL_HND_CERT_STATUS:
case SSL_HND_SUPPLEMENTAL_DATA:
case SSL_HND_ENCRYPTED_EXTS:
return true;
}
return false;
}
static gint
ssl_is_authoritative_version_message(const guint8 content_type, const guint8 next_byte){
if (content_type == SSL_ID_HANDSHAKE && ssl_is_valid_handshake_type(next_byte, false)) {
return (next_byte != SSL_HND_CLIENT_HELLO);
} else if (ssl_is_valid_content_type(content_type) && content_type != SSL_ID_HANDSHAKE){
return 1;
}
return 0;
}
/*********************************************************************
*
* SSL version 3 and TLS Dissection Routines
*
*********************************************************************/
void
ssl_data_set(StringInfo* str, const guchar* data, guint len)
{
if(!data) return;
//DISSECTOR_ASSERT(data);
memcpy(str->data, data, len);
str->data_len = len;
}
/* stringinfo interface */
static gint
ssl_data_realloc(StringInfo* str, guint len)
{
str->data = (guchar *)g_realloc(str->data, len);
if (!str->data)
return -1;
str->data_len = len;
return 0;
}
#define SSL_HMAC gcry_md_hd_t
static inline gint
ssl_hmac_init(SSL_HMAC* md, const void * key, gint len, gint algo)
{
gcry_error_t err;
const char *err_str, *err_src;
err = gcry_md_open(md,algo, GCRY_MD_FLAG_HMAC);
if (err != 0) {
err_str = gcry_strerror(err);
err_src = gcry_strsource(err);
if (debug) printf("ssl_hmac_init(): gcry_md_open failed %s/%s", err_str, err_src);
return -1;
}
gcry_md_setkey (*(md), key, len);
return 0;
}
static inline void
ssl_hmac_update(SSL_HMAC* md, const void* data, gint len)
{
gcry_md_write(*(md), data, len);
}
static inline void
ssl_hmac_final(SSL_HMAC* md, guchar* data, guint* datalen)
{
gint algo;
guint len;
algo = gcry_md_get_algo (*(md));
len = gcry_md_get_algo_dlen(algo);
if(!(len <= *datalen)) return;
// DISSECTOR_ASSERT(len <= *datalen);
memcpy(data, gcry_md_read(*(md), algo), len);
*datalen = len;
}
static inline void
ssl_hmac_cleanup(SSL_HMAC* md)
{
gcry_md_close(*(md));
}
static gint
tls_check_mac(SslDecoder*decoder, gint ct, gint ver, guint8* data,
guint32 datalen, guint8* mac)
{
SSL_HMAC hm;
gint md;
guint32 len;
guint8 buf[DIGEST_MAX_SIZE];
gint16 temp;
md=ssl_get_digest_by_name(ssl_cipher_suite_dig(decoder->cipher_suite)->name);
if (debug) printf("tls_check_mac mac type:%s md %d\n",
ssl_cipher_suite_dig(decoder->cipher_suite)->name, md);
if (ssl_hmac_init(&hm,decoder->mac_key.data,decoder->mac_key.data_len,md) != 0)
return -1;
/* hash sequence number */
fmt_seq(decoder->seq,buf);
decoder->seq++;
ssl_hmac_update(&hm,buf,8);
/* hash content type */
buf[0]=ct;
ssl_hmac_update(&hm,buf,1);
/* hash version,data length and data*/
/* *((gint16*)buf) = g_htons(ver); */
temp = g_htons(ver);
memcpy(buf, &temp, 2);
ssl_hmac_update(&hm,buf,2);
/* *((gint16*)buf) = g_htons(datalen); */
temp = g_htons(datalen);
memcpy(buf, &temp, 2);
ssl_hmac_update(&hm,buf,2);
ssl_hmac_update(&hm,data,datalen);
/* get digest and digest len*/
len = sizeof(buf);
ssl_hmac_final(&hm,buf,&len);
ssl_hmac_cleanup(&hm);
ssl_print_data("Mac", buf, len);
if(memcmp(mac,buf,len))
return -1;
return 0;
}
static int
ssl_decompress_record(SslDecompress* decomp, const guchar* in, guint inl, StringInfo* out_str, guint* outl)
{
gint err;
switch (decomp->compression) {
case 1: /* DEFLATE */
err = Z_OK;
if (out_str->data_len < 16384) { /* maximal plain length */
ssl_data_realloc(out_str, 16384);
}
decomp->istream.next_in = (guchar*)in;
decomp->istream.avail_in = inl;
decomp->istream.next_out = out_str->data;
decomp->istream.avail_out = out_str->data_len;
if (inl > 0)
err = inflate(&decomp->istream, Z_SYNC_FLUSH);
if (err != Z_OK) {
if (debug) printf("ssl_decompress_record: inflate() failed - %d\n", err);
return -1;
}
*outl = out_str->data_len - decomp->istream.avail_out;
break;
default:
if (debug) printf("ssl_decompress_record: unsupported compression method %d\n", decomp->compression);
return -1;
}
return 0;
}
static gint
ssl_data_copy(StringInfo* dst, StringInfo* src)
{
if (dst->data_len < src->data_len) {
if (ssl_data_realloc(dst, src->data_len))
return -1;
}
memcpy(dst->data, src->data, src->data_len);
dst->data_len = src->data_len;
return 0;
}
static gint
dtls_check_mac(SslDecoder*decoder, gint ct,int ver, guint8* data,
guint32 datalen, guint8* mac)
{
SSL_HMAC hm;
gint md;
guint32 len;
guint8 buf[DIGEST_MAX_SIZE];
gint16 temp;
md=ssl_get_digest_by_name(ssl_cipher_suite_dig(decoder->cipher_suite)->name);
if (debug) printf("dtls_check_mac mac type:%s md %d\n",
ssl_cipher_suite_dig(decoder->cipher_suite)->name, md);
if (ssl_hmac_init(&hm,decoder->mac_key.data,decoder->mac_key.data_len,md) != 0)
return -1;
if (debug) printf("dtls_check_mac seq: %d epoch: %d\n",decoder->seq,decoder->epoch);
/* hash sequence number */
fmt_seq(decoder->seq,buf);
buf[0]=decoder->epoch>>8;
buf[1]=(guint8)decoder->epoch;
ssl_hmac_update(&hm,buf,8);
/* hash content type */
buf[0]=ct;
ssl_hmac_update(&hm,buf,1);
/* hash version,data length and data */
temp = g_htons(ver);
memcpy(buf, &temp, 2);
ssl_hmac_update(&hm,buf,2);
temp = g_htons(datalen);
memcpy(buf, &temp, 2);
ssl_hmac_update(&hm,buf,2);
ssl_hmac_update(&hm,data,datalen);
/* get digest and digest len */
len = sizeof(buf);
ssl_hmac_final(&hm,buf,&len);
ssl_hmac_cleanup(&hm);
ssl_print_data("Mac", buf, len);
if(memcmp(mac,buf,len))
return -1;
return(0);
}
int
ssl_decrypt_record(SslDecryptSessionC *ssl,SslDecoder* decoder, gint ct, const guchar* in, guint inl, StringInfo* comp_str, StringInfo* out_str, guint* outl)
{
guint pad, worklen, uncomplen;
guint8 *mac;
if (debug) printf("ssl_decrypt_record ciphertext len %d\n", inl);
ssl_print_data("Ciphertext",in, inl);
/* ensure we have enough storage space for decrypted data */
if (inl > out_str->data_len)
{
if (debug) printf("ssl_decrypt_record: allocating %d bytes for decrypt data (old len %d)\n",
inl + 32, out_str->data_len);
ssl_data_realloc(out_str, inl + 32);
}
/* RFC 6101/2246: SSLCipherText/TLSCipherText has two structures for types:
* (notation: { unencrypted, [ encrypted ] })
* GenericStreamCipher: { [content, mac] }
* GenericBlockCipher: { IV (TLS 1.1+), [content, mac, padding, padding_len] }
* RFC 5426 (TLS 1.2): TLSCipherText has additionally:
* GenericAEADCipher: { nonce_explicit, [content] }
* RFC 4347 (DTLS): based on TLS 1.1, only GenericBlockCipher is supported.
* RFC 6347 (DTLS 1.2): based on TLS 1.2, includes GenericAEADCipher too.
*/
/* (TLS 1.1 and later, DTLS) Extract explicit IV for GenericBlockCipher */
if (decoder->cipher_suite->mode == MODE_CBC) {
switch (ssl->version_netorder) {
case TLSV1DOT1_VERSION:
case TLSV1DOT2_VERSION:
case DTLSV1DOT0_VERSION:
case DTLSV1DOT2_VERSION:
case DTLSV1DOT0_VERSION_NOT:
if ((gint)inl < decoder->cipher_suite->block) {
if (debug) printf("ssl_decrypt_record failed: input %d has no space for IV %d\n",
inl, decoder->cipher_suite->block);
return -1;
}
pad = gcry_cipher_setiv(decoder->evp, in, decoder->cipher_suite->block);
if (pad != 0) {
if (debug) printf("ssl_decrypt_record failed: failed to set IV: %s %s\n",
gcry_strsource (pad), gcry_strerror (pad));
}
inl -= decoder->cipher_suite->block;
in += decoder->cipher_suite->block;
break;
}
}
/* Nonce for GenericAEADCipher */
if (decoder->cipher_suite->mode == MODE_GCM ||
decoder->cipher_suite->mode == MODE_CCM ||
decoder->cipher_suite->mode == MODE_CCM_8) {
/* 4 bytes write_iv, 8 bytes explicit_nonce, 4 bytes counter */
guchar gcm_nonce[16] = { 0 };
if ((gint)inl < SSL_EX_NONCE_LEN_GCM) {
if (debug) printf("ssl_decrypt_record failed: input %d has no space for nonce %d\n",
inl, SSL_EX_NONCE_LEN_GCM);
return -1;
}
if (decoder->cipher_suite->mode == MODE_GCM) {
memcpy(gcm_nonce, decoder->write_iv.data, decoder->write_iv.data_len); /* salt */
memcpy(gcm_nonce + decoder->write_iv.data_len, in, SSL_EX_NONCE_LEN_GCM);
/* NIST SP 800-38D, sect. 7.2 says that the 32-bit counter part starts
* at 1, and gets incremented before passing to the block cipher. */
gcm_nonce[4 + SSL_EX_NONCE_LEN_GCM + 3] = 2;
} else { /* MODE_CCM and MODE_CCM_8 */
/* The nonce for CCM and GCM are the same, but the nonce is used as input
* in the CCM algorithm described in RFC 3610. The nonce generated here is
* the one from RFC 3610 sect 2.3. Encryption. */
/* Flags: (L-1) ; L = 16 - 1 - nonceSize */
gcm_nonce[0] = 3 - 1;
memcpy(gcm_nonce + 1, decoder->write_iv.data, decoder->write_iv.data_len); /* salt */
memcpy(gcm_nonce + 1 + decoder->write_iv.data_len, in, SSL_EX_NONCE_LEN_GCM);
gcm_nonce[4 + SSL_EX_NONCE_LEN_GCM + 3] = 1;
}
pad = gcry_cipher_setctr (decoder->evp, gcm_nonce, sizeof (gcm_nonce));
if (pad != 0) {
if (debug) printf("ssl_decrypt_record failed: failed to set CTR: %s %s\n",
gcry_strsource (pad), gcry_strerror (pad));
return -1;
}
inl -= SSL_EX_NONCE_LEN_GCM;
in += SSL_EX_NONCE_LEN_GCM;
}
/* First decrypt*/
if ((pad = ssl_cipher_decrypt(&decoder->evp, out_str->data, out_str->data_len, in, inl))!= 0) {
if (debug) printf("ssl_decrypt_record failed: ssl_cipher_decrypt: %s %s\n", gcry_strsource (pad),
gcry_strerror (pad));
return -1;
}
ssl_print_data("Plaintext", out_str->data, inl);
worklen=inl;
/* RFC 5116 sect 5.1/5.3: AES128/256 GCM/CCM uses 16 bytes for auth tag
* RFC 6655 sect 6.1: AEAD_AES_128_CCM uses 16 bytes for auth tag */
if (decoder->cipher_suite->mode == MODE_GCM ||
decoder->cipher_suite->mode == MODE_CCM) {
if (worklen < 16) {
if (debug) printf("ssl_decrypt_record failed: missing tag, work %d\n", worklen);
return -1;
}
/* XXX - validate auth tag */
worklen -= 16;
}
/* RFC 6655 sect 6.1: AEAD_AES_128_CCM_8 uses 8 bytes for auth tag */
if (decoder->cipher_suite->mode == MODE_CCM_8) {
if (worklen < 8) {
if (debug) printf("ssl_decrypt_record failed: missing tag, work %d\n", worklen);
return -1;
}
/* XXX - validate auth tag */
worklen -= 8;
}
/* strip padding for GenericBlockCipher */
if (decoder->cipher_suite->mode == MODE_CBC) {
pad=out_str->data[inl-1];
if (worklen <= pad) {
if (debug) printf("ssl_decrypt_record failed: padding %d too large for work %d\n",
pad, worklen);
return -1;
}
worklen-=(pad+1);
if (debug) printf("ssl_decrypt_record found padding %d final len %d\n",
pad, worklen);
}
/* MAC for GenericStreamCipher and GenericBlockCipher */
if (decoder->cipher_suite->mode == MODE_STREAM ||
decoder->cipher_suite->mode == MODE_CBC) {
if (ssl_cipher_suite_dig(decoder->cipher_suite)->len > (gint)worklen) {
if (debug) printf("ssl_decrypt_record wrong record len/padding outlen %d\n work %d\n",*outl, worklen);
return -1;
}
worklen-=ssl_cipher_suite_dig(decoder->cipher_suite)->len;
mac = out_str->data + worklen;
} else /* if (decoder->cipher_suite->mode == MODE_GCM) */ {
/* GenericAEADCipher has no MAC */
goto skip_mac;
}
/* Now check the MAC */
if (debug) printf("checking mac (len %d, version %X, ct %d seq %d)\n",
worklen, ssl->version_netorder, ct, decoder->seq);
if(ssl->version_netorder==SSLV3_VERSION){
if(ssl3_check_mac(decoder,ct,out_str->data,worklen,mac) < 0) {
if(ssl_ignore_mac_failed) {
if (debug) printf("ssl_decrypt_record: mac failed, but ignored for troubleshooting ;-)\n");
}
else{
if (debug) printf("ssl_decrypt_record: mac failed\n");
return -1;
}
}
else{
if (debug) printf("ssl_decrypt_record: mac ok\n");
}
}
else if(ssl->version_netorder==TLSV1_VERSION || ssl->version_netorder==TLSV1DOT1_VERSION || ssl->version_netorder==TLSV1DOT2_VERSION){
if(tls_check_mac(decoder,ct,ssl->version_netorder,out_str->data,worklen,mac)< 0) {
if(ssl_ignore_mac_failed) {
if (debug) printf("ssl_decrypt_record: mac failed, but ignored for troubleshooting ;-)\n");
}
else{
if (debug) printf("ssl_decrypt_record: mac failed\n");
return -1;
}
}
else{
if (debug) printf("ssl_decrypt_record: mac ok\n");
}
}
else if(ssl->version_netorder==DTLSV1DOT0_VERSION ||
ssl->version_netorder==DTLSV1DOT2_VERSION ||
ssl->version_netorder==DTLSV1DOT0_VERSION_NOT){
/* Try rfc-compliant mac first, and if failed, try old openssl's non-rfc-compliant mac */
if(dtls_check_mac(decoder,ct,ssl->version_netorder,out_str->data,worklen,mac)>= 0) {
if (debug) printf("ssl_decrypt_record: mac ok\n");
}
else if(tls_check_mac(decoder,ct,TLSV1_VERSION,out_str->data,worklen,mac)>= 0) {
if (debug) printf("ssl_decrypt_record: dtls rfc-compliant mac failed, but old openssl's non-rfc-compliant mac ok\n");
}
else if(ssl_ignore_mac_failed) {
if (debug) printf("ssl_decrypt_record: mac failed, but ignored for troubleshooting ;-)\n");
}
else{
if (debug) printf("ssl_decrypt_record: mac failed\n");
return -1;
}
}
skip_mac:
*outl = worklen;
if (decoder->compression > 0) {
if (debug) printf("ssl_decrypt_record: compression method %d\n", decoder->compression);
ssl_data_copy(comp_str, out_str);
ssl_print_data("Plaintext compressed", comp_str->data, worklen);
if (!decoder->decomp) {
if (debug) printf("decrypt_ssl3_record: no decoder available\n");
return -1;
}
if (ssl_decompress_record(decoder->decomp, comp_str->data, worklen, out_str, &uncomplen) < 0) return -1;
ssl_print_data("Plaintext uncompressed", out_str->data, uncomplen);
*outl = uncomplen;
}
return 0;
}
static gint
decrypt_ssl3_record(char *data, int datalen, packet_info *pinfo, guint32 offset,
guint32 record_length, guint8 content_type, SslDecryptSessionC *ssl,
gboolean save_plaintext)
{
gint ret;
gint direction;
StringInfo *data_for_iv;
gint data_for_iv_len;
SslDecoder *decoder;
ret = 0;
/* if we can decrypt and decryption was a success
* add decrypted data to this packet info */
if(debug) printf("decrypt_ssl3_record: app_data len %d, ssl state 0x%02X\n", record_length, ssl->state);
direction = ssl_packet_from_server(ssl, pinfo);
/* retrieve decoder for this packet direction */
if (direction != 0) {
if(debug) printf("decrypt_ssl3_record: using server decoder\n");
decoder = ssl->server;
}
else {
if(debug) printf("decrypt_ssl3_record: using client decoder\n");
decoder = ssl->client;
}
/* save data to update IV if decoder is available or updated later */
data_for_iv = (direction != 0) ? &ssl->server_data_for_iv : &ssl->client_data_for_iv;
data_for_iv_len = (record_length < 24) ? record_length : 24;
ssl_data_set(data_for_iv, (const guchar*)(guint8*)(data + offset + record_length - data_for_iv_len), data_for_iv_len);
if (!decoder) {
if(debug) printf("decrypt_ssl3_record: no decoder available\n");
return ret;
}
/* run decryption and add decrypted payload to protocol data, if decryption
* is successful*/
ssl_decrypted_data_avail = ssl_decrypted_data.data_len;
if (ssl_decrypt_record(ssl, decoder, content_type, (const guchar*)(data + offset), record_length, &ssl_compressed_data, &ssl_decrypted_data, (guint*)&ssl_decrypted_data_avail) == 0)
ret = 1;
/* */
if (!ret) {
/* save data to update IV if valid session key is obtained later */
data_for_iv = (direction != 0) ? &ssl->server_data_for_iv : &ssl->client_data_for_iv;
data_for_iv_len = (record_length < 24) ? record_length : 24;
ssl_data_set(data_for_iv, (const guchar*)(data + offset + record_length - data_for_iv_len), data_for_iv_len);
}
if (ret && save_plaintext) {
//TODO
//ssl_add_data_info(proto_ssl, pinfo, ssl_decrypted_data.data, ssl_decrypted_data_avail, tvb_raw_offset(tvb)+offset, decoder->flow);
pinfo->decrypt_vec.push_back(string((char*)ssl_decrypted_data.data, ssl_decrypted_data_avail));
}
return ret;
}
#define RSA_PARS 6
static SSL_PRIVATE_KEY*
ssl_privkey_to_sexp(struct gnutls_x509_privkey_int* priv_key)
{
gnutls_datum_t rsa_datum[RSA_PARS]; /* m, e, d, p, q, u */
size_t tmp_size;
gcry_sexp_t rsa_priv_key = NULL;
gint i;
int ret;
size_t buf_len;
unsigned char buf_keyid[32];
gcry_mpi_t rsa_params[RSA_PARS];
buf_len = sizeof(buf_keyid);
ret = gnutls_x509_privkey_get_key_id(priv_key, 0, buf_keyid, &buf_len);
if (ret != 0) {
if (debug) printf( "gnutls_x509_privkey_get_key_id(ssl_pkey, 0, buf_keyid, &buf_len) - %s\n", gnutls_strerror(ret));
} else {
if(debug) {
gchar *tmp = bytes_to_ep_str_punct(buf_keyid, (int) buf_len, ':');
printf( "Private key imported: KeyID %s\n", tmp);
free(tmp);
}
}
/* RSA get parameter */
if(debug) printf("gnutls_x509_privkey_export_rsa_raw [%p] (x509_pkey)\n", priv_key);
if (gnutls_x509_privkey_export_rsa_raw(priv_key,
&rsa_datum[0],
&rsa_datum[1],
&rsa_datum[2],
&rsa_datum[3],
&rsa_datum[4],
&rsa_datum[5]) != 0) {
if (debug) printf("ssl_load_key: can't export rsa param (is a rsa private key file ?!?)\n");
return NULL;
}
/* convert each rsa parameter to mpi format*/
for(i=0; i<RSA_PARS; i++) {
if (gcry_mpi_scan(&rsa_params[i], GCRYMPI_FMT_USG, rsa_datum[i].data, rsa_datum[i].size,&tmp_size) != 0) {
if (debug) printf("ssl_load_key: can't convert m rsa param to int (size %d)\n", rsa_datum[i].size);
for (i = 0; i < RSA_PARS; i++) {
if(rsa_datum[i].data)
free(rsa_datum[i].data);
}
return NULL;
}
}
/* libgcrypt expects p < q, and gnutls might not return it as such, depending on gnutls version and its crypto backend */
if (gcry_mpi_cmp(rsa_params[3], rsa_params[4]) > 0)
{
if (debug) printf("ssl_load_key: swapping p and q parameters and recomputing u\n");
gcry_mpi_swap(rsa_params[3], rsa_params[4]);
gcry_mpi_invm(rsa_params[5], rsa_params[3], rsa_params[4]);
}