aboutsummaryrefslogtreecommitdiffstats
path: root/epan/dissectors/packet-ssl.c
blob: 1b8513278f363aed1f75b670644c8521d3735215 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
/* packet-ssl.c
 * Routines for ssl dissection
 * Copyright (c) 2000-2001, Scott Renfro <scott@renfro.org>
 *
 * Wireshark - Network traffic analyzer
 * By Gerald Combs <gerald@wireshark.org>
 * Copyright 1998 Gerald Combs
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * See
 *
 *    http://www.mozilla.org/projects/security/pki/nss/ssl/draft02.html
 *
 * for SSL 2.0 specs.
 *
 * See
 *
 *    http://www.mozilla.org/projects/security/pki/nss/ssl/draft302.txt
 *
 * for SSL 3.0 specs.
 *
 * See RFC 2246 for SSL 3.1/TLS 1.0 specs.
 *
 * See (among other places)
 *
 *    http://www.graphcomp.com/info/specs/ms/pct.htm
 *
 * for PCT 1 draft specs.
 *
 * See
 *
 *    http://research.sun.com/projects/crypto/draft-ietf-tls-ecc-05.txt
 *
 * for Elliptic Curve Cryptography cipher suites.
 *
 * See
 *
 *    http://www.ietf.org/internet-drafts/draft-ietf-tls-camellia-04.txt
 *
 * for Camellia-based cipher suites.
 *
 * Notes:
 *
 *   - Does not support dissection
 *     of frames that would require state maintained between frames
 *     (e.g., single ssl records spread across multiple tcp frames)
 *
 *   - Identifies, but does not fully dissect the following messages:
 *
 *     - SSLv3/TLS (These need more state from previous handshake msgs)
 *       - Certificate Verify
 *
 *     - SSLv2 (These don't appear in the clear)
 *       - Error
 *       - Client Finished
 *       - Server Verify
 *       - Server Finished
 *       - Request Certificate
 *       - Client Certificate
 *
 *    - Decryption needs to be performed 'sequentially', so it's done
 *      at packet reception time. This may cause a significant packet capture
 *      slow down. This also causes dissection of some ssl info that in previous
 *      dissector versions was dissected only when a proto_tree context was
 *      available
 *
 *     We are at Packet reception if time pinfo->fd->flags.visited == 0
 *
 */

#include "config.h"

#include <epan/packet.h>
#include <epan/reassemble.h>
#include <epan/asn1.h>
#include <epan/tap.h>
#include <epan/uat.h>
#include <epan/addr_resolv.h>
#include <epan/follow.h>
#include <epan/exported_pdu.h>
#include <epan/proto_data.h>
#include <epan/decode_as.h>

#include <wsutil/utf8_entities.h>
#include <wsutil/str_util.h>
#include <wsutil/strtoi.h>
#include <wsutil/rsa.h>
#include "packet-tcp.h"
#include "packet-x509af.h"
#include "packet-ssl.h"
#include "packet-ssl-utils.h"
#include "packet-ber.h"

void proto_register_ssl(void);

static ssldecrypt_assoc_t *sslkeylist_uats = NULL;
static guint nssldecrypt = 0;

static gboolean ssl_desegment          = TRUE;
static gboolean ssl_desegment_app_data = TRUE;

gboolean ssl_ignore_mac_failed = FALSE;


/*********************************************************************
 *
 * Protocol Constants, Variables, Data Structures
 *
 *********************************************************************/

/* Initialize the protocol and registered fields */
static gint ssl_tap                           = -1;
static gint exported_pdu_tap                  = -1;
static gint proto_ssl                         = -1;
static gint hf_ssl_record                     = -1;
static gint hf_ssl_record_content_type        = -1;
static gint hf_ssl_record_opaque_type         = -1;
static gint hf_ssl_record_version             = -1;
static gint hf_ssl_record_length              = -1;
static gint hf_ssl_record_appdata             = -1;
static gint hf_ssl2_record                    = -1;
static gint hf_ssl2_record_is_escape          = -1;
static gint hf_ssl2_record_padding_length     = -1;
static gint hf_ssl2_msg_type                  = -1;
static gint hf_pct_msg_type                   = -1;
static gint hf_ssl_alert_message              = -1;
static gint hf_ssl_alert_message_level        = -1;
static gint hf_ssl_alert_message_description  = -1;
static gint hf_ssl_handshake_protocol         = -1;
static gint hf_ssl_handshake_type             = -1;
static gint hf_ssl_handshake_length           = -1;
static gint hf_ssl_handshake_npn_selected_protocol_len = -1;
static gint hf_ssl_handshake_npn_selected_protocol = -1;
static gint hf_ssl_handshake_npn_padding_len = -1;
static gint hf_ssl_handshake_npn_padding = -1;
static gint hf_ssl2_handshake_cipher_spec_len = -1;
static gint hf_ssl2_handshake_session_id_len  = -1;
static gint hf_ssl2_handshake_challenge_len   = -1;
static gint hf_ssl2_handshake_cipher_spec     = -1;
static gint hf_ssl2_handshake_challenge       = -1;
static gint hf_ssl2_handshake_clear_key_len   = -1;
static gint hf_ssl2_handshake_enc_key_len     = -1;
static gint hf_ssl2_handshake_key_arg_len     = -1;
static gint hf_ssl2_handshake_clear_key       = -1;
static gint hf_ssl2_handshake_enc_key         = -1;
static gint hf_ssl2_handshake_key_arg         = -1;
static gint hf_ssl2_handshake_session_id_hit  = -1;
static gint hf_ssl2_handshake_cert_type       = -1;
static gint hf_ssl2_handshake_connection_id_len = -1;
static gint hf_ssl2_handshake_connection_id   = -1;
static gint hf_pct_handshake_cipher_spec      = -1;
static gint hf_pct_handshake_hash_spec        = -1;
static gint hf_pct_handshake_cert_spec        = -1;
static gint hf_pct_handshake_cert             = -1;
static gint hf_pct_handshake_server_cert      = -1;
static gint hf_pct_handshake_exch_spec        = -1;
static gint hf_pct_handshake_hash             = -1;
static gint hf_pct_handshake_cipher           = -1;
static gint hf_pct_handshake_exch             = -1;
static gint hf_pct_handshake_sig              = -1;
static gint hf_pct_msg_error_type             = -1;

/* Generated from convert_proto_tree_add_text.pl */
static int hf_ssl_pct_client_version = -1;
static int hf_ssl_pct_pad = -1;
static int hf_ssl_pct_client_session_id_data = -1;
static int hf_ssl_pct_challenge_data = -1;
static int hf_ssl_pct_ch_offset = -1;
static int hf_ssl_pct_cipher_specs_length = -1;
static int hf_ssl_pct_hash_specs_length = -1;
static int hf_ssl_pct_cert_specs_length = -1;
static int hf_ssl_pct_exch_specs_length = -1;
static int hf_ssl_pct_iv_length = -1;
static int hf_ssl_pct_encryption_key_length = -1;
static int hf_ssl_pct_mac_key_length_in_bits = -1;
static int hf_ssl_pct_iv_data = -1;
static int hf_ssl_pct_server_version = -1;
static int hf_ssl_pct_sh_restart_session_ok_flag = -1;
static int hf_ssl_pct_sh_client_auth_req_flag = -1;
static int hf_ssl_pct_connection_id_data = -1;
static int hf_ssl_pct_server_certificate_length = -1;
static int hf_ssl_pct_client_cert_specs_length = -1;
static int hf_ssl_pct_client_sig_specs_length = -1;
static int hf_ssl_pct_response_length = -1;
static int hf_ssl_pct_client_cert_specs = -1;
static int hf_ssl_pct_client_signature = -1;
static int hf_ssl_pct_server_response = -1;
static int hf_ssl_pct_clear_key_length = -1;
static int hf_ssl_pct_encrypted_key_length = -1;
static int hf_ssl_pct_verify_prelude_length = -1;
static int hf_ssl_pct_client_cert_length = -1;
static int hf_ssl_pct_clear_key_data = -1;
static int hf_ssl_pct_encrypted_key_data = -1;
static int hf_ssl_pct_verify_prelude_data = -1;
static int hf_ssl_pct_client_certificate_data = -1;
static int hf_ssl_pct_response_data = -1;
static int hf_ssl_pct_server_session_id_data = -1;
static int hf_ssl_pct_server_response_length = -1;
static int hf_ssl_pct_error_information_length = -1;
static int hf_ssl_pct_specs_mismatch_cipher = -1;
static int hf_ssl_pct_specs_mismatch_hash = -1;
static int hf_ssl_pct_specs_mismatch_cert = -1;
static int hf_ssl_pct_specs_mismatch_exch = -1;
static int hf_ssl_pct_specs_mismatch_client_cert = -1;
static int hf_ssl_pct_specs_mismatch_client_sig = -1;
static int hf_ssl_pct_error_information_data = -1;

static int hf_ssl_reassembled_in              = -1;
static int hf_ssl_reassembled_length          = -1;
static int hf_ssl_reassembled_data            = -1;
static int hf_ssl_segments                    = -1;
static int hf_ssl_segment                     = -1;
static int hf_ssl_segment_overlap             = -1;
static int hf_ssl_segment_overlap_conflict    = -1;
static int hf_ssl_segment_multiple_tails      = -1;
static int hf_ssl_segment_too_long_fragment   = -1;
static int hf_ssl_segment_error               = -1;
static int hf_ssl_segment_count               = -1;
static int hf_ssl_segment_data                = -1;

static gint hf_ssl_heartbeat_message                 = -1;
static gint hf_ssl_heartbeat_message_type            = -1;
static gint hf_ssl_heartbeat_message_payload_length  = -1;
static gint hf_ssl_heartbeat_message_payload         = -1;
static gint hf_ssl_heartbeat_message_padding         = -1;

static ssl_hfs_t ssl_hfs = { -1, -1 };

/* Initialize the subtree pointers */
static gint ett_ssl                   = -1;
static gint ett_ssl_record            = -1;
static gint ett_ssl_alert             = -1;
static gint ett_ssl_handshake         = -1;
static gint ett_ssl_heartbeat         = -1;
static gint ett_ssl_certs             = -1;
static gint ett_pct_cipher_suites     = -1;
static gint ett_pct_hash_suites       = -1;
static gint ett_pct_cert_suites       = -1;
static gint ett_pct_exch_suites       = -1;
static gint ett_ssl_segments          = -1;
static gint ett_ssl_segment           = -1;

static expert_field ei_ssl2_handshake_session_id_len_error = EI_INIT;
static expert_field ei_ssl3_heartbeat_payload_length = EI_INIT;
static expert_field ei_tls_unexpected_message = EI_INIT;

/* Generated from convert_proto_tree_add_text.pl */
static expert_field ei_ssl_pct_ch_offset = EI_INIT;
static expert_field ei_ssl_pct_server_version = EI_INIT;
static expert_field ei_ssl_ignored_unknown_record = EI_INIT;
static expert_field ei_ssl_pct_client_version = EI_INIT;

/* not all of the hf_fields below make sense for SSL but we have to provide
   them anyways to comply with the api (which was aimed for ip fragment
   reassembly) */
static const fragment_items ssl_segment_items = {
    &ett_ssl_segment,
    &ett_ssl_segments,
    &hf_ssl_segments,
    &hf_ssl_segment,
    &hf_ssl_segment_overlap,
    &hf_ssl_segment_overlap_conflict,
    &hf_ssl_segment_multiple_tails,
    &hf_ssl_segment_too_long_fragment,
    &hf_ssl_segment_error,
    &hf_ssl_segment_count,
    &hf_ssl_reassembled_in,
    &hf_ssl_reassembled_length,
    &hf_ssl_reassembled_data,
    "Segments"
};

static SSL_COMMON_LIST_T(dissect_ssl3_hf);

static void
ssl_proto_tree_add_segment_data(
    proto_tree  *tree,
    tvbuff_t    *tvb,
    gint         offset,
    gint         length,
    const gchar *prefix)
{
    proto_tree_add_bytes_format(
        tree,
        hf_ssl_segment_data,
        tvb,
        offset,
        length,
        NULL,
        "%sSSL segment data (%u %s)",
        prefix != NULL ? prefix : "",
        length,
        plurality(length, "byte", "bytes"));
}


static ssl_master_key_map_t       ssl_master_key_map;
/* used by "Export SSL Session Keys" */
GHashTable *ssl_session_hash;
GHashTable *ssl_crandom_hash;

static GHashTable         *ssl_key_hash             = NULL;
static wmem_stack_t       *key_list_stack            = NULL;
static dissector_table_t   ssl_associations         = NULL;
static dissector_handle_t  ssl_handle               = NULL;
static StringInfo          ssl_compressed_data      = {NULL, 0};
static StringInfo          ssl_decrypted_data       = {NULL, 0};
static gint                ssl_decrypted_data_avail = 0;
static FILE               *ssl_keylog_file          = NULL;

static uat_t              *ssldecrypt_uat           = NULL;
static const gchar        *ssl_keys_list            = NULL;
static ssl_common_options_t ssl_options = { NULL, NULL};

/* List of dissectors to call for SSL data */
static heur_dissector_list_t ssl_heur_subdissector_list;

static const gchar *ssl_debug_file_name     = NULL;


/* Forward declaration we need below */
void proto_reg_handoff_ssl(void);

/* Desegmentation of SSL streams */
/* table to hold defragmented SSL streams */
static reassembly_table ssl_reassembly_table;

/* initialize/reset per capture state data (ssl sessions cache) */
static void
ssl_init(void)
{
    module_t *ssl_module = prefs_find_module("ssl");
    pref_t   *keys_list_pref;

    ssl_common_init(&ssl_master_key_map,
                    &ssl_decrypted_data, &ssl_compressed_data);
    ssl_debug_flush();

    /* for "Export SSL Session Keys" */
    ssl_session_hash = ssl_master_key_map.session;
    ssl_crandom_hash = ssl_master_key_map.crandom;

    /* We should have loaded "keys_list" by now. Mark it obsolete */
    if (ssl_module) {
        keys_list_pref = prefs_find_preference(ssl_module, "keys_list");
        if (! prefs_get_preference_obsolete(keys_list_pref)) {
            prefs_set_preference_obsolete(keys_list_pref);
        }
    }
}

static void
ssl_cleanup(void)
{
    if (key_list_stack != NULL) {
        wmem_destroy_stack(key_list_stack);
        key_list_stack = NULL;
    }
    ssl_common_cleanup(&ssl_master_key_map, &ssl_keylog_file,
                       &ssl_decrypted_data, &ssl_compressed_data);

    /* should not be needed since the UI code prevents this from being accessed
     * when no file is open. Clear it anyway just to be sure. */
    ssl_session_hash = NULL;
    ssl_crandom_hash = NULL;
}

/* parse ssl related preferences (private keys and ports association strings) */
static void
ssl_parse_uat(void)
{
    guint              i;
    guint16            port;
    dissector_handle_t handle;

    ssl_set_debug(ssl_debug_file_name);

    if (ssl_key_hash)
    {
        g_hash_table_destroy(ssl_key_hash);
    }

    /* remove only associations created from key list */
    if (key_list_stack != NULL) {
        while (wmem_stack_count(key_list_stack) > 0) {
          port = GPOINTER_TO_UINT(wmem_stack_pop(key_list_stack));
          handle = dissector_get_uint_handle(ssl_associations, port);
          if (handle != NULL)
              ssl_association_remove("ssl.port", ssl_handle, handle, port, FALSE);
        }
    }
    /* parse private keys string, load available keys and put them in key hash*/
    ssl_key_hash = g_hash_table_new_full(ssl_private_key_hash,
            ssl_private_key_equal, g_free, rsa_private_key_free);


    if (nssldecrypt > 0) {
        if (key_list_stack == NULL)
            key_list_stack = wmem_stack_new(NULL);
        for (i = 0; i < nssldecrypt; i++) {
            ssldecrypt_assoc_t *ssl_uat = &(sslkeylist_uats[i]);
            ssl_parse_key_list(ssl_uat, ssl_key_hash, "ssl.port", ssl_handle, TRUE);
            if (key_list_stack && ws_strtou16(ssl_uat->port, NULL, &port) && port > 0)
                wmem_stack_push(key_list_stack, GUINT_TO_POINTER(port));
        }
    }

    ssl_debug_flush();
}

#if defined(HAVE_LIBGNUTLS)
static void
ssl_reset_uat(void)
{
    g_hash_table_destroy(ssl_key_hash);
    ssl_key_hash = NULL;
}
#endif

static void
ssl_parse_old_keys(void)
{
    gchar **old_keys, **parts, *err;
    gchar  *uat_entry;
    guint   i;

    /* Import old-style keys */
    if (ssldecrypt_uat && ssl_keys_list && ssl_keys_list[0]) {
        old_keys = wmem_strsplit(NULL, ssl_keys_list, ";", 0);
        for (i = 0; old_keys[i] != NULL; i++) {
            parts = wmem_strsplit(NULL, old_keys[i], ",", 5);
            if (parts[0] && parts[1] && parts[2] && parts[3]) {
                gchar *path = uat_esc(parts[3], (guint)strlen(parts[3]));
                const gchar *password = parts[4] ? parts[4] : "";
                uat_entry = wmem_strdup_printf(NULL, "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"",
                                parts[0], parts[1], parts[2], path, password);
                g_free(path);
                if (!uat_load_str(ssldecrypt_uat, uat_entry, &err)) {
                    ssl_debug_printf("ssl_parse_old_keys: Can't load UAT string %s: %s\n",
                                     uat_entry, err);
                    g_free(err);
                }
                wmem_free(NULL, uat_entry);
            }
            wmem_free(NULL, parts);
        }
        wmem_free(NULL, old_keys);
    }
}


static gboolean
ssl_follow_tap_listener(void *tapdata, packet_info *pinfo, epan_dissect_t *edt _U_, const void *ssl)
{
    follow_info_t *      follow_info = (follow_info_t*) tapdata;
    follow_record_t * follow_record = NULL;
    const SslRecordInfo *appl_data = NULL;
    const SslPacketInfo *pi = (const SslPacketInfo*)ssl;
    show_stream_t        from = FROM_CLIENT;

    /* Skip packets without decrypted payload data. */
    if (!pi || !pi->records) return FALSE;

    /* Compute the packet's sender. */
    if (follow_info->client_port == 0) {
        follow_info->client_port = pinfo->srcport;
        copy_address(&follow_info->client_ip, &pinfo->src);
    }
    if (addresses_equal(&follow_info->client_ip, &pinfo->src) &&
            follow_info->client_port == pinfo->srcport) {
        from = FROM_CLIENT;
    } else {
        from = FROM_SERVER;
    }

    for (appl_data = pi->records; appl_data != NULL; appl_data = appl_data->next) {

        /* Include only application data in the record, skipping things like
         * Handshake messages and alerts. */
        if (appl_data->type != SSL_ID_APP_DATA) continue;

        /* TCP segments that contain the end of two or more SSL PDUs will be
           queued to SSL taps for each of those PDUs. Therefore a single
           packet could be processed by this SSL tap listener multiple times.
           The following test handles that scenario by treating the
           follow_info->bytes_written[] values as the next expected
           appl_data->seq. Any appl_data instances that fall below that have
           already been processed and must be skipped. */
        if (appl_data->seq < follow_info->bytes_written[from]) continue;

        /* Allocate a follow_record_t to hold the current appl_data
           instance's decrypted data. Even though it would be possible to
           consolidate multiple appl_data instances into a single record, it is
           beneficial to use a one-to-one mapping. This affords the Follow
           Stream dialog view modes (ASCII, EBCDIC, Hex Dump, C Arrays, Raw)
           the opportunity to accurately reflect SSL PDU boundaries. Currently
           the Hex Dump view does by starting a new line, and the C Arrays
           view does by starting a new array declaration. */
        follow_record = g_new(follow_record_t,1);

        follow_record->is_server = (from == FROM_SERVER);
        follow_record->packet_num = pinfo->num;

        follow_record->data = g_byte_array_sized_new(appl_data->data_len);
        follow_record->data = g_byte_array_append(follow_record->data,
                                              appl_data->plain_data,
                                              appl_data->data_len);

        /* Append the record to the follow_info structure. */
        follow_info->payload = g_list_append(follow_info->payload, follow_record);
        follow_info->bytes_written[from] += appl_data->data_len;
    }

    return FALSE;
}

/*********************************************************************
 *
 * Forward Declarations
 *
 *********************************************************************/

/*
 * SSL version 3 and TLS dissectors
 *
 */
/* record layer dissector */
static gint dissect_ssl3_record(tvbuff_t *tvb, packet_info *pinfo,
                                proto_tree *tree, guint32 offset,
                                SslSession *session, gint is_from_server,
                                gboolean *need_desegmentation,
                                SslDecryptSession *conv_data,
                                guint8 curr_layer_num_ssl);

/* alert message dissector */
static void dissect_ssl3_alert(tvbuff_t *tvb, packet_info *pinfo,
                               proto_tree *tree, guint32 offset,
                               const SslSession *session);

/* handshake protocol dissector */
static void dissect_ssl3_handshake(tvbuff_t *tvb, packet_info *pinfo,
                                   proto_tree *tree, guint32 offset,
                                   guint32 record_length, gboolean maybe_encrypted,
                                   SslSession *session, gint is_from_server,
                                   SslDecryptSession *conv_data,
                                   const guint8 content_type, const guint16 version);

/* heartbeat message dissector */
static void dissect_ssl3_heartbeat(tvbuff_t *tvb, packet_info *pinfo,
                                   proto_tree *tree, guint32 offset,
                                   const SslSession *session, guint32 record_length,
                                   gboolean decrypted);

