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
|
/* -- sslhelper.c -- */
#include "x11vnc.h"
#include "inet.h"
#include "cleanup.h"
#include "screen.h"
#include "scan.h"
#include "connections.h"
#include "sslcmds.h"
#include "unixpw.h"
#define OPENSSL_INETD 1
#define OPENSSL_VNC 2
#define OPENSSL_HTTPS 3
#define OPENSSL_REVERSE 4
#define DO_DH 0
#if LIBVNCSERVER_HAVE_FORK
#if LIBVNCSERVER_HAVE_SYS_WAIT_H && LIBVNCSERVER_HAVE_WAITPID
#define FORK_OK
#endif
#endif
int openssl_sock = -1;
int openssl_port_num = 0;
int https_sock = -1;
pid_t openssl_last_helper_pid = 0;
char *openssl_last_ip = NULL;
static char *certret = NULL;
static int certret_fd = -1;
static mode_t omode;
char *certret_str = NULL;
static char *dhret = NULL;
static int dhret_fd = -1;
char *dhret_str = NULL;
char *new_dh_params = NULL;
void raw_xfer(int csock, int s_in, int s_out);
#if !LIBVNCSERVER_HAVE_LIBSSL
int openssl_present(void) {return 0;}
static void badnews(void) {
use_openssl = 0;
use_stunnel = 0;
rfbLog("** not compiled with libssl OpenSSL support **\n");
clean_up_exit(1);
}
void openssl_init(int isclient) {badnews();}
void openssl_port(void) {badnews();}
void https_port(void) {badnews();}
void check_openssl(void) {if (use_openssl) badnews();}
void check_https(void) {if (use_openssl) badnews();}
void ssl_helper_pid(pid_t pid, int sock) {badnews(); sock = pid;}
void accept_openssl(int mode, int presock) {mode = 0; presock = 0; badnews();}
char *find_openssl_bin(void) {badnews(); return NULL;}
char *get_saved_pem(char *string, int create) {badnews(); return NULL;}
#else
/*
* This is because on older systems both zlib.h and ssl.h define
* 'free_func' nothing we do below (currently) induces an external
* dependency on 'free_func'.
*/
#define free_func my_jolly_little_free_func
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rand.h>
int openssl_present(void);
void openssl_init(int isclient);
void openssl_port(void);
void check_openssl(void);
void check_https(void);
void ssl_helper_pid(pid_t pid, int sock);
void accept_openssl(int mode, int presock);
char *find_openssl_bin(void);
char *get_saved_pem(char *string, int create);
static SSL_CTX *ctx = NULL;
static RSA *rsa_512 = NULL;
static RSA *rsa_1024 = NULL;
static SSL *ssl = NULL;
static X509_STORE *revocation_store = NULL;
static void init_prng(void);
static void sslerrexit(void);
static char *get_input(char *tag, char **in);
static char *create_tmp_pem(char *path, int prompt);
static int ssl_init(int s_in, int s_out);
static void ssl_xfer(int csock, int s_in, int s_out, int is_https);
#ifndef FORK_OK
void openssl_init(int isclient) {
rfbLog("openssl_init: fork is not supported. cannot create"
" ssl helper process.\n");
clean_up_exit(1);
}
int openssl_present(void) {return 0;}
#else
int openssl_present(void) {return 1;}
static void sslerrexit(void) {
unsigned long err = ERR_get_error();
if (err) {
char str[256];
ERR_error_string(err, str);
fprintf(stderr, "ssl error: %s\n", str);
}
clean_up_exit(1);
}
char *get_saved_pem(char *save, int create) {
char *s = NULL, *path, *cdir, *tmp;
int prompt = 0, len;
struct stat sbuf;
if (! save) {
rfbLog("get_saved_pem: save string is null.\n");
clean_up_exit(1);
}
if (strstr(save, "SAVE_PROMPT") == save) {
prompt = 1;
s = save + strlen("SAVE_PROMPT");
} else if (strstr(save, "SAVE_NOPROMPT") == save) {
set_env("GENCERT_NOPROMPT", "1");
s = save + strlen("SAVE_NOPROMPT");
} else if (strstr(save, "SAVE") == save) {
s = save + strlen("SAVE");
} else {
rfbLog("get_saved_pem: invalid save string: %s\n", save);
clean_up_exit(1);
}
if (strchr(s, '/')) {
rfbLog("get_saved_pem: invalid save string: %s\n", s);
clean_up_exit(1);
}
cdir = get_Cert_dir(NULL, &tmp);
if (! cdir || ! tmp) {
rfbLog("get_saved_pem: could not find Cert dir.\n");
clean_up_exit(1);
}
len = strlen(cdir) + strlen("/server.pem") + strlen(s) + 1;
path = (char *) malloc(len);
sprintf(path, "%s/server%s.pem", cdir, s);
if (stat(path, &sbuf) != 0) {
char *new = NULL;
if (create) {
new = create_tmp_pem(path, prompt);
if (! getenv("X11VNC_SSL_NO_PASSPHRASE") && ! inetd) {
sslEncKey(new, 0);
}
}
return new;
}
if (! quiet) {
char line[1024];
int on = 0;
FILE *in = fopen(path, "r");
if (in != NULL) {
rfbLog("\n");
rfbLog("Using SSL Certificate:\n");
fprintf(stderr, "\n");
while (fgets(line, 1024, in) != NULL) {
if (strstr(line, "BEGIN CERTIFICATE")) {
on = 1;
}
if (on) {
fprintf(stderr, "%s", line);
}
if (strstr(line, "END CERTIFICATE")) {
on = 0;
}
if (strstr(line, "PRIVATE KEY")) {
on = 0;
}
}
fprintf(stderr, "\n");
fclose(in);
}
}
return strdup(path);
}
static char *get_input(char *tag, char **in) {
char line[1024], *str;
if (! tag || ! in || ! *in) {
return NULL;
}
fprintf(stderr, "%s:\n [%s] ", tag, *in);
if (fgets(line, 1024, stdin) == NULL) {
rfbLog("could not read stdin!\n");
rfbLogPerror("fgets");
clean_up_exit(1);
}
if ((str = strrchr(line, '\n')) != NULL) {
*str = '\0';
}
str = lblanks(line);
if (!strcmp(str, "")) {
return *in;
} else {
return strdup(line);
}
}
char *find_openssl_bin(void) {
char *path, *exe, *p, *gp;
struct stat sbuf;
int found_openssl = 0;
char extra[] = ":/usr/bin:/bin:/usr/sbin:/usr/local/bin"
":/usr/local/sbin:/usr/sfw/bin";
gp = getenv("PATH");
if (! gp) {
fprintf(stderr, "could not find openssl(1) program in PATH.\n");
return NULL;
}
path = (char *) malloc(strlen(gp) + strlen(extra) + 1);
strcpy(path, gp);
strcat(path, extra);
/* find openssl binary: */
exe = (char *) malloc(strlen(path) + strlen("/openssl") + 1);
p = strtok(path, ":");
while (p) {
sprintf(exe, "%s/openssl", p);
if (stat(exe, &sbuf) == 0) {
if (! S_ISDIR(sbuf.st_mode)) {
found_openssl = 1;
break;
}
}
p = strtok(NULL, ":");
}
free(path);
if (! found_openssl) {
fprintf(stderr, "could not find openssl(1) program in PATH.\n");
fprintf(stderr, "(also checked: %s)\n", extra);
return NULL;
}
return exe;
}
/* uses /usr/bin/openssl to create a tmp cert */
static char *create_tmp_pem(char *pathin, int prompt) {
pid_t pid, pidw;
FILE *in, *out;
char cnf[] = "/tmp/x11vnc-cnf.XXXXXX";
char pem[] = "/tmp/x11vnc-pem.XXXXXX";
char str[8*1024], line[1024], *exe;
int cnf_fd, pem_fd, status, show_cert = 1;
char *days;
char *C, *L, *OU, *O, *CN, *EM;
char tmpl[] =
"[ req ]\n"
"prompt = no\n"
"default_bits = 2048\n"
"encrypt_key = yes\n"
"distinguished_name = req_dn\n"
"x509_extensions = cert_type\n"
"\n"
"[ req_dn ]\n"
"countryName=%s\n"
"localityName=%s\n"
"organizationalUnitName=%s\n"
"organizationName=%s\n"
"commonName=%s\n"
"emailAddress=%s\n"
"\n"
"[ cert_type ]\n"
"nsCertType = server\n"
;
C = strdup("AU");
L = strdup(UT.sysname ? UT.sysname : "unknown-os");
snprintf(line, 1024, "%s-%f", UT.nodename ? UT.nodename :
"unknown-node", dnow());
line[1024-1] = '\0';
OU = strdup(line);
O = strdup("x11vnc");
if (pathin) {
snprintf(line, 1024, "x11vnc-SELF-SIGNED-CERT-%d", getpid());
} else {
snprintf(line, 1024, "x11vnc-SELF-SIGNED-TEMPORARY-CERT-%d",
getpid());
}
line[1024-1] = '\0';
CN = strdup(line);
EM = strdup("x11vnc@server.nowhere");
/* ssl */
if (no_external_cmds || !cmd_ok("ssl")) {
rfbLog("create_tmp_pem: cannot run external commands.\n");
return NULL;
}
rfbLog("\n");
if (pathin) {
rfbLog("Creating a self-signed PEM certificate...\n");
} else {
rfbLog("Creating a temporary, self-signed PEM certificate...\n");
}
rfbLog("\n");
rfbLog("This will NOT prevent Man-In-The-Middle attacks UNLESS you\n");
rfbLog("get the certificate information to the VNC viewers SSL\n");
rfbLog("tunnel configuration or you take the extra steps to sign it\n");
rfbLog("with a CA key. However, it will prevent passive network\n");
rfbLog("sniffing.\n");
rfbLog("\n");
rfbLog("The cert inside -----BEGIN CERTIFICATE-----\n");
rfbLog(" ....\n");
rfbLog(" -----END CERTIFICATE-----\n");
rfbLog("printed below may be used on the VNC viewer-side to\n");
rfbLog("authenticate this server for this session. See the -ssl\n");
rfbLog("help output and the FAQ for how to create a permanent\n");
rfbLog("server certificate.\n");
rfbLog("\n");
exe = find_openssl_bin();
if (! exe) {
return NULL;
}
/* create template file with our made up stuff: */
if (prompt) {
fprintf(stderr, "\nReply to the following prompts to set"
" your Certificate parameters.\n");
fprintf(stderr, "(press Enter to accept the default in [...], "
"or type in the value you want)\n\n");
C = get_input("CountryName", &C);
L = get_input("LocalityName", &L);
OU = get_input("OrganizationalUnitName", &OU);
O = get_input("OrganizationalName", &O);
CN = get_input("CommonName", &CN);
EM = get_input("EmailAddress", &EM);
}
sprintf(str, tmpl, C, L, OU, O, CN, EM);
cnf_fd = mkstemp(cnf);
pem_fd = mkstemp(pem);
if (cnf_fd < 0 || pem_fd < 0) {
return NULL;
}
close(pem_fd);
write(cnf_fd, str, strlen(str));
close(cnf_fd);
if (pathin) {
days = "365";
} else {
days = "30";
}
/* make RSA key */
pid = fork();
if (pid < 0) {
return NULL;
} else if (pid == 0) {
int i;
for (i=0; i<256; i++) {
close(i);
}
execlp(exe, exe, "req", "-new", "-x509", "-nodes",
"-days", days, "-config", cnf, "-out", pem,
"-keyout", pem, (char *)0);
exit(1);
}
pidw = waitpid(pid, &status, 0);
if (pidw != pid) {
return NULL;
}
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
;
} else {
return NULL;
}
#if DO_DH
/* make DH parameters */
pid = fork();
if (pid < 0) {
return NULL;
} else if (pid == 0) {
int i;
for (i=0; i<256; i++) {
close(i);
}
/* rather slow at 1024 */
execlp(exe, exe, "dhparam", "-out", cnf, "512", (char *)0);
exit(1);
}
pidw = waitpid(pid, &status, 0);
if (pidw != pid) {
return NULL;
}
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
;
} else {
return NULL;
}
/* append result: */
in = fopen(cnf, "r");
if (in == NULL) {
return NULL;
}
out = fopen(pem, "a");
if (out == NULL) {
fclose(in);
return NULL;
}
while (fgets(line, 1024, in) != NULL) {
fprintf(out, "%s", line);
}
fclose(in);
fclose(out);
#endif
unlink(cnf);
free(exe);
if (pathin != NULL) {
char *q, *pathcrt = strdup(pathin);
FILE *crt = NULL;
int on = 0;
q = strrchr(pathcrt, '/');
if (q) {
q = strstr(q, ".pem");
if (q) {
*(q+1) = 'c';
*(q+2) = 'r';
*(q+3) = 't';
crt = fopen(pathcrt, "w");
}
}
if (crt == NULL) {
rfbLog("could not open: %s\n", pathcrt);
rfbLogPerror("fopen");
return NULL;
}
out = fopen(pathin, "w");
chmod(pathin, 0600);
if (out == NULL) {
rfbLog("could not open: %s\n", pathin);
rfbLogPerror("fopen");
fclose(crt);
return NULL;
}
in = fopen(pem, "r");
if (in == NULL) {
rfbLog("could not open: %s\n", pem);
rfbLogPerror("fopen");
fclose(out);
fclose(crt);
unlink(pathin);
unlink(pathcrt);
return NULL;
}
while (fgets(line, 1024, in) != NULL) {
if (strstr(line, "BEGIN CERTIFICATE")) {
on = 1;
}
fprintf(out, "%s", line);
if (on) {
fprintf(crt, "%s", line);
if (!quiet) {
fprintf(stderr, "%s", line);
}
}
if (strstr(line, "END CERTIFICATE")) {
on = 0;
}
if (strstr(line, "PRIVATE KEY")) {
on = 0;
}
}
fclose(in);
fclose(out);
fclose(crt);
}
if (show_cert) {
char cmd[100];
if (inetd) {
sprintf(cmd, "openssl x509 -text -in '%s' 1>&2", pem);
} else {
sprintf(cmd, "openssl x509 -text -in '%s'", pem);
}
fprintf(stderr, "\n");
system(cmd);
fprintf(stderr, "\n");
}
if (pathin) {
unlink(pem);
return strdup(pathin);
} else {
return strdup(pem);
}
}
static int pem_passwd_callback(char *buf, int size, int rwflag,
void *userdata) {
char *q, line[1024];
if (! buf) {
exit(1);
}
fprintf(stderr, "\nA passphrase is needed to unlock an OpenSSL "
"private key (PEM file).\n");
fprintf(stderr, "Enter passphrase> ");
system("stty -echo");
if(fgets(line, 1024, stdin) == NULL) {
fprintf(stdout, "\n");
system("stty echo");
exit(1);
}
system("stty echo");
fprintf(stdout, "\n\n");
q = strrchr(line, '\n');
if (q) {
*q = '\0';
}
line[1024 - 1] = '\0';
strncpy(buf, line, size);
buf[size - 1] = '\0';
if (0) rwflag = 0; /* compiler warning. */
if (0) userdata = 0; /* compiler warning. */
return strlen(buf);
}
static int appendfile(FILE *out, char *infile) {
char line[1024];
FILE *in;
if (! infile) {
rfbLog("appendfile: null infile.\n");
return 0;
}
if (! out) {
rfbLog("appendfile: null out handle.\n");
return 0;
}
in = fopen(infile, "r");
if (in == NULL) {
rfbLog("appendfile: %s\n", infile);
rfbLogPerror("fopen");
return 0;
}
while (fgets(line, 1024, in) != NULL) {
fprintf(out, "%s", line);
}
fclose(in);
return 1;
}
static char *get_ssl_verify_file(char *str_in) {
char *p, *str, *cdir, *tmp;
char *tfile, *tfile2;
FILE *file;
struct stat sbuf;
int count = 0, fd;
if (! str_in) {
rfbLog("get_ssl_verify_file: no filename\n");
exit(1);
}
if (stat(str_in, &sbuf) == 0) {
/* assume he knows what he is doing. */
return str_in;
}
cdir = get_Cert_dir(NULL, &tmp);
if (! cdir || ! tmp) {
rfbLog("get_ssl_verify_file: invalid cert-dir.\n");
exit(1);
}
tfile = (char *) malloc(strlen(tmp) + 1024);
tfile2 = (char *) malloc(strlen(tmp) + 1024);
sprintf(tfile, "%s/sslverify-load-%d.crts.XXXXXX", tmp, getpid());
fd = mkstemp(tfile);
if (fd < 0) {
rfbLog("get_ssl_verify_file: %s\n", tfile);
rfbLogPerror("mkstemp");
exit(1);
}
close(fd);
file = fopen(tfile, "w");
chmod(tfile, 0600);
if (file == NULL) {
rfbLog("get_ssl_verify_file: %s\n", tfile);
rfbLogPerror("fopen");
exit(1);
}
str = strdup(str_in);
p = strtok(str, ",");
while (p) {
if (!strcmp(p, "CA")) {
sprintf(tfile2, "%s/CA/cacert.pem", cdir);
if (! appendfile(file, tfile2)) {
unlink(tfile);
exit(1);
}
rfbLog("sslverify: loaded %s\n", tfile2);
count++;
} else if (!strcmp(p, "clients")) {
DIR *dir;
struct dirent *dp;
sprintf(tfile2, "%s/clients", cdir);
dir = opendir(tfile2);
if (! dir) {
rfbLog("get_ssl_verify_file: %s\n", tfile2);
rfbLogPerror("opendir");
unlink(tfile);
exit(1);
}
while ( (dp = readdir(dir)) != NULL) {
char *n = dp->d_name;
char *q = strstr(n, ".crt");
if (! q || strlen(q) != strlen(".crt")) {
continue;
}
if (strlen(n) > 512) {
continue;
}
sprintf(tfile2, "%s/clients/%s", cdir, n);
if (! appendfile(file, tfile2)) {
unlink(tfile);
exit(1);
}
rfbLog("sslverify: loaded %s\n",
tfile2);
count++;
}
closedir(dir);
} else {
if (strlen(p) > 512) {
unlink(tfile);
exit(1);
}
sprintf(tfile2, "%s/clients/%s.crt", cdir, p);
if (stat(tfile2, &sbuf) != 0) {
sprintf(tfile2, "%s/clients/%s", cdir, p);
}
if (! appendfile(file, tfile2)) {
unlink(tfile);
exit(1);
}
rfbLog("sslverify: loaded %s\n", tfile2);
count++;
}
p = strtok(NULL, ",");
}
fclose(file);
free(tfile2);
free(str);
rfbLog("sslverify: using %d client certs in\n", count);
rfbLog("sslverify: %s\n", tfile);
return tfile;
}
/* based on mod_ssl */
static int crl_callback(X509_STORE_CTX *callback_ctx) {
X509_STORE_CTX store_ctx;
X509_OBJECT obj;
X509_NAME *subject;
X509_NAME *issuer;
X509 *xs;
X509_CRL *crl;
X509_REVOKED *revoked;
EVP_PKEY *pubkey;
long serial;
BIO *bio;
int i, n, rc;
char *cp, *cp2;
ASN1_TIME *t;
/* Determine certificate ingredients in advance */
xs = X509_STORE_CTX_get_current_cert(callback_ctx);
subject = X509_get_subject_name(xs);
issuer = X509_get_issuer_name(xs);
/* Try to retrieve a CRL corresponding to the _subject_ of
* the current certificate in order to verify it's integrity. */
memset((char *)&obj, 0, sizeof(obj));
X509_STORE_CTX_init(&store_ctx, revocation_store, NULL, NULL);
rc=X509_STORE_get_by_subject(&store_ctx, X509_LU_CRL, subject, &obj);
X509_STORE_CTX_cleanup(&store_ctx);
crl=obj.data.crl;
if(rc>0 && crl) {
/* Log information about CRL
* (A little bit complicated because of ASN.1 and BIOs...) */
bio=BIO_new(BIO_s_mem());
BIO_printf(bio, "lastUpdate: ");
ASN1_UTCTIME_print(bio, X509_CRL_get_lastUpdate(crl));
BIO_printf(bio, ", nextUpdate: ");
ASN1_UTCTIME_print(bio, X509_CRL_get_nextUpdate(crl));
n=BIO_pending(bio);
cp=malloc(n+1);
n=BIO_read(bio, cp, n);
cp[n]='\0';
BIO_free(bio);
cp2=X509_NAME_oneline(subject, NULL, 0);
rfbLog("CA CRL: Issuer: %s, %s\n", cp2, cp);
OPENSSL_free(cp2);
free(cp);
/* Verify the signature on this CRL */
pubkey=X509_get_pubkey(xs);
if(X509_CRL_verify(crl, pubkey)<=0) {
rfbLog("Invalid signature on CRL\n");
X509_STORE_CTX_set_error(callback_ctx,
X509_V_ERR_CRL_SIGNATURE_FAILURE);
X509_OBJECT_free_contents(&obj);
if(pubkey)
EVP_PKEY_free(pubkey);
return 0; /* Reject connection */
}
if(pubkey)
EVP_PKEY_free(pubkey);
/* Check date of CRL to make sure it's not expired */
t=X509_CRL_get_nextUpdate(crl);
if(!t) {
rfbLog("Found CRL has invalid nextUpdate field\n");
X509_STORE_CTX_set_error(callback_ctx,
X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD);
X509_OBJECT_free_contents(&obj);
return 0; /* Reject connection */
}
if(X509_cmp_current_time(t)<0) {
rfbLog("Found CRL is expired - "
"revoking all certificates until you get updated CRL\n");
X509_STORE_CTX_set_error(callback_ctx, X509_V_ERR_CRL_HAS_EXPIRED);
X509_OBJECT_free_contents(&obj);
return 0; /* Reject connection */
}
X509_OBJECT_free_contents(&obj);
}
/* Try to retrieve a CRL corresponding to the _issuer_ of
* the current certificate in order to check for revocation. */
memset((char *)&obj, 0, sizeof(obj));
X509_STORE_CTX_init(&store_ctx, revocation_store, NULL, NULL);
rc=X509_STORE_get_by_subject(&store_ctx, X509_LU_CRL, issuer, &obj);
X509_STORE_CTX_cleanup(&store_ctx);
crl=obj.data.crl;
if(rc>0 && crl) {
/* Check if the current certificate is revoked by this CRL */
n=sk_X509_REVOKED_num(X509_CRL_get_REVOKED(crl));
for(i=0; i<n; i++) {
revoked=sk_X509_REVOKED_value(X509_CRL_get_REVOKED(crl), i);
if(ASN1_INTEGER_cmp(revoked->serialNumber,
X509_get_serialNumber(xs)) == 0) {
serial=ASN1_INTEGER_get(revoked->serialNumber);
cp=X509_NAME_oneline(issuer, NULL, 0);
rfbLog("Certificate with serial %ld (0x%lX) "
"revoked per CRL from issuer %s\n", serial, serial, cp);
OPENSSL_free(cp);
X509_STORE_CTX_set_error(callback_ctx, X509_V_ERR_CERT_REVOKED);
X509_OBJECT_free_contents(&obj);
return 0; /* Reject connection */
}
}
X509_OBJECT_free_contents(&obj);
}
return 1; /* Accept connection */
}
static int verify_callback(int ok, X509_STORE_CTX *callback_ctx) {
if (!ssl_verify) {
rfbLog("CRL_check: skipped.\n");
return ok;
}
if (!ssl_crl) {
rfbLog("CRL_check: skipped.\n");
return ok;
}
if (!ok) {
rfbLog("CRL_check: client cert is already rejected.\n");
return ok;
}
if (revocation_store) {
if (crl_callback(callback_ctx)) {
rfbLog("CRL_check: succeeded.\n");
return 1;
} else {
rfbLog("CRL_check: did not pass.\n");
return 0;
}
}
/* NOTREACHED */
return 1;
}
#define rfbSecTypeTlsVnc 18
#define rfbSecTypeVencrypt 19
#define rfbVencryptPlain 256
#define rfbVencryptTlsNone 257
#define rfbVencryptTlsVnc 258
#define rfbVencryptTlsPlain 259
#define rfbVencryptX509None 260
#define rfbVencryptX509Vnc 261
#define rfbVencryptX509Plain 262
static int vencrypt_selected = 0;
static int tlsvnc_selected = 0;
static int ssl_client_mode = 0;
static int switch_to_anon_dh(void);
void openssl_init(int isclient) {
int db = 0, tmp_pem = 0, do_dh;
FILE *in;
double ds;
long mode;
static int first = 1;
do_dh = DO_DH;
if (enc_str != NULL) {
if (first) {
init_prng();
}
first = 0;
return;
}
if (! quiet) {
rfbLog("\n");
rfbLog("Initializing SSL (%s connect mode).\n", isclient ? "client":"server");
}
if (first) {
if (db) fprintf(stderr, "\nSSL_load_error_strings()\n");
SSL_load_error_strings();
if (db) fprintf(stderr, "SSL_library_init()\n");
SSL_library_init();
if (db) fprintf(stderr, "init_prng()\n");
init_prng();
first = 0;
}
if (isclient) {
ssl_client_mode = 1;
} else {
ssl_client_mode = 0;
}
if (ssl_client_mode) {
if (db) fprintf(stderr, "SSLv23_client_method()\n");
ctx = SSL_CTX_new( SSLv23_client_method() );
} else {
if (db) fprintf(stderr, "SSLv23_server_method()\n");
ctx = SSL_CTX_new( SSLv23_server_method() );
}
if (ctx == NULL) {
rfbLog("openssl_init: SSL_CTX_new failed.\n");
sslerrexit();
}
ds = dnow();
rsa_512 = RSA_generate_key(512, RSA_F4, NULL, NULL);
if (rsa_512 == NULL) {
rfbLog("openssl_init: RSA_generate_key(512) failed.\n");
sslerrexit();
}
rfbLog("created 512 bit temporary RSA key: %.3fs\n", dnow() - ds);
ds = dnow();
rsa_1024 = RSA_generate_key(1024, RSA_F4, NULL, NULL);
if (rsa_1024 == NULL) {
rfbLog("openssl_init: RSA_generate_key(1024) failed.\n");
sslerrexit();
}
rfbLog("created 1024 bit temporary RSA key: %.3fs\n", dnow() - ds);
if (db) fprintf(stderr, "SSL_CTX_set_tmp_rsa()\n");
if (! SSL_CTX_set_tmp_rsa(ctx, rsa_1024)) {
rfbLog("openssl_init: SSL_CTX_set_tmp_rsa(1024) failed.\n");
sslerrexit();
}
mode = 0;
mode |= SSL_MODE_ENABLE_PARTIAL_WRITE;
mode |= SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
SSL_CTX_set_mode(ctx, mode);
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_BOTH);
SSL_CTX_set_timeout(ctx, 300);
ds = dnow();
if (! openssl_pem) {
openssl_pem = create_tmp_pem(NULL, 0);
if (! openssl_pem) {
rfbLog("openssl_init: could not create temporary,"
" self-signed PEM.\n");
clean_up_exit(1);
}
tmp_pem = 1;
} else if (!strcmp(openssl_pem, "ANON")) {
if (ssl_verify) {
rfbLog("openssl_init: Anonymous Diffie-Hellman cannot"
" be used in -sslverify mode.\n");
clean_up_exit(1);
}
if (ssl_crl) {
rfbLog("openssl_init: Anonymous Diffie-Hellman cannot"
" be used in -sslCRL mode.\n");
clean_up_exit(1);
}
if (!switch_to_anon_dh()) {
rfbLog("openssl_init: Anonymous Diffie-Hellman setup"
" failed.\n");
clean_up_exit(1);
}
} else if (strstr(openssl_pem, "SAVE") == openssl_pem) {
openssl_pem = get_saved_pem(openssl_pem, 1);
if (! openssl_pem) {
rfbLog("openssl_init: could not create or open"
" saved PEM: %s\n", openssl_pem);
clean_up_exit(1);
}
tmp_pem = 0;
}
rfbLog("using PEM %s %.3fs\n", openssl_pem, dnow() - ds);
SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_callback);
if (do_dh) {
DH *dh;
BIO *bio;
ds = dnow();
in = fopen(openssl_pem, "r");
if (in == NULL) {
rfbLogPerror("fopen");
clean_up_exit(1);
}
bio = BIO_new_fp(in, BIO_CLOSE|BIO_FP_TEXT);
if (! bio) {
rfbLog("openssl_init: BIO_new_fp() failed.\n");
sslerrexit();
}
dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
if (dh == NULL) {
rfbLog("openssl_init: PEM_read_bio_DHparams() failed.\n");
BIO_free(bio);
sslerrexit();
}
BIO_free(bio);
SSL_CTX_set_tmp_dh(ctx, dh);
rfbLog("loaded Diffie Hellman %d bits, %.3fs\n",
8*DH_size(dh), dnow()-ds);
DH_free(dh);
}
if (strcmp(openssl_pem, "ANON")) {
if (! SSL_CTX_use_certificate_chain_file(ctx, openssl_pem)) {
rfbLog("openssl_init: SSL_CTX_use_certificate_chain_file() failed.\n");
sslerrexit();
}
if (! SSL_CTX_use_RSAPrivateKey_file(ctx, openssl_pem,
SSL_FILETYPE_PEM)) {
rfbLog("openssl_init: SSL_CTX_set_tmp_rsa(1024) failed.\n");
sslerrexit();
}
if (! SSL_CTX_check_private_key(ctx)) {
rfbLog("openssl_init: SSL_CTX_set_tmp_rsa(1024) failed.\n");
sslerrexit();
}
}
if (tmp_pem && ! getenv("X11VNC_KEEP_TMP_PEM")) {
if (getenv("X11VNC_SHOW_TMP_PEM")) {
FILE *in = fopen(openssl_pem, "r");
if (in != NULL) {
char line[128];
fprintf(stderr, "\n");
while (fgets(line, 128, in) != NULL) {
fprintf(stderr, "%s", line);
}
fprintf(stderr, "\n");
fclose(in);
}
}
unlink(openssl_pem);
free(openssl_pem);
openssl_pem = NULL;
}
if (ssl_crl) {
struct stat sbuf;
X509_LOOKUP *lookup;
if (stat(ssl_crl, &sbuf) != 0) {
rfbLog("openssl_init: -sslCRL does not exist %s.\n",
ssl_crl ? ssl_crl : "null");
rfbLogPerror("stat");
clean_up_exit(1);
}
revocation_store = X509_STORE_new();
if (!revocation_store) {
rfbLog("openssl_init: X509_STORE_new failed.\n");
sslerrexit();
}
if (! S_ISDIR(sbuf.st_mode)) {
lookup = X509_STORE_add_lookup(revocation_store, X509_LOOKUP_file());
if (!lookup) {
rfbLog("openssl_init: X509_STORE_add_lookup failed.\n");
sslerrexit();
}
if (!X509_LOOKUP_load_file(lookup, ssl_crl, X509_FILETYPE_PEM)) {
rfbLog("openssl_init: X509_LOOKUP_load_file failed.\n");
sslerrexit();
}
} else {
lookup = X509_STORE_add_lookup(revocation_store, X509_LOOKUP_hash_dir());
if (!lookup) {
rfbLog("openssl_init: X509_STORE_add_lookup failed.\n");
sslerrexit();
}
if (!X509_LOOKUP_add_dir(lookup, ssl_crl, X509_FILETYPE_PEM)) {
rfbLog("openssl_init: X509_LOOKUP_add_dir failed.\n");
sslerrexit();
}
}
rfbLog("loaded CRL file: %s\n", ssl_crl);
}
if (ssl_verify) {
struct stat sbuf;
char *file;
int lvl;
file = get_ssl_verify_file(ssl_verify);
if (!file || stat(file, &sbuf) != 0) {
rfbLog("openssl_init: -sslverify does not exist %s.\n",
file ? file : "null");
rfbLogPerror("stat");
clean_up_exit(1);
}
if (! S_ISDIR(sbuf.st_mode)) {
if (! SSL_CTX_load_verify_locations(ctx, file, NULL)) {
rfbLog("openssl_init: SSL_CTX_load_verify_"
"locations() failed.\n");
sslerrexit();
}
} else {
if (! SSL_CTX_load_verify_locations(ctx, NULL, file)) {
rfbLog("openssl_init: SSL_CTX_load_verify_"
"locations() failed.\n");
sslerrexit();
}
}
lvl = SSL_VERIFY_FAIL_IF_NO_PEER_CERT|SSL_VERIFY_PEER;
if (ssl_crl == NULL) {
SSL_CTX_set_verify(ctx, lvl, NULL);
} else {
SSL_CTX_set_verify(ctx, lvl, verify_callback);
}
if (strstr(file, "tmp/sslverify-load-")) {
/* temporary file */
unlink(file);
}
} else {
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
}
rfbLog("\n");
}
void openssl_port(void) {
int sock, shutdown = 0;
static int port = 0;
static in_addr_t iface = INADDR_ANY;
int db = 0;
if (! screen) {
rfbLog("openssl_port: no screen!\n");
clean_up_exit(1);
}
if (inetd) {
ssl_initialized = 1;
return;
}
if (screen->listenSock > -1 && screen->port > 0) {
port = screen->port;
shutdown = 1;
}
if (screen->listenInterface) {
iface = screen->listenInterface;
}
if (shutdown) {
if (db) fprintf(stderr, "shutting down %d/%d\n",
port, screen->listenSock);
#if LIBVNCSERVER_HAS_SHUTDOWNSOCKETS
rfbShutdownSockets(screen);
#endif
}
sock = rfbListenOnTCPPort(port, iface);
if (sock < 0) {
rfbLog("openssl_port: could not reopen port %d\n", port);
clean_up_exit(1);
}
rfbLog("openssl_port: listen on port/sock %d/%d\n", port, sock);
if (!quiet) {
announce(port, 1, NULL);
}
openssl_sock = sock;
openssl_port_num = port;
ssl_initialized = 1;
}
void https_port(void) {
int sock;
static int port = 0;
static in_addr_t iface = INADDR_ANY;
int db = 0;
/* as openssl_port above: open a listening socket for pure https: */
if (https_port_num < 0) {
return;
}
if (! screen) {
rfbLog("https_port: no screen!\n");
clean_up_exit(1);
}
if (screen->listenInterface) {
iface = screen->listenInterface;
}
if (https_port_num == 0) {
https_port_num = find_free_port(5801, 5851);
}
if (https_port_num <= 0) {
rfbLog("https_port: could not find port %d\n", https_port_num);
clean_up_exit(1);
}
port = https_port_num;
sock = rfbListenOnTCPPort(port, iface);
if (sock < 0) {
rfbLog("https_port: could not open port %d\n", port);
clean_up_exit(1);
}
if (db) fprintf(stderr, "https_port: listen on port/sock %d/%d\n",
port, sock);
https_sock = sock;
}
static void lose_ram(void) {
/*
* for a forked child that will be around for a long time
* without doing exec(). we really should re-exec, but a pain
* to redo all SSL ctx.
*/
free_old_fb();
free_tiles();
}
/* utility to keep track of existing helper processes: */
void ssl_helper_pid(pid_t pid, int sock) {
# define HPSIZE 256
static pid_t helpers[HPSIZE];
static int sockets[HPSIZE], first = 1;
int i, empty, set, status, db = 0;
if (first) {
for (i=0; i < HPSIZE; i++) {
helpers[i] = 0;
sockets[i] = 0;
}
first = 0;
}
if (pid == 0) {
/* killall */
for (i=0; i < HPSIZE; i++) {
if (helpers[i] == 0) {
sockets[i] = -1;
continue;
}
if (kill(helpers[i], 0) == 0) {
if (sock != -2) {
if (sockets[i] >= 0) {
close(sockets[i]);
}
kill(helpers[i], SIGTERM);
}
#if LIBVNCSERVER_HAVE_SYS_WAIT_H && LIBVNCSERVER_HAVE_WAITPID
if (db) fprintf(stderr, "waitpid(%d)\n", helpers[i]);
waitpid(helpers[i], &status, WNOHANG);
#endif
if (sock == -2) {
continue;
}
}
helpers[i] = 0;
sockets[i] = -1;
}
return;
}
if (db) fprintf(stderr, "ssl_helper_pid(%d, %d)\n", pid, sock);
/* add (or delete for sock == -1) */
set = 0;
empty = -1;
for (i=0; i < HPSIZE; i++) {
if (helpers[i] == pid) {
if (sock == -1) {
#if LIBVNCSERVER_HAVE_SYS_WAIT_H && LIBVNCSERVER_HAVE_WAITPID
if (db) fprintf(stderr, "waitpid(%d) 2\n", helpers[i]);
waitpid(helpers[i], &status, WNOHANG);
#endif
helpers[i] = 0;
}
sockets[i] = sock;
set = 1;
} else if (empty == -1 && helpers[i] == 0) {
empty = i;
}
}
if (set || sock == -1) {
return; /* done */
}
/* now try to store */
if (empty >= 0) {
helpers[empty] = pid;
sockets[empty] = sock;
return;
}
for (i=0; i < HPSIZE; i++) {
if (helpers[i] == 0) {
continue;
}
/* clear out stale pids: */
if (kill(helpers[i], 0) != 0) {
helpers[i] = 0;
sockets[i] = -1;
if (empty == -1) {
empty = i;
}
}
}
if (empty >= 0) {
helpers[empty] = pid;
sockets[empty] = sock;
}
}
static int is_ssl_readable(int s_in, time_t last_https, char *last_get,
int mode) {
int nfd, db = 0;
struct timeval tv;
fd_set rd;
if (getenv("ACCEPT_OPENSSL_DEBUG")) {
db = atoi(getenv("ACCEPT_OPENSSL_DEBUG"));
}
/*
* we'll do a select() on s_in for reading. this is not an
* absolute proof that SSL_read is ready (XXX use SSL utility).
*/
tv.tv_sec = 2;
tv.tv_usec = 0;
if (mode == OPENSSL_INETD) {
/*
* https via inetd is icky because x11vnc is restarted
* for each socket (and some clients send requests
* rapid fire).
*/
tv.tv_sec = 6;
}
/*
* increase the timeout if we know HTTP traffic has occurred
* recently:
*/
if (time(NULL) < last_https + 30) {
tv.tv_sec = 8;
if (last_get && strstr(last_get, "VncViewer")) {
tv.tv_sec = 4;
}
}
if (getenv("X11VNC_HTTPS_VS_VNC_TIMEOUT")) {
tv.tv_sec = atoi(getenv("X11VNC_HTTPS_VS_VNC_TIMEOUT"));
}
if (db) fprintf(stderr, "tv_sec: %d - %s\n", (int) tv.tv_sec, last_get);
FD_ZERO(&rd);
FD_SET(s_in, &rd);
do {
nfd = select(s_in+1, &rd, NULL, NULL, &tv);
} while (nfd < 0 && errno == EINTR);
if (db) fprintf(stderr, "https nfd: %d\n", nfd);
if (nfd <= 0 || ! FD_ISSET(s_in, &rd)) {
return 0;
}
return 1;
}
#define ABSIZE 16384
static int watch_for_http_traffic(char *buf_a, int *n_a, int raw_sock) {
int is_http, err, n, n2;
char *buf;
int db = 0;
/*
* sniff the first couple bytes of the stream and try to see
* if it is http or not. if we read them OK, we must read the
* rest of the available data otherwise we may deadlock.
* what has been read is returned in buf_a and n_a.
* *buf_a is ABSIZE+1 long and zeroed.
*/
if (getenv("ACCEPT_OPENSSL_DEBUG")) {
db = atoi(getenv("ACCEPT_OPENSSL_DEBUG"));
}
if (! buf_a || ! n_a) {
return 0;
}
buf = (char *) calloc((ABSIZE+1), 1);
*n_a = 0;
if (enc_str && !strcmp(enc_str, "none")) {
n = read(raw_sock, buf, 2);
err = SSL_ERROR_NONE;
} else {
n = SSL_read(ssl, buf, 2);
err = SSL_get_error(ssl, n);
}
if (err != SSL_ERROR_NONE || n < 2) {
if (n > 0) {
strncpy(buf_a, buf, n);
*n_a = n;
}
if (db) fprintf(stderr, "watch_for_http_traffic ssl err: %d/%d\n", err, n);
return -1;
}
/* look for GET, HEAD, POST, CONNECT */
is_http = 0;
if (!strncmp("GE", buf, 2)) {
is_http = 1;
} else if (!strncmp("HE", buf, 2)) {
is_http = 1;
} else if (!strncmp("PO", buf, 2)) {
is_http = 1;
} else if (!strncmp("CO", buf, 2)) {
is_http = 1;
}
if (db) fprintf(stderr, "watch_for_http_traffic read: '%s' %d\n", buf, n);
/*
* better read all we can and fwd it along to avoid blocking
* in ssl_xfer().
*/
if (enc_str && !strcmp(enc_str, "none")) {
n2 = read(raw_sock, buf + n, ABSIZE - n);
} else {
n2 = SSL_read(ssl, buf + n, ABSIZE - n);
}
if (n2 >= 0) {
n += n2;
}
*n_a = n;
if (db) fprintf(stderr, "watch_for_http_traffic readmore: %d\n", n2);
if (n > 0) {
memcpy(buf_a, buf, n);
}
if (db > 1) {
fprintf(stderr, "watch_for_http_traffic readmore: ");
write(2, buf_a, *n_a);
fprintf(stderr, "\n");
}
if (db) fprintf(stderr, "watch_for_http_traffic return: %d\n", is_http);
return is_http;
}
static int csock_timeout_sock = -1;
static void csock_timeout (int sig) {
rfbLog("sig: %d, csock_timeout.\n", sig);
if (csock_timeout_sock >= 0) {
close(csock_timeout_sock);
csock_timeout_sock = -1;
}
}
#define PROXY_HACK 0
#if PROXY_HACK
static int wait_conn(int sock) {
int conn;
struct sockaddr_in addr;
#ifdef __hpux
int addrlen = sizeof(addr);
#else
socklen_t addrlen = sizeof(addr);
#endif
signal(SIGALRM, csock_timeout);
csock_timeout_sock = sock;
alarm(15);
conn = accept(sock, (struct sockaddr *)&addr, &addrlen);
alarm(0);
signal(SIGALRM, SIG_DFL);
return conn;
}
/* no longer used */
int proxy_hack(int vncsock, int listen, int s_in, int s_out, char *cookie,
int mode) {
int sock1, db = 0;
char reply[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: octet-stream\r\n"
"Pragma: no-cache\r\n\r\n";
char reply0[] = "HTTP/1.0 200 OK\r\n"
"Content-Type: octet-stream\r\n"
"Content-Length: 9\r\n"
"Pragma: no-cache\r\n\r\nGO_AHEAD\n";
rfbLog("SSL: accept_openssl: detected https proxied connection"
" request.\n");
if (getenv("ACCEPT_OPENSSL_DEBUG")) {
db = atoi(getenv("ACCEPT_OPENSSL_DEBUG"));
}
SSL_write(ssl, reply0, strlen(reply0));
SSL_shutdown(ssl);
SSL_shutdown(ssl);
close(s_in);
close(s_out);
SSL_free(ssl);
if (mode == OPENSSL_VNC) {
listen = openssl_sock;
} else if (mode == OPENSSL_HTTPS) {
listen = https_sock;
} else {
/* inetd */
return 0;
}
sock1 = wait_conn(listen);
if (csock_timeout_sock < 0 || sock1 < 0) {
close(sock1);
return 0;
}
if (db) fprintf(stderr, "got applet input sock1: %d\n", sock1);
if (! ssl_init(sock1, sock1)) {
if (db) fprintf(stderr, "ssl_init FAILED\n");
exit(1);
}
SSL_write(ssl, reply, strlen(reply));
{
char *buf;
int n = 0, ptr = 0;
buf = (char *) calloc((8192+1), 1);
while (ptr < 8192) {
n = SSL_read(ssl, buf + ptr, 8192 - ptr);
if (n > 0) {
ptr += n;
}
if (db) fprintf(stderr, "buf: '%s'\n", buf);
if (strstr(buf, "\r\n\r\n")) {
break;
}
}
}
if (cookie) {
write(vncsock, cookie, strlen(cookie));
}
ssl_xfer(vncsock, sock1, sock1, 0);
return 1;
}
#endif /* PROXY_HACK */
static int check_ssl_access(char *addr) {
static char *save_allow_once = NULL;
static time_t time_allow_once = 0;
/* due to "Fetch Cert" activities for SSL really need to "allow twice" */
if (allow_once != NULL) {
save_allow_once = strdup(allow_once);
time_allow_once = time(NULL);
} else if (save_allow_once != NULL) {
if (getenv("X11VNC_NO_SSL_ALLOW_TWICE")) {
;
} else if (time(NULL) < time_allow_once + 30) {
/* give them 30 secs to check and save the fetched cert. */
allow_once = save_allow_once;
rfbLog("SSL: Permitting 30 sec grace period for allowonce.\n");
rfbLog("SSL: Set X11VNC_NO_SSL_ALLOW_TWICE=1 to disable.\n");
}
save_allow_once = NULL;
time_allow_once = 0;
}
return check_access(addr);
}
static int write_exact(int sock, char *buf, int len);
static int read_exact(int sock, char *buf, int len);
static int finish_auth(rfbClientPtr client, char *type) {
int security_result, ret;
ret = 0;
if (getenv("X11VNC_DEBUG_TLSPLAIN")) fprintf(stderr, "finish_auth type=%s\n", type);
if (!strcmp(type, "None")) {
security_result = 0; /* success */
if (write_exact(client->sock, (char *) &security_result, 4)) {
ret = 1;
}
rfbLog("finish_auth: using auth 'None'\n");
client->state = RFB_INITIALISATION;
} else if (!strcmp(type, "Vnc")) {
RAND_bytes(client->authChallenge, CHALLENGESIZE);
if (write_exact(client->sock, (char *) &client->authChallenge, CHALLENGESIZE)) {
ret = 1;
}
rfbLog("finish_auth: using auth 'Vnc', sent challenge.\n");
client->state = RFB_AUTHENTICATION;
} else if (!strcmp(type, "Plain")) {
if (!unixpw) {
rfbLog("finish_auth: *Plain not allowed outside unixpw mode.\n");
ret = 0;
} else {
char *un, *pw;
int unlen, pwlen;
if (getenv("X11VNC_DEBUG_TLSPLAIN")) fprintf(stderr, "*Plain begin: onHold=%d client=%p unixpw_client=%p\n", client->onHold, (void *) client, (void *) unixpw_client);
if (!read_exact(client->sock, (char *)&unlen, 4)) goto fail;
unlen = Swap32IfLE(unlen);
if (getenv("X11VNC_DEBUG_TLSPLAIN")) fprintf(stderr, "unlen: %d\n", unlen);
if (!read_exact(client->sock, (char *)&pwlen, 4)) goto fail;
pwlen = Swap32IfLE(pwlen);
if (getenv("X11VNC_DEBUG_TLSPLAIN")) fprintf(stderr, "pwlen: %d\n", pwlen);
un = (char *) malloc(unlen+1);
memset(un, 0, unlen+1);
pw = (char *) malloc(pwlen+2);
memset(pw, 0, pwlen+2);
if (!read_exact(client->sock, un, unlen)) goto fail;
if (!read_exact(client->sock, pw, pwlen)) goto fail;
if (getenv("X11VNC_DEBUG_TLSPLAIN")) fprintf(stderr, "*Plain: %d %d '%s' ... \n", unlen, pwlen, un);
strcat(pw, "\n");
if (unixpw_verify(un, pw)) {
security_result = 0; /* success */
if (write_exact(client->sock, (char *) &security_result, 4)) {
ret = 1;
unixpw_verify_screen(un, pw);
}
client->onHold = FALSE;
client->state = RFB_INITIALISATION;
}
if (ret == 0) {
rfbClientSendString(client, "unixpw failed");
}
memset(un, 0, unlen+1);
memset(pw, 0, pwlen+2);
free(un);
free(pw);
}
} else {
rfbLog("finish_auth: unknown sub-type: %s\n", type);
ret = 0;
}
fail:
return ret;
}
static int finish_vencrypt_auth(rfbClientPtr client, int subtype) {
if (subtype == rfbVencryptTlsNone || subtype == rfbVencryptX509None) {
return finish_auth(client, "None");
} else if (subtype == rfbVencryptTlsVnc || subtype == rfbVencryptX509Vnc) {
return finish_auth(client, "Vnc");
} else if (subtype == rfbVencryptTlsPlain || subtype == rfbVencryptX509Plain) {
return finish_auth(client, "Plain");
} else {
rfbLog("finish_vencrypt_auth: unknown sub-type: %d\n", subtype);
return 0;
}
}
void accept_openssl(int mode, int presock) {
int sock = -1, listen = -1, cport, csock, vsock;
int peerport = 0;
int status, n, i, db = 0;
struct sockaddr_in addr;
#ifdef __hpux
int addrlen = sizeof(addr);
#else
socklen_t addrlen = sizeof(addr);
#endif
rfbClientPtr client;
pid_t pid;
char uniq[] = "_evilrats_";
char cookie[256], rcookie[256], *name = NULL;
int vencrypt_sel = 0;
int tlsvnc_sel = 0;
static time_t last_https = 0;
static char last_get[256];
static int first = 1;
unsigned char *rb;
openssl_last_helper_pid = 0;
/* zero buffers for use below. */
for (i=0; i<256; i++) {
if (first) {
last_get[i] = '\0';
}
cookie[i] = '\0';
rcookie[i] = '\0';
}
first = 0;
if (getenv("ACCEPT_OPENSSL_DEBUG")) {
db = atoi(getenv("ACCEPT_OPENSSL_DEBUG"));
}
/* do INETD, VNC, or HTTPS cases (result is client socket or pipe) */
if (mode == OPENSSL_INETD) {
ssl_initialized = 1;
} else if (mode == OPENSSL_VNC) {
sock = accept(openssl_sock, (struct sockaddr *)&addr, &addrlen);
if (sock < 0) {
rfbLog("SSL: accept_openssl: accept connection failed\n");
rfbLogPerror("accept");
if (ssl_no_fail) {
clean_up_exit(1);
}
return;
}
listen = openssl_sock;
} else if (mode == OPENSSL_REVERSE) {
sock = presock;
if (sock < 0) {
rfbLog("SSL: accept_openssl: connection failed\n");
if (ssl_no_fail) {
clean_up_exit(1);
}
return;
}
listen = -1;
} else if (mode == OPENSSL_HTTPS) {
sock = accept(https_sock, (struct sockaddr *)&addr, &addrlen);
if (sock < 0) {
rfbLog("SSL: accept_openssl: accept connection failed\n");
rfbLogPerror("accept");
if (ssl_no_fail) {
clean_up_exit(1);
}
return;
}
listen = https_sock;
}
if (db) fprintf(stderr, "SSL: accept_openssl: sock: %d\n", sock);
if (openssl_last_ip) {
free(openssl_last_ip);
openssl_last_ip = NULL;
}
if (mode == OPENSSL_INETD) {
openssl_last_ip = get_remote_host(fileno(stdin));
} else {
openssl_last_ip = get_remote_host(sock);
}
if (!check_ssl_access(openssl_last_ip)) {
rfbLog("SSL: accept_openssl: denying client %s\n", openssl_last_ip);
rfbLog("SSL: accept_openssl: does not match -allow (or other reason).\n");
close(sock);
sock = -1;
if (ssl_no_fail) {
clean_up_exit(1);
}
return;
}
/* now make a listening socket for child to connect back to us by: */
cport = find_free_port(20000, 0);
if (! cport) {
rfbLog("SSL: accept_openssl: could not find open port.\n");
close(sock);
if (mode == OPENSSL_INETD || ssl_no_fail) {
clean_up_exit(1);
}
return;
}
if (db) fprintf(stderr, "accept_openssl: cport: %d\n", cport);
csock = rfbListenOnTCPPort(cport, htonl(INADDR_LOOPBACK));
if (csock < 0) {
rfbLog("SSL: accept_openssl: could not listen on port %d.\n",
cport);
close(sock);
if (mode == OPENSSL_INETD || ssl_no_fail) {
clean_up_exit(1);
}
return;
}
if (db) fprintf(stderr, "accept_openssl: csock: %d\n", csock);
fflush(stderr);
/*
* make a simple cookie to id the child socket, not foolproof
* but hard to guess exactly (just worrying about local lusers
* here, since we use INADDR_LOOPBACK).
*/
rb = (unsigned char *) malloc(6);
RAND_bytes((char *)rb, 6);
sprintf(cookie, "RB=%d%d%d%d%d%d/%f%f/0x%x",
rb[0], rb[1], rb[2], rb[3], rb[4], rb[5],
dnow() - x11vnc_start, x11vnc_start, rb);
if (mode != OPENSSL_INETD) {
name = get_remote_host(sock);
peerport = get_remote_port(sock);
} else {
openssl_last_ip = get_remote_host(fileno(stdin));
peerport = get_remote_port(fileno(stdin));
if (openssl_last_ip) {
name = strdup(openssl_last_ip);
} else {
name = strdup("unknown");
}
}
if (name) {
if (mode == OPENSSL_INETD) {
rfbLog("SSL: (inetd) spawning helper process "
"to handle: %s:%d\n", name, peerport);
} else {
rfbLog("SSL: spawning helper process to handle: "
"%s:%d\n", name, peerport);
}
free(name);
name = NULL;
}
if (certret) {
free(certret);
}
if (certret_str) {
free(certret_str);
certret_str = NULL;
}
certret = strdup("/tmp/x11vnc-certret.XXXXXX");
omode = umask(077);
certret_fd = mkstemp(certret);
umask(omode);
if (certret_fd < 0) {
free(certret);
certret = NULL;
certret_fd = -1;
}
if (dhret) {
free(dhret);
}
if (dhret_str) {
free(dhret_str);
dhret_str = NULL;
}
dhret = strdup("/tmp/x11vnc-dhret.XXXXXX");
omode = umask(077);
dhret_fd = mkstemp(dhret);
umask(omode);
if (dhret_fd < 0) {
free(dhret);
dhret = NULL;
dhret_fd = -1;
}
/* now fork the child to handle the SSL: */
pid = fork();
if (pid < 0) {
rfbLog("SSL: accept_openssl: could not fork.\n");
rfbLogPerror("fork");
close(sock);
close(csock);
if (mode == OPENSSL_INETD || ssl_no_fail) {
clean_up_exit(1);
}
return;
} else if (pid == 0) {
int s_in, s_out, httpsock = -1;
int vncsock;
int i, have_httpd = 0;
int f_in = fileno(stdin);
int f_out = fileno(stdout);
if (db) fprintf(stderr, "helper pid in: %d %d %d %d\n", f_in, f_out, sock, listen);
/* reset all handlers to default (no interrupted() calls) */
unset_signals();
/* close all non-essential fd's */
for (i=0; i<256; i++) {
if (mode == OPENSSL_INETD) {
if (i == f_in || i == f_out) {
continue;
}
}
if (i == sock) {
continue;
}
if (i == 2) {
continue;
}
close(i);
}
/*
* sadly, we are a long lived child and so the large
* framebuffer memory areas will soon differ from parent.
* try to free as much as possible.
*/
lose_ram();
/* now connect back to parent socket: */
vncsock = rfbConnectToTcpAddr("127.0.0.1", cport);
if (vncsock < 0) {
rfbLog("SSL: ssl_helper[%d]: could not connect"
" back to: %d\n", getpid(), cport);
exit(1);
}
if (db) fprintf(stderr, "vncsock %d\n", vncsock);
/* try to initialize SSL with the remote client */
if (mode == OPENSSL_INETD) {
s_in = fileno(stdin);
s_out = fileno(stdout);
} else {
s_in = s_out = sock;
}
if (! ssl_init(s_in, s_out)) {
close(vncsock);
exit(1);
}
if (vencrypt_selected != 0) {
char *tbuf;
tbuf = (char *) malloc(strlen(cookie) + 100);
sprintf(tbuf, "%s,VENCRYPT=%d,%s", uniq, vencrypt_selected, cookie);
write(vncsock, tbuf, strlen(cookie));
goto wrote_cookie;
} else if (tlsvnc_selected != 0) {
char *tbuf;
tbuf = (char *) malloc(strlen(cookie) + 100);
sprintf(tbuf, "%s,TLSVNC=%d,%s", uniq, tlsvnc_selected, cookie);
write(vncsock, tbuf, strlen(cookie));
goto wrote_cookie;
}
/*
* things get messy below since we are trying to do
* *both* VNC and Java applet httpd through the same
* SSL socket.
*/
if (! screen) {
close(vncsock);
exit(1);
}
if (screen->httpListenSock >= 0 && screen->httpPort > 0) {
have_httpd = 1;
}
if (screen->httpListenSock == -2) {
have_httpd = 1;
}
if (mode == OPENSSL_HTTPS && ! have_httpd) {
rfbLog("SSL: accept_openssl[%d]: no httpd socket for "
"-https mode\n", getpid());
close(vncsock);
exit(1);
}
if (have_httpd) {
int n = 0, is_http;
int hport = screen->httpPort;
char *iface = NULL;
char *buf, *tbuf;
buf = (char *) calloc((ABSIZE+1), 1);
tbuf = (char *) calloc((2*ABSIZE+1), 1);
if (mode == OPENSSL_HTTPS) {
/*
* for this mode we know it is HTTP traffic
* so we skip trying to guess.
*/
is_http = 1;
n = 0;
goto connect_to_httpd;
}
/*
* Check if there is stuff to read from remote end
* if so it is likely a GET or HEAD.
*/
if (! is_ssl_readable(s_in, last_https, last_get,
mode)) {
goto write_cookie;
}
/*
* read first 2 bytes to try to guess. sadly,
* the user is often pondering a "non-verified
* cert" dialog for a long time before the GET
* is ever sent. So often we timeout here.
*/
if (db) fprintf(stderr, "watch_for_http_traffic\n");
is_http = watch_for_http_traffic(buf, &n, s_in);
if (is_http < 0 || is_http == 0) {
/*
* error or http not detected, fall back
* to normal VNC socket.
*/
if (db) fprintf(stderr, "is_http err: %d n: %d\n", is_http, n);
write(vncsock, cookie, strlen(cookie));
if (n > 0) {
write(vncsock, buf, n);
}
goto wrote_cookie;
}
if (db) fprintf(stderr, "is_http: %d n: %d\n",
is_http, n);
if (db) fprintf(stderr, "buf: '%s'\n", buf);
if (strstr(buf, "/request.https.vnc.connection")) {
char reply[] = "HTTP/1.0 200 OK\r\n"
"Content-Type: octet-stream\r\n"
"Connection: Keep-Alive\r\n"
"Pragma: no-cache\r\n\r\n";
/*
* special case proxy coming thru https
* instead of a direct SSL connection.
*/
rfbLog("Handling VNC request via https GET. [%d]\n", getpid());
rfbLog("-- %s\n", buf);
if (strstr(buf, "/reverse.proxy")) {
char *buf2;
int n, ptr;
SSL_write(ssl, reply, strlen(reply));
buf2 = (char *) calloc((8192+1), 1);
n = 0;
ptr = 0;
while (ptr < 8192) {
n = SSL_read(ssl, buf2 + ptr, 1);
if (n > 0) {
ptr += n;
}
if (db) fprintf(stderr, "buf2: '%s'\n", buf2);
if (strstr(buf2, "\r\n\r\n")) {
break;
}
}
free(buf2);
}
goto write_cookie;
} else if (strstr(buf, "/check.https.proxy.connection")) {
char reply[] = "HTTP/1.0 200 OK\r\n"
"Connection: close\r\n"
"Content-Type: octet-stream\r\n"
"Pragma: no-cache\r\n\r\n";
rfbLog("Handling Check HTTPS request via https GET. [%d]\n", getpid());
rfbLog("-- %s\n", buf);
SSL_write(ssl, reply, strlen(reply));
SSL_shutdown(ssl);
strcpy(tbuf, uniq);
strcat(tbuf, cookie);
write(vncsock, tbuf, strlen(tbuf));
close(vncsock);
exit(0);
}
connect_to_httpd:
/*
* Here we go... no turning back. we have to
* send failure to parent and close socket to have
* http processed at all in a timely fashion...
*/
/* send the failure tag: */
strcpy(tbuf, uniq);
if (https_port_redir < 0 || (strstr(buf, "PORT=") || strstr(buf, "port="))) {
char *q = strstr(buf, "Host:");
int fport = 443, match = 0;
char num[16];
if (q && strstr(q, "\n")) {
q += strlen("Host:") + 1;
while (*q != '\n') {
int p;
if (*q == ':' && sscanf(q, ":%d", &p) == 1) {
if (p > 0 && p < 65536) {
fport = p;
match = 1;
break;
}
}
q++;
}
}
if (!match || !https_port_redir) {
int p;
if (sscanf(buf, "PORT=%d,", &p) == 1) {
if (p > 0 && p < 65536) {
fport = p;
}
} else if (sscanf(buf, "port=%d,", &p) == 1) {
if (p > 0 && p < 65536) {
fport = p;
}
}
}
sprintf(num, "HP=%d,", fport);
strcat(tbuf, num);
}
if (strstr(buf, "HTTP/") != NULL) {
char *q, *str;
/*
* Also send back the GET line for heuristics.
* (last_https, get file).
*/
str = strdup(buf);
q = strstr(str, "HTTP/");
if (q != NULL) {
*q = '\0';
strcat(tbuf, str);
}
free(str);
}
/*
* Also send the cookie to pad out the number of
* bytes to more than the parent wants to read.
* Since this is the failure case, it does not
* matter that we send more than strlen(cookie).
*/
strcat(tbuf, cookie);
write(vncsock, tbuf, strlen(tbuf));
usleep(150*1000);
if (db) fprintf(stderr, "close vncsock: %d\n", vncsock);
close(vncsock);
/* now, finally, connect to the libvncserver httpd: */
if (screen->listenInterface == htonl(INADDR_ANY) ||
screen->listenInterface == htonl(INADDR_NONE)) {
iface = "127.0.0.1";
} else {
struct in_addr in;
in.s_addr = screen->listenInterface;
iface = inet_ntoa(in);
}
if (iface == NULL || !strcmp(iface, "")) {
iface = "127.0.0.1";
}
if (db) fprintf(stderr, "iface: %s:%d\n", iface, hport);
usleep(150*1000);
httpsock = rfbConnectToTcpAddr(iface, hport);
if (httpsock < 0) {
/* UGH, after all of that! */
rfbLog("Could not connect to httpd socket!\n");
exit(1);
}
if (db) fprintf(stderr, "ssl_helper[%d]: httpsock: %d %d\n",
getpid(), httpsock, n);
/*
* send what we read to httpd, and then connect
* the rest of the SSL session to it:
*/
if (n > 0) {
if (db) fprintf(stderr, "sending http buffer httpsock: %d\n'%s'\n", httpsock, buf);
write(httpsock, buf, n);
}
ssl_xfer(httpsock, s_in, s_out, is_http);
exit(0);
}
/*
* ok, back from the above https mess, simply send the
* cookie back to the parent (who will attach us to
* libvncserver), and connect the rest of the SSL session
* to it.
*/
write_cookie:
write(vncsock, cookie, strlen(cookie));
wrote_cookie:
ssl_xfer(vncsock, s_in, s_out, 0);
exit(0);
}
/* parent here */
if (mode != OPENSSL_INETD) {
close(sock);
}
if (db) fprintf(stderr, "helper process is: %d\n", pid);
/* accept connection from our child. */
signal(SIGALRM, csock_timeout);
csock_timeout_sock = csock;
alarm(20);
vsock = accept(csock, (struct sockaddr *)&addr, &addrlen);
alarm(0);
signal(SIGALRM, SIG_DFL);
close(csock);
if (vsock < 0) {
rfbLog("SSL: accept_openssl: connection from ssl_helper FAILED.\n");
rfbLogPerror("accept");
kill(pid, SIGTERM);
waitpid(pid, &status, WNOHANG);
if (mode == OPENSSL_INETD || ssl_no_fail) {
clean_up_exit(1);
}
if (certret_fd >= 0) {
close(certret_fd);
certret_fd = -1;
}
if (certret) {
unlink(certret);
}
if (dhret_fd >= 0) {
close(dhret_fd);
dhret_fd = -1;
}
if (dhret) {
unlink(dhret);
}
return;
}
if (db) fprintf(stderr, "accept_openssl: vsock: %d\n", vsock);
n = read(vsock, rcookie, strlen(cookie));
if (n < 0 && errno != 0) {
rfbLogPerror("read");
}
if (certret) {
struct stat sbuf;
sbuf.st_size = 0;
if (certret_fd >= 0 && stat(certret, &sbuf) == 0 && sbuf.st_size > 0) {
certret_str = (char *) calloc(sbuf.st_size+1, 1);
read(certret_fd, certret_str, sbuf.st_size);
close(certret_fd);
certret_fd = -1;
}
if (certret_fd >= 0) {
close(certret_fd);
certret_fd = -1;
}
unlink(certret);
if (certret_str && strstr(certret_str, "NOCERT") == certret_str) {
free(certret_str);
certret_str = NULL;
}
if (0 && certret_str) {
fprintf(stderr, "certret_str[%d]:\n%s\n", (int) sbuf.st_size, certret_str);
}
}
if (dhret) {
struct stat sbuf;
sbuf.st_size = 0;
if (dhret_fd >= 0 && stat(dhret, &sbuf) == 0 && sbuf.st_size > 0) {
dhret_str = (char *) calloc(sbuf.st_size+1, 1);
read(dhret_fd, dhret_str, sbuf.st_size);
close(dhret_fd);
dhret_fd = -1;
}
if (dhret_fd >= 0) {
close(dhret_fd);
dhret_fd = -1;
}
unlink(dhret);
if (dhret_str && strstr(dhret_str, "NOCERT") == dhret_str) {
free(dhret_str);
dhret_str = NULL;
}
if (dhret_str) {
if (new_dh_params == NULL) {
fprintf(stderr, "dhret_str[%d]:\n%s\n", (int) sbuf.st_size, dhret_str);
new_dh_params = strdup(dhret_str);
}
}
}
if (0) {
fprintf(stderr, "rcookie: %s\n", rcookie);
fprintf(stderr, "cookie: %s\n", cookie);
}
if (strstr(rcookie, uniq) == rcookie) {
char *q = strstr(rcookie, "RB=");
if (q && strstr(cookie, q) == cookie) {
vencrypt_sel = 0;
tlsvnc_sel = 0;
q = strstr(rcookie, "VENCRYPT=");
if (q && sscanf(q, "VENCRYPT=%d,", &vencrypt_sel) == 1) {
if (vencrypt_sel != 0) {
rfbLog("SSL: VENCRYPT mode=%d accepted.\n", vencrypt_sel);
goto accept_client;
}
}
q = strstr(rcookie, "TLSVNC=");
if (q && sscanf(q, "TLSVNC=%d,", &tlsvnc_sel) == 1) {
if (tlsvnc_sel != 0) {
rfbLog("SSL: TLSVNC mode=%d accepted.\n", tlsvnc_sel);
goto accept_client;
}
}
}
}
if (n != (int) strlen(cookie) || strncmp(cookie, rcookie, n)) {
rfbLog("SSL: accept_openssl: cookie from ssl_helper FAILED. %d\n", n);
if (db) fprintf(stderr, "'%s'\n'%s'\n", cookie, rcookie);
close(vsock);
if (strstr(rcookie, uniq) == rcookie) {
int i;
rfbLog("SSL: BUT WAIT! HTTPS for helper process succeeded. Good.\n");
if (mode != OPENSSL_HTTPS) {
last_https = time(NULL);
for (i=0; i<256; i++) {
last_get[i] = '\0';
}
strncpy(last_get, rcookie, 100);
if (db) fprintf(stderr, "last_get: '%s'\n", last_get);
}
if (rcookie && strstr(rcookie, "VncViewer.class")) {
rfbLog("\n");
rfbLog("***********************************************************\n");
rfbLog("SSL: WARNING CLIENT ASKED FOR NONEXISTENT 'VncViewer.class'\n");
rfbLog("SSL: USER NEEDS TO **RESTART** HIS WEB BROWSER.\n");
rfbLog("***********************************************************\n");
rfbLog("\n");
}
ssl_helper_pid(pid, -2);
if (https_port_redir) {
double start;
int origport = screen->port;
int useport = screen->port;
/* to expand $PORT correctly in index.vnc */
if (https_port_redir < 0) {
char *q = strstr(rcookie, "HP=");
if (q) {
int p;
if (sscanf(q, "HP=%d,", &p) == 1) {
useport = p;
}
}
} else {
useport = https_port_redir;
}
screen->port = useport;
if (origport != useport) {
rfbLog("SSL: -httpsredir guess port: %d\n", screen->port);
}
start = dnow();
while (dnow() < start + 10.0) {
rfbPE(10000);
usleep(10000);
waitpid(pid, &status, WNOHANG);
if (kill(pid, 0) != 0) {
rfbPE(10000);
rfbPE(10000);
break;
}
}
screen->port = origport;
rfbLog("SSL: guessing child https finished.\n");
if (mode == OPENSSL_INETD) {
clean_up_exit(1);
}
} else if (mode == OPENSSL_INETD) {
double start;
/* to expand $PORT correctly in index.vnc */
if (screen->port == 0) {
int fd = fileno(stdin);
if (getenv("X11VNC_INETD_PORT")) {
screen->port = atoi(getenv(
"X11VNC_INETD_PORT"));
} else {
int tport = get_local_port(fd);
if (tport > 0) {
screen->port = tport;
}
}
}
rfbLog("SSL: screen->port %d\n", screen->port);
/* kludge for https fetch via inetd */
start = dnow();
while (dnow() < start + 10.0) {
rfbPE(10000);
usleep(10000);
waitpid(pid, &status, WNOHANG);
if (kill(pid, 0) != 0) {
rfbPE(10000);
rfbPE(10000);
break;
}
}
rfbLog("SSL: OPENSSL_INETD guessing "
"child https finished.\n");
clean_up_exit(1);
}
return;
}
kill(pid, SIGTERM);
waitpid(pid, &status, WNOHANG);
if (mode == OPENSSL_INETD || ssl_no_fail) {
clean_up_exit(1);
}
return;
}
accept_client:
if (db) fprintf(stderr, "accept_openssl: cookie good: %s\n", cookie);
rfbLog("SSL: handshake with helper process succeeded.\n");
openssl_last_helper_pid = pid;
ssl_helper_pid(pid, vsock);
if (vnc_redirect) {
vnc_redirect_sock = vsock;
openssl_last_helper_pid = 0;
return;
}
client = rfbNewClient(screen, vsock);
openssl_last_helper_pid = 0;
if (client) {
if (db) fprintf(stderr, "accept_openssl: client %p\n", (void *) client);
if (db) fprintf(stderr, "accept_openssl: new_client %p\n", (void *) screen->newClientHook);
if (db) fprintf(stderr, "accept_openssl: new_client %p\n", (void *) new_client);
if (mode == OPENSSL_INETD) {
inetd_client = client;
client->clientGoneHook = client_gone;
}
if (openssl_last_ip &&
strpbrk(openssl_last_ip, "0123456789") == openssl_last_ip) {
client->host = strdup(openssl_last_ip);
}
if (vencrypt_sel != 0) {
client->protocolMajorVersion = 3;
client->protocolMinorVersion = 8;
if (!finish_vencrypt_auth(client, vencrypt_sel)) {
rfbCloseClient(client);
}
} else if (tlsvnc_sel != 0) {
client->protocolMajorVersion = 3;
client->protocolMinorVersion = 8;
rfbAuthNewClient(client);
}
} else {
rfbLog("SSL: accept_openssl: rfbNewClient failed.\n");
close(vsock);
kill(pid, SIGTERM);
waitpid(pid, &status, WNOHANG);
if (mode == OPENSSL_INETD || ssl_no_fail) {
clean_up_exit(1);
}
return;
}
}
static int read_exact(int sock, char *buf, int len) {
int n, fail = 0;
if (sock < 0) {
return 0;
}
while (len > 0) {
n = read(sock, buf, len);
if (n > 0) {
buf += n;
len -= n;
} else if (n == 0) {
fail = 1;
break;
} else if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
usleep(10*1000);
} else if (n < 0 && errno != EINTR) {
fail = 1;
break;
}
}
if (fail) {
return 0;
} else {
return 1;
}
}
static int write_exact(int sock, char *buf, int len) {
int n, fail = 0;
if (sock < 0) {
return 0;
}
while (len > 0) {
n = write(sock, buf, len);
if (n > 0) {
buf += n;
len -= n;
} else if (n == 0) {
fail = 1;
break;
} else if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
usleep(10*1000);
} else if (n < 0 && errno != EINTR) {
fail = 1;
break;
}
}
if (fail) {
return 0;
} else {
return 1;
}
}
static int add_anon_dh(void) {
pid_t pid, pidw;
char cnf[] = "/tmp/x11vnc-dh.XXXXXX";
char *infile = NULL;
int status, cnf_fd;
DH *dh;
BIO *bio;
FILE *in;
double ds;
/*
* These are dh parameters (prime, generator), not dh keys.
* Evidently it is ok for them to be publicly known.
* openssl dhparam -out dh.out 1024
*/
char *fixed_dh_params =
"-----BEGIN DH PARAMETERS-----\n"
"MIGHAoGBAL28w69ZnLYBvp8R2OeqtAIms+oatY19iBL4WhGI/7H1OMmkJjIe+OHs\n"
"PXoJfe5ucrnvno7Xm+HJZYa1jnPGQuWoa/VJKXdVjYdJVNzazJKM2daKKcQA4GDc\n"
"msFS5DxLbzUR5jy1n12K3EcbvpyFqDYVTJJXm7NuNuiWRfz3wTozAgEC\n"
"-----END DH PARAMETERS-----\n";
if (dhparams_file != NULL) {
infile = dhparams_file;
rfbLog("add_anon_dh: using %s\n", dhparams_file);
goto readin;
}
cnf_fd = mkstemp(cnf);
if (cnf_fd < 0) {
return 0;
}
infile = cnf;
if (create_fresh_dhparams) {
if (new_dh_params != NULL) {
write(cnf_fd, new_dh_params, strlen(new_dh_params));
close(cnf_fd);
} else {
char *exe = find_openssl_bin();
struct stat sbuf;
if (no_external_cmds || !cmd_ok("ssl")) {
rfbLog("add_anon_dh: cannot run external commands.\n");
return 0;
}
close(cnf_fd);
if (exe == NULL) {
return 0;
}
ds = dnow();
pid = fork();
if (pid < 0) {
return 0;
} else if (pid == 0) {
int i;
for (i=0; i<256; i++) {
if (i == 2) continue;
close(i);
}
/* rather slow at 1024 */
execlp(exe, exe, "dhparam", "-out", cnf, "1024", (char *)0);
exit(1);
}
pidw = waitpid(pid, &status, 0);
if (pidw != pid) {
return 0;
}
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
;
} else {
return 0;
}
rfbLog("add_anon_dh: created new DH params in %.3f secs\n", dnow() - ds);
if (stat(cnf, &sbuf) == 0 && sbuf.st_size > 0) {
/* save it to reuse during our process's lifetime: */
int d = open(cnf, O_RDONLY);
if (d >= 0) {
int n, len = sbuf.st_size;
new_dh_params = (char *) calloc(len+1, 1);
n = read(d, new_dh_params, len);
close(d);
if (n != len) {
free(new_dh_params);
new_dh_params = NULL;
} else if (dhret != NULL) {
d = open(dhret, O_WRONLY);
if (d >= 0) {
write(d, new_dh_params, strlen(new_dh_params));
close(d);
}
}
}
}
}
} else {
write(cnf_fd, fixed_dh_params, strlen(fixed_dh_params));
close(cnf_fd);
}
readin:
ds = dnow();
in = fopen(infile, "r");
if (in == NULL) {
rfbLogPerror("fopen");
unlink(cnf);
return 0;
}
bio = BIO_new_fp(in, BIO_CLOSE|BIO_FP_TEXT);
if (! bio) {
rfbLog("openssl_init: BIO_new_fp() failed.\n");
unlink(cnf);
return 0;
}
dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
if (dh == NULL) {
rfbLog("openssl_init: PEM_read_bio_DHparams() failed.\n");
unlink(cnf);
BIO_free(bio);
return 0;
}
BIO_free(bio);
SSL_CTX_set_tmp_dh(ctx, dh);
rfbLog("loaded Diffie Hellman %d bits, %.3fs\n", 8*DH_size(dh), dnow()-ds);
DH_free(dh);
unlink(cnf);
return 1;
}
static int switch_to_anon_dh(void) {
long mode;
rfbLog("Using Anonymous Diffie-Hellman mode.\n");
rfbLog("WARNING: Anonymous Diffie-Hellman uses encryption but is\n");
rfbLog("WARNING: susceptible to a Man-In-The-Middle attack.\n");
ctx = SSL_CTX_new( SSLv23_server_method() );
if (ctx == NULL) {
return 0;
}
if (!SSL_CTX_set_cipher_list(ctx, "ADH:@STRENGTH")) {
return 0;
}
if (!add_anon_dh()) {
return 0;
}
mode = 0;
mode |= SSL_MODE_ENABLE_PARTIAL_WRITE;
mode |= SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
SSL_CTX_set_mode(ctx, mode);
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_BOTH);
SSL_CTX_set_timeout(ctx, 300);
SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_callback);
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
return 1;
}
static int tlsvnc_dialog(int s_in, int s_out) {
tlsvnc_selected = 1;
if (!switch_to_anon_dh()) {
rfbLog("tlsvnc: Anonymous Diffie-Hellman failed.\n");
return 0;
}
/* continue with SSL/TLS */
return 1;
}
/*
* Using spec:
* http://www.mail-archive.com/qemu-devel@nongnu.org/msg08681.html
*/
static int vencrypt_dialog(int s_in, int s_out) {
char buf[256], buf2[256];
int subtypes[16];
int n, i, ival, ok, db = 1, nsubtypes = 0;
vencrypt_selected = 0;
/* send version 0.2 */
buf[0] = 0;
buf[1] = 2;
if (!write_exact(s_out, buf, 2)) {
close(s_in); close(s_out);
return 0;
}
/* read client version 0.2 */
memset(buf, 0, sizeof(buf));
if (!read_exact(s_in, buf, 2)) {
close(s_in); close(s_out);
return 0;
}
rfbLog("vencrypt: received %d.%d client version.\n", (int) buf[0], (int) buf[1]);
/* close 0.0 */
if (buf[0] == 0 && buf[1] == 0) {
rfbLog("vencrypt: received 0.0 version, closing connection.\n");
close(s_in); close(s_out);
return 0;
}
/* accept only 0.2 */
if (buf[0] != 0 || buf[1] != 2) {
rfbLog("vencrypt: unsupported VeNCrypt version, closing connection.\n");
buf[0] = 255;
write_exact(s_out, buf, 1);
close(s_in); close(s_out);
return 0;
}
/* tell them OK */
buf[0] = 0;
if (!write_exact(s_out, buf, 1)) {
close(s_in); close(s_out);
return 0;
}
if (getenv("X11VNC_ENABLE_VENCRYPT_PLAIN_LOGIN")) {
vencrypt_enable_plain_login = atoi(getenv("X11VNC_ENABLE_VENCRYPT_PLAIN_LOGIN"));
}
/* load our list of sub-types: */
n = 0;
if (!ssl_verify && vencrypt_kx != VENCRYPT_NODH) {
if (screen->authPasswdData != NULL) {
subtypes[n++] = rfbVencryptTlsVnc;
} else {
if (vencrypt_enable_plain_login && unixpw) {
subtypes[n++] = rfbVencryptTlsPlain;
} else {
subtypes[n++] = rfbVencryptTlsNone;
}
}
}
if (vencrypt_kx != VENCRYPT_NOX509) {
if (screen->authPasswdData != NULL) {
subtypes[n++] = rfbVencryptX509Vnc;
} else {
if (vencrypt_enable_plain_login && unixpw) {
subtypes[n++] = rfbVencryptX509Plain;
} else {
subtypes[n++] = rfbVencryptX509None;
}
}
}
nsubtypes = n;
for (i = 0; i < nsubtypes; i++) {
((uint32_t *)buf)[i] = Swap32IfLE(subtypes[i]);
}
/* send number first: */
buf2[0] = (char) nsubtypes;
if (!write_exact(s_out, buf2, 1)) {
close(s_in); close(s_out);
return 0;
}
/* and now the list: */
if (!write_exact(s_out, buf, 4*n)) {
close(s_in); close(s_out);
return 0;
}
/* read client's selection: */
if (!read_exact(s_in, (char *)&ival, 4)) {
close(s_in); close(s_out);
return 0;
}
ival = Swap32IfLE(ival);
/* zero means no dice: */
if (ival == 0) {
rfbLog("vencrypt: client selected no sub-type, closing connection.\n");
close(s_in); close(s_out);
return 0;
}
/* check if he selected a valid one: */
ok = 0;
for (i = 0; i < nsubtypes; i++) {
if (ival == subtypes[i]) {
ok = 1;
}
}
if (!ok) {
rfbLog("vencrypt: client selected invalid sub-type: %d\n", ival);
close(s_in); close(s_out);
return 0;
} else {
char *st = "unknown!!";
if (ival == rfbVencryptTlsNone) st = "rfbVencryptTlsNone";
if (ival == rfbVencryptTlsVnc) st = "rfbVencryptTlsVnc";
if (ival == rfbVencryptTlsPlain) st = "rfbVencryptTlsPlain";
if (ival == rfbVencryptX509None) st = "rfbVencryptX509None";
if (ival == rfbVencryptX509Vnc) st = "rfbVencryptX509Vnc";
if (ival == rfbVencryptX509Plain) st = "rfbVencryptX509Plain";
rfbLog("vencrypt: client selected sub-type: %d (%s)\n", ival, st);
}
vencrypt_selected = ival;
/* not documented in spec, send OK: */
buf[0] = 1;
if (!write_exact(s_out, buf, 1)) {
close(s_in); close(s_out);
return 0;
}
if (vencrypt_selected == rfbVencryptTlsNone ||
vencrypt_selected == rfbVencryptTlsVnc ||
vencrypt_selected == rfbVencryptTlsPlain) {
/* these modes are Anonymous Diffie-Hellman */
if (!switch_to_anon_dh()) {
rfbLog("vencrypt: Anonymous Diffie-Hellman failed.\n");
return 0;
}
}
/* continue with SSL/TLS */
return 1;
}
static int check_vnc_tls_mode(int s_in, int s_out) {
double waited = 0.0, dt = 0.01, start = dnow();
struct timeval tv;
int input = 0, i, n, ok;
int major, minor, sectype = -1;
char *proto = "RFB 003.008\n";
char *stype = "unknown";
char buf[256];
vencrypt_selected = 0;
tlsvnc_selected = 0;
if (vencrypt_mode == VENCRYPT_NONE && tlsvnc_mode == TLSVNC_NONE) {
/* only normal SSL */
return 1;
}
if (ssl_client_mode) {
/* XXX check if this can be done in SSL client mode. */
if (vencrypt_mode == VENCRYPT_FORCE || tlsvnc_mode == TLSVNC_FORCE) {
rfbLog("check_vnc_tls_mode: VENCRYPT_FORCE/TLSVNC_FORCE prevents normal SSL\n");
return 0;
}
return 1;
}
if (ssl_verify && vencrypt_mode != VENCRYPT_FORCE && tlsvnc_mode == TLSVNC_FORCE) {
rfbLog("check_vnc_tls_mode: Cannot use TLSVNC_FORCE with -sslverify (Anon DH only)\n");
/* fallback to normal SSL */
return 1;
}
while (waited < 0.7) {
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(s_in, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 0;
select(s_in+1, &rfds, NULL, NULL, &tv);
if (FD_ISSET(s_in, &rfds)) {
input = 1;
break;
}
usleep((int) (1000 * 1000 * dt));
waited += dt;
}
rfbLog("check_vnc_tls_mode: waited: %f input: %s\n", dnow() - start, input ? "SSL Handshake" : "(future) RFB Handshake");
if (input) {
/* got SSL client hello, can only assume normal SSL */
if (vencrypt_mode == VENCRYPT_FORCE || tlsvnc_mode == TLSVNC_FORCE) {
rfbLog("check_vnc_tls_mode: VENCRYPT_FORCE/TLSVNC_FORCE prevents normal SSL\n");
return 0;
}
return 1;
}
/* send RFB 003.008 -- there is no turning back from this point... */
if (!write_exact(s_out, proto, strlen(proto))) {
close(s_in); close(s_out);
return 0;
}
memset(buf, 0, sizeof(buf));
if (!read_exact(s_in, buf, 12)) {
close(s_in); close(s_out);
return 0;
}
if (sscanf(buf, "RFB %03d.%03d\n", &major, &minor) != 2) {
rfbLog("check_vnc_tls_mode: abnormal handshake: '%s'\n", buf);
close(s_in); close(s_out);
return 0;
}
rfbLog("check_vnc_tls_mode: version: %d.%d\n", major, minor);
if (major != 3 || minor < 8) {
rfbLog("check_vnc_tls_mode: invalid version: '%s'\n", buf);
close(s_in); close(s_out);
return 0;
}
n = 1;
if (vencrypt_mode == VENCRYPT_FORCE) {
buf[n++] = rfbSecTypeVencrypt;
} else if (tlsvnc_mode == TLSVNC_FORCE && !ssl_verify) {
buf[n++] = rfbSecTypeTlsVnc;
} else if (vencrypt_mode == VENCRYPT_SOLE) {
buf[n++] = rfbSecTypeVencrypt;
} else if (tlsvnc_mode == TLSVNC_SOLE && !ssl_verify) {
buf[n++] = rfbSecTypeTlsVnc;
} else {
if (vencrypt_mode == VENCRYPT_SUPPORT) {
buf[n++] = rfbSecTypeVencrypt;
}
if (tlsvnc_mode == TLSVNC_SUPPORT && !ssl_verify) {
buf[n++] = rfbSecTypeTlsVnc;
}
}
n--;
buf[0] = (char) n;
if (!write_exact(s_out, buf, n+1)) {
close(s_in); close(s_out);
return 0;
}
if (0) fprintf(stderr, "wrote[%d] %d %d %d\n", n, buf[0], buf[1], buf[2]);
buf[0] = 0;
if (!read_exact(s_in, buf, 1)) {
close(s_in); close(s_out);
return 0;
}
if (buf[0] == rfbSecTypeVencrypt) stype = "VeNCrypt";
if (buf[0] == rfbSecTypeTlsVnc) stype = "TLSVNC";
rfbLog("check_vnc_tls_mode: reply: %d (%s)\n", (int) buf[0], stype);
ok = 0;
for (i=1; i < n+1; i++) {
if (buf[0] == buf[i]) {
ok = 1;
}
}
if (!ok) {
char *msg = "check_vnc_tls_mode: invalid security-type";
int len = strlen(msg);
rfbLog("%s: %d\n", msg, (int) buf[0]);
((uint32_t *)buf)[0] = Swap32IfLE(len);
write_exact(s_out, buf, 4);
write_exact(s_out, msg, strlen(msg));
close(s_in); close(s_out);
return 0;
}
sectype = (int) buf[0];
if (sectype == rfbSecTypeVencrypt) {
return vencrypt_dialog(s_in, s_out);
} else if (sectype == rfbSecTypeTlsVnc) {
return tlsvnc_dialog(s_in, s_out);
} else {
return 0;
}
}
static void pr_ssl_info(int verb) {
SSL_CIPHER *c;
SSL_SESSION *s;
char *proto = "unknown";
if (ssl == NULL) {
return;
}
c = SSL_get_current_cipher(ssl);
s = SSL_get_session(ssl);
if (s == NULL) {
proto = "nosession";
} else if (s->ssl_version == SSL2_VERSION) {
proto = "SSLv2";
} else if (s->ssl_version == SSL3_VERSION) {
proto = "SSLv3";
} else if (s->ssl_version == TLS1_VERSION) {
proto = "TLSv1";
}
if (c != NULL) {
rfbLog("SSL: ssl_helper[%d]: Cipher: %s %s Proto: %s\n", getpid(),
SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c), proto);
} else {
rfbLog("SSL: ssl_helper[%d]: Proto: %s\n", getpid(),
proto);
}
}
static void ssl_timeout (int sig) {
rfbLog("sig: %d, ssl_init timed out.\n", sig);
exit(1);
}
static int ssl_init(int s_in, int s_out) {
unsigned char *sid = (unsigned char *) "x11vnc SID";
char *name;
int peerport = 0;
int db = 0, rc, err;
int ssock = s_in;
double start = dnow();
int timeout = 20;
if (enc_str != NULL) {
return 1;
}
if (getenv("SSL_DEBUG")) {
db = atoi(getenv("SSL_DEBUG"));
}
if (getenv("SSL_INIT_TIMEOUT")) {
timeout = atoi(getenv("SSL_INIT_TIMEOUT"));
}
if (db) fprintf(stderr, "ssl_init: %d/%d\n", s_in, s_out);
if (!check_vnc_tls_mode(s_in, s_out)) {
return 0;
}
ssl = SSL_new(ctx);
if (ssl == NULL) {
fprintf(stderr, "SSL_new failed\n");
return 0;
}
if (db > 1) fprintf(stderr, "ssl_init: 1\n");
SSL_set_session_id_context(ssl, sid, strlen((char *)sid));
if (s_in == s_out) {
if (! SSL_set_fd(ssl, ssock)) {
fprintf(stderr, "SSL_set_fd failed\n");
return 0;
}
} else {
if (! SSL_set_rfd(ssl, s_in)) {
fprintf(stderr, "SSL_set_rfd failed\n");
return 0;
}
if (! SSL_set_wfd(ssl, s_out)) {
fprintf(stderr, "SSL_set_wfd failed\n");
return 0;
}
}
if (db > 1) fprintf(stderr, "ssl_init: 2\n");
if (ssl_client_mode) {
SSL_set_connect_state(ssl);
} else {
SSL_set_accept_state(ssl);
}
if (db > 1) fprintf(stderr, "ssl_init: 3\n");
name = get_remote_host(ssock);
peerport = get_remote_port(ssock);
if (db > 1) fprintf(stderr, "ssl_init: 4\n");
while (1) {
if (db) fprintf(stderr, "calling SSL_accept...\n");
signal(SIGALRM, ssl_timeout);
alarm(timeout);
if (ssl_client_mode) {
rc = SSL_connect(ssl);
} else {
rc = SSL_accept(ssl);
}
err = SSL_get_error(ssl, rc);
alarm(0);
signal(SIGALRM, SIG_DFL);
if (db) fprintf(stderr, "SSL_accept %d/%d\n", rc, err);
if (err == SSL_ERROR_NONE) {
break;
} else if (err == SSL_ERROR_WANT_READ) {
if (db) fprintf(stderr, "got SSL_ERROR_WANT_READ\n");
rfbLog("SSL: ssl_helper[%d]: SSL_accept() failed for: %s:%d\n",
getpid(), name, peerport);
pr_ssl_info(1);
return 0;
} else if (err == SSL_ERROR_WANT_WRITE) {
if (db) fprintf(stderr, "got SSL_ERROR_WANT_WRITE\n");
rfbLog("SSL: ssl_helper[%d]: SSL_accept() failed for: %s:%d\n",
getpid(), name, peerport);
pr_ssl_info(1);
return 0;
} else if (err == SSL_ERROR_SYSCALL) {
if (db) fprintf(stderr, "got SSL_ERROR_SYSCALL\n");
rfbLog("SSL: ssl_helper[%d]: SSL_accept() failed for: %s:%d\n",
getpid(), name, peerport);
pr_ssl_info(1);
return 0;
} else if (err == SSL_ERROR_ZERO_RETURN) {
if (db) fprintf(stderr, "got SSL_ERROR_ZERO_RETURN\n");
rfbLog("SSL: ssl_helper[%d]: SSL_accept() failed for: %s:%d\n",
getpid(), name, peerport);
pr_ssl_info(1);
return 0;
} else if (rc < 0) {
unsigned long err;
int cnt = 0;
rfbLog("SSL: ssl_helper[%d]: SSL_accept() *FATAL: %d SSL FAILED\n", getpid(), rc);
while ((err = ERR_get_error()) != 0) {
rfbLog("SSL: %s\n", ERR_error_string(err, NULL));
if (cnt++ > 100) {
break;
}
}
pr_ssl_info(1);
return 0;
} else if (dnow() > start + 3.0) {
rfbLog("SSL: ssl_helper[%d]: timeout looping SSL_accept() "
"fatal.\n", getpid());
pr_ssl_info(1);
return 0;
} else {
BIO *bio = SSL_get_rbio(ssl);
if (bio == NULL) {
rfbLog("SSL: ssl_helper[%d]: ssl BIO is null. "
"fatal.\n", getpid());
pr_ssl_info(1);
return 0;
}
if (BIO_eof(bio)) {
rfbLog("SSL: ssl_helper[%d]: ssl BIO is EOF. "
"fatal.\n", getpid());
pr_ssl_info(1);
return 0;
}
}
usleep(10 * 1000);
}
rfbLog("SSL: ssl_helper[%d]: SSL_accept() succeeded for: %s:%d\n", getpid(), name, peerport);
pr_ssl_info(0);
if (SSL_get_verify_result(ssl) == X509_V_OK) {
X509 *x;
FILE *cr = NULL;
if (certret != NULL) {
cr = fopen(certret, "w");
}
x = SSL_get_peer_certificate(ssl);
if (x == NULL) {
rfbLog("SSL: ssl_helper[%d]: accepted client %s x509 peer cert is null\n", getpid(), name);
if (cr != NULL) {
fprintf(cr, "NOCERT\n");
fclose(cr);
}
} else {
rfbLog("SSL: ssl_helper[%d]: accepted client %s x509 cert is:\n", getpid(), name);
#if LIBVNCSERVER_HAVE_X509_PRINT_EX_FP
X509_print_ex_fp(stderr, x, 0, XN_FLAG_MULTILINE);
#endif
if (cr != NULL) {
#if LIBVNCSERVER_HAVE_X509_PRINT_EX_FP
X509_print_ex_fp(cr, x, 0, XN_FLAG_MULTILINE);
#else
rfbLog("** not compiled with libssl X509_print_ex_fp() function **\n");
if (users_list && strstr(users_list, "sslpeer=")) {
rfbLog("** -users sslpeer= will not work! **\n");
}
#endif
fclose(cr);
}
}
}
free(name);
return 1;
}
static symmetric_encryption_xfer(int csock, int s_in, int s_out);
static void ssl_xfer(int csock, int s_in, int s_out, int is_https) {
int dbxfer = 0, db = 0, check_pending, fdmax, nfd, n, i, err;
char cbuf[ABSIZE], sbuf[ABSIZE];
int cptr, sptr, c_rd, c_wr, s_rd, s_wr;
fd_set rd, wr;
struct timeval tv;
int ssock, cnt = 0, ndata = 0;
/*
* we want to switch to a longer timeout for long term VNC
* connections (in case the network is not working for periods of
* time), but we also want the timeout shorter at the beginning
* in case the client went away.
*/
time_t start;
int tv_https_early = 60;
int tv_https_later = 20;
int tv_vnc_early = 25;
int tv_vnc_later = 43200; /* was 300, stunnel: 43200 */
int tv_cutover = 70;
int tv_closing = 60;
int tv_use;
if (dbxfer) {
raw_xfer(csock, s_in, s_out);
return;
}
if (enc_str != NULL) {
if (!strcmp(enc_str, "none")) {
usleep(250*1000);
rfbLog("doing '-enc none' raw transfer (no encryption)\n");
raw_xfer(csock, s_in, s_out);
} else {
symmetric_encryption_xfer(csock, s_in, s_out);
}
return;
}
if (getenv("SSL_DEBUG")) {
db = atoi(getenv("SSL_DEBUG"));
}
if (db) fprintf(stderr, "ssl_xfer begin\n");
start = time(NULL);
if (is_https) {
tv_use = tv_https_early;
} else {
tv_use = tv_vnc_early;
}
/*
* csock: clear text socket with libvncserver. "C"
* ssock: ssl data socket with remote vnc viewer. "S"
*
* to cover inetd mode, we have s_in and s_out, but in non-inetd
* mode they both ssock.
*
* cbuf[] is data from csock that we have read but not passed on to ssl
* sbuf[] is data from ssl that we have read but not passed on to csock
*/
for (i=0; i<ABSIZE; i++) {
cbuf[i] = '\0';
sbuf[i] = '\0';
}
if (s_out > s_in) {
ssock = s_out;
} else {
ssock = s_in;
}
if (csock > ssock) {
fdmax = csock;
} else {
fdmax = ssock;
}
c_rd = 1; /* clear text (libvncserver) socket open for reading */
c_wr = 1; /* clear text (libvncserver) socket open for writing */
s_rd = 1; /* ssl data (remote client) socket open for reading */
s_wr = 1; /* ssl data (remote client) socket open for writing */
cptr = 0; /* offsets into ABSIZE buffers */
sptr = 0;
if (vencrypt_selected > 0 || tlsvnc_selected > 0) {
char tmp[16];
/* read and discard the extra RFB version */
memset(tmp, 0, sizeof(tmp));
read(csock, tmp, 12);
if (0) fprintf(stderr, "extra: %s\n", tmp);
}
while (1) {
int c_to_s, s_to_c, closing;
if ( s_wr && (c_rd || cptr > 0) ) {
/*
* S is writable and
* C is readable or some cbuf data remaining
*/
c_to_s = 1;
} else {
c_to_s = 0;
}
if ( c_wr && (s_rd || sptr > 0) ) {
/*
* C is writable and
* S is readable or some sbuf data remaining
*/
s_to_c = 1;
} else {
s_to_c = 0;
}
if (! c_to_s && ! s_to_c) {
/*
* nothing can be sent either direction.
* break out of the loop to finish all work.
*/
break;
}
cnt++;
/* set up the fd sets for the two sockets for read & write: */
FD_ZERO(&rd);
if (c_rd && cptr < ABSIZE) {
/* we could read more from C since cbuf is not full */
FD_SET(csock, &rd);
}
if (s_rd) {
/*
* we could read more from S since sbuf not full,
* OR ssl is waiting for more BIO to be able to
* read and we have some C data still buffered.
*/
if (sptr < ABSIZE || (cptr > 0 && SSL_want_read(ssl))) {
FD_SET(s_in, &rd);
}
}
FD_ZERO(&wr);
if (c_wr && sptr > 0) {
/* we could write more to C since sbuf is not empty */
FD_SET(csock, &wr);
}
if (s_wr) {
/*
* we could write more to S since cbuf not empty,
* OR ssl is waiting for more BIO to be able
* write and we haven't filled up sbuf yet.
*/
if (cptr > 0 || (sptr < ABSIZE && SSL_want_write(ssl))) {
FD_SET(s_out, &wr);
}
}
if (tv_cutover && time(NULL) > start + tv_cutover) {
rfbLog("SSL: ssl_xfer[%d]: tv_cutover: %d\n", getpid(),
tv_cutover);
tv_cutover = 0;
if (is_https) {
tv_use = tv_https_later;
} else {
tv_use = tv_vnc_later;
}
}
if (ssl_timeout_secs > 0) {
tv_use = ssl_timeout_secs;
}
if ( (s_rd && c_rd) || cptr || sptr) {
closing = 0;
} else {
closing = 1;
tv_use = tv_closing;
}
tv.tv_sec = tv_use;
tv.tv_usec = 0;
/* do the select, repeat if interrupted */
do {
if (ssl_timeout_secs == 0) {
nfd = select(fdmax+1, &rd, &wr, NULL, NULL);
} else {
nfd = select(fdmax+1, &rd, &wr, NULL, &tv);
}
} while (nfd < 0 && errno == EINTR);
if (db > 1) fprintf(stderr, "nfd: %d\n", nfd);
if (nfd < 0) {
rfbLog("SSL: ssl_xfer[%d]: select error: %d\n", getpid(), nfd);
perror("select");
/* connection finished */
return;
}
if (nfd == 0) {
if (!closing && tv_cutover && ndata > 25000) {
static int cn = 0;
/* probably ok, early windows iconify */
if (cn++ < 2) {
rfbLog("SSL: ssl_xfer[%d]: early time"
"out: %d\n", getpid(), ndata);
}
continue;
}
rfbLog("SSL: ssl_xfer[%d]: connection timedout. %d\n",
getpid(), ndata);
/* connection finished */
return;
}
/* used to see if SSL_pending() should be checked: */
check_pending = 0;
/* AUDIT */
if (c_wr && FD_ISSET(csock, &wr)) {
/* try to write some of our sbuf to C: */
n = write(csock, sbuf, sptr);
if (n < 0) {
if (errno != EINTR) {
/* connection finished */
return;
}
/* proceed */
} else if (n == 0) {
/* connection finished XXX double check */
return;
} else {
/* shift over the data in sbuf by n */
memmove(sbuf, sbuf + n, sptr - n);
if (sptr == ABSIZE) {
check_pending = 1;
}
sptr -= n;
if (! s_rd && sptr == 0) {
/* finished sending last of sbuf */
shutdown(csock, SHUT_WR);
c_wr = 0;
}
ndata += n;
}
}
if (s_wr) {
if ((cptr > 0 && FD_ISSET(s_out, &wr)) ||
(SSL_want_read(ssl) && FD_ISSET(s_in, &rd))) {
/* try to write some of our cbuf to S: */
n = SSL_write(ssl, cbuf, cptr);
err = SSL_get_error(ssl, n);
if (err == SSL_ERROR_NONE) {
/* shift over the data in cbuf by n */
memmove(cbuf, cbuf + n, cptr - n);
cptr -= n;
if (! c_rd && cptr == 0 && s_wr) {
/* finished sending last cbuf */
SSL_shutdown(ssl);
s_wr = 0;
}
ndata += n;
} else if (err == SSL_ERROR_WANT_WRITE
|| err == SSL_ERROR_WANT_READ
|| err == SSL_ERROR_WANT_X509_LOOKUP) {
; /* proceed */
} else if (err == SSL_ERROR_SYSCALL) {
if (n < 0 && errno != EINTR) {
/* connection finished */
return;
}
/* proceed */
} else if (err == SSL_ERROR_ZERO_RETURN) {
/* S finished */
s_rd = 0;
s_wr = 0;
} else if (err == SSL_ERROR_SSL) {
/* connection finished */
return;
}
}
}
if (c_rd && FD_ISSET(csock, &rd)) {
/* try to read some data from C into our cbuf */
n = read(csock, cbuf + cptr, ABSIZE - cptr);
if (n < 0) {
if (errno != EINTR) {
/* connection finished */
return;
}
/* proceed */
} else if (n == 0) {
/* C is EOF */
c_rd = 0;
if (cptr == 0 && s_wr) {
/* and no more in cbuf to send */
SSL_shutdown(ssl);
s_wr = 0;
}
} else {
/* good */
cptr += n;
ndata += n;
}
}
if (s_rd) {
if ((sptr < ABSIZE && FD_ISSET(s_in, &rd)) ||
(SSL_want_write(ssl) && FD_ISSET(s_out, &wr)) ||
(check_pending && SSL_pending(ssl))) {
/* try to read some data from S into our sbuf */
n = SSL_read(ssl, sbuf + sptr, ABSIZE - sptr);
err = SSL_get_error(ssl, n);
if (err == SSL_ERROR_NONE) {
/* good */
sptr += n;
ndata += n;
} else if (err == SSL_ERROR_WANT_WRITE
|| err == SSL_ERROR_WANT_READ
|| err == SSL_ERROR_WANT_X509_LOOKUP) {
; /* proceed */
} else if (err == SSL_ERROR_SYSCALL) {
if (n < 0) {
if(errno != EINTR) {
/* connection finished */
return;
}
/* proceed */
} else {
/* S finished */
s_rd = 0;
s_wr = 0;
}
} else if (err == SSL_ERROR_ZERO_RETURN) {
/* S is EOF */
s_rd = 0;
if (cptr == 0 && s_wr) {
/* and no more in cbuf to send */
SSL_shutdown(ssl);
s_wr = 0;
}
if (sptr == 0 && c_wr) {
/* and no more in sbuf to send */
shutdown(csock, SHUT_WR);
c_wr = 0;
}
} else if (err == SSL_ERROR_SSL) {
/* connection finished */
return;
}
}
}
}
}
void check_openssl(void) {
fd_set fds;
struct timeval tv;
int nfds;
static time_t last_waitall = 0;
static double last_check = 0.0;
double now;
if (! use_openssl || openssl_sock < 0) {
return;
}
now = dnow();
if (now < last_check + 0.5) {
return;
}
last_check = now;
if (time(NULL) > last_waitall + 150) {
last_waitall = time(NULL);
ssl_helper_pid(0, -2); /* waitall */
}
FD_ZERO(&fds);
FD_SET(openssl_sock, &fds);
tv.tv_sec = 0;
tv.tv_usec = 0;
nfds = select(openssl_sock+1, &fds, NULL, NULL, &tv);
if (nfds <= 0) {
return;
}
rfbLog("SSL: accept_openssl(OPENSSL_VNC)\n");
accept_openssl(OPENSSL_VNC, -1);
}
void check_https(void) {
fd_set fds;
struct timeval tv;
int nfds;
static double last_check = 0.0;
double now;
if (! use_openssl || https_sock < 0) {
return;
}
now = dnow();
if (now < last_check + 0.5) {
return;
}
last_check = now;
FD_ZERO(&fds);
FD_SET(https_sock, &fds);
tv.tv_sec = 0;
tv.tv_usec = 0;
nfds = select(https_sock+1, &fds, NULL, NULL, &tv);
if (nfds <= 0) {
return;
}
rfbLog("SSL: accept_openssl(OPENSSL_HTTPS)\n");
accept_openssl(OPENSSL_HTTPS, -1);
}
#define MSZ 4096
static void init_prng(void) {
int db = 0, bytes, ubytes, fd;
char file[MSZ], dtmp[100];
RAND_file_name(file, MSZ);
rfbLog("RAND_file_name: %s\n", file);
bytes = RAND_load_file(file, -1);
if (db) fprintf(stderr, "bytes read: %d\n", bytes);
ubytes = RAND_load_file("/dev/urandom", 64);
bytes += ubytes;
if (db) fprintf(stderr, "bytes read: %d / %d\n", bytes, ubytes);
/* mix in more predictable stuff as well for fallback */
sprintf(dtmp, "/tmp/p%.8f.XXXXXX", dnow());
fd = mkstemp(dtmp);
RAND_add(dtmp, strlen(dtmp), 0);
if (fd >= 0) {
close(fd);
unlink(dtmp);
}
sprintf(dtmp, "%d-%.8f", (int) getpid(), dnow());
RAND_add(dtmp, strlen(dtmp), 0);
if (!RAND_status()) {
ubytes = -1;
rfbLog("calling RAND_poll()\n");
RAND_poll();
}
if (bytes > 0) {
if (! quiet) {
rfbLog("initialized PRNG with %d random bytes.\n",
bytes);
}
if (ubytes > 32 && rnow() < 0.25) {
RAND_write_file(file);
}
return;
}
bytes += RAND_load_file("/dev/random", 8);
if (db) fprintf(stderr, "bytes read: %d\n", bytes);
RAND_poll();
if (! quiet) {
rfbLog("initialized PRNG with %d random bytes.\n", bytes);
}
}
#endif /* FORK_OK */
#endif /* LIBVNCSERVER_HAVE_LIBSSL */
void raw_xfer(int csock, int s_in, int s_out) {
char buf0[8192];
int sz = 8192, n, m, status, db = 1;
char *buf;
#ifdef FORK_OK
pid_t par = getpid();
pid_t pid = fork();
buf = buf0;
if (vnc_redirect) {
/* change buf size some direction. */
}
/* this is for testing, no SSL just socket redir */
if (pid < 0) {
exit(1);
}
if (getenv("X11VNC_DEBUG_RAW_XFER")) {
db = atoi(getenv("X11VNC_DEBUG_RAW_XFER"));
}
if (pid) {
if (db) rfbLog("raw_xfer start: %d -> %d/%d\n", csock, s_in, s_out);
while (1) {
n = read(csock, buf, sz);
if (n == 0 || (n < 0 && errno != EINTR) ) {
break;
} else if (n > 0) {
int len = n;
char *src = buf;
if (db > 1) write(2, buf, n);
while (len > 0) {
m = write(s_out, src, len);
if (m > 0) {
src += m;
len -= m;
continue;
}
if (m < 0 && (errno == EINTR || errno == EAGAIN)) {
continue;
}
if (db) rfbLog("raw_xfer bad write: %d -> %d | %d/%d errno=%d\n", csock, s_out, m, n, errno);
break;
}
}
}
usleep(250*1000);
kill(pid, SIGTERM);
waitpid(pid, &status, WNOHANG);
if (db) rfbLog("raw_xfer done: %d -> %d\n", csock, s_out);
} else {
if (db) usleep(50*1000);
if (db) rfbLog("raw_xfer start: %d <- %d\n", csock, s_in);
while (1) {
n = read(s_in, buf, sz);
if (n == 0 || (n < 0 && errno != EINTR) ) {
break;
} else if (n > 0) {
int len = n;
char *src = buf;
if (db > 1) write(2, buf, n);
while (len > 0) {
m = write(csock, src, len);
if (m > 0) {
src += m;
len -= m;
continue;
}
if (m < 0 && (errno == EINTR || errno == EAGAIN)) {
continue;
}
if (db) rfbLog("raw_xfer bad write: %d <- %d | %d/%d errno=%d\n", csock, s_in, m, n, errno);
break;
}
}
}
usleep(250*1000);
kill(par, SIGTERM);
waitpid(par, &status, WNOHANG);
if (db) rfbLog("raw_xfer done: %d <- %d\n", csock, s_in);
}
close(csock);
close(s_in);
close(s_out);
#endif /* FORK_OK */
}
#define ENC_MODULE
#if LIBVNCSERVER_HAVE_LIBSSL
#define ENC_HAVE_OPENSSL 1
#else
#define ENC_HAVE_OPENSSL 0
#endif
#include "enc.h"
static symmetric_encryption_xfer(int csock, int s_in, int s_out) {
char tmp[100];
char *cipher, *keyfile, *q;
if (! enc_str) {
return;
}
cipher = (char *) malloc(strlen(enc_str) + 100);
q = strchr(enc_str, ':');
if (!q) return;
*q = '\0';
if (getenv("X11VNC_USE_ULTRADSM_IV")) {
sprintf(cipher, "rev:%s", enc_str);
} else {
sprintf(cipher, "noultra:rev:%s", enc_str);
}
keyfile = strdup(q+1);
*q = ':';
/* TBD: s_in != s_out */
sprintf(tmp, "fd=%d,%d", s_in, csock);
enc_do(cipher, keyfile, "-1", tmp);
}
|