static void dissect_ssl3_hnd_encrypted_exts(tvbuff_t *tvb,
                                            proto_tree *tree,
                                            guint32 offset);

/*
 * SSL version 2 dissectors
 *
 */

/* record layer dissector */
static gint dissect_ssl2_record(tvbuff_t *tvb, packet_info *pinfo,
                                proto_tree *tree, guint32 offset,
                                SslSession *session,
                                gboolean *need_desegmentation,
                                SslDecryptSession *ssl);

/* client hello dissector */
static void dissect_ssl2_hnd_client_hello(tvbuff_t *tvb, packet_info *pinfo,
                                          proto_tree *tree,
                                          guint32 offset,
                                          SslDecryptSession *ssl);

static void dissect_pct_msg_client_hello(tvbuff_t *tvb, packet_info *pinfo,
                                          proto_tree *tree,
                                          guint32 offset);

/* client master key dissector */
static void dissect_ssl2_hnd_client_master_key(tvbuff_t *tvb,
                                               proto_tree *tree,
                                               guint32 offset);
static void dissect_pct_msg_client_master_key(tvbuff_t *tvb,
                                              proto_tree *tree,
                                              guint32 offset);

/* server hello dissector */
static void dissect_ssl2_hnd_server_hello(tvbuff_t *tvb,
                                          proto_tree *tree,
                                          guint32 offset, packet_info *pinfo);
static void dissect_pct_msg_server_hello(tvbuff_t *tvb,
                                         proto_tree *tree,
                                         guint32 offset, packet_info *pinfo);


static void dissect_pct_msg_server_verify(tvbuff_t *tvb,
                                          proto_tree *tree,
                                          guint32 offset);

static void dissect_pct_msg_error(tvbuff_t *tvb,
                                  proto_tree *tree,
                                  guint32 offset);

/*
 * Support Functions
 *
 */
static gint  ssl_is_valid_ssl_version(const guint16 version);
static gint  ssl_is_v2_client_hello(tvbuff_t *tvb, const guint32 offset);
static gint  ssl_looks_like_sslv2(tvbuff_t *tvb, const guint32 offset);
static gint  ssl_looks_like_sslv3(tvbuff_t *tvb, const guint32 offset);
static gint  ssl_looks_like_valid_v2_handshake(tvbuff_t *tvb,
                                               const guint32 offset,
                                               const guint32 record_length);
static gint  ssl_looks_like_valid_pct_handshake(tvbuff_t *tvb,
                                                const guint32 offset,
                                                const guint32 record_length);

/*********************************************************************
 *
 * Main dissector
 *
 *********************************************************************/
/*
 * Code to actually dissect the packets
 */
static int
dissect_ssl(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
{

    conversation_t    *conversation;
    proto_item        *ti;
    proto_tree        *ssl_tree;
    guint32            offset;
    gboolean           need_desegmentation;
    SslDecryptSession *ssl_session;
    SslSession        *session;
    gint               is_from_server;
    guint8             curr_layer_num_ssl = pinfo->curr_layer_num;

    ti = NULL;
    ssl_tree   = NULL;
    offset = 0;
    ssl_session = NULL;


    if (tvb_captured_length(tvb) > 4) {
        const guint8 *tmp = tvb_get_ptr(tvb, 0, 4);
        if (g_ascii_isprint(tmp[0]) &&
                g_ascii_isprint(tmp[1]) &&
                g_ascii_isprint(tmp[2]) &&
                g_ascii_isprint(tmp[3])) {
            /* it is extremely unlikely that real SSL traffic starts with four
             * printable ascii characters; this looks like it's unencrypted
             * text, so assume it's not ours (SSL does have some unencrypted
             * text fields in certain packets, but you'd have to get very
             * unlucky with TCP fragmentation to have one of those fields at the
             * beginning of a TCP payload at the beginning of the capture where
             * reassembly hasn't started yet) */
            return 0;
        }
    }

    ssl_debug_printf("\ndissect_ssl enter frame #%u (%s)\n", pinfo->num, (pinfo->fd->flags.visited)?"already visited":"first time");

    /* Track the version using conversations to reduce the
     * chance that a packet that simply *looks* like a v2 or
     * v3 packet is dissected improperly.  This also allows
     * us to more frequently set the protocol column properly
     * for continuation data frames.
     *
     * Also: We use the copy in conv_version as our cached copy,
     *       so that we don't have to search the conversation
     *       table every time we want the version; when setting
     *       the conv_version, must set the copy in the conversation
     *       in addition to conv_version
     */
    conversation = find_or_create_conversation(pinfo);
    ssl_session = ssl_get_session(conversation, ssl_handle);
    session = &ssl_session->session;
    is_from_server = ssl_packet_from_server(session, ssl_associations, pinfo);

    if (session->last_nontls_frame != 0 &&
        session->last_nontls_frame >= pinfo->num) {
        /* This conversation started at a different protocol and STARTTLS was
         * used, but this packet comes too early. */
        return 0;
    }

    /* try decryption only the first time we see this packet
     * (to keep cipher synchronized) */
    if (pinfo->fd->flags.visited)
         ssl_session = NULL;

    ssl_debug_printf("  conversation = %p, ssl_session = %p\n", (void *)conversation, (void *)ssl_session);

    /* Initialize the protocol column; we'll override it later when we
     * detect a different version or flavor of SSL (assuming we don't
     * throw an exception before we get the chance to do so). */
    col_set_str(pinfo->cinfo, COL_PROTOCOL,
             val_to_str_const(session->version, ssl_version_short_names, "SSL"));
    /* clear the the info column */
    col_clear(pinfo->cinfo, COL_INFO);

    /* TCP packets and SSL records are orthogonal.
     * A tcp packet may contain multiple ssl records and an ssl
     * record may be spread across multiple tcp packets.
     *
     * This loop accounts for multiple ssl records in a single
     * frame, but not a single ssl record across multiple tcp
     * packets.
     *
     * Handling the single ssl record across multiple packets
     * may be possible using wireshark conversations, but
     * probably not cleanly.  May have to wait for tcp stream
     * reassembly.
     */

    /* Create display subtree for SSL as a whole */
    if (tree)
    {
        ti = proto_tree_add_item(tree, proto_ssl, tvb, 0, -1, ENC_NA);
        ssl_tree = proto_item_add_subtree(ti, ett_ssl);
    }
    /* iterate through the records in this tvbuff */
    while (tvb_reported_length_remaining(tvb, offset) > 0)
    {
        ssl_debug_printf("  record: offset = %d, reported_length_remaining = %d\n", offset, tvb_reported_length_remaining(tvb, offset));

        /*
         * Assume, for now, that this doesn't need desegmentation.
         */
        need_desegmentation = FALSE;

        /* first try to dispatch off the cached version
         * known to be associated with the conversation
         */
        switch (session->version) {
        case SSLV2_VERSION:
        case PCT_VERSION:
            offset = dissect_ssl2_record(tvb, pinfo, ssl_tree,
                                         offset, session,
                                         &need_desegmentation,
                                         ssl_session);
            break;

        case SSLV3_VERSION:
        case TLSV1_VERSION:
        case TLSV1DOT1_VERSION:
        case TLSV1DOT2_VERSION:
            /* SSLv3/TLS record headers need at least 1+2+2 = 5 bytes. */
            if (tvb_reported_length_remaining(tvb, offset) < 5) {
                if (ssl_desegment && pinfo->can_desegment) {
                    pinfo->desegment_offset = offset;
                    pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT;
                    need_desegmentation = TRUE;
                } else {
                    /* Not enough bytes available. Stop here. */
                    offset = tvb_reported_length(tvb);
                }
                break;
            }

            /* the version tracking code works too well ;-)
             * at times, we may visit a v2 client hello after
             * we already know the version of the connection;
             * work around that here by detecting and calling
             * the v2 dissector instead
             */
            if (ssl_is_v2_client_hello(tvb, offset))
            {
                offset = dissect_ssl2_record(tvb, pinfo, ssl_tree,
                                             offset, session,
                                             &need_desegmentation,
                                             ssl_session);
            }
            else
            {
                offset = dissect_ssl3_record(tvb, pinfo, ssl_tree,
                                             offset, session, is_from_server,
                                             &need_desegmentation,
                                             ssl_session,
                                             curr_layer_num_ssl);
            }
            break;

            /* that failed, so apply some heuristics based
             * on this individual packet
             */
        default:
            if (ssl_looks_like_sslv2(tvb, offset))
            {
                /* looks like sslv2 or pct client hello */
                offset = dissect_ssl2_record(tvb, pinfo, ssl_tree,
                                             offset, session,
                                             &need_desegmentation,
                                             ssl_session);
            }
            else if (ssl_looks_like_sslv3(tvb, offset))
            {
                /* looks like sslv3 or tls */
                offset = dissect_ssl3_record(tvb, pinfo, ssl_tree,
                                             offset, session, is_from_server,
                                             &need_desegmentation,
                                             ssl_session,
                                             curr_layer_num_ssl);
            }
            else
            {
                /* looks like something unknown, so lump into
                 * continuation data
                 */
                offset = tvb_reported_length(tvb);
                col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Continuation Data");
            }
            break;
        }

        /* Desegmentation return check */
        if (need_desegmentation) {
          ssl_debug_printf("  need_desegmentation: offset = %d, reported_length_remaining = %d\n",
                           offset, tvb_reported_length_remaining(tvb, offset));
          /* Make data available to ssl_follow_tap_listener */
          tap_queue_packet(ssl_tap, pinfo, p_get_proto_data(wmem_file_scope(), pinfo, proto_ssl, curr_layer_num_ssl));
          return tvb_captured_length(tvb);
        }
    }

    col_set_fence(pinfo->cinfo, COL_INFO);

    ssl_debug_flush();

    /* Make data available to ssl_follow_tap_listener */
    tap_queue_packet(ssl_tap, pinfo, p_get_proto_data(wmem_file_scope(), pinfo, proto_ssl, curr_layer_num_ssl));

    return tvb_captured_length(tvb);
}

static gboolean
is_sslv3_or_tls(tvbuff_t *tvb)
{
    guint8              content_type;
    guint16             protocol_version, record_length;

    /*
     * Heuristics should match a non-empty TLS record:
     * ContentType (1), ProtocolVersion (2), Length (2), fragment (...)
     */
    if (tvb_captured_length(tvb) < 6) {
        return FALSE;
    }

    content_type = tvb_get_guint8(tvb, 0);
    protocol_version = tvb_get_ntohs(tvb, 1);
    record_length = tvb_get_ntohs(tvb, 3);

    /* These are the common types. */
    if (content_type != SSL_ID_HANDSHAKE && content_type != SSL_ID_APP_DATA) {
        return FALSE;
    }

    /*
     * Match SSLv3, TLS 1.0/1.1/1.2 (TLS 1.3 uses same value as TLS 1.0). Most
     * likely you'll see 0x300 (SSLv3) or 0x301 (TLS 1.1) for interoperability
     * reasons. Per RFC 5246 we should accept any 0x3xx value, but this is just
     * a heuristic that catches common/likely cases.
     */
    if (protocol_version != SSLV3_VERSION &&
        protocol_version != TLSV1_VERSION &&
        protocol_version != TLSV1DOT1_VERSION &&
        protocol_version != TLSV1DOT2_VERSION) {
        return FALSE;
    }

    /* Check for sane length, see also ssl_check_record_length in packet-ssl-utils.c */
    if (record_length == 0 || record_length >= TLS_MAX_RECORD_LENGTH + 2048) {
        return FALSE;
    }

    return TRUE;
}

static gboolean
is_sslv2_clienthello(tvbuff_t *tvb)
{
    /*
     * Detect SSL 2.0 compatible Client Hello as used in SSLv3 and TLS.
     *
     * https://tools.ietf.org/html/rfc5246#appendix-E.2
     *  uint8 V2CipherSpec[3];
     *  struct {
     *      uint16 msg_length;          // 0: highest bit must be 1
     *      uint8 msg_type;             // 2: 1 for Client Hello
     *      Version version;            // 3: equal to ClientHello.client_version
     *      uint16 cipher_spec_length;  // 5: cannot be 0, must be multiple of 3
     *      uint16 session_id_length;   // 7: zero or 16 (in TLS 1.0)
     *      uint16 challenge_length;    // 9: must be 32
     *      // length so far: 2 + 1 + 2 + 2 + 2 + 2 = 11
     *      V2CipherSpec cipher_specs[V2ClientHello.cipher_spec_length];    // len: min 3
     *      opaque session_id[V2ClientHello.session_id_length];             // len: zero or 16
     *      opaque challenge[V2ClientHello.challenge_length;                // len: 32
     *      // min. length: 11 + 3 + (0 or 16) + 32 = 46 or 62
     *  } V2ClientHello;
     */
    if (tvb_captured_length(tvb) < 46) {
        return FALSE;
    }

    /* Assume that message length is less than 256 (at most 64 cipherspecs). */
    if (tvb_get_guint8(tvb, 0) != 0x80) {
        return FALSE;
    }

    /* msg_type must be 1 for Client Hello */
    if (tvb_get_guint8(tvb, 2) != 1) {
        return FALSE;
    }

    /* cipher spec length must be a non-zero multiple of 3 */
    guint16 cipher_spec_length = tvb_get_ntohs(tvb, 5);
    if (cipher_spec_length == 0 || cipher_spec_length % 3 != 0) {
        return FALSE;
    }

    /* session ID length must be 0 or 16 in TLS 1.0 */
    guint16 session_id_length = tvb_get_ntohs(tvb, 7);
    if (session_id_length != 0 && session_id_length != 16) {
        return FALSE;
    }

    /* Challenge Length must be 32 */
    if (tvb_get_ntohs(tvb, 9) != 32) {
        return FALSE;
    }

    return TRUE;
}

static int
dissect_ssl_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
    conversation_t     *conversation;

    if (!is_sslv3_or_tls(tvb) && !is_sslv2_clienthello(tvb)) {
        return 0;
    }

    conversation = find_or_create_conversation(pinfo);
    conversation_set_dissector(conversation, ssl_handle);
    return dissect_ssl(tvb, pinfo, tree, data);
}

/**
 * Try to decrypt the record and update the internal cipher state.
 * On success, the decrypted data will be available in "ssl_decrypted_data" of
 * length "ssl_decrypted_data_avail".
 */
static gboolean
decrypt_ssl3_record(tvbuff_t *tvb, packet_info *pinfo, guint32 offset, SslDecryptSession *ssl,
        guint8 content_type, guint16 record_version, guint16 record_length,
        gboolean allow_fragments, guint8 curr_layer_num_ssl)
{
    gboolean    success;
    gint        direction;
    StringInfo *data_for_iv;
    gint        data_for_iv_len;
    SslDecoder *decoder;

    /* if we can decrypt and decryption was a success
     * add decrypted data to this packet info */
    ssl_debug_printf("decrypt_ssl3_record: app_data len %d, ssl state 0x%02X\n",
        record_length, ssl->state);
    direction = ssl_packet_from_server(&ssl->session, ssl_associations, pinfo);

    /* retrieve decoder for this packet direction */
    if (direction != 0) {
        ssl_debug_printf("decrypt_ssl3_record: using server decoder\n");
        decoder = ssl->server;
    }
    else {
        ssl_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*)tvb_get_ptr(tvb, offset + record_length - data_for_iv_len, data_for_iv_len), data_for_iv_len);

    if (!decoder) {
        ssl_debug_printf("decrypt_ssl3_record: no decoder available\n");
        return FALSE;
    }

    /* run decryption and add decrypted payload to protocol data, if decryption
     * is successful*/
    ssl_decrypted_data_avail = ssl_decrypted_data.data_len;
    success = ssl_decrypt_record(ssl, decoder, content_type, record_version,
                           tvb_get_ptr(tvb, offset, record_length), record_length,
                           &ssl_compressed_data, &ssl_decrypted_data, &ssl_decrypted_data_avail) == 0;
    /*  */
    if (!success) {
        /* 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*)tvb_get_ptr(tvb, offset + record_length - data_for_iv_len, data_for_iv_len), data_for_iv_len);
    }
    if (success && ssl_decrypted_data_avail > 0) {
        const guchar *data = ssl_decrypted_data.data;
        guint datalen = ssl_decrypted_data_avail;

        if (ssl->session.version == TLSV1DOT3_VERSION) {
            /*
             * The actual data is followed by the content type and then zero or
             * more padding. Scan backwards for content type, skipping padding.
             */
            while (datalen > 0 && data[datalen - 1] == 0) {
                datalen--;
            }
            ssl_debug_printf("%s found %d padding bytes\n", G_STRFUNC, ssl_decrypted_data_avail - datalen);
            if (datalen == 0) {
                ssl_debug_printf("%s there is no room for content type!\n", G_STRFUNC);
                return FALSE;
            }
            content_type = data[--datalen];
            if (datalen == 0) {
                /* XXX should we remember that the decrypted contents was zero-length? */
                return FALSE;
            }
        }

        /* In TLS 1.3 only Handshake and Application Data can be fragmented.
         * Alert messages MUST NOT be fragmented across records, so do not
         * bother maintaining a flow for those. */
        ssl_add_record_info(proto_ssl, pinfo, data, datalen, tvb_raw_offset(tvb)+offset,
                allow_fragments ? decoder->flow : NULL, (ContentType)content_type, curr_layer_num_ssl);
    }
    return success;
}

static void
process_ssl_payload(tvbuff_t *tvb, int offset, packet_info *pinfo,
                    proto_tree *tree, SslSession *session,
                    dissector_handle_t app_handle_port);

static void
desegment_ssl(tvbuff_t *tvb, packet_info *pinfo, int offset,
              guint32 seq, guint32 nxtseq,
              SslSession *session,
              proto_tree *root_tree, proto_tree *tree,
              SslFlow *flow, dissector_handle_t app_handle_port)
{
    fragment_head *ipfd_head;
    gboolean       must_desegment;
    gboolean       called_dissector;
    int            another_pdu_follows;
    gboolean       another_segment_in_frame = FALSE;
    int            deseg_offset;
    guint32        deseg_seq;
    gint           nbytes;
    proto_item    *item;
    proto_item    *frag_tree_item;
    proto_item    *ssl_tree_item;
    struct tcp_multisegment_pdu *msp;

again:
    ipfd_head = NULL;
    must_desegment = FALSE;
    called_dissector = FALSE;
    another_pdu_follows = 0;
    msp = NULL;

    /*
     * Initialize these to assume no desegmentation.
     * If that's not the case, these will be set appropriately
     * by the subdissector.
     */
    pinfo->desegment_offset = 0;
    pinfo->desegment_len = 0;

    /*
     * Initialize this to assume that this segment will just be
     * added to the middle of a desegmented chunk of data, so
     * that we should show it all as data.
     * If that's not the case, it will be set appropriately.
     */
    deseg_offset = offset;

    /* If we've seen this segment before (e.g., it's a retransmission),
     * there's nothing for us to do.  Certainly, don't add it to the list
     * of multisegment_pdus (that would cause subsequent lookups to find
     * the retransmission instead of the original transmission, breaking
     * dissection of the desegmented pdu if we'd already seen the end of
     * the pdu).
     */
    if ((msp = (struct tcp_multisegment_pdu *)wmem_tree_lookup32(flow->multisegment_pdus, seq))) {
        const char *prefix;

        if (msp->first_frame == pinfo->num) {
            prefix = "";
            col_set_str(pinfo->cinfo, COL_INFO, "[SSL segment of a reassembled PDU]");
        } else {
            prefix = "Retransmitted ";
        }

        nbytes = tvb_reported_length_remaining(tvb, offset);
        ssl_proto_tree_add_segment_data(tree, tvb, offset, nbytes, prefix);
        return;
    }

    /* Else, find the most previous PDU starting before this sequence number */
    msp = (struct tcp_multisegment_pdu *)wmem_tree_lookup32_le(flow->multisegment_pdus, seq-1);
    if (msp && msp->seq <= seq && msp->nxtpdu > seq) {
        int len;

        if (!PINFO_FD_VISITED(pinfo)) {
            msp->last_frame = pinfo->num;
            msp->last_frame_time = pinfo->abs_ts;
        }

        /* OK, this PDU was found, which means the segment continues
         * a higher-level PDU and that we must desegment it.
         */
        if (msp->flags & MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT) {
            /* The dissector asked for the entire segment */
            len = MAX(0, tvb_reported_length_remaining(tvb, offset));
        } else {
            len = MIN(nxtseq, msp->nxtpdu) - seq;
        }

        ipfd_head = fragment_add(&ssl_reassembly_table, tvb, offset,
                                 pinfo, msp->first_frame, NULL,
                                 seq - msp->seq,
                                 len, (LT_SEQ (nxtseq,msp->nxtpdu)));

        if (msp->flags & MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT) {
            msp->flags &= (~MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT);

            /* If we consumed the entire segment there is no
             * other pdu starting anywhere inside this segment.
             * So update nxtpdu to point at least to the start
             * of the next segment.
             * (If the subdissector asks for even more data we
             * will advance nxtpdu even further later down in
             * the code.)
             */
            msp->nxtpdu = nxtseq;
        }

        if ( (msp->nxtpdu < nxtseq)
        &&  (msp->nxtpdu >= seq)
        &&  (len > 0)) {
            another_pdu_follows = msp->nxtpdu - seq;
        }
    } else {
        /* This segment was not found in our table, so it doesn't
         * contain a continuation of a higher-level PDU.
         * Call the normal subdissector.
         */
        process_ssl_payload(tvb, offset, pinfo, tree, session, app_handle_port);
        called_dissector = TRUE;

        /* Did the subdissector ask us to desegment some more data
         * before it could handle the packet?
         * If so we have to create some structures in our table but
         * this is something we only do the first time we see this
         * packet.
         */
        if (pinfo->desegment_len) {
            if (!PINFO_FD_VISITED(pinfo))
                must_desegment = TRUE;

            /*
             * Set "deseg_offset" to the offset in "tvb"
             * of the first byte of data that the
             * subdissector didn't process.
             */
            deseg_offset = offset + pinfo->desegment_offset;
        }

        /* Either no desegmentation is necessary, or this is
         * segment contains the beginning but not the end of
         * a higher-level PDU and thus isn't completely
         * desegmented.
         */
        ipfd_head = NULL;
    }


    /* is it completely desegmented? */
    if (ipfd_head) {
        /*
         * Yes, we think it is.
         * We only call subdissector for the last segment.
         * Note that the last segment may include more than what
         * we needed.
         */
        if (ipfd_head->reassembled_in == pinfo->num &&
            nxtseq < ipfd_head->datalen) {
            /*
             * This is *not* the last segment. It is part of a PDU in the same
             * frame, so no another PDU can follow this one.
             * Do not reassemble SSL yet, it will be done in the final segment.
             * Clear the Info column and avoid displaying [SSL segment of a
             * reassembled PDU], the payload dissector will typically set it.
             * (This is needed here for the second pass.)
             */
            another_pdu_follows = 0;
            col_clear(pinfo->cinfo, COL_INFO);
            another_segment_in_frame = TRUE;
        } else if (ipfd_head->reassembled_in == pinfo->num) {
            /*
             * OK, this is the last segment of the PDU and also the
             * last segment in this frame.
             * Let's call the subdissector with the desegmented
             * data.
             */
            tvbuff_t *next_tvb;
            int old_len;

            /*
             * Reset column in case multiple SSL segments form the
             * PDU and this last SSL segment is not in the first TCP segment of
             * this frame.
             * XXX prevent clearing the column if the last layer is not SSL?
             */
            /* Clear column during the first pass. */
            col_clear(pinfo->cinfo, COL_INFO);

            /* create a new TVB structure for desegmented data */
            next_tvb = tvb_new_chain(tvb, ipfd_head->tvb_data);

            /* add desegmented data to the data source list */
            add_new_data_source(pinfo, next_tvb, "Reassembled SSL");

            /* call subdissector */
            process_ssl_payload(next_tvb, 0, pinfo, tree, session, app_handle_port);
            called_dissector = TRUE;

            /*
             * OK, did the subdissector think it was completely
             * desegmented, or does it think we need even more
             * data?
             */
            old_len = (int)(tvb_reported_length(next_tvb) - tvb_reported_length_remaining(tvb, offset));
            if (pinfo->desegment_len && pinfo->desegment_offset <= old_len) {
                /*
                 * "desegment_len" isn't 0, so it needs more
                 * data for something - and "desegment_offset"
                 * is before "old_len", so it needs more data
                 * to dissect the stuff we thought was
                 * completely desegmented (as opposed to the
                 * stuff at the beginning being completely
                 * desegmented, but the stuff at the end
                 * being a new higher-level PDU that also
                 * needs desegmentation).
                 */
                fragment_set_partial_reassembly(&ssl_reassembly_table,
                                                pinfo, msp->first_frame, NULL);
                /* Update msp->nxtpdu to point to the new next
                 * pdu boundary.
                 */
                if (pinfo->desegment_len == DESEGMENT_ONE_MORE_SEGMENT) {
                    /* We want reassembly of at least one
                     * more segment so set the nxtpdu
                     * boundary to one byte into the next
                     * segment.
                     * This means that the next segment
                     * will complete reassembly even if it
                     * is only one single byte in length.
                     */
                    msp->nxtpdu = seq + tvb_reported_length_remaining(tvb, offset) + 1;
                    msp->flags |= MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT;
                } else {
                    msp->nxtpdu = seq + tvb_reported_length_remaining(tvb, offset) + pinfo->desegment_len;
                }
                /* Since we need at least some more data
                 * there can be no pdu following in the
                 * tail of this segment.
                 */
                another_pdu_follows = 0;
            } else {
                /*
                 * Show the stuff in this TCP segment as
                 * just raw TCP segment data.
                 */
                nbytes = tvb_reported_length_remaining(tvb, offset);
                ssl_proto_tree_add_segment_data(tree, tvb, offset, nbytes, NULL);

                /*
                 * The subdissector thought it was completely
                 * desegmented (although the stuff at the
                 * end may, in turn, require desegmentation),
                 * so we show a tree with all segments.
                 */
                show_fragment_tree(ipfd_head, &ssl_segment_items,
                                   root_tree, pinfo, next_tvb, &frag_tree_item);
                /*
                 * The toplevel fragment subtree is now
                 * behind all desegmented data; move it
                 * right behind the TCP tree.
                 */
                ssl_tree_item = proto_tree_get_parent(tree);
                if (frag_tree_item && ssl_tree_item) {
                    proto_tree_move_item(root_tree, ssl_tree_item, frag_tree_item);
                }

                /* Did the subdissector ask us to desegment
                 * some more data?  This means that the data
                 * at the beginning of this segment completed
                 * a higher-level PDU, but the data at the
                 * end of this segment started a higher-level
                 * PDU but didn't complete it.
                 *
                 * If so, we have to create some structures
                 * in our table, but this is something we
                 * only do the first time we see this packet.
                 */
                if (pinfo->desegment_len) {
                    if (!PINFO_FD_VISITED(pinfo))
                        must_desegment = TRUE;

                    /* The stuff we couldn't dissect
                     * must have come from this segment,
                     * so it's all in "tvb".
                     *
                     * "pinfo->desegment_offset" is
                     * relative to the beginning of
                     * "next_tvb"; we want an offset
                     * relative to the beginning of "tvb".
                     *
                     * First, compute the offset relative
                     * to the *end* of "next_tvb" - i.e.,
                     * the number of bytes before the end
                     * of "next_tvb" at which the
                     * subdissector stopped.  That's the
                     * length of "next_tvb" minus the
                     * offset, relative to the beginning
                     * of "next_tvb, at which the
                     * subdissector stopped.
                     */
                    deseg_offset = ipfd_head->datalen - pinfo->desegment_offset;

                    /* "tvb" and "next_tvb" end at the
                     * same byte of data, so the offset
                     * relative to the end of "next_tvb"
                     * of the byte at which we stopped
                     * is also the offset relative to
                     * the end of "tvb" of the byte at
                     * which we stopped.
                     *
                     * Convert that back into an offset
                     * relative to the beginning of
                     * "tvb", by taking the length of
                     * "tvb" and subtracting the offset
                     * relative to the end.
                     */
                    deseg_offset = tvb_reported_length(tvb) - deseg_offset;
                }
            }
        }
    }

    if (must_desegment) {
        /* If the dissector requested "reassemble until FIN"
         * just set this flag for the flow and let reassembly
         * proceed at normal.  We will check/pick up these
         * reassembled PDUs later down in dissect_tcp() when checking
         * for the FIN flag.
         */
        if (pinfo->desegment_len == DESEGMENT_UNTIL_FIN) {
            flow->flags |= TCP_FLOW_REASSEMBLE_UNTIL_FIN;
        }
        /*
         * The sequence number at which the stuff to be desegmented
         * starts is the sequence number of the byte at an offset
         * of "deseg_offset" into "tvb".
         *
         * The sequence number of the byte at an offset of "offset"
         * is "seq", i.e. the starting sequence number of this
         * segment, so the sequence number of the byte at
         * "deseg_offset" is "seq + (deseg_offset - offset)".
         */
        deseg_seq = seq + (deseg_offset - offset);

        if (((nxtseq - deseg_seq) <= 1024*1024)
            &&  (!PINFO_FD_VISITED(pinfo))) {
            if (pinfo->desegment_len == DESEGMENT_ONE_MORE_SEGMENT) {
                /* The subdissector asked to reassemble using the
                 * entire next segment.
                 * Just ask reassembly for one more byte
                 * but set this msp flag so we can pick it up
                 * above.
                 */
                msp = pdu_store_sequencenumber_of_next_pdu(pinfo,
                    deseg_seq, nxtseq+1, flow->multisegment_pdus);
                msp->flags |= MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT;
            } else {
                msp = pdu_store_sequencenumber_of_next_pdu(pinfo,
                    deseg_seq, nxtseq+pinfo->desegment_len, flow->multisegment_pdus);
            }

            /* add this segment as the first one for this new pdu */
            fragment_add(&ssl_reassembly_table, tvb, deseg_offset,
                         pinfo, msp->first_frame, NULL,
                         0, nxtseq - deseg_seq,
                         LT_SEQ(nxtseq, msp->nxtpdu));
        }
    }

    if (!called_dissector || pinfo->desegment_len != 0) {
        if (ipfd_head != NULL && ipfd_head->reassembled_in != 0 &&
            !(ipfd_head->flags & FD_PARTIAL_REASSEMBLY)) {
            /*
             * We know what frame this PDU is reassembled in;
             * let the user know.
             */
            item=proto_tree_add_uint(tree, *ssl_segment_items.hf_reassembled_in,
                                     tvb, 0, 0, ipfd_head->reassembled_in);
            PROTO_ITEM_SET_GENERATED(item);
        }

        /*
         * Either we didn't call the subdissector at all (i.e.,
         * this is a segment that contains the middle of a
         * higher-level PDU, but contains neither the beginning
         * nor the end), or the subdissector couldn't dissect it
         * all, as some data was missing (i.e., it set
         * "pinfo->desegment_len" to the amount of additional
         * data it needs).
         */
        if (!another_segment_in_frame && pinfo->desegment_offset == 0) {
            /*
             * It couldn't, in fact, dissect any of it (the
             * first byte it couldn't dissect is at an offset
             * of "pinfo->desegment_offset" from the beginning
             * of the payload, and that's 0).
             * Just mark this as SSL.
             */
            col_set_str(pinfo->cinfo, COL_PROTOCOL,
                    val_to_str_const(session->version, ssl_version_short_names, "SSL"));
            col_set_str(pinfo->cinfo, COL_INFO, "[SSL segment of a reassembled PDU]");
        }

        /*
         * Show what's left in the packet as just raw TCP segment
         * data.
         * XXX - remember what protocol the last subdissector
         * was, and report it as a continuation of that, instead?
         */
        nbytes = tvb_reported_length_remaining(tvb, deseg_offset);
        ssl_proto_tree_add_segment_data(tree, tvb, deseg_offset, nbytes, NULL);
    }
    pinfo->can_desegment = 0;
    pinfo->desegment_offset = 0;
    pinfo->desegment_len = 0;

    if (another_pdu_follows) {
        /* there was another pdu following this one. */
        pinfo->can_desegment=2;
        /* we also have to prevent the dissector from changing the
         * PROTOCOL and INFO colums since what follows may be an
         * incomplete PDU and we don't want it be changed back from
         *  <Protocol>   to <TCP>
         */
        col_set_fence(pinfo->cinfo, COL_INFO);
        col_set_writable(pinfo->cinfo, COL_PROTOCOL, FALSE);
        offset += another_pdu_follows;
        seq += another_pdu_follows;
        goto again;
    }
}

static void
export_pdu_packet(tvbuff_t *tvb, packet_info *pinfo, guint8 tag, const gchar *name)
{
    exp_pdu_data_t *exp_pdu_data = export_pdu_create_common_tags(pinfo, name, tag);

    exp_pdu_data->tvb_captured_length = tvb_captured_length(tvb);
    exp_pdu_data->tvb_reported_length = tvb_reported_length(tvb);
    exp_pdu_data->pdu_tvb = tvb;

    tap_queue_packet(exported_pdu_tap, pinfo, exp_pdu_data);
}

static void
process_ssl_payload(tvbuff_t *tvb, int offset, packet_info *pinfo,
                    proto_tree *tree, SslSession *session,
                    dissector_handle_t app_handle_port)
{
    tvbuff_t *next_tvb;
    heur_dtbl_entry_t *hdtbl_entry;
    guint16 saved_match_port;

    next_tvb = tvb_new_subset_remaining(tvb, offset);

    /* If the appdata proto is not yet known (no STARTTLS), try heuristics
     * first, then ports-based dissectors. Port 443 is too overloaded... */
    if (!session->app_handle) {
        /* The heuristics dissector should set the app_handle if it wants to be
         * called in the future. */
        if (dissector_try_heuristic(ssl_heur_subdissector_list, next_tvb,
                                    pinfo, proto_tree_get_root(tree), &hdtbl_entry,
                                    &session->app_handle)) {
            ssl_debug_printf("%s: found heuristics dissector %s, app_handle is %p (%s)\n",
                             G_STRFUNC, hdtbl_entry->short_name,
                             (void *)session->app_handle,
                             dissector_handle_get_dissector_name(session->app_handle));
            if (have_tap_listener(exported_pdu_tap)) {
                export_pdu_packet(next_tvb, pinfo, EXP_PDU_TAG_HEUR_PROTO_NAME, hdtbl_entry->short_name);
            }
            return;
        }
        if (app_handle_port) {
            /* Heuristics failed, just try the port-based dissector. */
            ssl_debug_printf("%s: no heuristics dissector, falling back to "
                             "handle %p (%s)\n", G_STRFUNC,
                             (void *)app_handle_port,
                             dissector_handle_get_dissector_name(app_handle_port));
            session->app_handle = app_handle_port;
        } else {
            /* No heuristics, no port-based proto, unknown protocol. */
            ssl_debug_printf("%s: no appdata dissector found\n", G_STRFUNC);
            return;
        }
    }

    ssl_debug_printf("%s: found handle %p (%s)\n", G_STRFUNC,
                     (void *)session->app_handle,
                     dissector_handle_get_dissector_name(session->app_handle));

    if (have_tap_listener(exported_pdu_tap)) {
        export_pdu_packet(next_tvb, pinfo, EXP_PDU_TAG_PROTO_NAME,
                          dissector_handle_get_dissector_name(session->app_handle));
    }
    saved_match_port = pinfo->match_uint;
    if (ssl_packet_from_server(session, ssl_associations, pinfo)) {
        pinfo->match_uint = pinfo->srcport;
    } else {
        pinfo->match_uint = pinfo->destport;
    }
    call_dissector(session->app_handle, next_tvb, pinfo, proto_tree_get_root(tree));
    pinfo->match_uint = saved_match_port;
}

static void
dissect_ssl_payload(tvbuff_t *decrypted, packet_info *pinfo,
                    proto_tree *tree, SslSession *session,
                    SslRecordInfo *record,
                    dissector_handle_t app_handle_port)
{
    gboolean     save_fragmented;
    guint16      save_can_desegment;

    /* Preserve current desegmentation ability to prevent the subdissector
     * from messing up the ssl desegmentation */
    save_can_desegment = pinfo->can_desegment;

    /* try to dissect decrypted data*/
    ssl_debug_printf("%s decrypted len %d\n", G_STRFUNC, record->data_len);
    ssl_print_data("decrypted app data fragment", record->plain_data, record->data_len);

    /* Can we desegment this segment? */
    if (ssl_desegment_app_data) {
        /* Yes. */
        pinfo->can_desegment = 2;
        desegment_ssl(decrypted, pinfo, 0, record->seq, record->seq + record->data_len,
                      session, proto_tree_get_root(tree), tree,
                      record->flow, app_handle_port);
    } else if (session->app_handle || app_handle_port) {
        /* No - just call the subdissector.
           Mark this as fragmented, so if somebody throws an exception,
           we don't report it as a malformed frame. */
        pinfo->can_desegment = 0;
        save_fragmented = pinfo->fragmented;
        pinfo->fragmented = TRUE;

        process_ssl_payload(decrypted, 0, pinfo, tree, session, app_handle_port);
        pinfo->fragmented = save_fragmented;
    }

    /* restore desegmentation ability */
    pinfo->can_desegment = save_can_desegment;
}


/*********************************************************************
 *
 * SSL version 3 and TLS Dissection Routines
 *
 *********************************************************************/
static gint
dissect_ssl3_record(tvbuff_t *tvb, packet_info *pinfo,
                    proto_tree *tree, guint32 offset,
                    SslSession *session, gint is_from_server,
                    gboolean *need_desegmentation,
                    SslDecryptSession *ssl,
                    guint8 curr_layer_num_ssl)
{

    /*
     *    struct {
     *        uint8 major, minor;
     *    } ProtocolVersion;
     *
     *
     *    enum {
     *        change_cipher_spec(20), alert(21), handshake(22),
     *        application_data(23), (255)
     *    } ContentType;
     *
     *    struct {
     *        ContentType type;
     *        ProtocolVersion version;
     *        uint16 length;
     *        opaque fragment[TLSPlaintext.length];
     *    } TLSPlaintext;
     */
    guint32         record_length;
    guint16         record_version, version;
    guint8          content_type;
    guint8          next_byte;
    proto_tree     *ti;
    proto_tree     *ssl_record_tree;
    proto_item     *length_pi, *ct_pi;
    guint           content_type_offset;
    guint32         available_bytes;
    tvbuff_t       *decrypted;
    SslRecordInfo  *record = NULL;

    ti = NULL;
    ssl_record_tree = NULL;

    available_bytes = tvb_reported_length_remaining(tvb, offset);

    /* TLS 1.0/1.1 just ignores unknown records - RFC 2246 chapter 6. The TLS Record Protocol */
    if ((session->version==TLSV1_VERSION ||
         session->version==TLSV1DOT1_VERSION ||
         session->version==TLSV1DOT2_VERSION) &&
        (available_bytes >=1 ) && !ssl_is_valid_content_type(tvb_get_guint8(tvb, offset))) {
        proto_tree_add_expert(tree, pinfo, &ei_ssl_ignored_unknown_record, tvb, offset, available_bytes);
        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Ignored Unknown Record");
        return offset + available_bytes;
    }

    /*
     * Is the record header split across segment boundaries?
     */
    if (available_bytes < 5) {
        /*
         * Yes - can we do reassembly?
         */
        if (ssl_desegment && pinfo->can_desegment) {
            /*
             * Yes.  Tell the TCP dissector where the data for this
             * message starts in the data it handed us, and that we need
             * "some more data."  Don't tell it exactly how many bytes we
             * need because if/when we ask for even more (after the header)
             * that will break reassembly.
             */
            pinfo->desegment_offset = offset;
            pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT;
            *need_desegmentation = TRUE;
            return offset;
        } else {
            /* Not enough bytes available. Stop here. */
            return offset + available_bytes;
        }
    }

    /*
     * Get the record layer fields of interest
     */
    content_type  = tvb_get_guint8(tvb, offset);
    version       = tvb_get_ntohs(tvb, offset + 1);
    record_version = version;
    record_length = tvb_get_ntohs(tvb, offset + 3);

    if (ssl_is_valid_content_type(content_type)) {

        /*
         * Is the record split across segment boundaries?
         */
        if (available_bytes < record_length + 5) {
            /*
             * Yes - can we do reassembly?
             */
            if (ssl_desegment && pinfo->can_desegment) {
                /*
                 * Yes.  Tell the TCP dissector where the data for this
                 * message starts in the data it handed us, and how many
                 * more bytes we need, and return.
                 */
                pinfo->desegment_offset = offset;

                /* Don't use:
                 * pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT;
                 * it avoids some minor display glitches when a frame contains
                 * the continuation of a previous PDU together with a full new
                 * PDU, but it completely breaks dissection for jumbo SSL frames
                 */

                pinfo->desegment_len = (record_length + 5) - available_bytes;
                *need_desegmentation = TRUE;
                return offset;
            } else {
                /* Not enough bytes available. Stop here. */
                return offset + available_bytes;
            }
        }

    } else {
        /* if we don't have a valid content_type, there's no sense
         * continuing any further
         */
        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Continuation Data");

        return offset + 5 + record_length;
    }

    /* add the record layer subtree header */
    ti = proto_tree_add_item(tree, hf_ssl_record, tvb,
                             offset, 5 + record_length, ENC_NA);
    ssl_record_tree = proto_item_add_subtree(ti, ett_ssl_record);

    /* show the one-byte content type */
    if (session->version == TLSV1DOT3_VERSION && content_type == SSL_ID_APP_DATA) {
        ct_pi = proto_tree_add_item(ssl_record_tree, hf_ssl_record_opaque_type,
                            tvb, offset, 1, ENC_BIG_ENDIAN);
    } else {
        ct_pi = proto_tree_add_item(ssl_record_tree, hf_ssl_record_content_type,
                            tvb, offset, 1, ENC_BIG_ENDIAN);
    }
    content_type_offset = offset;
    offset++;

    /* add the version */
    proto_tree_add_item(ssl_record_tree, hf_ssl_record_version, tvb,
                        offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    /* add the length */
    length_pi = proto_tree_add_uint(ssl_record_tree, hf_ssl_record_length, tvb,
                        offset, 2, record_length);
    offset += 2;    /* move past length field itself */

    /*
     * if we don't already have a version set for this conversation,
     * but this message's version is authoritative (i.e., it's
     * not client_hello, then save the version to to conversation
     * structure and print the column version. If the message is not authorative
     * (i.e. it is a Client Hello), then this version will still be used for
     * display purposes only (it will not be stored in the conversation).
     */
    next_byte = tvb_get_guint8(tvb, offset);
    if (session->version == SSL_VER_UNKNOWN) {
        ssl_try_set_version(session, ssl, content_type, next_byte, FALSE, version);
        /* Version has possibly changed, adjust the column accordingly. */
        col_set_str(pinfo->cinfo, COL_PROTOCOL,
                            val_to_str_const(version, ssl_version_short_names, "SSL"));
    } else {
        version = session->version;
    }

    /*
     * now dissect the next layer
     */
    ssl_debug_printf("dissect_ssl3_record: content_type %d %s\n",content_type, val_to_str_const(content_type, ssl_31_content_type, "unknown"));

    /* try to decrypt record on the first pass, if possible. Store decrypted
     * record for later usage (without having to decrypt again). The offset is
     * used as 'key' to identify this record in the packet (we can have multiple
     * handshake records in the same frame).
     * In TLS 1.3, only "Application Data" records are encrypted.
     */
    if (ssl && (session->version != TLSV1DOT3_VERSION || content_type == SSL_ID_APP_DATA)) {
        decrypt_ssl3_record(tvb, pinfo, offset, ssl,
                content_type, record_version, record_length,
                content_type == SSL_ID_APP_DATA ||
                content_type == SSL_ID_HANDSHAKE, curr_layer_num_ssl);
    }
    /* try to retrieve and use decrypted alert/handshake/appdata record, if any. */
    decrypted = ssl_get_record_info(tvb, proto_ssl, pinfo, tvb_raw_offset(tvb)+offset, curr_layer_num_ssl, &record);
    if (decrypted) {
        add_new_data_source(pinfo, decrypted, "Decrypted SSL");
        if (session->version == TLSV1DOT3_VERSION) {
            content_type = record->type;
            ti = proto_tree_add_uint(ssl_record_tree, hf_ssl_record_content_type,
                                     tvb, content_type_offset, 1, record->type);
            PROTO_ITEM_SET_GENERATED(ti);
        }
    }
    ssl_check_record_length(&dissect_ssl3_hf, pinfo, record_length, length_pi, version, decrypted);

    switch ((ContentType) content_type) {
    case SSL_ID_CHG_CIPHER_SPEC:
        if (version == TLSV1DOT3_VERSION) {
            expert_add_info_format(pinfo, ct_pi, &ei_tls_unexpected_message,
                                   "Record type is not allowed in TLS 1.3");
            break;
        }
        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Change Cipher Spec");
        ssl_dissect_change_cipher_spec(&dissect_ssl3_hf, tvb, pinfo,
                                       ssl_record_tree, offset, session,
                                       is_from_server, ssl);
        if (ssl) {
            ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file,
                             &ssl_master_key_map);
            ssl_finalize_decryption(ssl, &ssl_master_key_map);
            ssl_change_cipher(ssl, ssl_packet_from_server(session, ssl_associations, pinfo));
        }
        /* Heuristic: any later ChangeCipherSpec is not a resumption of this
         * session. Set the flag after ssl_finalize_decryption such that it has
         * a chance to use resume using Session Tickets. */
        if (is_from_server)
          session->is_session_resumed = FALSE;
        break;
    case SSL_ID_ALERT:
        if (decrypted) {
            dissect_ssl3_alert(decrypted, pinfo, ssl_record_tree, 0, session);
        } else {
            dissect_ssl3_alert(tvb, pinfo, ssl_record_tree, offset, session);
        }
        break;
    case SSL_ID_HANDSHAKE:
        if (decrypted) {
            dissect_ssl3_handshake(decrypted, pinfo, ssl_record_tree, 0,
                                   tvb_reported_length(decrypted), FALSE, session,
                                   is_from_server, ssl, content_type, version);
        } else {
            dissect_ssl3_handshake(tvb, pinfo, ssl_record_tree, offset,
                                   record_length, TRUE, session,
                                   is_from_server, ssl, content_type, version);
        }
        break;
    case SSL_ID_APP_DATA:
    {
        dissector_handle_t app_handle;

        /* show on info column what we are decoding */
        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Application Data");

        /* app_handle discovery is done here instead of dissect_ssl_payload()
         * because the protocol name needs to be displayed below. */
        app_handle = session->app_handle;
        if (!app_handle) {
            /* Unknown protocol handle, ssl_starttls_ack was not called before.
             * Try to find a port-based protocol and use it if there is no
             * heuristics dissector (see process_ssl_payload). */
            app_handle = dissector_get_uint_handle(ssl_associations, pinfo->srcport);
            if (!app_handle) app_handle = dissector_get_uint_handle(ssl_associations, pinfo->destport);
        }

        proto_item_set_text(ssl_record_tree,
           "%s Record Layer: %s Protocol: %s",
            val_to_str_const(version, ssl_version_short_names, "SSL"),
            val_to_str_const(content_type, ssl_31_content_type, "unknown"),
            app_handle ? dissector_handle_get_dissector_name(app_handle)
            : "Application Data");

        proto_tree_add_item(ssl_record_tree, hf_ssl_record_appdata, tvb,
                       offset, record_length, ENC_NA);

        if (decrypted) {
            dissect_ssl_payload(decrypted, pinfo, tree, session, record, app_handle);
        }

        /* Set app proto again in case the heuristics found a different proto. */
        if (session->app_handle && session->app_handle != app_handle)
            proto_item_set_text(ssl_record_tree,
               "%s Record Layer: %s Protocol: %s",
                val_to_str_const(version, ssl_version_short_names, "SSL"),
                val_to_str_const(content_type, ssl_31_content_type, "unknown"),
                dissector_handle_get_dissector_name(session->app_handle));

        break;
    }
    case SSL_ID_HEARTBEAT:
        if (version == TLSV1DOT3_VERSION) {
            expert_add_info_format(pinfo, ct_pi, &ei_tls_unexpected_message,
                                   "Record type is not allowed in TLS 1.3");
            break;
        }
        if (decrypted) {
            dissect_ssl3_heartbeat(decrypted, pinfo, ssl_record_tree, 0, session, tvb_reported_length (decrypted), TRUE);
        } else {
            gboolean plaintext = TRUE;
            /* heartbeats before ChangeCipherSpec are unencrypted */
            if (ssl) {
                if (ssl_packet_from_server(session, ssl_associations, pinfo)) {
                    plaintext = ssl->server == NULL;
                } else {
                    plaintext = ssl->client == NULL;
                }
            }
            dissect_ssl3_heartbeat(tvb, pinfo, ssl_record_tree, offset, session, record_length, plaintext);
        }
        break;
    }
    offset += record_length; /* skip to end of record */

    return offset;
}

/* dissects the alert message, filling in the tree */
static void
dissect_ssl3_alert(tvbuff_t *tvb, packet_info *pinfo,
                   proto_tree *tree, guint32 offset,
                   const SslSession *session)
{
    /*     struct {
     *         AlertLevel level;
     *         AlertDescription description;
     *     } Alert;
     */
    proto_tree  *ti;
    proto_tree  *ssl_alert_tree;
    const gchar *level;
    const gchar *desc;
    guint8       level_byte, desc_byte;

    ssl_alert_tree = NULL;
    if (tree)
    {
        ti = proto_tree_add_item(tree, hf_ssl_alert_message, tvb,
                                 offset, 2, ENC_NA);
        ssl_alert_tree = proto_item_add_subtree(ti, ett_ssl_alert);
    }

    /*
     * set the record layer label
     */

    /* first lookup the names for the alert level and description */
    level_byte = tvb_get_guint8(tvb, offset); /* grab the level byte */
    level = try_val_to_str(level_byte, ssl_31_alert_level);

    desc_byte = tvb_get_guint8(tvb, offset+1); /* grab the desc byte */
    desc = try_val_to_str(desc_byte, ssl_31_alert_description);

    /* now set the text in the record layer line */
    if (level && desc)
    {
        col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL,
                            "Alert (Level: %s, Description: %s)",
                            level, desc);
    }
    else
    {
        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Encrypted Alert");
    }

    if (tree)
    {
        if (level && desc)
        {
            proto_item_set_text(tree, "%s Record Layer: Alert "
                                "(Level: %s, Description: %s)",
                                val_to_str_const(session->version, ssl_version_short_names, "SSL"),
                                level, desc);
            proto_tree_add_item(ssl_alert_tree, hf_ssl_alert_message_level,
                                tvb, offset++, 1, ENC_BIG_ENDIAN);

            proto_tree_add_item(ssl_alert_tree, hf_ssl_alert_message_description,
                                tvb, offset++, 1, ENC_BIG_ENDIAN);
        }
        else
        {
            proto_item_set_text(tree,
                                "%s Record Layer: Encrypted Alert",
                                val_to_str_const(session->version, ssl_version_short_names, "SSL"));
            proto_item_set_text(ssl_alert_tree,
                                "Alert Message: Encrypted Alert");
        }
    }
}


/* dissects the handshake protocol, filling the tree */
static void
dissect_ssl3_handshake(tvbuff_t *tvb, packet_info *pinfo,
                       proto_tree *tree, guint32 offset,
                       guint32 record_length, gboolean maybe_encrypted,
                       SslSession *session, gint is_from_server,
                       SslDecryptSession *ssl, const guint8 content_type,
                       const guint16 version)
{
    /*     struct {
     *         HandshakeType msg_type;
     *         uint24 length;
     *         select (HandshakeType) {
     *             case hello_request:       HelloRequest;
     *             case client_hello:        ClientHello;
     *             case server_hello:        ServerHello;
     *             case certificate:         Certificate;
     *             case server_key_exchange: ServerKeyExchange;
     *             case certificate_request: CertificateRequest;
     *             case server_hello_done:   ServerHelloDone;
     *             case certificate_verify:  CertificateVerify;
     *             case client_key_exchange: ClientKeyExchange;
     *             case finished:            Finished;
     *             case certificate_url:     CertificateURL;
     *             case certificate_status:  CertificateStatus;
     *             case encrypted_extensions:NextProtocolNegotiationEncryptedExtension;
     *         } body;
     *     } Handshake;
     */
    proto_tree  *ssl_hand_tree = NULL;
    const gchar *msg_type_str;
    guint8       msg_type;
    guint32      length;
    gboolean     first_iteration = TRUE;
    proto_item  *ti;

    /*
     * If this is not a decrypted buffer, then perhaps it is still in plaintext.
     * Heuristics: if the buffer is too small, it is likely not encrypted.
     * Otherwise assume that the Handshake does not contain two successive
     * HelloRequest messages (type=0x00 length=0x000000, type=0x00). If this
     * occurs, then we have possibly found the explicit nonce preceding the
     * encrypted contents for GCM/CCM cipher suites as used in TLS 1.2.
     */
    if (maybe_encrypted) {
        maybe_encrypted = tvb_bytes_exist(tvb, offset, 5) && tvb_get_ntoh40(tvb, offset) == 0;
        /*
         * Everything after the ChangeCipherSpec message is encrypted.
         * TODO handle Finished message after CCS in the same frame and remove the
         * above nonce-based heuristic.
         */
        if (!maybe_encrypted) {
            guint32 ccs_frame = is_from_server ? session->server_ccs_frame : session->client_ccs_frame;
            maybe_encrypted = ccs_frame != 0 && pinfo->num > ccs_frame;
        }
    }

    /* just as there can be multiple records per packet, there
     * can be multiple messages per record as long as they have
     * the same content type
     *
     * we really only care about this for handshake messages
     */

    /* set record_length to the max offset */
    record_length += offset;
    while (offset < record_length)
    {
        guint32 hs_offset = offset;

        msg_type = tvb_get_guint8(tvb, offset);
        length   = tvb_get_ntoh24(tvb, offset + 1);

        /* Check the length in the handshake message. Assume it's an
         * encrypted handshake message if the message would pass
         * the record_length boundary. This is a workaround for the
         * situation where the first octet of the encrypted handshake
         * message is actually a known handshake message type.
         */
        if (!maybe_encrypted && offset + length <= record_length)
            msg_type_str = try_val_to_str(msg_type, ssl_31_handshake_type);
        else
            msg_type_str = NULL;

        ssl_debug_printf("dissect_ssl3_handshake iteration %d type %d offset %d length %d "
            "bytes, remaining %d \n", first_iteration, msg_type, offset, length, record_length);
        if (!msg_type_str && !first_iteration)
        {
            /* only dissect / report messages if they're
             * either the first message in this record
             * or they're a valid message type
             */
            return;
        }

        /*
         * Update our info string
         */
        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL,
                            (msg_type_str != NULL) ? msg_type_str : "Encrypted Handshake Message");

        /* set the label text on the record layer expanding node */
        if (first_iteration)
        {
            proto_item_set_text(tree, "%s Record Layer: %s Protocol: %s",
                    val_to_str_const(version, ssl_version_short_names, "SSL"),
                    val_to_str_const(content_type, ssl_31_content_type, "unknown"),
                    (msg_type_str!=NULL) ? msg_type_str :
                    "Encrypted Handshake Message");
        }
        else
        {
            proto_item_set_text(tree, "%s Record Layer: %s Protocol: %s",
                    val_to_str_const(version, ssl_version_short_names, "SSL"),
                    val_to_str_const(content_type, ssl_31_content_type, "unknown"),
                    "Multiple Handshake Messages");
        }

        /* add a subtree for the handshake protocol */
        ti = proto_tree_add_item(tree, hf_ssl_handshake_protocol, tvb,
                offset, length + 4, ENC_NA);
        ssl_hand_tree = proto_item_add_subtree(ti, ett_ssl_handshake);

        /* set the text label on the subtree node */
        proto_item_set_text(ssl_hand_tree, "Handshake Protocol: %s",
                (msg_type_str != NULL) ? msg_type_str :
                "Encrypted Handshake Message");

        /* if we don't have a valid handshake type, just quit dissecting */
        if (!msg_type_str)
            return;

        /* add nodes for the message type and message length */
        proto_tree_add_uint(ssl_hand_tree, hf_ssl_handshake_type,
                tvb, offset, 1, msg_type);
        offset += 1;
        proto_tree_add_uint(ssl_hand_tree, hf_ssl_handshake_length,
                tvb, offset, 3, length);
        offset += 3;

        /*
         * Add handshake message (including type, length, etc.) to hash (for
         * Extended Master Secret).
         * Hash ClientHello up to and including ClientKeyExchange. As the
         * premaster secret is looked up during ChangeCipherSpec processing (an
         * implementation detail), we must skip the CertificateVerify message
         * which can appear between CKE and CCS when mutual auth is enabled.
         */
        if (msg_type != SSL_HND_CERT_VERIFY) {
            ssl_calculate_handshake_hash(ssl, tvb, hs_offset, 4 + length);
        }

        /* now dissect the handshake message, if necessary */
        switch ((HandshakeType) msg_type) {
            case SSL_HND_HELLO_REQUEST:
                /* hello_request has no fields, so nothing to do! */
                break;

            case SSL_HND_CLIENT_HELLO:
                if (ssl) {
                    /* ClientHello is first packet so set direction */
                    ssl_set_server(session, &pinfo->dst, pinfo->ptype, pinfo->destport);
                }
                ssl_dissect_hnd_cli_hello(&dissect_ssl3_hf, tvb, pinfo,
                        ssl_hand_tree, offset, offset + length, session, ssl,
                        NULL);
                /*
                 * Cannot call tls13_change_key here with TLS_SECRET_HANDSHAKE
                 * since the server may not agree on using TLS 1.3. If
                 * early_data is advertised, it must be TLS 1.3 though.
                 */
                if (ssl && ssl->has_early_data) {
                    session->version = TLSV1DOT3_VERSION;
                    ssl->state |= SSL_VERSION;
                    ssl_debug_printf("%s forcing version 0x%04X -> state 0x%02X\n", G_STRFUNC, version, ssl->state);
                    ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
                    tls13_change_key(ssl, &ssl_master_key_map, FALSE, TLS_SECRET_0RTT_APP);
                }
                break;

            case SSL_HND_SERVER_HELLO:
                ssl_dissect_hnd_srv_hello(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree,
                        offset, offset + length, session, ssl, FALSE);
                if (ssl) {
                    ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
                    /* Create client and server decoders for TLS 1.3. */
                    if (!ssl->has_early_data) {
                        tls13_change_key(ssl, &ssl_master_key_map, FALSE, TLS_SECRET_HANDSHAKE);
                    }
                    tls13_change_key(ssl, &ssl_master_key_map, TRUE, TLS_SECRET_HANDSHAKE);
                }
                break;

            case SSL_HND_HELLO_VERIFY_REQUEST:
                /* only valid for DTLS */
                break;

            case SSL_HND_NEWSESSION_TICKET:
                /* no need to load keylog file here as it only links a previous
                 * master key with this Session Ticket */
                ssl_dissect_hnd_new_ses_ticket(&dissect_ssl3_hf, tvb, pinfo,
                        ssl_hand_tree, offset, offset + length, session, ssl, FALSE,
                        ssl_master_key_map.tickets);
                break;

            case SSL_HND_END_OF_EARLY_DATA:
                /* https://tools.ietf.org/html/draft-ietf-tls-tls13-19#section-4.5 */
                if (!is_from_server && ssl) {
                    ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
                    tls13_change_key(ssl, &ssl_master_key_map, FALSE, TLS_SECRET_HANDSHAKE);
                    ssl->has_early_data = FALSE;
                }
                break;

            case SSL_HND_HELLO_RETRY_REQUEST:
                ssl_dissect_hnd_hello_retry_request(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree,
                                                    offset, offset + length, session, ssl, FALSE);
                break;

            case SSL_HND_ENCRYPTED_EXTENSIONS:
                /* XXX expert info if used with non-TLS 1.3? */
                ssl_dissect_hnd_encrypted_extensions(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree,
                                                     offset, offset + length, session, ssl, FALSE);

                break;

            case SSL_HND_CERTIFICATE:
                ssl_dissect_hnd_cert(&dissect_ssl3_hf, tvb, ssl_hand_tree,
                        offset, offset + length, pinfo, session, ssl, ssl_key_hash, is_from_server, FALSE);
                break;

            case SSL_HND_SERVER_KEY_EXCHG:
                ssl_dissect_hnd_srv_keyex(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree, offset, offset + length, session);
                break;

            case SSL_HND_CERT_REQUEST:
                ssl_dissect_hnd_cert_req(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree, offset, offset + length, session, FALSE);
                break;

            case SSL_HND_SVR_HELLO_DONE:
                /* This is not an abbreviated handshake, it is certainly not resumed. */
                session->is_session_resumed = FALSE;
                break;

            case SSL_HND_CERT_VERIFY:
                ssl_dissect_hnd_cli_cert_verify(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree, offset, offset + length, session->version);
                break;

            case SSL_HND_CLIENT_KEY_EXCHG:
                ssl_dissect_hnd_cli_keyex(&dissect_ssl3_hf, tvb, ssl_hand_tree, offset, length, session);

                if (!ssl)
                    break;

                ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file,
                        &ssl_master_key_map);
                /* try to find master key from pre-master key */
                if (!ssl_generate_pre_master_secret(ssl, length, tvb, offset,
                            ssl_options.psk,
                            &ssl_master_key_map)) {
                    ssl_debug_printf("dissect_ssl3_handshake can't generate pre master secret\n");
                }
                break;

            case SSL_HND_FINISHED:
                ssl_dissect_hnd_finished(&dissect_ssl3_hf, tvb, ssl_hand_tree,
                        offset, offset + length, session, &ssl_hfs);
                if (ssl) {
                    ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
                    tls13_change_key(ssl, &ssl_master_key_map, is_from_server, TLS_SECRET_APP);
                }
                break;

            case SSL_HND_CERT_URL:
                ssl_dissect_hnd_cert_url(&dissect_ssl3_hf, tvb, ssl_hand_tree, offset);
                break;

            case SSL_HND_CERT_STATUS:
                tls_dissect_hnd_certificate_status(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree, offset, offset + length);
                break;

            case SSL_HND_SUPPLEMENTAL_DATA:
                /* TODO: dissect this? */
                break;

            case SSL_HND_KEY_UPDATE:
                tls13_dissect_hnd_key_update(&dissect_ssl3_hf, tvb, tree, offset);
                if (ssl) {
                    tls13_key_update(ssl, is_from_server);
                }
                break;

            case SSL_HND_ENCRYPTED_EXTS:
                dissect_ssl3_hnd_encrypted_exts(tvb, ssl_hand_tree, offset);
                break;
        }

        offset += length;
        first_iteration = FALSE; /* set up for next pass, if any */
    }
}

/* dissects the heartbeat message, filling in the tree */
static void
dissect_ssl3_heartbeat(tvbuff_t *tvb, packet_info *pinfo,
                       proto_tree *tree, guint32 offset,
                       const SslSession *session, guint32 record_length,
                       gboolean decrypted)
{
    /*     struct {
     *         HeartbeatMessageType type;
     *         uint16 payload_length;
     *         opaque payload;
     *         opaque padding;
     *     } HeartbeatMessage;
     */

    proto_item  *ti;
    proto_tree  *tls_heartbeat_tree;
    const gchar *type;
    guint8       byte;
    guint16      payload_length;
    guint16      padding_length;

    tls_heartbeat_tree = NULL;

    if (tree) {
        ti = proto_tree_add_item(tree, hf_ssl_heartbeat_message, tvb,
                                 offset, record_length, ENC_NA);
        tls_heartbeat_tree = proto_item_add_subtree(ti, ett_ssl_heartbeat);
    }

    /*
     * set the record layer label
     */

    /* first lookup the names for the message type and the payload length */
    byte = tvb_get_guint8(tvb, offset);
    type = try_val_to_str(byte, tls_heartbeat_type);

    payload_length = tvb_get_ntohs(tvb, offset + 1);
    padding_length = record_length - 3 - payload_length;

    /* assume plaintext if the (expected) record size is smaller than the type
     * (1), length (2)[, payload] and padding (16) fields combined */
    if (record_length <= 19u || 3u + payload_length + 16 <= record_length) {
        decrypted = TRUE;
    }

    /* now set the text in the record layer line */
    if (type && decrypted) {
        col_append_fstr(pinfo->cinfo, COL_INFO, "Heartbeat %s", type);
    } else {
        col_append_str(pinfo->cinfo, COL_INFO, "Encrypted Heartbeat");
    }

    if (type && decrypted) {
        proto_item_set_text(tree, "%s Record Layer: Heartbeat "
                            "%s",
                            val_to_str_const(session->version, ssl_version_short_names, "SSL"),
                            type);
        proto_tree_add_item(tls_heartbeat_tree, hf_ssl_heartbeat_message_type,
                            tvb, offset, 1, ENC_BIG_ENDIAN);
        offset += 1;
        ti = proto_tree_add_uint(tls_heartbeat_tree, hf_ssl_heartbeat_message_payload_length,
                                 tvb, offset, 2, payload_length);
        offset += 2;
        if (3u + payload_length + 16 > record_length) {
            expert_add_info_format(pinfo, ti, &ei_ssl3_heartbeat_payload_length,
                                   "Invalid heartbeat payload length (%d)", payload_length);
            /* There is no room for padding... truncate the payload such that
             * the field can be selected (for the interested). */
            payload_length = record_length - 3;
            padding_length = 0;
            proto_item_append_text (ti, " (invalid, using %u to decode payload)", payload_length);
        }
        proto_tree_add_bytes_format(tls_heartbeat_tree, hf_ssl_heartbeat_message_payload,
                                    tvb, offset, payload_length,
                                    NULL, "Payload (%u byte%s)",
                                    payload_length,
                                    plurality(payload_length, "", "s"));
        offset += payload_length;
        if (padding_length)
            proto_tree_add_bytes_format(tls_heartbeat_tree, hf_ssl_heartbeat_message_padding,
                                        tvb, offset, padding_length,
                                        NULL, "Padding and HMAC (%u byte%s)",
                                        padding_length,
                                        plurality(padding_length, "", "s"));
    } else {
        proto_item_set_text(tree,
                            "%s Record Layer: Encrypted Heartbeat",
                            val_to_str_const(session->version, ssl_version_short_names, "SSL"));
        proto_item_set_text(tls_heartbeat_tree,
                            "Encrypted Heartbeat Message");
    }
}

/* based on https://tools.ietf.org/html/draft-agl-tls-nextprotoneg-04 */
static void
dissect_ssl3_hnd_encrypted_exts(tvbuff_t *tvb, proto_tree *tree,
                                guint32 offset)
{
    guint8       selected_protocol_len;
    guint8       padding_len;

    selected_protocol_len = tvb_get_guint8(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_handshake_npn_selected_protocol_len,
        tvb, offset, 1, ENC_BIG_ENDIAN);
    offset++;
    proto_tree_add_item(tree, hf_ssl_handshake_npn_selected_protocol,
        tvb, offset, selected_protocol_len, ENC_ASCII|ENC_NA);
    offset += selected_protocol_len;

    padding_len = tvb_get_guint8(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_handshake_npn_padding_len,
        tvb, offset, 1, ENC_BIG_ENDIAN);
    offset++;
    proto_tree_add_item(tree, hf_ssl_handshake_npn_padding,
        tvb, offset, padding_len, ENC_NA);
}

/*********************************************************************
 *
 * SSL version 2 Dissectors
 *
 *********************************************************************/


/* record layer dissector */
static gint
dissect_ssl2_record(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
                    guint32 offset, SslSession *session,
                    gboolean *need_desegmentation,
                    SslDecryptSession *ssl)
{
    guint32      initial_offset;
    guint8       byte;
    guint8       record_length_length;
    guint32      record_length;
    gint         is_escape;
    gint16       padding_length;
    guint8       msg_type;
    const gchar *msg_type_str;
    guint32      available_bytes;
    proto_item  *ti;
    proto_tree  *ssl_record_tree;

    initial_offset  = offset;
    record_length   = 0;
    is_escape       = -1;
    padding_length  = -1;
    msg_type_str    = NULL;
    ssl_record_tree = NULL;

    /* pull first byte; if high bit is unset, then record
     * length is three bytes due to padding; otherwise
     * record length is two bytes
     */
    byte = tvb_get_guint8(tvb, offset);
    record_length_length = (byte & 0x80) ? 2 : 3;

    available_bytes = tvb_reported_length_remaining(tvb, offset);

    /*
     * Is the record header split across segment boundaries?
     */
    if (available_bytes < record_length_length) {
        /*
         * Yes - can we do reassembly?
         */
        if (ssl_desegment && pinfo->can_desegment) {
            /*
             * Yes.  Tell the TCP dissector where the data for this
             * message starts in the data it handed us, and that we need
             * "some more data."  Don't tell it exactly how many bytes we
             * need because if/when we ask for even more (after the header)
             * that will break reassembly.
             */
            pinfo->desegment_offset = offset;
            pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT;
            *need_desegmentation = TRUE;
            return offset;
        } else {
            /* Not enough bytes available. Stop here. */
            return offset + available_bytes;
        }
    }

    /* parse out the record length */
    switch (record_length_length) {
    case 2:                     /* two-byte record length */
        record_length = (byte & 0x7f) << 8;
        byte = tvb_get_guint8(tvb, offset + 1);
        record_length += byte;
        break;
    case 3:                     /* three-byte record length */
        is_escape = (byte & 0x40) ? TRUE : FALSE;
        record_length = (byte & 0x3f) << 8;
        byte = tvb_get_guint8(tvb, offset + 1);
        record_length += byte;
        byte = tvb_get_guint8(tvb, offset + 2);
        padding_length = byte;
    }

    /*
     * Is the record split across segment boundaries?
     */
    if (available_bytes < (record_length_length + record_length)) {
        /*
         * Yes - Can we do reassembly?
         */
        if (ssl_desegment && pinfo->can_desegment) {
            /*
             * Yes.  Tell the TCP dissector where the data for this
             * message starts in the data it handed us, and how many
             * more bytes we need, and return.
             */
            pinfo->desegment_offset = offset;
            pinfo->desegment_len = (record_length_length + record_length)
                                   - available_bytes;
            *need_desegmentation = TRUE;
            return offset;
        } else {
            /* Not enough bytes available. Stop here. */
            return offset + available_bytes;
        }
    }
    offset += record_length_length;

    /* add the record layer subtree header */
    ti = proto_tree_add_item(tree, hf_ssl2_record, tvb, initial_offset,
                             record_length_length + record_length, ENC_NA);
    ssl_record_tree = proto_item_add_subtree(ti, ett_ssl_record);

    /* pull the msg_type so we can bail if it's unknown */
    msg_type = tvb_get_guint8(tvb, initial_offset + record_length_length);

    /* if we get a server_hello or later handshake in v2, then set
     * this to sslv2
     */
    if (session->version == SSL_VER_UNKNOWN)
    {
        if (ssl_looks_like_valid_pct_handshake(tvb,
                                               (initial_offset +
                                                record_length_length),
                                               record_length)) {
            session->version = PCT_VERSION;
        }
        else if (msg_type >= 2 && msg_type <= 8)
        {
            session->version = SSLV2_VERSION;
        }
    }

    /* if we get here, but don't have a version set for the
     * conversation, then set a version for just this frame
     * (e.g., on a client hello)
     */
    col_set_str(pinfo->cinfo, COL_PROTOCOL,
                    (session->version == PCT_VERSION) ? "PCT" : "SSLv2");

    /* see if the msg_type is valid; if not the payload is
     * probably encrypted, so note that fact and bail
     */
    msg_type_str = try_val_to_str(msg_type,
                                (session->version == PCT_VERSION)
                                ? pct_msg_types : ssl_20_msg_types);
    if (!msg_type_str
        || ((session->version != PCT_VERSION) &&
            !ssl_looks_like_valid_v2_handshake(tvb, initial_offset
                               + record_length_length,
                               record_length))
        || ((session->version == PCT_VERSION) &&
            !ssl_looks_like_valid_pct_handshake(tvb, initial_offset
                               + record_length_length,
                               record_length)))
    {
        if (ssl_record_tree)
        {
            proto_item_set_text(ssl_record_tree, "%s Record Layer: %s",
                                (session->version == PCT_VERSION)
                                ? "PCT" : "SSLv2",
                                "Encrypted Data");

            /* Unlike SSLv3, the SSLv2 record layer does not have a
             * version field. To make it possible to filter on record
             * layer version we create a generated field with ssl
             * record layer version 0x0002
             */
            ti = proto_tree_add_uint(ssl_record_tree,
                    hf_ssl_record_version, tvb,
                    initial_offset, 0, 0x0002);
            PROTO_ITEM_SET_GENERATED(ti);
        }

        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Encrypted Data");
        return initial_offset + record_length_length + record_length;
    }
    else
    {
        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, msg_type_str);

        if (ssl_record_tree)
        {
            proto_item_set_text(ssl_record_tree, "%s Record Layer: %s",
                                (session->version == PCT_VERSION)
                                ? "PCT" : "SSLv2",
                                msg_type_str);
        }
    }

    /* We have a valid message type, so move forward, filling in the
     * tree by adding the length, is_escape boolean and padding_length,
     * if present in the original packet
     */
    if (ssl_record_tree)
    {
        /* Unlike SSLv3, the SSLv2 record layer does not have a
         * version field. To make it possible to filter on record
         * layer version we create a generated field with ssl
         * record layer version 0x0002
         */
        ti = proto_tree_add_uint(ssl_record_tree,
                                 hf_ssl_record_version, tvb,
                                 initial_offset, 0, 0x0002);
        PROTO_ITEM_SET_GENERATED(ti);

        /* add the record length */
        tvb_ensure_bytes_exist(tvb, offset, record_length_length);
        proto_tree_add_uint (ssl_record_tree,
                             hf_ssl_record_length, tvb,
                             initial_offset, record_length_length,
                             record_length);
    }
    if (ssl_record_tree && is_escape != -1)
    {
        proto_tree_add_boolean(ssl_record_tree,
                               hf_ssl2_record_is_escape, tvb,
                               initial_offset, 1, is_escape);
    }
    if (ssl_record_tree && padding_length != -1)
    {
        proto_tree_add_uint(ssl_record_tree,
                            hf_ssl2_record_padding_length, tvb,
                            initial_offset + 2, 1, padding_length);
    }

    /*
     * dissect the record data
     */

    /* jump forward to the start of the record data */
    offset = initial_offset + record_length_length;

    /* add the message type */
    if (ssl_record_tree)
    {
        proto_tree_add_item(ssl_record_tree,
                            (session->version == PCT_VERSION)
                            ? hf_pct_msg_type : hf_ssl2_msg_type,
                            tvb, offset, 1, ENC_BIG_ENDIAN);
    }
    offset += 1;                   /* move past msg_type byte */

    if (session->version != PCT_VERSION)
    {
        /* dissect the message (only handle client hello right now) */
        switch (msg_type) {
        case SSL2_HND_CLIENT_HELLO:
            dissect_ssl2_hnd_client_hello(tvb, pinfo, ssl_record_tree, offset, ssl);
            break;

        case SSL2_HND_CLIENT_MASTER_KEY:
            dissect_ssl2_hnd_client_master_key(tvb, ssl_record_tree, offset);
            break;

        case SSL2_HND_SERVER_HELLO:
            dissect_ssl2_hnd_server_hello(tvb, ssl_record_tree, offset, pinfo);
            break;

        case SSL2_HND_ERROR:
        case SSL2_HND_CLIENT_FINISHED:
        case SSL2_HND_SERVER_VERIFY:
        case SSL2_HND_SERVER_FINISHED:
        case SSL2_HND_REQUEST_CERTIFICATE:
        case SSL2_HND_CLIENT_CERTIFICATE:
            /* unimplemented */
            break;

        default:                    /* unknown */
            break;
        }
    }
    else
    {
        /* dissect the message */
        switch (msg_type) {
        case PCT_MSG_CLIENT_HELLO:
            dissect_pct_msg_client_hello(tvb, pinfo, ssl_record_tree, offset);
            break;
        case PCT_MSG_SERVER_HELLO:
            dissect_pct_msg_server_hello(tvb, ssl_record_tree, offset, pinfo);
            break;
        case PCT_MSG_CLIENT_MASTER_KEY:
            dissect_pct_msg_client_master_key(tvb, ssl_record_tree, offset);
            break;
        case PCT_MSG_SERVER_VERIFY:
            dissect_pct_msg_server_verify(tvb, ssl_record_tree, offset);
            break;
        case PCT_MSG_ERROR:
            dissect_pct_msg_error(tvb, ssl_record_tree, offset);
            break;

        default:                    /* unknown */
            break;
        }
    }
    return (initial_offset + record_length_length + record_length);
}

static void
dissect_ssl2_hnd_client_hello(tvbuff_t *tvb, packet_info *pinfo,
                              proto_tree *tree, guint32 offset,
                              SslDecryptSession *ssl)
{
    /* struct {
     *    uint8 msg_type;
     *     Version version;
     *     uint16 cipher_spec_length;
     *     uint16 session_id_length;
     *     uint16 challenge_length;
     *     V2CipherSpec cipher_specs[V2ClientHello.cipher_spec_length];
     *     opaque session_id[V2ClientHello.session_id_length];
     *     Random challenge;
     * } V2ClientHello;
     *
     * Note: when we get here, offset's already pointing at Version
     *
     */
    guint16 version;
    guint16 cipher_spec_length;
    guint16 session_id_length;
    guint16 challenge_length;

    proto_item *ti;
    proto_tree *cs_tree;
    cs_tree=0;

    version = tvb_get_ntohs(tvb, offset);
    if (!ssl_is_valid_ssl_version(version))
    {
        /* invalid version; probably encrypted data */
        return;
    }

    if (ssl) {
      ssl_set_server(&ssl->session, &pinfo->dst, pinfo->ptype, pinfo->destport);
    }

    /* show the version */
    proto_tree_add_item(tree, dissect_ssl3_hf.hf.hs_client_version, tvb,
                        offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    cipher_spec_length = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl2_handshake_cipher_spec_len,
                        tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    session_id_length = tvb_get_ntohs(tvb, offset);
    ti = proto_tree_add_item(tree, hf_ssl2_handshake_session_id_len,
                        tvb, offset, 2, ENC_BIG_ENDIAN);
    if (session_id_length > SSLV2_MAX_SESSION_ID_LENGTH_IN_BYTES) {
        expert_add_info_format(pinfo, ti, &ei_ssl2_handshake_session_id_len_error,
                               "Session ID length (%u) must be less than %u.",
                               session_id_length, SSLV2_MAX_SESSION_ID_LENGTH_IN_BYTES);
        return;
    }
    offset += 2;

    challenge_length = tvb_get_ntohs(tvb, offset);
    if (tree)
        proto_tree_add_item(tree, hf_ssl2_handshake_challenge_len,
                        tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    if (tree)
    {
        /* tell the user how many cipher specs they've won */
        ti = proto_tree_add_none_format(tree, dissect_ssl3_hf.hf.hs_cipher_suites,
                                        tvb, offset, cipher_spec_length,
                                        "Cipher Specs (%u specs)",
                                        cipher_spec_length/3);

        /* make this a subtree and expand the actual specs below */
        cs_tree = proto_item_add_subtree(ti, dissect_ssl3_hf.ett.cipher_suites);
        if (!cs_tree)
        {
            cs_tree = tree;     /* failsafe */
        }
    }

    /* iterate through the cipher specs, showing them */
    while (cipher_spec_length > 0)
    {
        if (cs_tree)
            proto_tree_add_item(cs_tree, hf_ssl2_handshake_cipher_spec,
                            tvb, offset, 3, ENC_BIG_ENDIAN);
        offset += 3;        /* length of one cipher spec */
        cipher_spec_length -= 3;
    }

    /* if there's a session id, show it */
    if (session_id_length > 0)
    {
        proto_tree_add_bytes_format(tree,
                                        dissect_ssl3_hf.hf.hs_session_id,
                                        tvb, offset, session_id_length,
                                        NULL, "Session ID (%u byte%s)",
                                        session_id_length,
                                        plurality(session_id_length, "", "s"));

        /* PAOLO: get session id and reset session state for key [re]negotiation */
        if (ssl)
        {
            tvb_memcpy(tvb,ssl->session_id.data, offset, session_id_length);
            ssl->session_id.data_len = session_id_length;
            ssl->state &= ~(SSL_HAVE_SESSION_KEY|SSL_MASTER_SECRET|SSL_PRE_MASTER_SECRET|
                    SSL_CIPHER|SSL_SERVER_RANDOM);
        }
        offset += session_id_length;
    }

    /* if there's a challenge, show it */
    if (challenge_length > 0)
    {
        proto_tree_add_item(tree, hf_ssl2_handshake_challenge,
                            tvb, offset, challenge_length, ENC_NA);
        if (ssl)
        {
            /* PAOLO: get client random data; we get at most 32 bytes from
             challenge */
            gint max;
            max = challenge_length > 32? 32: challenge_length;

            ssl_debug_printf("client random len: %d padded to 32\n", challenge_length);

            /* client random is padded with zero and 'right' aligned */
            memset(ssl->client_random.data, 0, 32 - max);
            tvb_memcpy(tvb, &ssl->client_random.data[32 - max], offset, max);
            ssl->client_random.data_len = 32;
            ssl->state |= SSL_CLIENT_RANDOM;
            ssl_debug_printf("dissect_ssl2_hnd_client_hello found CLIENT RANDOM -> state 0x%02X\n", ssl->state);
        }
    }
}

static void
dissect_pct_msg_client_hello(tvbuff_t *tvb, packet_info *pinfo,
                             proto_tree *tree, guint32 offset)
{
    guint16 CH_CLIENT_VERSION, CH_OFFSET, CH_CIPHER_SPECS_LENGTH, CH_HASH_SPECS_LENGTH, CH_CERT_SPECS_LENGTH, CH_EXCH_SPECS_LENGTH, CH_KEY_ARG_LENGTH, mac_key_length;
    proto_item *CH_CIPHER_SPECS_ti, *CH_HASH_SPECS_ti, *CH_CERT_SPECS_ti, *CH_EXCH_SPECS_ti, *ti;
    proto_tree *CH_CIPHER_SPECS_tree, *CH_HASH_SPECS_tree, *CH_CERT_SPECS_tree, *CH_EXCH_SPECS_tree;
    gint i;

    CH_CLIENT_VERSION = tvb_get_ntohs(tvb, offset);
    ti = proto_tree_add_item(tree, hf_ssl_pct_client_version, tvb, offset, 2, ENC_BIG_ENDIAN);
    if (CH_CLIENT_VERSION != PCT_VERSION_1)
        expert_add_info_format(pinfo, ti, &ei_ssl_pct_client_version, "Client Version, should be %x in PCT version 1", PCT_VERSION_1);
    offset += 2;

    proto_tree_add_item(tree, hf_ssl_pct_pad, tvb, offset, 1, ENC_NA);
    offset += 1;

    proto_tree_add_item(tree, hf_ssl_pct_client_session_id_data, tvb, offset, 32, ENC_NA);
    offset += 32;

    proto_tree_add_item(tree, hf_ssl_pct_challenge_data, tvb, offset, 32, ENC_NA);
    offset += 32;

    CH_OFFSET = tvb_get_ntohs(tvb, offset);
    ti = proto_tree_add_item(tree, hf_ssl_pct_ch_offset, tvb, offset, 2, ENC_BIG_ENDIAN);
    if (CH_OFFSET != PCT_CH_OFFSET_V1)
        expert_add_info_format(pinfo, ti, &ei_ssl_pct_ch_offset, "should be %d in PCT version 1", PCT_CH_OFFSET_V1);
    offset += 2;

    CH_CIPHER_SPECS_LENGTH = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_cipher_specs_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    CH_HASH_SPECS_LENGTH = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_hash_specs_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    CH_CERT_SPECS_LENGTH = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_cert_specs_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    CH_EXCH_SPECS_LENGTH = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_exch_specs_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    CH_KEY_ARG_LENGTH = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_iv_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    if (CH_CIPHER_SPECS_LENGTH) {
        CH_CIPHER_SPECS_ti = proto_tree_add_item(tree, hf_pct_handshake_cipher_spec, tvb, offset, CH_CIPHER_SPECS_LENGTH, ENC_NA);
        CH_CIPHER_SPECS_tree = proto_item_add_subtree(CH_CIPHER_SPECS_ti, ett_pct_cipher_suites);

        for(i=0; i<(CH_CIPHER_SPECS_LENGTH/4); i++) {
            proto_tree_add_item(CH_CIPHER_SPECS_tree, hf_pct_handshake_cipher, tvb, offset, 2, ENC_BIG_ENDIAN);
            offset += 2;
            proto_tree_add_item(CH_CIPHER_SPECS_tree, hf_ssl_pct_encryption_key_length, tvb, offset, 1, ENC_NA);
            offset += 1;
            mac_key_length = tvb_get_guint8(tvb, offset) + 64;
            proto_tree_add_uint(CH_CIPHER_SPECS_tree, hf_ssl_pct_mac_key_length_in_bits, tvb, offset, 1, mac_key_length);
            offset += 1;
        }
    }

    if (CH_HASH_SPECS_LENGTH) {
        CH_HASH_SPECS_ti = proto_tree_add_item(tree, hf_pct_handshake_hash_spec, tvb, offset, CH_HASH_SPECS_LENGTH, ENC_NA);
        CH_HASH_SPECS_tree = proto_item_add_subtree(CH_HASH_SPECS_ti, ett_pct_hash_suites);

        for(i=0; i<(CH_HASH_SPECS_LENGTH/2); i++) {
            proto_tree_add_item(CH_HASH_SPECS_tree, hf_pct_handshake_hash, tvb, offset, 2, ENC_BIG_ENDIAN);
            offset += 2;
        }
    }

    if (CH_CERT_SPECS_LENGTH) {
        CH_CERT_SPECS_ti = proto_tree_add_item(tree, hf_pct_handshake_cert_spec, tvb, offset, CH_CERT_SPECS_LENGTH, ENC_NA);
        CH_CERT_SPECS_tree = proto_item_add_subtree(CH_CERT_SPECS_ti, ett_pct_cert_suites);

        for(i=0; i< (CH_CERT_SPECS_LENGTH/2); i++) {
            proto_tree_add_item(CH_CERT_SPECS_tree, hf_pct_handshake_cert, tvb, offset, 2, ENC_BIG_ENDIAN);
            offset += 2;
        }
    }

    if (CH_EXCH_SPECS_LENGTH) {
        CH_EXCH_SPECS_ti = proto_tree_add_item(tree, hf_pct_handshake_exch_spec, tvb, offset, CH_EXCH_SPECS_LENGTH, ENC_NA);
        CH_EXCH_SPECS_tree = proto_item_add_subtree(CH_EXCH_SPECS_ti, ett_pct_exch_suites);

        for(i=0; i<(CH_EXCH_SPECS_LENGTH/2); i++) {
            proto_tree_add_item(CH_EXCH_SPECS_tree, hf_pct_handshake_exch, tvb, offset, 2, ENC_BIG_ENDIAN);
            offset += 2;
        }
    }

    if (CH_KEY_ARG_LENGTH) {
        proto_tree_add_item(tree, hf_ssl_pct_iv_data, tvb, offset, CH_KEY_ARG_LENGTH, ENC_NA);
    }
}

static void
dissect_pct_msg_server_hello(tvbuff_t *tvb, proto_tree *tree, guint32 offset, packet_info *pinfo)
{
/* structure:
   char SH_MSG_SERVER_HELLO
   char SH_PAD
   char SH_SERVER_VERSION_MSB
   char SH_SERVER_VERSION_LSB
   char SH_RESTART_SESSION_OK
   char SH_CLIENT_AUTH_REQ
   char SH_CIPHER_SPECS_DATA[4]
   char SH_HASH_SPECS_DATA[2]
   char SH_CERT_SPECS_DATA[2]
   char SH_EXCH_SPECS_DATA[2]
   char SH_CONNECTION_ID_DATA[32]
   char SH_CERTIFICATE_LENGTH_MSB
   char SH_CERTIFICATE_LENGTH_LSB
   char SH_CLIENT_CERT_SPECS_LENGTH_MSB
   char SH_CLIENT_CERT_SPECS_LENGTH_LSB
   char SH_CLIENT_SIG_SPECS_LENGTH_MSB
   char SH_CLIENT_SIG_SPECS_LENGTH_LSB
   char SH_RESPONSE_LENGTH_MSB
   char SH_RESPONSE_LENGTH_LSB
   char SH_CERTIFICATE_DATA[MSB<<8|LSB]
   char SH_CLIENT_CERT_SPECS_DATA[MSB<<8|LSB]
   char SH_CLIENT_SIG_SPECS_DATA[MSB<<8|LSB]
   char SH_RESPONSE_DATA[MSB<<8|LSB]

*/

    guint16 SH_SERVER_VERSION, SH_CERT_LENGTH, SH_CERT_SPECS_LENGTH, SH_CLIENT_SIG_LENGTH, SH_RESPONSE_LENGTH, mac_key_length;
    proto_item* ti;
    asn1_ctx_t asn1_ctx;
    asn1_ctx_init(&asn1_ctx, ASN1_ENC_BER, TRUE, pinfo);

    proto_tree_add_item(tree, hf_ssl_pct_pad, tvb, offset, 1, ENC_NA);
    offset += 1;

    SH_SERVER_VERSION = tvb_get_ntohs(tvb, offset);
    ti = proto_tree_add_item(tree, hf_ssl_pct_server_version, tvb, offset, 2, ENC_BIG_ENDIAN);
    if (SH_SERVER_VERSION != PCT_VERSION_1)
        expert_add_info_format(pinfo, ti, &ei_ssl_pct_server_version, "Server Version, should be %x in PCT version 1", PCT_VERSION_1);
    offset += 2;

    proto_tree_add_item(tree, hf_ssl_pct_sh_restart_session_ok_flag, tvb, offset, 1, ENC_NA);
    offset += 1;

    proto_tree_add_item(tree, hf_ssl_pct_sh_client_auth_req_flag, tvb, offset, 1, ENC_NA);
    offset += 1;

    proto_tree_add_item(tree, hf_pct_handshake_cipher, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;
    proto_tree_add_item(tree, hf_ssl_pct_encryption_key_length, tvb, offset, 1, ENC_NA);
    offset += 1;
    mac_key_length = tvb_get_guint8(tvb, offset) + 64;
    proto_tree_add_uint(tree, hf_ssl_pct_mac_key_length_in_bits, tvb, offset, 1, mac_key_length);
    offset += 1;

    proto_tree_add_item(tree, hf_pct_handshake_hash, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    proto_tree_add_item(tree, hf_pct_handshake_cert, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    proto_tree_add_item(tree, hf_pct_handshake_exch, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    proto_tree_add_item(tree, hf_ssl_pct_connection_id_data, tvb, offset, 32, ENC_NA);
    offset += 32;

    SH_CERT_LENGTH = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_server_certificate_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    SH_CERT_SPECS_LENGTH = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_client_cert_specs_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    SH_CLIENT_SIG_LENGTH = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_client_sig_specs_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    SH_RESPONSE_LENGTH = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_response_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    if (SH_CERT_LENGTH) {
        dissect_x509af_Certificate(FALSE, tvb, offset, &asn1_ctx, tree, hf_pct_handshake_server_cert);
        offset += SH_CERT_LENGTH;
    }

    if (SH_CERT_SPECS_LENGTH) {
        proto_tree_add_item(tree, hf_ssl_pct_client_cert_specs, tvb, offset, SH_CERT_SPECS_LENGTH, ENC_NA);
        offset += SH_CERT_SPECS_LENGTH;
    }

    if (SH_CLIENT_SIG_LENGTH) {
        proto_tree_add_item(tree, hf_ssl_pct_client_signature, tvb, offset, SH_CLIENT_SIG_LENGTH, ENC_NA);
        offset += SH_CLIENT_SIG_LENGTH;
    }

    if (SH_RESPONSE_LENGTH) {
        proto_tree_add_item(tree, hf_ssl_pct_server_response, tvb, offset, SH_RESPONSE_LENGTH, ENC_NA);
    }

}

static void
dissect_pct_msg_client_master_key(tvbuff_t *tvb, proto_tree *tree, guint32 offset)
{
    guint16 CMK_CLEAR_KEY_LENGTH, CMK_ENCRYPTED_KEY_LENGTH, CMK_KEY_ARG_LENGTH, CMK_VERIFY_PRELUDE, CMK_CLIENT_CERT_LENGTH, CMK_RESPONSE_LENGTH;

    proto_tree_add_item(tree, hf_ssl_pct_pad, tvb, offset, 1, ENC_NA);
    offset += 1;

    proto_tree_add_item(tree, hf_pct_handshake_cert, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    proto_tree_add_item(tree, hf_pct_handshake_sig, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    CMK_CLEAR_KEY_LENGTH = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_clear_key_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    CMK_ENCRYPTED_KEY_LENGTH = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_encrypted_key_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    CMK_KEY_ARG_LENGTH= tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_iv_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    CMK_VERIFY_PRELUDE = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_verify_prelude_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    CMK_CLIENT_CERT_LENGTH = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_client_cert_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    CMK_RESPONSE_LENGTH = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_response_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    if (CMK_CLEAR_KEY_LENGTH) {
        proto_tree_add_item(tree, hf_ssl_pct_clear_key_data, tvb, offset, CMK_CLEAR_KEY_LENGTH, ENC_NA);
        offset += CMK_CLEAR_KEY_LENGTH;
    }
    if (CMK_ENCRYPTED_KEY_LENGTH) {
        proto_tree_add_item(tree, hf_ssl_pct_encrypted_key_data, tvb, offset, CMK_ENCRYPTED_KEY_LENGTH, ENC_NA);
        offset += CMK_ENCRYPTED_KEY_LENGTH;
    }
    if (CMK_KEY_ARG_LENGTH) {
        proto_tree_add_item(tree, hf_ssl_pct_iv_data, tvb, offset, CMK_KEY_ARG_LENGTH, ENC_NA);
        offset += CMK_KEY_ARG_LENGTH;
    }
    if (CMK_VERIFY_PRELUDE) {
        proto_tree_add_item(tree, hf_ssl_pct_verify_prelude_data, tvb, offset, CMK_VERIFY_PRELUDE, ENC_NA);
        offset += CMK_VERIFY_PRELUDE;
    }
    if (CMK_CLIENT_CERT_LENGTH) {
        proto_tree_add_item(tree, hf_ssl_pct_client_certificate_data, tvb, offset, CMK_CLIENT_CERT_LENGTH, ENC_NA);
        offset += CMK_CLIENT_CERT_LENGTH;
    }
    if (CMK_RESPONSE_LENGTH) {
        proto_tree_add_item(tree, hf_ssl_pct_response_data, tvb, offset, CMK_RESPONSE_LENGTH, ENC_NA);
    }
}

static void
dissect_pct_msg_server_verify(tvbuff_t *tvb,
                              proto_tree *tree, guint32 offset)
{
    guint16 SV_RESPONSE_LENGTH;

    proto_tree_add_item(tree, hf_ssl_pct_pad, tvb, offset, 1, ENC_NA);
    offset += 1;

    proto_tree_add_item(tree, hf_ssl_pct_server_session_id_data, tvb, offset, 32, ENC_NA);
    offset += 32;

    SV_RESPONSE_LENGTH = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_server_response_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    if (SV_RESPONSE_LENGTH) {
        proto_tree_add_item(tree, hf_ssl_pct_server_response, tvb, offset, SV_RESPONSE_LENGTH, ENC_NA);
    }
}

static void
dissect_pct_msg_error(tvbuff_t *tvb,
                      proto_tree *tree, guint32 offset)
{
    guint16 ERROR_CODE, INFO_LEN;

    ERROR_CODE = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_pct_msg_error_type, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    INFO_LEN = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl_pct_error_information_length, tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;
    if (ERROR_CODE == PCT_ERR_SPECS_MISMATCH && INFO_LEN == 6)
    {
        proto_tree_add_item(tree, hf_ssl_pct_specs_mismatch_cipher, tvb, offset, 1, ENC_NA);
        offset += 1;
        proto_tree_add_item(tree, hf_ssl_pct_specs_mismatch_hash, tvb, offset, 1, ENC_NA);
        offset += 1;
        proto_tree_add_item(tree, hf_ssl_pct_specs_mismatch_cert, tvb, offset, 1, ENC_NA);
        offset += 1;
        proto_tree_add_item(tree, hf_ssl_pct_specs_mismatch_exch, tvb, offset, 1, ENC_NA);
        offset += 1;
        proto_tree_add_item(tree, hf_ssl_pct_specs_mismatch_client_cert, tvb, offset, 1, ENC_NA);
        offset += 1;
        proto_tree_add_item(tree, hf_ssl_pct_specs_mismatch_client_sig, tvb, offset, 1, ENC_NA);
    }
    else if (INFO_LEN) {
        proto_tree_add_item(tree, hf_ssl_pct_error_information_data, tvb, offset, INFO_LEN, ENC_NA);
    }
}

static void
dissect_ssl2_hnd_client_master_key(tvbuff_t *tvb,
                                   proto_tree *tree, guint32 offset)
{
    /* struct {
     *    uint8 msg_type;
     *    V2Cipherspec cipher;
     *    uint16 clear_key_length;
     *    uint16 encrypted_key_length;
     *    uint16 key_arg_length;
     *    opaque clear_key_data[V2ClientMasterKey.clear_key_length];
     *    opaque encrypted_key_data[V2ClientMasterKey.encrypted_key_length];
     *    opaque key_arg_data[V2ClientMasterKey.key_arg_length];
     * } V2ClientMasterKey;
     *
     * Note: when we get here, offset's already pointing at cipher
     */
    guint16 clear_key_length;
    guint16 encrypted_key_length;
    guint16 key_arg_length;

    /* at this point, everything we do involves the tree,
     * so quit now if we don't have one ;-)
     */
    if (!tree)
    {
        return;
    }

    /* show the selected cipher */
    proto_tree_add_item(tree, hf_ssl2_handshake_cipher_spec,
                        tvb, offset, 3, ENC_BIG_ENDIAN);
    offset += 3;

    /* get the fixed fields */
    clear_key_length = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl2_handshake_clear_key_len,
                        tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    encrypted_key_length = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl2_handshake_enc_key_len,
                        tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    key_arg_length = tvb_get_ntohs(tvb, offset);
    proto_tree_add_item(tree, hf_ssl2_handshake_key_arg_len,
                        tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    /* show the variable length fields */
    if (clear_key_length > 0)
    {
        proto_tree_add_item(tree, hf_ssl2_handshake_clear_key,
                            tvb, offset, clear_key_length, ENC_NA);
        offset += clear_key_length;
    }

    if (encrypted_key_length > 0)
    {
        proto_tree_add_item(tree, hf_ssl2_handshake_enc_key,
                            tvb, offset, encrypted_key_length, ENC_NA);
        offset += encrypted_key_length;
    }

    if (key_arg_length > 0)
    {
        proto_tree_add_item(tree, hf_ssl2_handshake_key_arg,
                            tvb, offset, key_arg_length, ENC_NA);
    }

}

static void
dissect_ssl2_hnd_server_hello(tvbuff_t *tvb,
                              proto_tree *tree, guint32 offset, packet_info *pinfo)
{
    /* struct {
     *    uint8  msg_type;
     *    uint8  session_id_hit;
     *    uint8  certificate_type;
     *    uint16 server_version;
     *    uint16 certificate_length;
     *    uint16 cipher_specs_length;
     *    uint16 connection_id_length;
     *    opaque certificate_data[V2ServerHello.certificate_length];
     *    opaque cipher_specs_data[V2ServerHello.cipher_specs_length];
     *    opaque connection_id_data[V2ServerHello.connection_id_length];
     * } V2ServerHello;
     *
     * Note: when we get here, offset's already pointing at session_id_hit
     */
    guint16     certificate_length;
    guint16     cipher_spec_length;
    guint16     connection_id_length;
    guint16     version;
    proto_item *ti;
    proto_tree *subtree;
    asn1_ctx_t  asn1_ctx;

    asn1_ctx_init(&asn1_ctx, ASN1_ENC_BER, TRUE, pinfo);

    /* everything we do only makes sense with a tree, so
     * quit now if we don't have one
     */
    if (!tree)
    {
        return;
    }

    version = tvb_get_ntohs(tvb, offset + 2);
    if (!ssl_is_valid_ssl_version(version))
    {
        /* invalid version; probably encrypted data */
        return;
    }


    /* is there a hit? */
    proto_tree_add_item(tree, hf_ssl2_handshake_session_id_hit,
                        tvb, offset, 1, ENC_BIG_ENDIAN);
    offset += 1;

    /* what type of certificate is this? */
    proto_tree_add_item(tree, hf_ssl2_handshake_cert_type,
                        tvb, offset, 1, ENC_BIG_ENDIAN);
    offset += 1;

    /* now the server version */
    proto_tree_add_item(tree, dissect_ssl3_hf.hf.hs_server_version,
                        tvb, offset, 2, ENC_BIG_ENDIAN);
    offset += 2;

    /* get the fixed fields */
    certificate_length = tvb_get_ntohs(tvb, offset);
    proto_tree_add_uint(tree, dissect_ssl3_hf.hf.hs_certificate_len,
                        tvb, offset, 2, certificate_length);
    offset += 2;

    cipher_spec_length = tvb_get_ntohs(tvb, offset);
    proto_tree_add_uint(tree, hf_ssl2_handshake_cipher_spec_len,
                        tvb, offset, 2, cipher_spec_length);
    offset += 2;

    connection_id_length = tvb_get_ntohs(tvb, offset);
    proto_tree_add_uint(tree, hf_ssl2_handshake_connection_id_len,
                        tvb, offset, 2, connection_id_length);
    offset += 2;

    /* now the variable length fields */
    if (certificate_length > 0)
    {
        (void)dissect_x509af_Certificate(FALSE, tvb, offset, &asn1_ctx, tree, dissect_ssl3_hf.hf.hs_certificate);
        offset += certificate_length;
    }

    if (cipher_spec_length > 0)
    {
        /* provide a collapsing node for the cipher specs */
        ti = proto_tree_add_none_format(tree,
                                        dissect_ssl3_hf.hf.hs_cipher_suites,
                                        tvb, offset, cipher_spec_length,
                                        "Cipher Specs (%u spec%s)",
                                        cipher_spec_length/3,
                                        plurality(cipher_spec_length/3, "", "s"));
        subtree = proto_item_add_subtree(ti, dissect_ssl3_hf.ett.cipher_suites);
        if (!subtree)
        {
            subtree = tree;
        }

        /* iterate through the cipher specs */
        while (cipher_spec_length > 0)
        {
            proto_tree_add_item(subtree, hf_ssl2_handshake_cipher_spec,
                                tvb, offset, 3, ENC_BIG_ENDIAN);
            offset += 3;
            cipher_spec_length -= 3;
        }
    }

    if (connection_id_length > 0)
    {
        proto_tree_add_item(tree, hf_ssl2_handshake_connection_id,
                            tvb, offset, connection_id_length, ENC_NA);
    }

}


void ssl_set_master_secret(guint32 frame_num, address *addr_srv, address *addr_cli,
                           port_type ptype, guint32 port_srv, guint32 port_cli,
                           guint32 version, gint cipher, const guchar *_master_secret,
                           const guchar *_client_random, const guchar *_server_random,
                           guint32 client_seq, guint32 server_seq)
{
    conversation_t    *conversation;
    SslDecryptSession *ssl;
    guint              iv_len;

    ssl_debug_printf("\nssl_set_master_secret enter frame #%u\n", frame_num);

    conversation = find_conversation(frame_num, addr_srv, addr_cli, conversation_pt_to_endpoint_type(ptype), port_srv, port_cli, 0);

    if (!conversation) {
        /* create a new conversation */
        conversation = conversation_new(frame_num, addr_srv, addr_cli, conversation_pt_to_endpoint_type(ptype), port_srv, port_cli, 0);
        ssl_debug_printf("  new conversation = %p created\n", (void *)conversation);
    }
    ssl = ssl_get_session(conversation, ssl_handle);

    ssl_debug_printf("  conversation = %p, ssl_session = %p\n", (void *)conversation, (void *)ssl);

    ssl_set_server(&ssl->session, addr_srv, ptype, port_srv);

    /* version */
    if ((ssl->session.version==SSL_VER_UNKNOWN) && (version!=SSL_VER_UNKNOWN)) {
        switch (version) {
        case SSLV3_VERSION:
        case TLSV1_VERSION:
        case TLSV1DOT1_VERSION:
        case TLSV1DOT2_VERSION:
            ssl->session.version = version;
            ssl->state |= SSL_VERSION;
            ssl_debug_printf("%s set version 0x%04X -> state 0x%02X\n", G_STRFUNC, ssl->session.version, ssl->state);
            break;
        default:
            /* API change: version number is no longer an internal value
             * (SSL_VER_*) but the ProtocolVersion from wire (*_VERSION) */
            ssl_debug_printf("%s WARNING must pass ProtocolVersion, not 0x%04x!\n", G_STRFUNC, version);
            break;
        }
    }

    /* cipher */
    if (cipher > 0) {
        ssl->session.cipher = cipher;
        if (!(ssl->cipher_suite = ssl_find_cipher(ssl->session.cipher))) {
            ssl->state &= ~SSL_CIPHER;
            ssl_debug_printf("ssl_set_master_secret can't find cipher suite 0x%X\n", ssl->session.cipher);
        } else {
            ssl->state |= SSL_CIPHER;
            ssl_debug_printf("ssl_set_master_secret set CIPHER 0x%04X -> state 0x%02X\n", ssl->session.cipher, ssl->state);
        }
    }

    /* client random */
    if (_client_random) {
        ssl_data_set(&ssl->client_random, _client_random, 32);
        ssl->state |= SSL_CLIENT_RANDOM;
        ssl_debug_printf("ssl_set_master_secret set CLIENT RANDOM -> state 0x%02X\n", ssl->state);
    }

    /* server random */
    if (_server_random) {
        ssl_data_set(&ssl->server_random, _server_random, 32);
        ssl->state |= SSL_SERVER_RANDOM;
        ssl_debug_printf("ssl_set_master_secret set SERVER RANDOM -> state 0x%02X\n", ssl->state);
    }

    /* master secret */
    if (_master_secret) {
        ssl_data_set(&ssl->master_secret, _master_secret, 48);
        ssl->state |= SSL_MASTER_SECRET;
        ssl_debug_printf("ssl_set_master_secret set MASTER SECRET -> state 0x%02X\n", ssl->state);
    }

    ssl_debug_printf("ssl_set_master_secret trying to generate keys\n");
    if (ssl_generate_keyring_material(ssl)<0) {
        ssl_debug_printf("ssl_set_master_secret can't generate keyring material\n");
        return;
    }

    /* change ciphers immediately */
    ssl_change_cipher(ssl, TRUE);
    ssl_change_cipher(ssl, FALSE);

    /* update seq numbers if available */
    /* TODO change API to accept 64-bit sequence numbers. */
    if (ssl->client && (client_seq != (guint32)-1)) {
        ssl->client->seq = client_seq;
        ssl_debug_printf("ssl_set_master_secret client->seq updated to %" G_GUINT64_FORMAT "\n", ssl->client->seq);
    }
    if (ssl->server && (server_seq != (guint32)-1)) {
        ssl->server->seq = server_seq;
        ssl_debug_printf("ssl_set_master_secret server->seq updated to %" G_GUINT64_FORMAT "\n", ssl->server->seq);
    }

    /* update IV from last data */
    iv_len = ssl_get_cipher_blocksize(ssl->cipher_suite);
    if (ssl->client && ((ssl->client->seq > 0) || (ssl->client_data_for_iv.data_len > iv_len))) {
        ssl_cipher_setiv(&ssl->client->evp, ssl->client_data_for_iv.data + ssl->client_data_for_iv.data_len - iv_len, iv_len);
        ssl_print_data("ssl_set_master_secret client IV updated",ssl->client_data_for_iv.data + ssl->client_data_for_iv.data_len - iv_len, iv_len);
    }
    if (ssl->server && ((ssl->server->seq > 0) || (ssl->server_data_for_iv.data_len > iv_len))) {
        ssl_cipher_setiv(&ssl->server->evp, ssl->server_data_for_iv.data + ssl->server_data_for_iv.data_len - iv_len, iv_len);
        ssl_print_data("ssl_set_master_secret server IV updated",ssl->server_data_for_iv.data + ssl->server_data_for_iv.data_len - iv_len, iv_len);
    }
}


/*********************************************************************
 *
 * Support Functions
 *
 *********************************************************************/
static gint
ssl_is_valid_ssl_version(const guint16 version)
{
    const gchar *version_str;

    version_str = try_val_to_str(version, ssl_versions);
    return version_str != NULL;
}

static gint
ssl_is_v2_client_hello(tvbuff_t *tvb, const guint32 offset)
{
    guint8 byte;

    byte = tvb_get_guint8(tvb, offset);
    if (byte != 0x80)           /* v2 client hello should start this way */
    {
        return 0;
    }

    byte = tvb_get_guint8(tvb, offset+2);
    if (byte != 0x01)           /* v2 client hello msg type */
    {
        return 0;
    }

    /* 1 in 2^16 of being right; improve later if necessary */
    return 1;
}

/* this applies a heuristic to determine whether
 * or not the data beginning at offset looks like a
 * valid sslv2 record.  this isn't really possible,
 * but we'll try to do a reasonable job anyway.
 */
static gint
ssl_looks_like_sslv2(tvbuff_t *tvb, const guint32 offset)
{
    /* here's the current approach:
     *
     * we only try to catch unencrypted handshake messages, so we can
     * assume that there is not padding.  This means that the
     * first byte must be >= 0x80 and there must be a valid sslv2
     * msg_type in the third byte
     */

    /* get the first byte; must have high bit set */
    guint8 byte;
    byte = tvb_get_guint8(tvb, offset);

    if (byte < 0x80)
    {
        return 0;
    }

    /* get the supposed msg_type byte; since we only care about
     * unencrypted handshake messages (we can't tell the type for
     * encrypted messages), we just check against that list
     */
    byte = tvb_get_guint8(tvb, offset + 2);
    switch (byte) {
    case SSL2_HND_ERROR:
    case SSL2_HND_CLIENT_HELLO:
    case SSL2_HND_CLIENT_MASTER_KEY:
    case SSL2_HND_SERVER_HELLO:
    case PCT_MSG_CLIENT_MASTER_KEY:
    case PCT_MSG_ERROR:
        return 1;
    }
    return 0;
}

/* 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(tvbuff_t *tvb, 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 = tvb_get_guint8(tvb, offset);
    if (!ssl_is_valid_content_type(byte))
    {
        return 0;
    }

    /* now check to see if the version byte appears valid */
    version = tvb_get_ntohs(tvb, offset + 1);
    switch (version) {
    case SSLV3_VERSION:
    case TLSV1_VERSION:
    case TLSV1DOT1_VERSION:
    case TLSV1DOT2_VERSION:
        return 1;
    }
    return 0;
}

/* applies a heuristic to determine whether
 * or not the data beginning at offset looks
 * like a valid, unencrypted v2 handshake message.
 * since it isn't possible to completely tell random
 * data apart from a valid message without state,
 * we try to help the odds.
 */
static gint
ssl_looks_like_valid_v2_handshake(tvbuff_t *tvb, const guint32 offset,
                                  const guint32 record_length)
{
    /* first byte should be a msg_type.
     *
     *   - we know we only see client_hello, client_master_key,
     *     and server_hello in the clear, so check to see if
     *     msg_type is one of those (this gives us a 3 in 2^8
     *     chance of saying yes with random payload)
     *
     *   - for those three types that we know about, do some
     *     further validation to reduce the chance of an error
     */
    guint8  msg_type;
    guint16 version;
    guint32 sum;
    gint    ret = 0;

    /* fetch the msg_type */
    msg_type = tvb_get_guint8(tvb, offset);

    switch (msg_type) {
    case SSL2_HND_CLIENT_HELLO:
        /* version follows msg byte, so verify that this is valid */
        version = tvb_get_ntohs(tvb, offset+1);
        ret = ssl_is_valid_ssl_version(version);
        break;

    case SSL2_HND_SERVER_HELLO:
        /* version is three bytes after msg_type */
        version = tvb_get_ntohs(tvb, offset+3);
        ret = ssl_is_valid_ssl_version(version);
        break;

    case SSL2_HND_CLIENT_MASTER_KEY:
        /* sum of clear_key_length, encrypted_key_length, and key_arg_length
         * must be less than record length
         */
        sum  = tvb_get_ntohs(tvb, offset + 4); /* clear_key_length */
        sum += tvb_get_ntohs(tvb, offset + 6); /* encrypted_key_length */
        sum += tvb_get_ntohs(tvb, offset + 8); /* key_arg_length */
        if (sum <= record_length) {
            ret = 1;
        }
        break;

    default:
        break;
    }

    return ret;
}

/* applies a heuristic to determine whether
 * or not the data beginning at offset looks
 * like a valid, unencrypted pct handshake message.
 * since it isn't possible to completely tell random
 * data apart from a valid message without state,
 * we try to help the odds.
 */
static gint
ssl_looks_like_valid_pct_handshake(tvbuff_t *tvb, const guint32 offset,
                   const guint32 record_length)
{
    /* first byte should be a msg_type.
     *
     *   - we know we only see client_hello, client_master_key,
     *     and server_hello in the clear, so check to see if
     *     msg_type is one of those (this gives us a 3 in 2^8
     *     chance of saying yes with random payload)
     *
     *   - for those three types that we know about, do some
     *     further validation to reduce the chance of an error
     */
    guint8  msg_type;
    guint16 version;
    guint32 sum;
    gint    ret = 0;

    /* fetch the msg_type */
    msg_type = tvb_get_guint8(tvb, offset);

    switch (msg_type) {
    case PCT_MSG_CLIENT_HELLO:
        /* version follows msg byte, so verify that this is valid */
        version = tvb_get_ntohs(tvb, offset+1);
        ret = (version == PCT_VERSION_1);
        break;

    case PCT_MSG_SERVER_HELLO:
        /* version is one byte after msg_type */
        version = tvb_get_ntohs(tvb, offset+2);
        ret = (version == PCT_VERSION_1);
        break;

    case PCT_MSG_CLIENT_MASTER_KEY:
        /* sum of various length fields must be less than record length */
        sum  = tvb_get_ntohs(tvb, offset +  6); /* clear_key_length */
        sum += tvb_get_ntohs(tvb, offset +  8); /* encrypted_key_length */
        sum += tvb_get_ntohs(tvb, offset + 10); /* key_arg_length */
        sum += tvb_get_ntohs(tvb, offset + 12); /* verify_prelude_length */
        sum += tvb_get_ntohs(tvb, offset + 14); /* client_cert_length */
        sum += tvb_get_ntohs(tvb, offset + 16); /* response_length */
        if (sum <= record_length) {
            ret = 1;
        }
        break;

    case PCT_MSG_SERVER_VERIFY:
        /* record is 36 bytes longer than response_length */
        sum = tvb_get_ntohs(tvb, offset + 34); /* response_length */
        if ((sum + 36) == record_length) {
            ret = 1;
        }
        break;

    default:
        break;
    }

    return ret;
}


/* UAT */

#if defined(HAVE_LIBGNUTLS)
static void
ssldecrypt_free_cb(void *r)
{
    ssldecrypt_assoc_t *h = (ssldecrypt_assoc_t *)r;

    g_free(h->ipaddr);
    g_free(h->port);
    g_free(h->protocol);
    g_free(h->keyfile);
    g_free(h->password);
}

static void*
ssldecrypt_copy_cb(void *dest, const void *orig, size_t len _U_)
{
    const ssldecrypt_assoc_t *o = (const ssldecrypt_assoc_t *)orig;
    ssldecrypt_assoc_t       *d = (ssldecrypt_assoc_t *)dest;

    d->ipaddr    = g_strdup(o->ipaddr);
    d->port      = g_strdup(o->port);
    d->protocol  = g_strdup(o->protocol);
    d->keyfile   = g_strdup(o->keyfile);
    d->password  = g_strdup(o->password);

    return d;
}

UAT_CSTRING_CB_DEF(sslkeylist_uats,ipaddr,ssldecrypt_assoc_t)
UAT_CSTRING_CB_DEF(sslkeylist_uats,port,ssldecrypt_assoc_t)
UAT_CSTRING_CB_DEF(sslkeylist_uats,protocol,ssldecrypt_assoc_t)
UAT_FILENAME_CB_DEF(sslkeylist_uats,keyfile,ssldecrypt_assoc_t)
UAT_CSTRING_CB_DEF(sslkeylist_uats,password,ssldecrypt_assoc_t)

static gboolean
ssldecrypt_uat_fld_protocol_chk_cb(void* r _U_, const char* p, guint len _U_, const void* u1 _U_, const void* u2 _U_, char** err)
{
    if (!p || strlen(p) == 0u) {
        // This should be removed in favor of Decode As. Make it optional.
        *err = NULL;
        return TRUE;
    }

    if (!ssl_find_appdata_dissector(p)) {
        if (proto_get_id_by_filter_name(p) != -1) {
            *err = g_strdup_printf("While '%s' is a valid dissector filter name, that dissector is not configured"
                                   " to support SSL decryption.\n\n"
                                   "If you need to decrypt '%s' over SSL, please contact the Wireshark development team.", p, p);
        } else {
            char* ssl_str = ssl_association_info("ssl.port", "TCP");
            *err = g_strdup_printf("Could not find dissector for: '%s'\nCommonly used SSL dissectors include:\n%s", p, ssl_str);
            g_free(ssl_str);
        }
        return FALSE;
    }

    *err = NULL;
    return TRUE;
}
#endif

static void
ssl_src_prompt(packet_info *pinfo, gchar *result)
{
    SslPacketInfo* pi;
    guint32 srcport = pinfo->srcport;

    pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_ssl, pinfo->curr_layer_num);
    if (pi != NULL)
        srcport = pi->srcport;

    g_snprintf(result, MAX_DECODE_AS_PROMPT_LEN, "source (%u%s)", srcport, UTF8_RIGHTWARDS_ARROW);
}

static gpointer
ssl_src_value(packet_info *pinfo)
{
    SslPacketInfo* pi;

    pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_ssl, pinfo->curr_layer_num);
    if (pi == NULL)
        return GUINT_TO_POINTER(pinfo->srcport);

    return GUINT_TO_POINTER(pi->srcport);
}

static void
ssl_dst_prompt(packet_info *pinfo, gchar *result)
{
    SslPacketInfo* pi;
    guint32 destport = pinfo->destport;

    pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_ssl, pinfo->curr_layer_num);
    if (pi != NULL)
        destport = pi->destport;

    g_snprintf(result, MAX_DECODE_AS_PROMPT_LEN, "destination (%s%u)", UTF8_RIGHTWARDS_ARROW, destport);
}

static gpointer
ssl_dst_value(packet_info *pinfo)
{
    SslPacketInfo* pi;

    pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_ssl, pinfo->curr_layer_num);
    if (pi == NULL)
        return GUINT_TO_POINTER(pinfo->destport);

    return GUINT_TO_POINTER(pi->destport);
}

static void
ssl_both_prompt(packet_info *pinfo, gchar *result)
{
    SslPacketInfo* pi;
    guint32 srcport = pinfo->srcport,
            destport = pinfo->destport;

    pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_ssl, pinfo->curr_layer_num);
    if (pi != NULL)
    {
        srcport = pi->srcport;
        destport = pi->destport;
    }

    g_snprintf(result, MAX_DECODE_AS_PROMPT_LEN, "both (%u%s%u)", srcport, UTF8_LEFT_RIGHT_ARROW, destport);
}

/*********************************************************************
 *
 * Standard Wireshark Protocol Registration and housekeeping
 *
 *********************************************************************/
void
proto_register_ssl(void)
{

    /* Setup list of header fields See Section 1.6.1 for details*/
    static hf_register_info hf[] = {
        { &hf_ssl_record,
          { "Record Layer", "ssl.record",
            FT_NONE, BASE_NONE, NULL, 0x0,
            NULL, HFILL }
        },
        { &hf_ssl_record_content_type,
          { "Content Type", "ssl.record.content_type",
            FT_UINT8, BASE_DEC, VALS(ssl_31_content_type), 0x0,
            NULL, HFILL}
        },
        { &hf_ssl_record_opaque_type,
          { "Opaque Type", "ssl.record.opaque_type",
            FT_UINT8, BASE_DEC, VALS(ssl_31_content_type), 0x0,
            "Always set to value 23, actual content type is known after decryption", HFILL}
        },
        { &hf_ssl2_msg_type,
          { "Handshake Message Type", "ssl.handshake.type",
            FT_UINT8, BASE_DEC, VALS(ssl_20_msg_types), 0x0,
            "SSLv2 handshake message type", HFILL}
        },
        { &hf_pct_msg_type,
          { "Handshake Message Type", "ssl.pct_handshake.type",
            FT_UINT8, BASE_DEC, VALS(pct_msg_types), 0x0,
            "PCT handshake message type", HFILL}
        },
        { &hf_ssl_record_version,
          { "Version", "ssl.record.version",
            FT_UINT16, BASE_HEX, VALS(ssl_versions), 0x0,
            "Record layer version", HFILL }
        },
        { &hf_ssl_record_length,
          { "Length", "ssl.record.length",
            FT_UINT16, BASE_DEC, NULL, 0x0,
            "Length of SSL record data", HFILL }
        },
        { &hf_ssl_record_appdata,
          { "Encrypted Application Data", "ssl.app_data",
            FT_BYTES, BASE_NONE, NULL, 0x0,
            "Payload is encrypted application data", HFILL }
        },

        { &hf_ssl2_record,
          { "SSLv2/PCT Record Header", "ssl.record",
            FT_NONE, BASE_NONE, NULL, 0x0,
            "SSLv2/PCT record data", HFILL }
        },
        { &hf_ssl2_record_is_escape,
          { "Is Escape", "ssl.record.is_escape",
            FT_BOOLEAN, BASE_NONE, NULL, 0x0,
            "Indicates a security escape", HFILL}
        },
        { &hf_ssl2_record_padding_length,
          { "Padding Length", "ssl.record.padding_length",
            FT_UINT8, BASE_DEC, NULL, 0x0,
            "Length of padding at end of record", HFILL }
        },
        { &hf_ssl_alert_message,
          { "Alert Message", "ssl.alert_message",
            FT_NONE, BASE_NONE, NULL, 0x0,
            NULL, HFILL }
        },
        { &hf_ssl_alert_message_level,
          { "Level", "ssl.alert_message.level",
            FT_UINT8, BASE_DEC, VALS(ssl_31_alert_level), 0x0,
            "Alert message level", HFILL }
        },
        { &hf_ssl_alert_message_description,
          { "Description", "ssl.alert_message.desc",
            FT_UINT8, BASE_DEC, VALS(ssl_31_alert_description), 0x0,
            "Alert message description", HFILL }
        },
        { &hf_ssl_handshake_protocol,
          { "Handshake Protocol", "ssl.handshake",
            FT_NONE, BASE_NONE, NULL, 0x0,
            "Handshake protocol message", HFILL}
        },
        { &hf_ssl_handshake_type,
          { "Handshake Type", "ssl.handshake.type",
            FT_UINT8, BASE_DEC, VALS(ssl_31_handshake_type), 0x0,
            "Type of handshake message", HFILL}
        },
        { &hf_ssl_handshake_length,
          { "Length", "ssl.handshake.length",
            FT_UINT24, BASE_DEC, NULL, 0x0,
            "Length of handshake message", HFILL }
        },
        { &hf_ssl2_handshake_cipher_spec,
          { "Cipher Spec", "ssl.handshake.cipherspec",
            FT_UINT24, BASE_HEX|BASE_EXT_STRING, &ssl_20_cipher_suites_ext, 0x0,
            "Cipher specification", HFILL }
        },
        { &hf_ssl_handshake_npn_selected_protocol_len,
          { "Selected Protocol Length", "ssl.handshake.npn_selected_protocol_len",
            FT_UINT8, BASE_DEC, NULL, 0x0,
            NULL, HFILL }
        },
        { &hf_ssl_handshake_npn_selected_protocol,
          { "Selected Protocol", "ssl.handshake.npn_selected_protocol",
            FT_STRING, BASE_NONE, NULL, 0x0,
            "Protocol to be used for connection", HFILL }
        },
        { &hf_ssl_handshake_npn_padding_len,
          { "Padding Length", "ssl.handshake.npn_padding_len",
            FT_UINT8, BASE_DEC, NULL, 0x0,
            NULL, HFILL }
        },
        { &hf_ssl_handshake_npn_padding,
          { "Padding", "ssl.handshake.npn_padding",
            FT_BYTES, BASE_NONE, NULL, 0x0,
            NULL, HFILL }
        },
        { &ssl_hfs.hs_md5_hash,
          { "MD5 Hash", "ssl.handshake.md5_hash",
            FT_NONE, BASE_NONE, NULL, 0x0,
            "Hash of messages, master_secret, etc.", HFILL }
        },
        { &ssl_hfs.hs_sha_hash,
          { "SHA-1 Hash", "ssl.handshake.sha_hash",
            FT_NONE, BASE_NONE, NULL, 0x0,
            "Hash of messages, master_secret, etc.", HFILL }
        },
        { &hf_ssl_heartbeat_message,
          { "Heartbeat Message", "ssl.heartbeat_message",
            FT_NONE, BASE_NONE, NULL, 0x0,
            NULL, HFILL }
        },
        { &hf_ssl_heartbeat_message_type,
          { "Type", "ssl.heartbeat_message.type",
            FT_UINT8, BASE_DEC, VALS(tls_heartbeat_type), 0x0,
            "Heartbeat message type", HFILL }
        },
        { &hf_ssl_heartbeat_message_payload_length,
          { "Payload Length", "ssl.heartbeat_message.payload_length",
            FT_UINT16, BASE_DEC, NULL, 0x00, NULL, HFILL }
        },
        { &hf_ssl_heartbeat_message_payload,
          { "Payload Length", "ssl.heartbeat_message.payload",
            FT_BYTES, BASE_NONE, NULL, 0x00, NULL, HFILL }
        },
        { &hf_ssl_heartbeat_message_padding,
          { "Payload Length", "ssl.heartbeat_message.padding",
            FT_BYTES, BASE_NONE, NULL, 0x00, NULL, HFILL }
        },
        { &hf_ssl2_handshake_challenge,
          { "Challenge", "ssl.handshake.challenge",
            FT_NONE, BASE_NONE, NULL, 0x0,
            "Challenge data used to authenticate server", HFILL }
        },
        { &hf_ssl2_handshake_cipher_spec_len,
          { "Cipher Spec Length", "ssl.handshake.cipher_spec_len",
            FT_UINT16, BASE_DEC, NULL, 0x0,
            "Length of cipher specs field", HFILL }
        },
        { &hf_ssl2_handshake_session_id_len,
          { "Session ID Length", "ssl.handshake.session_id_length",
            FT_UINT16, BASE_DEC, NULL, 0x0,
            "Length of session ID field", HFILL }
        },
        { &hf_ssl2_handshake_challenge_len,
          { "Challenge Length", "ssl.handshake.challenge_length",
            FT_UINT16, BASE_DEC, NULL, 0x0,
            "Length of challenge field", HFILL }
        },
        { &hf_ssl2_handshake_clear_key_len,
          { "Clear Key Data Length", "ssl.handshake.clear_key_length",
            FT_UINT16, BASE_DEC, NULL, 0x0,
            "Length of clear key data", HFILL }
        },
        { &hf_ssl2_handshake_enc_key_len,
          { "Encrypted Key Data Length", "ssl.handshake.encrypted_key_length",
            FT_UINT16, BASE_DEC, NULL, 0x0,
            "Length of encrypted key data", HFILL }
        },
        { &hf_ssl2_handshake_key_arg_len,
          { "Key Argument Length", "ssl.handshake.key_arg_length",
            FT_UINT16, BASE_DEC, NULL, 0x0,
            "Length of key argument", HFILL }
        },
        { &hf_ssl2_handshake_clear_key,
          { "Clear Key Data", "ssl.handshake.clear_key_data",
            FT_NONE, BASE_NONE, NULL, 0x0,
            "Clear portion of MASTER-KEY", HFILL }
        },
        { &hf_ssl2_handshake_enc_key,
          { "Encrypted Key", "ssl.handshake.encrypted_key",
            FT_NONE, BASE_NONE, NULL, 0x0,
            "Secret portion of MASTER-KEY encrypted to server", HFILL }
        },
        { &hf_ssl2_handshake_key_arg,
          { "Key Argument", "ssl.handshake.key_arg",
            FT_NONE, BASE_NONE, NULL, 0x0,
            "Key Argument (e.g., Initialization Vector)", HFILL }
        },
        { &hf_ssl2_handshake_session_id_hit,
          { "Session ID Hit", "ssl.handshake.session_id_hit",
            FT_BOOLEAN, BASE_NONE, NULL, 0x0,
            "Did the server find the client's Session ID?", HFILL }
        },
        { &hf_ssl2_handshake_cert_type,
          { "Certificate Type", "ssl.handshake.cert_type",
            FT_UINT8, BASE_DEC, VALS(ssl_20_certificate_type), 0x0,
            NULL, HFILL }
        },
        { &hf_ssl2_handshake_connection_id_len,
          { "Connection ID Length", "ssl.handshake.connection_id_length",
            FT_UINT16, BASE_DEC, NULL, 0x0,
            "Length of connection ID", HFILL }
        },
        { &hf_ssl2_handshake_connection_id,
          { "Connection ID", "ssl.handshake.connection_id",
            FT_NONE, BASE_NONE, NULL, 0x0,
            "Server's challenge to client", HFILL }
        },
        { &hf_pct_handshake_cipher_spec,
          { "Cipher Spec", "ssl.pct.handshake.cipherspec",
            FT_NONE, BASE_NONE, NULL, 0x0,
            "PCT Cipher specification", HFILL }
        },
        { &hf_pct_handshake_cipher,
          { "Cipher", "ssl.pct.handshake.cipher",
            FT_UINT16, BASE_HEX, VALS(pct_cipher_type), 0x0,
            "PCT Ciper", HFILL }
        },
        { &hf_pct_handshake_hash_spec,
          { "Hash Spec", "ssl.pct.handshake.hashspec",
            FT_NONE, BASE_NONE, NULL, 0x0,
            "PCT Hash specification", HFILL }
        },
        { &hf_pct_handshake_hash,
          { "Hash", "ssl.pct.handshake.hash",
            FT_UINT16, BASE_HEX, VALS(pct_hash_type), 0x0,
            "PCT Hash", HFILL }
        },
        { &hf_pct_handshake_cert_spec,
          { "Cert Spec", "ssl.pct.handshake.certspec",
            FT_NONE, BASE_NONE, NULL, 0x0,
            "PCT Certificate specification", HFILL }
        },
        { &hf_pct_handshake_cert,
          { "Cert", "ssl.pct.handshake.cert",
            FT_UINT16, BASE_HEX, VALS(pct_cert_type), 0x0,
            "PCT Certificate", HFILL }
        },
        { &hf_pct_handshake_exch_spec,
          { "Exchange Spec", "ssl.pct.handshake.exchspec",
            FT_NONE, BASE_NONE, NULL, 0x0,
            "PCT Exchange specification", HFILL }
        },
        { &hf_pct_handshake_exch,
          { "Exchange", "ssl.pct.handshake.exch",
            FT_UINT16, BASE_HEX, VALS(pct_exch_type), 0x0,
            "PCT Exchange", HFILL }
        },
        { &hf_pct_handshake_sig,
          { "Sig Spec", "ssl.pct.handshake.sig",
            FT_UINT16, BASE_HEX, VALS(pct_sig_type), 0x0,
            "PCT Signature", HFILL }
        },
        { &hf_pct_msg_error_type,
          { "PCT Error Code", "ssl.pct.msg_error_code",
            FT_UINT16, BASE_HEX, VALS(pct_error_code), 0x0,
            NULL, HFILL }
        },
        { &hf_pct_handshake_server_cert,
          { "Server Cert", "ssl.pct.handshake.server_cert",
            FT_BYTES, BASE_NONE, NULL , 0x0,
            "PCT Server Certificate", HFILL }
        },

      /* Generated from convert_proto_tree_add_text.pl */
      { &hf_ssl_pct_client_version, { "Client Version", "ssl.pct.client_version", FT_UINT16, BASE_HEX, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_pad, { "PAD", "ssl.pct.pad", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_client_session_id_data, { "Client Session ID Data", "ssl.pct.client_session_id_data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_challenge_data, { "Challenge Data", "ssl.pct.challenge_data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_ch_offset, { "CH_OFFSET", "ssl.pct.ch_offset", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_cipher_specs_length, { "CIPHER_SPECS Length", "ssl.pct.cipher_specs_length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_hash_specs_length, { "HASH_SPECS Length", "ssl.pct.hash_specs_length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_cert_specs_length, { "CERT_SPECS Length", "ssl.pct.cert_specs_length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_exch_specs_length, { "EXCH_SPECS Length", "ssl.pct.exch_specs_length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_iv_length, { "IV Length", "ssl.pct.iv_length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_encryption_key_length, { "Encryption key length", "ssl.pct.encryption_key_length", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_mac_key_length_in_bits, { "MAC key length in bits", "ssl.pct.mac_key_length_in_bits", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_iv_data, { "IV data", "ssl.pct.iv_data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_server_version, { "Server Version", "ssl.pct.server_version", FT_UINT16, BASE_HEX, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_sh_restart_session_ok_flag, { "SH_RESTART_SESSION_OK flag", "ssl.pct.sh_restart_session_ok_flag", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_sh_client_auth_req_flag, { "SH_CLIENT_AUTH_REQ flag", "ssl.pct.sh_client_auth_req_flag", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_connection_id_data, { "Connection ID Data", "ssl.connection_id_data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_server_certificate_length, { "Server Certificate Length", "ssl.pct.server_certificate_length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_client_cert_specs_length, { "Client CERT_SPECS Length", "ssl.pct.client_cert_specs_length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_client_sig_specs_length, { "Client SIG_SPECS Length", "ssl.pct.client_sig_specs_length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_response_length, { "Response Length", "ssl.pct.response_length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_client_cert_specs, { "Client CERT_SPECS", "ssl.pct.client_cert_specs", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_client_signature, { "Client Signature", "ssl.pct.client_signature", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_server_response, { "Server Response", "ssl.pct.server_response", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_clear_key_length, { "Clear Key Length", "ssl.pct.clear_key_length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_encrypted_key_length, { "Encrypted Key Length", "ssl.pct.encrypted_key_length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_verify_prelude_length, { "Verify Prelude Length", "ssl.pct.verify_prelude_length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_client_cert_length, { "Client Cert Length", "ssl.pct.client_cert_length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_clear_key_data, { "Clear Key data", "ssl.pct.clear_key_data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_encrypted_key_data, { "Encrypted Key data", "ssl.pct.encrypted_key_data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_verify_prelude_data, { "Verify Prelude data", "ssl.pct.verify_prelude_data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_client_certificate_data, { "Client Certificate data", "ssl.pct.client_certificate_data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_response_data, { "Response data", "ssl.pct.response_data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_server_session_id_data, { "Server Session ID data", "ssl.pct.server_session_id_data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_server_response_length, { "Server Response Length", "ssl.pct.server_response_length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_error_information_length, { "Error Information Length", "ssl.pct.error_information_length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_specs_mismatch_cipher, { "SPECS_MISMATCH_CIPHER", "ssl.pct.specs_mismatch_cipher", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_specs_mismatch_hash, { "SPECS_MISMATCH_HASH", "ssl.pct.specs_mismatch_hash", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_specs_mismatch_cert, { "SPECS_MISMATCH_CERT", "ssl.pct.specs_mismatch_cert", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_specs_mismatch_exch, { "SPECS_MISMATCH_EXCH", "ssl.pct.specs_mismatch_exch", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_specs_mismatch_client_cert, { "SPECS_MISMATCH_CLIENT_CERT", "ssl.pct.specs_mismatch_client_cert", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_specs_mismatch_client_sig, { "SPECS_MISMATCH_CLIENT_SIG", "ssl.pct.specs_mismatch_client_sig", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL }},
      { &hf_ssl_pct_error_information_data, { "Error Information data", "ssl.pct.error_information_data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},


        { &hf_ssl_segment_overlap,
          { "Segment overlap", "ssl.segment.overlap",
            FT_BOOLEAN, BASE_NONE, NULL, 0x0,
            "Segment overlaps with other segments", HFILL }},

        { &hf_ssl_segment_overlap_conflict,
          { "Conflicting data in segment overlap", "ssl.segment.overlap.conflict",
            FT_BOOLEAN, BASE_NONE, NULL, 0x0,
            "Overlapping segments contained conflicting data", HFILL }},

        { &hf_ssl_segment_multiple_tails,
          { "Multiple tail segments found", "ssl.segment.multipletails",
            FT_BOOLEAN, BASE_NONE, NULL, 0x0,
            "Several tails were found when reassembling the pdu", HFILL }},

        { &hf_ssl_segment_too_long_fragment,
          { "Segment too long", "ssl.segment.toolongfragment",
            FT_BOOLEAN, BASE_NONE, NULL, 0x0,
            "Segment contained data past end of the pdu", HFILL }},

        { &hf_ssl_segment_error,
          { "Reassembling error", "ssl.segment.error",
            FT_FRAMENUM, BASE_NONE, NULL, 0x0,
            "Reassembling error due to illegal segments", HFILL }},

        { &hf_ssl_segment_count,
          { "Segment count", "ssl.segment.count",
            FT_UINT32, BASE_DEC, NULL, 0x0,
            NULL, HFILL }},

        { &hf_ssl_segment,
          { "SSL segment", "ssl.segment",
            FT_FRAMENUM, BASE_NONE, NULL, 0x0,
            NULL, HFILL }},

        { &hf_ssl_segments,
          { "Reassembled SSL segments", "ssl.segments",
            FT_NONE, BASE_NONE, NULL, 0x0,
            "SSL Segments", HFILL }},

        { &hf_ssl_reassembled_in,
          { "Reassembled PDU in frame", "ssl.reassembled_in",
            FT_FRAMENUM, BASE_NONE, NULL, 0x0,
            "The PDU that doesn't end in this segment is reassembled in this frame", HFILL }},

        { &hf_ssl_reassembled_length,
          { "Reassembled PDU length", "ssl.reassembled.length",
            FT_UINT32, BASE_DEC, NULL, 0x0,
            "The total length of the reassembled payload", HFILL }},

        { &hf_ssl_reassembled_data,
          { "Reassembled PDU data", "ssl.reassembled.data",
            FT_BYTES, BASE_NONE, NULL, 0x00,
            "The payload of multiple reassembled SSL segments", HFILL }},

        { &hf_ssl_segment_data,
          { "SSL segment data", "ssl.segment.data",
            FT_BYTES, BASE_NONE, NULL, 0x00,
            "The payload of a single SSL segment", HFILL }
        },
        SSL_COMMON_HF_LIST(dissect_ssl3_hf, "ssl")
    };

    /* Setup protocol subtree array */
    static gint *ett[] = {
        &ett_ssl,
        &ett_ssl_record,
        &ett_ssl_alert,
        &ett_ssl_handshake,
        &ett_ssl_heartbeat,
        &ett_ssl_certs,
        &ett_pct_cipher_suites,
        &ett_pct_hash_suites,
        &ett_pct_cert_suites,
        &ett_pct_exch_suites,
        &ett_ssl_segments,
        &ett_ssl_segment,
        SSL_COMMON_ETT_LIST(dissect_ssl3_hf)
    };

    static ei_register_info ei[] = {
        { &ei_ssl2_handshake_session_id_len_error, { "ssl.handshake.session_id_length.error", PI_MALFORMED, PI_ERROR, "Session ID length error", EXPFILL }},
        { &ei_ssl3_heartbeat_payload_length, { "ssl.heartbeat_message.payload_length.invalid", PI_MALFORMED, PI_ERROR, "Invalid heartbeat payload length", EXPFILL }},
        { &ei_tls_unexpected_message, { "ssl.unexpected_message", PI_PROTOCOL, PI_ERROR, "Unexpected message", EXPFILL }},

      /* Generated from convert_proto_tree_add_text.pl */
      { &ei_ssl_ignored_unknown_record, { "ssl.ignored_unknown_record", PI_PROTOCOL, PI_WARN, "Ignored Unknown Record", EXPFILL }},
      { &ei_ssl_pct_client_version, { "ssl.pct.client_version.invalid", PI_PROTOCOL, PI_WARN, "Client Version invalid", EXPFILL }},
      { &ei_ssl_pct_ch_offset, { "ssl.pct.ch_offset.invalid", PI_PROTOCOL, PI_WARN, "CH_OFFSET invalid", EXPFILL }},
      { &ei_ssl_pct_server_version, { "ssl.pct.server_version.invalid", PI_PROTOCOL, PI_WARN, "Server Version invalid", EXPFILL }},

        SSL_COMMON_EI_LIST(dissect_ssl3_hf, "ssl")
    };

    static build_valid_func ssl_da_src_values[1] = {ssl_src_value};
    static build_valid_func ssl_da_dst_values[1] = {ssl_dst_value};
    static build_valid_func ssl_da_both_values[2] = {ssl_src_value, ssl_dst_value};
    static decode_as_value_t ssl_da_values[3] = {{ssl_src_prompt, 1, ssl_da_src_values}, {ssl_dst_prompt, 1, ssl_da_dst_values}, {ssl_both_prompt, 2, ssl_da_both_values}};
    static decode_as_t ssl_da = {"ssl", "Transport", "ssl.port", 3, 2, ssl_da_values, "TCP", "port(s) as",
                                 decode_as_default_populate_list, decode_as_default_reset, decode_as_default_change, NULL};

    expert_module_t* expert_ssl;

    /* Register the protocol name and description */
    proto_ssl = proto_register_protocol("Secure Sockets Layer",
                                        "SSL", "ssl");

    ssl_associations = register_dissector_table("ssl.port", "SSL Port", proto_ssl, FT_UINT16, BASE_DEC);

    /* Required function calls to register the header fields and
     * subtrees used */
    proto_register_field_array(proto_ssl, hf, array_length(hf));
    proto_register_subtree_array(ett, array_length(ett));
    expert_ssl = expert_register_protocol(proto_ssl);
    expert_register_field_array(expert_ssl, ei, array_length(ei));

    {
        module_t *ssl_module = prefs_register_protocol(proto_ssl, proto_reg_handoff_ssl);

#ifdef HAVE_LIBGNUTLS
        static uat_field_t sslkeylist_uats_flds[] = {
            UAT_FLD_CSTRING_OTHER(sslkeylist_uats, ipaddr, "IP address", ssldecrypt_uat_fld_ip_chk_cb, "IPv4 or IPv6 address (unused)"),
            UAT_FLD_CSTRING_OTHER(sslkeylist_uats, port, "Port", ssldecrypt_uat_fld_port_chk_cb, "Port Number (optional)"),
            UAT_FLD_CSTRING_OTHER(sslkeylist_uats, protocol, "Protocol", ssldecrypt_uat_fld_protocol_chk_cb, "Application Layer Protocol (optional)"),
            UAT_FLD_FILENAME_OTHER(sslkeylist_uats, keyfile, "Key File", ssldecrypt_uat_fld_fileopen_chk_cb, "Private keyfile."),
            UAT_FLD_CSTRING_OTHER(sslkeylist_uats, password,"Password", ssldecrypt_uat_fld_password_chk_cb, "Password (for PCKS#12 keyfile)"),
            UAT_END_FIELDS
        };

        ssldecrypt_uat = uat_new("SSL Decrypt",
            sizeof(ssldecrypt_assoc_t),
            "ssl_keys",                     /* filename */
            TRUE,                           /* from_profile */
            &sslkeylist_uats,               /* data_ptr */
            &nssldecrypt,                   /* numitems_ptr */
            UAT_AFFECTS_DISSECTION,         /* affects dissection of packets, but not set of named fields */
            NULL,                           /* Help section (currently a wiki page) */
            ssldecrypt_copy_cb,
            NULL,
            ssldecrypt_free_cb,
            ssl_parse_uat,
            ssl_reset_uat,
            sslkeylist_uats_flds);

        prefs_register_uat_preference(ssl_module, "key_table",
            "RSA keys list",
            "A table of RSA keys for SSL decryption",
            ssldecrypt_uat);
#endif /* HAVE_LIBGNUTLS */

        prefs_register_filename_preference(ssl_module, "debug_file", "SSL debug file",
            "Redirect SSL debug to the file specified. Leave empty to disable debugging "
            "or use \"" SSL_DEBUG_USE_STDERR "\" to redirect output to stderr.",
            &ssl_debug_file_name, TRUE);

        prefs_register_string_preference(ssl_module, "keys_list", "RSA keys list (deprecated)",
             "Semicolon-separated list of private RSA keys used for SSL decryption. "
             "Used by versions of Wireshark prior to 1.6",
             &ssl_keys_list);

        prefs_register_bool_preference(ssl_module,
             "desegment_ssl_records",
             "Reassemble SSL records spanning multiple TCP segments",
             "Whether the SSL dissector should reassemble SSL records spanning multiple TCP segments. "
             "To use this option, you must also enable \"Allow subdissectors to reassemble TCP streams\" in the TCP protocol settings.",
             &ssl_desegment);
        prefs_register_bool_preference(ssl_module,
             "desegment_ssl_application_data",
             "Reassemble SSL Application Data spanning multiple SSL records",
             "Whether the SSL dissector should reassemble SSL Application Data spanning multiple SSL records. ",
             &ssl_desegment_app_data);
        prefs_register_bool_preference(ssl_module,
             "ignore_ssl_mac_failed",
             "Message Authentication Code (MAC), ignore \"mac failed\"",
             "For troubleshooting ignore the mac check result and decrypt also if the Message Authentication Code (MAC) fails.",
             &ssl_ignore_mac_failed);
        ssl_common_register_options(ssl_module, &ssl_options);
    }

    /* heuristic dissectors for any premable e.g. CredSSP before RDP */
    ssl_heur_subdissector_list = register_heur_dissector_list("ssl", proto_ssl);

    ssl_handle = register_dissector("ssl", dissect_ssl, proto_ssl);

    register_init_routine(ssl_init);
    register_cleanup_routine(ssl_cleanup);
    reassembly_table_register(&ssl_reassembly_table,
                          &addresses_ports_reassembly_table_functions);
    register_decode_as(&ssl_da);

    /* XXX: this seems unused due to new "Follow SSL" method, remove? */
    ssl_tap = register_tap("ssl");
    ssl_debug_printf("proto_register_ssl: registered tap %s:%d\n",
        "ssl", ssl_tap);

    register_follow_stream(proto_ssl, "ssl", tcp_follow_conv_filter, tcp_follow_index_filter, tcp_follow_address_filter,
                            tcp_port_to_display, ssl_follow_tap_listener);
}

static int dissect_tls_sct_ber(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
{
    guint32 offset = 0;
    /* Skip through tag and length for OCTET STRING encoding. */
    offset = dissect_ber_identifier(pinfo, tree, tvb, offset, NULL, NULL, NULL);
    offset = dissect_ber_length(pinfo, tree, tvb, offset, NULL, NULL);
    /*
     * RFC 6962 (Certificate Transparency) refers to RFC 5246 (TLS 1.2) for the
     * DigitallySigned format, so asssume that version.
     */
    return tls_dissect_sct_list(&dissect_ssl3_hf, tvb, pinfo, tree, offset, tvb_captured_length(tvb), TLSV1DOT2_VERSION);
}

/* If this dissector uses sub-dissector registration add a registration
 * routine.  This format is required because a script is used to find
 * these routines and create the code that calls these routines.
 */
void
proto_reg_handoff_ssl(void)
{

    /* parse key list */
    ssl_parse_uat();
    ssl_parse_old_keys();

    /*
     * XXX the port preferences should probably be removed in favor of Decode
     * As. Then proto_reg_handoff_ssl can be removed from
     * prefs_register_protocol.
     */
    static gboolean initialized = FALSE;
    if (initialized) {
        return;
    }
    initialized = TRUE;

    exported_pdu_tap = find_tap_id(EXPORT_PDU_TAP_NAME_LAYER_7);

    /* Certificate Transparency extensions: 2 (Certificate), 5 (OCSP Response) */
    register_ber_oid_dissector("1.3.6.1.4.1.11129.2.4.2", dissect_tls_sct_ber, proto_ssl, "SignedCertificateTimestampList");
    register_ber_oid_dissector("1.3.6.1.4.1.11129.2.4.5", dissect_tls_sct_ber, proto_ssl, "SignedCertificateTimestampList");

    heur_dissector_add("tcp", dissect_ssl_heur, "SSL/TLS over TCP", "ssl_tcp", proto_ssl, HEURISTIC_ENABLE);
}

void
ssl_dissector_add(guint port, dissector_handle_t handle)
{
    ssl_association_add("ssl.port", ssl_handle, handle, port, TRUE);
}

void
ssl_dissector_delete(guint port, dissector_handle_t handle)
{
    ssl_association_remove("ssl.port", ssl_handle, handle, port, TRUE);
}

/*
 * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
 *
 * Local variables:
 * c-basic-offset: 4
 * tab-width: 8
 * indent-tabs-mode: nil
 * End:
 *
 * vi: set shiftwidth=4 tabstop=8 expandtab:
 * :indentSize=4:tabSize=8:noTabs=true:
 */