1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347
|
/*
* mod_tls - An RFC2228 SSL/TLS module for ProFTPD
*
* Copyright (c) 2000-2002 Peter 'Luna' Runestig <peter@runestig.com>
* Copyright (c) 2002-2011 TJ Saunders <tj@castaglia.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modifi-
* cation, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright no-
* tice, this list of conditions and the following disclaimer in the do-
* cumentation and/or other materials provided with the distribution.
*
* o The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LI-
* ABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN-
* TIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEV-
* ER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABI-
* LITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* --- DO NOT DELETE BELOW THIS LINE ----
* $Libraries: -lssl -lcrypto$
*/
#include "conf.h"
#include "privs.h"
#include "mod_tls.h"
#ifdef PR_USE_CTRLS
# include "mod_ctrls.h"
#endif
/* Note that the openssl/ssl.h header is already included in mod_tls.h, so
* we don't need to include it here.
*/
#include <openssl/err.h>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/x509v3.h>
#include <openssl/pkcs12.h>
#include <openssl/rand.h>
#if OPENSSL_VERSION_NUMBER > 0x000907000L
# include <openssl/engine.h>
# include <openssl/ocsp.h>
#endif
#ifdef HAVE_MLOCK
# include <sys/mman.h>
#endif
#define MOD_TLS_VERSION "mod_tls/2.4.3"
/* Make sure the version of proftpd is as necessary. */
#if PROFTPD_VERSION_NUMBER < 0x0001030402
# error "ProFTPD 1.3.4rc2 or later required"
#endif
extern session_t session;
extern xaset_t *server_list;
/* DH parameters. These are generated using:
*
* # openssl dhparam -2|-5 512|768|1024|1536|2048 -C
*
* These should be regenerated periodically by the mod_tls maintainer.
* Last updated on 2008-09-07.
*/
/*
-----BEGIN DH PARAMETERS-----
MEYCQQD+qPGFmhNpRTRktay+Z+V1kGEknYZbxh6zktAWjqeeWJGOMwbE7EVuAWW0
I+o1MkCDkg6MtO3NFLisMh9NJVjrAgEC
-----END DH PARAMETERS-----
*/
static unsigned char dh512_p[] = {
0xFE,0xA8,0xF1,0x85,0x9A,0x13,0x69,0x45,0x34,0x64,0xB5,0xAC,
0xBE,0x67,0xE5,0x75,0x90,0x61,0x24,0x9D,0x86,0x5B,0xC6,0x1E,
0xB3,0x92,0xD0,0x16,0x8E,0xA7,0x9E,0x58,0x91,0x8E,0x33,0x06,
0xC4,0xEC,0x45,0x6E,0x01,0x65,0xB4,0x23,0xEA,0x35,0x32,0x40,
0x83,0x92,0x0E,0x8C,0xB4,0xED,0xCD,0x14,0xB8,0xAC,0x32,0x1F,
0x4D,0x25,0x58,0xEB,
};
static unsigned char dh512_g[] = {
0x02,
};
static DH *get_dh512(void) {
DH *dh;
dh = DH_new();
if (dh == NULL)
return NULL;
dh->p = BN_bin2bn(dh512_p, sizeof(dh512_p), NULL);
dh->g = BN_bin2bn(dh512_g, sizeof(dh512_g), NULL);
if (dh->p == NULL ||
dh->g == NULL) {
DH_free(dh);
return NULL;
}
return dh;
}
/*
-----BEGIN DH PARAMETERS-----
MGYCYQD86LGZfS1NNkMtu4u+1QiV33mhjtrBljv+3TtoTMLulWgIUz0qxYdFtisC
Isc/29WPOBn4m8hxj57x4DjkKYeYnA2poxHxPF/eQZC2AUezPRrhk1ZSJz8337DA
vq6pv2MCAQU=
-----END DH PARAMETERS-----
*/
static unsigned char dh768_p[] = {
0xFC,0xE8,0xB1,0x99,0x7D,0x2D,0x4D,0x36,0x43,0x2D,0xBB,0x8B,
0xBE,0xD5,0x08,0x95,0xDF,0x79,0xA1,0x8E,0xDA,0xC1,0x96,0x3B,
0xFE,0xDD,0x3B,0x68,0x4C,0xC2,0xEE,0x95,0x68,0x08,0x53,0x3D,
0x2A,0xC5,0x87,0x45,0xB6,0x2B,0x02,0x22,0xC7,0x3F,0xDB,0xD5,
0x8F,0x38,0x19,0xF8,0x9B,0xC8,0x71,0x8F,0x9E,0xF1,0xE0,0x38,
0xE4,0x29,0x87,0x98,0x9C,0x0D,0xA9,0xA3,0x11,0xF1,0x3C,0x5F,
0xDE,0x41,0x90,0xB6,0x01,0x47,0xB3,0x3D,0x1A,0xE1,0x93,0x56,
0x52,0x27,0x3F,0x37,0xDF,0xB0,0xC0,0xBE,0xAE,0xA9,0xBF,0x63,
};
static unsigned char dh768_g[] = {
0x05,
};
static DH *get_dh768(void) {
DH *dh;
dh = DH_new();
if (dh == NULL)
return NULL;
dh->p = BN_bin2bn(dh768_p, sizeof(dh768_p), NULL);
dh->g = BN_bin2bn(dh768_g, sizeof(dh768_g), NULL);
if (dh->p == NULL ||
dh->g == NULL) {
DH_free(dh);
return NULL;
}
return dh;
}
/*
-----BEGIN DH PARAMETERS-----
MIGHAoGBAM34dKi6BP27gG9DOCuTB6Ue8uLY2t4K8le0w1yIa7a58vAnDq1CR3sl
MIcwK4Rz2pv7MyrIg9Haf5l4kUMx4wr0ORxCBesFLqFPVBjbL+wB8mfJmYC9zq81
02rLUgfDwHVI0dW9kwZPTiQJ0QXPI3OiYIyCR8vvebVI/Kjb5IcvAgEF
-----END DH PARAMETERS-----
*/
static unsigned char dh1024_p[] = {
0xCD,0xF8,0x74,0xA8,0xBA,0x04,0xFD,0xBB,0x80,0x6F,0x43,0x38,
0x2B,0x93,0x07,0xA5,0x1E,0xF2,0xE2,0xD8,0xDA,0xDE,0x0A,0xF2,
0x57,0xB4,0xC3,0x5C,0x88,0x6B,0xB6,0xB9,0xF2,0xF0,0x27,0x0E,
0xAD,0x42,0x47,0x7B,0x25,0x30,0x87,0x30,0x2B,0x84,0x73,0xDA,
0x9B,0xFB,0x33,0x2A,0xC8,0x83,0xD1,0xDA,0x7F,0x99,0x78,0x91,
0x43,0x31,0xE3,0x0A,0xF4,0x39,0x1C,0x42,0x05,0xEB,0x05,0x2E,
0xA1,0x4F,0x54,0x18,0xDB,0x2F,0xEC,0x01,0xF2,0x67,0xC9,0x99,
0x80,0xBD,0xCE,0xAF,0x35,0xD3,0x6A,0xCB,0x52,0x07,0xC3,0xC0,
0x75,0x48,0xD1,0xD5,0xBD,0x93,0x06,0x4F,0x4E,0x24,0x09,0xD1,
0x05,0xCF,0x23,0x73,0xA2,0x60,0x8C,0x82,0x47,0xCB,0xEF,0x79,
0xB5,0x48,0xFC,0xA8,0xDB,0xE4,0x87,0x2F,
};
static unsigned char dh1024_g[] = {
0x05,
};
static DH *get_dh1024(void) {
DH *dh;
dh = DH_new();
if (dh == NULL)
return NULL;
dh->p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), NULL);
dh->g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), NULL);
if (dh->p == NULL ||
dh->g == NULL) {
DH_free(dh);
return NULL;
}
return(dh);
}
/*
-----BEGIN DH PARAMETERS-----
MIHHAoHBANj1DAo+95M9B8V7pS3k8UROz+gu2Huuve0PglXlEtTfSr3KF6ga3EWs
22j97IJTkoxu0QswRjRBr64Kfk4pMTpX827oJoPc9n63xVpS47cpg/2W8ZyE9/ZK
lgABM2z0NasOXBMaau38U8cEebHwmrCi3rSJxBpwyU+7X4QEa3pI/WGml3NTzmRo
G95NAFZJcFLzFRX2VVf5YB4I4sVWCpRqVFL2HXB9ioauQ50DBYAjp72h182aCgWU
WR+44B88awIBAg==
-----END DH PARAMETERS-----
*/
static unsigned char dh1536_p[] = {
0xD8,0xF5,0x0C,0x0A,0x3E,0xF7,0x93,0x3D,0x07,0xC5,0x7B,0xA5,
0x2D,0xE4,0xF1,0x44,0x4E,0xCF,0xE8,0x2E,0xD8,0x7B,0xAE,0xBD,
0xED,0x0F,0x82,0x55,0xE5,0x12,0xD4,0xDF,0x4A,0xBD,0xCA,0x17,
0xA8,0x1A,0xDC,0x45,0xAC,0xDB,0x68,0xFD,0xEC,0x82,0x53,0x92,
0x8C,0x6E,0xD1,0x0B,0x30,0x46,0x34,0x41,0xAF,0xAE,0x0A,0x7E,
0x4E,0x29,0x31,0x3A,0x57,0xF3,0x6E,0xE8,0x26,0x83,0xDC,0xF6,
0x7E,0xB7,0xC5,0x5A,0x52,0xE3,0xB7,0x29,0x83,0xFD,0x96,0xF1,
0x9C,0x84,0xF7,0xF6,0x4A,0x96,0x00,0x01,0x33,0x6C,0xF4,0x35,
0xAB,0x0E,0x5C,0x13,0x1A,0x6A,0xED,0xFC,0x53,0xC7,0x04,0x79,
0xB1,0xF0,0x9A,0xB0,0xA2,0xDE,0xB4,0x89,0xC4,0x1A,0x70,0xC9,
0x4F,0xBB,0x5F,0x84,0x04,0x6B,0x7A,0x48,0xFD,0x61,0xA6,0x97,
0x73,0x53,0xCE,0x64,0x68,0x1B,0xDE,0x4D,0x00,0x56,0x49,0x70,
0x52,0xF3,0x15,0x15,0xF6,0x55,0x57,0xF9,0x60,0x1E,0x08,0xE2,
0xC5,0x56,0x0A,0x94,0x6A,0x54,0x52,0xF6,0x1D,0x70,0x7D,0x8A,
0x86,0xAE,0x43,0x9D,0x03,0x05,0x80,0x23,0xA7,0xBD,0xA1,0xD7,
0xCD,0x9A,0x0A,0x05,0x94,0x59,0x1F,0xB8,0xE0,0x1F,0x3C,0x6B,
};
static unsigned char dh1536_g[] = {
0x02,
};
static DH *get_dh1536(void) {
DH *dh;
dh = DH_new();
if (dh == NULL)
return NULL;
dh->p = BN_bin2bn(dh1536_p, sizeof(dh1536_p), NULL);
dh->g = BN_bin2bn(dh1536_g, sizeof(dh1536_g), NULL);
if (dh->p == NULL ||
dh->g == NULL) {
DH_free(dh);
return NULL;
}
return dh;
}
/*
-----BEGIN DH PARAMETERS-----
MIIBCAKCAQEAtIwmelcdbGINENw+vnQSB1GRpLrX2XW+jKX2EdYDsrrui7Kr7vbi
/qiWjvyzT0hCRjwIRc4dSnJrLDJgMit8dLCvvaamITdafpbVrnPE6jHV7AXuHdgH
T0hT4hrywYWrhs0GhlluFNtlYoBsD3953Uf6rxxCgkhySZu+HFEKEBQSk60OWS/6
HjIm+dH/vtN2TNWAefB/0vvGo0mTwhmqv45ZF1dzdEWkRtA3TCyVu7bpq6cseQ04
j6m3CeC06WoLVePnEQksSS9r5aloGAftoM+BlquS4oy9HDEtO+E2y0K45Yb0FUmA
TKHR1D+CqeQr/HWVGGQFBwPrk9MtHDna2wIBAg==
-----END DH PARAMETERS-----
*/
static unsigned char dh2048_p[] = {
0xB4,0x8C,0x26,0x7A,0x57,0x1D,0x6C,0x62,0x0D,0x10,0xDC,0x3E,
0xBE,0x74,0x12,0x07,0x51,0x91,0xA4,0xBA,0xD7,0xD9,0x75,0xBE,
0x8C,0xA5,0xF6,0x11,0xD6,0x03,0xB2,0xBA,0xEE,0x8B,0xB2,0xAB,
0xEE,0xF6,0xE2,0xFE,0xA8,0x96,0x8E,0xFC,0xB3,0x4F,0x48,0x42,
0x46,0x3C,0x08,0x45,0xCE,0x1D,0x4A,0x72,0x6B,0x2C,0x32,0x60,
0x32,0x2B,0x7C,0x74,0xB0,0xAF,0xBD,0xA6,0xA6,0x21,0x37,0x5A,
0x7E,0x96,0xD5,0xAE,0x73,0xC4,0xEA,0x31,0xD5,0xEC,0x05,0xEE,
0x1D,0xD8,0x07,0x4F,0x48,0x53,0xE2,0x1A,0xF2,0xC1,0x85,0xAB,
0x86,0xCD,0x06,0x86,0x59,0x6E,0x14,0xDB,0x65,0x62,0x80,0x6C,
0x0F,0x7F,0x79,0xDD,0x47,0xFA,0xAF,0x1C,0x42,0x82,0x48,0x72,
0x49,0x9B,0xBE,0x1C,0x51,0x0A,0x10,0x14,0x12,0x93,0xAD,0x0E,
0x59,0x2F,0xFA,0x1E,0x32,0x26,0xF9,0xD1,0xFF,0xBE,0xD3,0x76,
0x4C,0xD5,0x80,0x79,0xF0,0x7F,0xD2,0xFB,0xC6,0xA3,0x49,0x93,
0xC2,0x19,0xAA,0xBF,0x8E,0x59,0x17,0x57,0x73,0x74,0x45,0xA4,
0x46,0xD0,0x37,0x4C,0x2C,0x95,0xBB,0xB6,0xE9,0xAB,0xA7,0x2C,
0x79,0x0D,0x38,0x8F,0xA9,0xB7,0x09,0xE0,0xB4,0xE9,0x6A,0x0B,
0x55,0xE3,0xE7,0x11,0x09,0x2C,0x49,0x2F,0x6B,0xE5,0xA9,0x68,
0x18,0x07,0xED,0xA0,0xCF,0x81,0x96,0xAB,0x92,0xE2,0x8C,0xBD,
0x1C,0x31,0x2D,0x3B,0xE1,0x36,0xCB,0x42,0xB8,0xE5,0x86,0xF4,
0x15,0x49,0x80,0x4C,0xA1,0xD1,0xD4,0x3F,0x82,0xA9,0xE4,0x2B,
0xFC,0x75,0x95,0x18,0x64,0x05,0x07,0x03,0xEB,0x93,0xD3,0x2D,
0x1C,0x39,0xDA,0xDB,
};
static unsigned char dh2048_g[] = {
0x02,
};
static DH *get_dh2048(void) {
DH *dh;
dh = DH_new();
if (dh == NULL)
return NULL;
dh->p = BN_bin2bn(dh2048_p, sizeof(dh2048_p), NULL);
dh->g = BN_bin2bn(dh2048_g, sizeof(dh2048_g), NULL);
if (dh->p == NULL ||
dh->g == NULL) {
DH_free(dh);
return NULL;
}
return dh;
}
/* ASN1_BIT_STRING_cmp was renamed in 0.9.5 */
#if OPENSSL_VERSION_NUMBER < 0x00905100L
# define M_ASN1_BIT_STRING_cmp ASN1_BIT_STRING_cmp
#endif
/* From src/dirtree.c */
extern int ServerUseReverseDNS;
module tls_module;
typedef struct tls_pkey_obj {
struct tls_pkey_obj *next;
size_t pkeysz;
char *rsa_pkey;
void *rsa_pkey_ptr;
char *dsa_pkey;
void *dsa_pkey_ptr;
/* Used for stashing the password for a PKCS12 file, which should
* contain a certificate. Any passphrase for the private key for that
* certificate should be in one of the above RSA/DSA buffers.
*/
char *pkcs12_passwd;
void *pkcs12_passwd_ptr;
unsigned int flags;
server_rec *server;
} tls_pkey_t;
#define TLS_PKEY_USE_RSA 0x0100
#define TLS_PKEY_USE_DSA 0x0200
static tls_pkey_t *tls_pkey_list = NULL;
static unsigned int tls_npkeys = 0;
#define TLS_DEFAULT_CIPHER_SUITE "ALL:!ADH"
/* Module variables */
#if OPENSSL_VERSION_NUMBER > 0x000907000L
static const char *tls_crypto_device = NULL;
#endif
static unsigned char tls_engine = FALSE;
static unsigned long tls_flags = 0UL, tls_opts = 0UL;
static tls_pkey_t *tls_pkey = NULL;
static int tls_logfd = -1;
static char *tls_logname = NULL;
static char *tls_passphrase_provider = NULL;
#define TLS_PASSPHRASE_TIMEOUT 10
#define TLS_PASSPHRASE_FL_RSA_KEY 0x0001
#define TLS_PASSPHRASE_FL_DSA_KEY 0x0002
#define TLS_PASSPHRASE_FL_PKCS12_PASSWD 0x0004
#define TLS_PROTO_SSL_V3 0x0001
#define TLS_PROTO_TLS_V1 0x0002
static unsigned int tls_protocol = TLS_PROTO_SSL_V3|TLS_PROTO_TLS_V1;
static int tls_ssl_opts = SSL_OP_ALL|SSL_OP_NO_SSLv2|SSL_OP_SINGLE_DH_USE^SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
static int tls_required_on_auth = 0;
static int tls_required_on_ctrl = 0;
static int tls_required_on_data = 0;
static unsigned char *tls_authenticated = NULL;
/* mod_tls session flags */
#define TLS_SESS_ON_CTRL 0x0001
#define TLS_SESS_ON_DATA 0x0002
#define TLS_SESS_PBSZ_OK 0x0004
#define TLS_SESS_TLS_REQUIRED 0x0010
#define TLS_SESS_VERIFY_CLIENT 0x0020
#define TLS_SESS_NO_PASSWD_NEEDED 0x0040
#define TLS_SESS_NEED_DATA_PROT 0x0100
#define TLS_SESS_CTRL_RENEGOTIATING 0x0200
#define TLS_SESS_DATA_RENEGOTIATING 0x0400
#define TLS_SESS_HAVE_CCC 0x0800
/* mod_tls option flags */
#define TLS_OPT_NO_CERT_REQUEST 0x0001
#define TLS_OPT_VERIFY_CERT_FQDN 0x0002
#define TLS_OPT_VERIFY_CERT_IP_ADDR 0x0004
#define TLS_OPT_ALLOW_DOT_LOGIN 0x0008
#define TLS_OPT_EXPORT_CERT_DATA 0x0010
#define TLS_OPT_STD_ENV_VARS 0x0020
#define TLS_OPT_ALLOW_PER_USER 0x0040
#define TLS_OPT_ENABLE_DIAGS 0x0080
#define TLS_OPT_NO_SESSION_REUSE_REQUIRED 0x0100
#define TLS_OPT_USE_IMPLICIT_SSL 0x0200
#define TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS 0x0400
#define TLS_OPT_VERIFY_CERT_CN 0x0800
/* mod_tls cleanup flags */
#define TLS_CLEANUP_FL_SESS_INIT 0x0001
static char *tls_cipher_suite = NULL;
static char *tls_crl_file = NULL, *tls_crl_path = NULL;
static char *tls_dhparam_file = NULL;
static char *tls_dsa_cert_file = NULL, *tls_dsa_key_file = NULL;
static char *tls_pkcs12_file = NULL;
static char *tls_rsa_cert_file = NULL, *tls_rsa_key_file = NULL;
static char *tls_rand_file = NULL;
/* Timeout given for TLS handshakes. The default is 5 minutes. */
static unsigned int tls_handshake_timeout = 300;
static unsigned char tls_handshake_timed_out = FALSE;
static int tls_handshake_timer_id = -1;
/* Note: 9 is the default OpenSSL depth. */
static int tls_verify_depth = 9;
#if OPENSSL_VERSION_NUMBER > 0x000907000L
/* Renegotiate control channel on TLS sessions after 4 hours, by default. */
static int tls_ctrl_renegotiate_timeout = 14400;
/* Renegotiate data channel on TLS sessions after 1 gigabyte, by default. */
static off_t tls_data_renegotiate_limit = 1024 * 1024 * 1024;
/* Timeout given for renegotiations to occur before the TLS session is
* shutdown. The default is 30 seconds.
*/
static int tls_renegotiate_timeout = 30;
/* Is client acceptance of a requested renegotiation required? */
static unsigned char tls_renegotiate_required = TRUE;
#endif
static pr_netio_t *tls_ctrl_netio = NULL;
static pr_netio_stream_t *tls_ctrl_rd_nstrm = NULL;
static pr_netio_stream_t *tls_ctrl_wr_nstrm = NULL;
static pr_netio_t *tls_data_netio = NULL;
static pr_netio_stream_t *tls_data_rd_nstrm = NULL;
static pr_netio_stream_t *tls_data_wr_nstrm = NULL;
static tls_sess_cache_t *tls_sess_cache = NULL;
/* OpenSSL variables */
static SSL *ctrl_ssl = NULL;
static SSL_CTX *ssl_ctx = NULL;
static X509_STORE *tls_crl_store = NULL;
static DH *tls_tmp_dh = NULL;
static RSA *tls_tmp_rsa = NULL;
/* SSL/TLS support functions */
static void tls_closelog(void);
static void tls_end_sess(SSL *, int, int);
#define TLS_SHUTDOWN_BIDIRECTIONAL 0x0001
static void tls_fatal_error(long, int);
static const char *tls_get_errors(void);
static char *tls_get_page(size_t, void **);
static size_t tls_get_pagesz(void);
static int tls_get_passphrase(server_rec *, const char *, const char *,
char *, size_t, int);
static char *tls_get_subj_name(void);
static int tls_openlog(void);
static RSA *tls_rsa_cb(SSL *, int, int);
static int tls_seed_prng(void);
static void tls_setup_environ(SSL *);
static int tls_verify_cb(int, X509_STORE_CTX *);
static int tls_verify_crl(int, X509_STORE_CTX *);
static int tls_verify_ocsp(int, X509_STORE_CTX *);
static char *tls_x509_name_oneline(X509_NAME *);
static int tls_readmore(int);
static int tls_writemore(int);
/* Session cache API */
static tls_sess_cache_t *tls_sess_cache_get_cache(const char *);
static long tls_sess_cache_get_cache_mode(void);
static int tls_sess_cache_open(char *, long);
static int tls_sess_cache_close(void);
#ifdef PR_USE_CTRLS
static int tls_sess_cache_clear(void);
static int tls_sess_cache_remove(void);
static int tls_sess_cache_status(pr_ctrls_t *, int);
#endif /* PR_USE_CTRLS */
static int tls_sess_cache_add_sess_cb(SSL *, SSL_SESSION *);
static SSL_SESSION *tls_sess_cache_get_sess_cb(SSL *, unsigned char *, int,
int *);
static void tls_sess_cache_delete_sess_cb(SSL_CTX *, SSL_SESSION *);
#ifdef PR_USE_CTRLS
static pool *tls_act_pool = NULL;
static ctrls_acttab_t tls_acttab[];
#endif /* PR_USE_CTRLS */
static int tls_need_init_handshake = TRUE;
static const char *trace_channel = "tls";
static void tls_diags_cb(const SSL *ssl, int where, int ret) {
const char *str = "(unknown)";
int w;
pr_signals_handle();
w = where & ~SSL_ST_MASK;
if (w & SSL_ST_CONNECT) {
str = "connecting";
} else if (w & SSL_ST_ACCEPT) {
str = "accepting";
} else {
int ssl_state;
ssl_state = SSL_get_state(ssl);
if (ssl_state == SSL_ST_OK) {
str = "ok";
}
}
if (where & SSL_CB_ACCEPT_LOOP) {
int ssl_state;
ssl_state = SSL_get_state(ssl);
if (ssl_state == SSL3_ST_SR_CLNT_HELLO_A ||
ssl_state == SSL23_ST_SR_CLNT_HELLO_A) {
/* If we have already completed our initial handshake, then this might
* a session renegotiation.
*/
if (!tls_need_init_handshake) {
/* Yes, this is indeed a session renegotiation. If it's a
* renegotiation that we requested, allow it. If it is from a
* data connection, allow it. Otherwise, it's a client-initiated
* renegotiation, and we probably don't want to allow it.
*/
if (ssl == ctrl_ssl &&
!(tls_flags & TLS_SESS_CTRL_RENEGOTIATING) &&
!(tls_flags & TLS_SESS_DATA_RENEGOTIATING)) {
if (!(tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS)) {
tls_log("warning: client-initiated session renegotiation "
"detected, aborting connection");
pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
": client-initiated session renegotiation detected, "
"aborting connection");
tls_end_sess(ctrl_ssl, PR_NETIO_STRM_CTRL, 0);
tls_ctrl_rd_nstrm->strm_data = tls_ctrl_wr_nstrm->strm_data =
ctrl_ssl = NULL;
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
"TLSOption AllowClientRenegotiations");
}
}
}
#if OPENSSL_VERSION_NUMBER >= 0x009080cfL
} else if (ssl_state & SSL_ST_RENEGOTIATE) {
if (!tls_need_init_handshake) {
if (ssl == ctrl_ssl &&
!(tls_flags & TLS_SESS_CTRL_RENEGOTIATING) &&
!(tls_flags & TLS_SESS_DATA_RENEGOTIATING)) {
/* In OpenSSL-0.9.8l and later, SSL session renegotiations are
* automatically disabled. Thus if the admin has not explicitly
* configured support for client-initiated renegotations via the
* AllowClientRenegotiations TLSOption, then we need to disconnect
* the client here. Otherwise, the client would hang (up to the
* TLSTimeoutHandshake limit). Since we know, right now, that the
* handshake won't succeed, just drop the connection.
*/
if (!(tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS)) {
tls_log("warning: client-initiated session renegotiation detected, "
"aborting connection");
pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
": client-initiated session renegotiation detected, "
"aborting connection");
tls_end_sess(ctrl_ssl, PR_NETIO_STRM_CTRL, 0);
tls_ctrl_rd_nstrm->strm_data = tls_ctrl_wr_nstrm->strm_data =
ctrl_ssl = NULL;
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
"TLSOption AllowClientRenegotiations");
}
}
}
#endif
}
if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
tls_log("[info] %s: %s", str, SSL_state_string_long(ssl));
}
} else if (where & SSL_CB_HANDSHAKE_DONE) {
if (!tls_need_init_handshake) {
/* If this is an accepted renegotiation, log the possibly-changed
* ciphersuite et al.
*/
tls_log("%s renegotiation accepted, using cipher %s (%d bits)",
SSL_get_cipher_version(ssl), SSL_get_cipher_name(ssl),
SSL_get_cipher_bits(ssl, NULL));
}
tls_need_init_handshake = FALSE;
/* Clear the flags set for server-requested renegotiations. */
if (tls_flags & TLS_SESS_CTRL_RENEGOTIATING) {
tls_flags &= ~TLS_SESS_CTRL_RENEGOTIATING;
}
if (tls_flags & ~TLS_SESS_DATA_RENEGOTIATING) {
tls_flags &= ~TLS_SESS_DATA_RENEGOTIATING;
}
if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
tls_log("[info] %s: %s", str, SSL_state_string_long(ssl));
}
} else if (where & SSL_CB_LOOP) {
if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
tls_log("[info] %s: %s", str, SSL_state_string_long(ssl));
}
} else if (where & SSL_CB_ALERT) {
if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
str = (where & SSL_CB_READ) ? "reading" : "writing";
tls_log("[info] %s: SSL/TLS alert %s: %s", str,
SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
}
} else if (where & SSL_CB_EXIT) {
if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
if (ret == 0) {
tls_log("[info] %s: failed in %s: %s", str,
SSL_state_string_long(ssl), tls_get_errors());
} else if (ret < 0 &&
errno != 0 &&
errno != EAGAIN) {
/* Ignore EAGAIN errors */
tls_log("[info] %s: error in %s (errno %d: %s)",
str, SSL_state_string_long(ssl), errno, strerror(errno));
}
}
}
}
#if OPENSSL_VERSION_NUMBER > 0x000907000L
static void tls_msg_cb(int io_flag, int version, int content_type,
const void *buf, size_t buflen, SSL *ssl, void *arg) {
char *action_str = NULL;
char *version_str = NULL;
char *bytes_str = buflen != 1 ? "bytes" : "byte";
if (io_flag == 0) {
action_str = "received";
} else if (io_flag == 1) {
action_str = "sent";
}
switch (version) {
case SSL2_VERSION:
version_str = "SSLv2";
break;
case SSL3_VERSION:
version_str = "SSLv3";
break;
case TLS1_VERSION:
version_str = "TLSv1";
break;
}
if (version == SSL3_VERSION ||
version == TLS1_VERSION) {
switch (content_type) {
case 20:
/* ChangeCipherSpec message */
tls_log("[msg] %s %s ChangeCipherSpec message (%u %s)",
action_str, version_str, (unsigned int) buflen, bytes_str);
break;
case 21: {
/* Alert messages */
if (buflen == 2) {
char *severity_str = NULL;
/* Peek naughtily into the buffer. */
switch (((const unsigned char *) buf)[0]) {
case 1:
severity_str = "warning";
break;
case 2:
severity_str = "fatal";
break;
}
switch (((const unsigned char *) buf)[1]) {
case 0:
tls_log("[msg] %s %s %s 'close_notify' Alert message (%u %s)",
action_str, version_str, severity_str, (unsigned int) buflen,
bytes_str);
break;
case 10:
tls_log("[msg] %s %s %s 'unexpected_message' Alert message "
"(%u %s)", action_str, version_str, severity_str,
(unsigned int) buflen, bytes_str);
break;
case 20:
tls_log("[msg] %s %s %s 'bad_record_mac' Alert message (%u %s)",
action_str, version_str, severity_str, (unsigned int) buflen,
bytes_str);
break;
case 21:
tls_log("[msg] %s %s %s 'decryption_failed' Alert message "
"(%u %s)", action_str, version_str, severity_str,
(unsigned int) buflen, bytes_str);
break;
case 22:
tls_log("[msg] %s %s %s 'record_overflow' Alert message (%u %s)",
action_str, version_str, severity_str, (unsigned int) buflen,
bytes_str);
break;
case 30:
tls_log("[msg] %s %s %s 'decompression_failure' Alert message "
"(%u %s)", action_str, version_str, severity_str,
(unsigned int) buflen, bytes_str);
break;
case 40:
tls_log("[msg] %s %s %s 'handshake_failure' Alert message "
"(%u %s)", action_str, version_str, severity_str,
(unsigned int) buflen, bytes_str);
break;
}
} else {
tls_log("[msg] %s %s Alert message, unknown type (%u %s)", action_str,
version_str, (unsigned int) buflen, bytes_str);
}
break;
}
case 22: {
/* Handshake messages */
if (buflen > 0) {
/* Peek naughtily into the buffer. */
switch (((const unsigned char *) buf)[0]) {
case 0:
tls_log("[msg] %s %s 'HelloRequest' Handshake message (%u %s)",
action_str, version_str, (unsigned int) buflen, bytes_str);
break;
case 1:
tls_log("[msg] %s %s 'ClientHello' Handshake message (%u %s)",
action_str, version_str, (unsigned int) buflen, bytes_str);
break;
case 2:
tls_log("[msg] %s %s 'ServerHello' Handshake message (%u %s)",
action_str, version_str, (unsigned int) buflen, bytes_str);
break;
case 11:
tls_log("[msg] %s %s 'Certificate' Handshake message (%u %s)",
action_str, version_str, (unsigned int) buflen, bytes_str);
break;
case 12:
tls_log("[msg] %s %s 'ServerKeyExchange' Handshake message "
"(%u %s)", action_str, version_str, (unsigned int) buflen,
bytes_str);
break;
case 13:
tls_log("[msg] %s %s 'CertificateRequest' Handshake message "
"(%u %s)", action_str, version_str, (unsigned int) buflen,
bytes_str);
break;
case 14:
tls_log("[msg] %s %s 'ServerHelloDone' Handshake message (%u %s)",
action_str, version_str, (unsigned int) buflen, bytes_str);
break;
case 15:
tls_log("[msg] %s %s 'CertificateVerify' Handshake message "
"(%u %s)", action_str, version_str, (unsigned int) buflen,
bytes_str);
break;
case 16:
tls_log("[msg] %s %s 'ClientKeyExchange' Handshake message "
"(%u %s)", action_str, version_str, (unsigned int) buflen,
bytes_str);
break;
case 20:
tls_log("[msg] %s %s 'Finished' Handshake message (%u %s)",
action_str, version_str, (unsigned int) buflen, bytes_str);
break;
}
} else {
tls_log("[msg] %s %s Handshake message, unknown type (%u %s)",
action_str, version_str, (unsigned int) buflen, bytes_str);
}
break;
}
}
} else if (version == SSL2_VERSION) {
/* SSLv2 message. Ideally we wouldn't get these, but sometimes badly
* behaving FTPS clients send them.
*/
if (buflen > 0) {
/* Peek naughtily into the buffer. */
switch (((const unsigned char *) buf)[0]) {
case 0: {
/* Error */
if (buflen > 3) {
unsigned err_code = (((const unsigned char *) buf)[1] << 8) +
((const unsigned char *) buf)[2];
switch (err_code) {
case 0x0001:
tls_log("[msg] %s %s 'NO-CIPHER-ERROR' Error message (%u %s)",
action_str, version_str, (unsigned int) buflen, bytes_str);
break;
case 0x0002:
tls_log("[msg] %s %s 'NO-CERTIFICATE-ERROR' Error message "
"(%u %s)", action_str, version_str, (unsigned int) buflen,
bytes_str);
break;
case 0x0004:
tls_log("[msg] %s %s 'BAD-CERTIFICATE-ERROR' Error message "
"(%u %s)", action_str, version_str, (unsigned int) buflen,
bytes_str);
break;
case 0x0006:
tls_log("[msg] %s %s 'UNSUPPORTED-CERTIFICATE-TYPE-ERROR' "
"Error message (%u %s)", action_str, version_str,
(unsigned int) buflen, bytes_str);
break;
}
} else {
tls_log("[msg] %s %s Error message, unknown type (%u %s)",
action_str, version_str, (unsigned int) buflen, bytes_str);
}
break;
}
case 1:
tls_log("[msg] %s %s 'CLIENT-HELLO' message (%u %s)", action_str,
version_str, (unsigned int) buflen, bytes_str);
break;
case 2:
tls_log("[msg] %s %s 'CLIENT-MASTER-KEY' message (%u %s)", action_str,
version_str, (unsigned int) buflen, bytes_str);
break;
case 3:
tls_log("[msg] %s %s 'CLIENT-FINISHED' message (%u %s)", action_str,
version_str, (unsigned int) buflen, bytes_str);
break;
case 4:
tls_log("[msg] %s %s 'SERVER-HELLO' message (%u %s)", action_str,
version_str, (unsigned int) buflen, bytes_str);
break;
case 5:
tls_log("[msg] %s %s 'SERVER-VERIFY' message (%u %s)", action_str,
version_str, (unsigned int) buflen, bytes_str);
break;
case 6:
tls_log("[msg] %s %s 'SERVER-FINISHED' message (%u %s)", action_str,
version_str, (unsigned int) buflen, bytes_str);
break;
case 7:
tls_log("[msg] %s %s 'REQUEST-CERTIFICATE' message (%u %s)",
action_str, version_str, (unsigned int) buflen, bytes_str);
break;
case 8:
tls_log("[msg] %s %s 'CLIENT-CERTIFICATE' message (%u %s)",
action_str, version_str, (unsigned int) buflen, bytes_str);
break;
}
} else {
tls_log("[msg] %s %s message (%u %s)", action_str, version_str,
(unsigned int) buflen, bytes_str);
}
} else {
/* This case might indicate an issue with OpenSSL itself; the version
* given to the msg_callback function was not initialized, or not set to
* one of the recognized SSL/TLS versions. Weird.
*/
tls_log("[msg] %s message of unknown version (%d) (%u %s)", action_str,
version, (unsigned int) buflen, bytes_str);
}
}
#endif
static const char *get_printable_subjaltname(pool *p, const char *data,
size_t datalen) {
register unsigned int i;
char *ptr, *res;
size_t reslen = 0;
/* First, calculate the length of the resulting printable string we'll
* be generating.
*/
for (i = 0; i < datalen; i++) {
if (isprint((int) data[i])) {
reslen++;
} else {
reslen += 4;
}
}
/* Leave one space in the allocated string for the terminating NUL. */
ptr = res = pcalloc(p, reslen + 1);
for (i = 0; i < datalen; i++) {
if (isprint((int) data[i])) {
*(ptr++) = data[i];
} else {
snprintf(ptr, reslen - (ptr - res), "\\x%02x", data[i]);
ptr += 4;
}
}
return res;
}
static unsigned char tls_check_client_cert(SSL *ssl, conn_t *conn) {
X509 *cert = NULL;
unsigned char ok = FALSE, have_cn = FALSE, have_dns_ext = FALSE,
have_ipaddr_ext = FALSE;
/* Only perform these more stringent checks if asked to verify clients. */
if (!(tls_flags & TLS_SESS_VERIFY_CLIENT))
return TRUE;
/* Only perform these checks is configured to do so. */
if (!(tls_opts & TLS_OPT_VERIFY_CERT_FQDN) &&
!(tls_opts & TLS_OPT_VERIFY_CERT_IP_ADDR) &&
!(tls_opts & TLS_OPT_VERIFY_CERT_CN)) {
return TRUE;
}
/* Note: this should _never_ return NULL in this case. */
cert = SSL_get_peer_certificate(ssl);
/* Check the CN (Common Name) if configured. */
if (tls_opts & TLS_OPT_VERIFY_CERT_CN) {
X509_NAME *sn;
/* This does NOT increment a reference counter, thus we do NOT want
* call X509_NAME_free() on the returned pointer.
*/
sn = X509_get_subject_name(cert);
if (sn) {
STACK_OF(X509_NAME_ENTRY) *sk_name_ents;
register unsigned int i;
int nents;
/* XXX I don't like this direct access to the entries member */
sk_name_ents = sn->entries;
nents = sk_X509_NAME_ENTRY_num(sk_name_ents);
for (i = 0; i < nents; i++) {
X509_NAME_ENTRY *ent;
int nid;
ent = sk_X509_NAME_ENTRY_value(sk_name_ents, i);
nid = OBJ_obj2nid((ASN1_OBJECT *) X509_NAME_ENTRY_get_object(ent));
if (nid == NID_commonName) {
const char *ptr;
int len;
have_cn = TRUE;
/* XXX I don't like these direct accesses to the data and length
* members.
*/
ptr = (const char *) ent->value->data;
len = ent->value->length;
/* Check for CommonName values which contain embedded NULs. This
* can cause verification problems (spoofing), e.g. if the string is
* "www.goodguy.com\0www.badguy.com"; the use of strcmp() only checks
* "www.goodguy.com".
*/
if (len != strlen(ptr)) {
tls_log("%s", "client cert CommonName contains embedded NULs, "
"rejecting as possible spoof attempt");
tls_log("suspicious CommonName value: '%s'",
get_printable_subjaltname(conn->pool, (const char *) ptr, len));
X509_NAME_ENTRY_free(ent);
return FALSE;
} else {
if (strcmp(ptr, conn->remote_name) != 0) {
tls_log("client cert CommonName value '%s' != client FQDN '%s'",
ptr, conn->remote_name);
X509_NAME_ENTRY_free(ent);
return FALSE;
}
}
tls_log("%s", "client cert CommonName matches client FQDN");
ok = TRUE;
}
if (ok)
break;
}
}
}
/* Next, heck the subjectAltName X509v3 extensions, as is proper, for
* the IP address and FQDN.
*/
if ((tls_opts & TLS_OPT_VERIFY_CERT_IP_ADDR) ||
(tls_opts & TLS_OPT_VERIFY_CERT_FQDN)) {
STACK_OF(GENERAL_NAME) *sk_alt_names;
sk_alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
if (sk_alt_names) {
register unsigned int i;
int nnames = sk_GENERAL_NAME_num(sk_alt_names);
for (i = 0; i < nnames; i++) {
GENERAL_NAME *name = sk_GENERAL_NAME_value(sk_alt_names, i);
/* Only interested in the DNS and IP address types right now. */
switch (name->type) {
case GEN_DNS:
if (tls_opts & TLS_OPT_VERIFY_CERT_FQDN) {
const char *cert_dns_name = (const char *) name->d.ia5->data;
have_dns_ext = TRUE;
/* Check for subjectAltName values which contain embedded
* NULs. This can cause verification problems (spoofing),
* e.g. if the string is "www.goodguy.com\0www.badguy.com"; the
* use of strcmp() only checks "www.goodguy.com".
*/
if ((size_t) name->d.ia5->length != strlen(cert_dns_name)) {
tls_log("%s", "client cert dNSName contains embedded NULs, "
"rejecting as possible spoof attempt");
tls_log("suspicious dNSName value: '%s'",
get_printable_subjaltname(conn->pool,
(const char *) name->d.ia5->data,
(size_t) name->d.ia5->length));
GENERAL_NAME_free(name);
sk_GENERAL_NAME_free(sk_alt_names);
X509_free(cert);
return FALSE;
} else {
if (strcmp(cert_dns_name, conn->remote_name) != 0) {
tls_log("client cert dNSName value '%s' != client FQDN '%s'",
cert_dns_name, conn->remote_name);
GENERAL_NAME_free(name);
sk_GENERAL_NAME_free(sk_alt_names);
X509_free(cert);
return FALSE;
}
}
tls_log("%s", "client cert dNSName matches client FQDN");
ok = TRUE;
continue;
}
break;
case GEN_IPADD:
if (tls_opts & TLS_OPT_VERIFY_CERT_IP_ADDR) {
char cert_ipstr[INET_ADDRSTRLEN + 1] = {'\0'};
const char *cert_ipaddr = (const char *) name->d.ia5->data;
/* Note: OpenSSL doesn't support IPv6 addresses in the
* ipAddress name yet.
*/
memset(cert_ipstr, '\0', sizeof(cert_ipstr));
snprintf(cert_ipstr, sizeof(cert_ipstr) - 1, "%u.%u.%u.%u",
cert_ipaddr[0], cert_ipaddr[1], cert_ipaddr[2], cert_ipaddr[3]);
have_ipaddr_ext = TRUE;
if (strcmp(cert_ipstr, pr_netaddr_get_ipstr(conn->remote_addr))) {
tls_log("client cert iPAddress value '%s' != client IP '%s'",
cert_ipstr, pr_netaddr_get_ipstr(conn->remote_addr));
GENERAL_NAME_free(name);
sk_GENERAL_NAME_free(sk_alt_names);
X509_free(cert);
return FALSE;
}
tls_log("%s", "client cert iPAddress matches client IP");
ok = TRUE;
continue;
}
break;
default:
break;
}
GENERAL_NAME_free(name);
}
sk_GENERAL_NAME_free(sk_alt_names);
}
}
if ((tls_opts & TLS_OPT_VERIFY_CERT_CN) &&
!have_cn) {
tls_log("%s", "client cert missing required X509v3 CommonName");
}
if ((tls_opts & TLS_OPT_VERIFY_CERT_FQDN) &&
!have_dns_ext) {
tls_log("%s", "client cert missing required X509v3 subjectAltName dNSName");
}
if ((tls_opts & TLS_OPT_VERIFY_CERT_IP_ADDR) &&
!have_ipaddr_ext) {
tls_log("%s", "client cert missing required X509v3 subjectAltName iPAddress");
}
X509_free(cert);
if (!ok)
return FALSE;
return TRUE;
}
struct tls_pkey_data {
server_rec *s;
int flags;
char *buf;
size_t buflen, bufsz;
const char *prompt;
};
static void tls_prepare_provider_fds(int stdout_fd, int stderr_fd) {
unsigned long nfiles = 0;
register unsigned int i = 0;
struct rlimit rlim;
if (stdout_fd != STDOUT_FILENO) {
if (dup2(stdout_fd, STDOUT_FILENO) < 0)
tls_log("error duping fd %d to stdout: %s", stdout_fd, strerror(errno));
close(stdout_fd);
}
if (stderr_fd != STDERR_FILENO) {
if (dup2(stderr_fd, STDERR_FILENO) < 0)
tls_log("error duping fd %d to stderr: %s", stderr_fd, strerror(errno));
close(stderr_fd);
}
/* Make sure not to pass on open file descriptors. For stdout and stderr,
* we dup some pipes, so that we can capture what the command may write
* to stdout or stderr. The stderr output will be logged to the TLSLog.
*
* First, use getrlimit() to obtain the maximum number of open files
* for this process -- then close that number.
*/
#if defined(RLIMIT_NOFILE) || defined(RLIMIT_OFILE)
# if defined(RLIMIT_NOFILE)
if (getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
# elif defined(RLIMIT_OFILE)
if (getrlimit(RLIMIT_OFILE, &rlim) < 0) {
# endif
tls_log("getrlimit error: %s", strerror(errno));
/* Pick some arbitrary high number. */
nfiles = 255;
} else
nfiles = rlim.rlim_max;
#else /* no RLIMIT_NOFILE or RLIMIT_OFILE */
nfiles = 255;
#endif
if (nfiles > 255)
nfiles = 255;
/* Close the "non-standard" file descriptors. */
for (i = 3; i < nfiles; i++)
(void) close(i);
return;
}
static void tls_prepare_provider_pipes(int *stdout_pipe, int *stderr_pipe) {
if (pipe(stdout_pipe) < 0) {
tls_log("error opening stdout pipe: %s", strerror(errno));
stdout_pipe[0] = -1;
stdout_pipe[1] = STDOUT_FILENO;
} else {
if (fcntl(stdout_pipe[0], F_SETFD, FD_CLOEXEC) < 0)
tls_log("error setting close-on-exec flag on stdout pipe read fd: %s",
strerror(errno));
if (fcntl(stdout_pipe[1], F_SETFD, 0) < 0)
tls_log("error setting close-on-exec flag on stdout pipe write fd: %s",
strerror(errno));
}
if (pipe(stderr_pipe) < 0) {
tls_log("error opening stderr pipe: %s", strerror(errno));
stderr_pipe[0] = -1;
stderr_pipe[1] = STDERR_FILENO;
} else {
if (fcntl(stderr_pipe[0], F_SETFD, FD_CLOEXEC) < 0)
tls_log("error setting close-on-exec flag on stderr pipe read fd: %s",
strerror(errno));
if (fcntl(stderr_pipe[1], F_SETFD, 0) < 0)
tls_log("error setting close-on-exec flag on stderr pipe write fd: %s",
strerror(errno));
}
}
static int tls_exec_passphrase_provider(server_rec *s, char *buf, int buflen,
int flags) {
pid_t pid;
int status;
int stdout_pipe[2], stderr_pipe[2];
struct sigaction sa_ignore, sa_intr, sa_quit;
sigset_t set_chldmask, set_save;
/* Prepare signal dispositions. */
sa_ignore.sa_handler = SIG_IGN;
sigemptyset(&sa_ignore.sa_mask);
sa_ignore.sa_flags = 0;
if (sigaction(SIGINT, &sa_ignore, &sa_intr) < 0)
return -1;
if (sigaction(SIGQUIT, &sa_ignore, &sa_quit) < 0)
return -1;
sigemptyset(&set_chldmask);
sigaddset(&set_chldmask, SIGCHLD);
if (sigprocmask(SIG_BLOCK, &set_chldmask, &set_save) < 0)
return -1;
tls_prepare_provider_pipes(stdout_pipe, stderr_pipe);
pid = fork();
if (pid < 0) {
pr_log_pri(PR_LOG_ERR, MOD_TLS_VERSION ": error: unable to fork: %s",
strerror(errno));
status = -1;
} else if (pid == 0) {
char nbuf[32];
pool *tmp_pool;
char *stdin_argv[4];
/* Child process */
/* Note: there is no need to clean up this temporary pool, as we've
* forked. If the exec call succeeds, this child process will exit
* normally, and its process space recovered by the OS. If the exec
* call fails, we still exit, and the process space is recovered by
* the OS. Either way, the memory will be cleaned up without need for
* us to do it explicitly (unless one wanted to be pedantic about it,
* of course).
*/
tmp_pool = make_sub_pool(s->pool);
/* Restore previous signal actions. */
sigaction(SIGINT, &sa_intr, NULL);
sigaction(SIGQUIT, &sa_quit, NULL);
sigprocmask(SIG_SETMASK, &set_save, NULL);
stdin_argv[0] = pstrdup(tmp_pool, tls_passphrase_provider);
memset(nbuf, '\0', sizeof(nbuf));
snprintf(nbuf, sizeof(nbuf)-1, "%u", (unsigned int) s->ServerPort);
nbuf[sizeof(nbuf)-1] = '\0';
stdin_argv[1] = pstrcat(tmp_pool, s->ServerName, ":", nbuf, NULL);
if (flags & TLS_PASSPHRASE_FL_RSA_KEY) {
stdin_argv[2] = pstrdup(tmp_pool, "RSA");
} else if (flags & TLS_PASSPHRASE_FL_DSA_KEY) {
stdin_argv[2] = pstrdup(tmp_pool, "DSA");
} else if (flags & TLS_PASSPHRASE_FL_PKCS12_PASSWD) {
stdin_argv[2] = pstrdup(tmp_pool, "PKCS12");
}
stdin_argv[3] = NULL;
PRIVS_ROOT
pr_trace_msg(trace_channel, 17,
"executing '%s' with uid %lu (euid %lu), gid %lu (egid %lu)",
tls_passphrase_provider,
(unsigned long) getuid(), (unsigned long) geteuid(),
(unsigned long) getgid(), (unsigned long) getegid());
pr_log_debug(DEBUG6, MOD_TLS_VERSION
": executing '%s' with uid %lu (euid %lu), gid %lu (egid %lu)",
tls_passphrase_provider,
(unsigned long) getuid(), (unsigned long) geteuid(),
(unsigned long) getgid(), (unsigned long) getegid());
/* Prepare the file descriptors that the process will inherit. */
tls_prepare_provider_fds(stdout_pipe[1], stderr_pipe[1]);
errno = 0;
execv(tls_passphrase_provider, stdin_argv);
/* Since all previous file descriptors (including those for log files)
* have been closed, and root privs have been revoked, there's little
* chance of directing a message of execv() failure to proftpd's log
* files. execv() only returns if there's an error; the only way we
* can signal this to the waiting parent process is to exit with a
* non-zero value (the value of errno will do nicely).
*/
exit(errno);
} else {
int res;
int maxfd, fds, send_sigterm = 1;
fd_set readfds;
time_t start_time = time(NULL);
struct timeval tv;
/* Parent process */
close(stdout_pipe[1]);
close(stderr_pipe[1]);
maxfd = (stderr_pipe[0] > stdout_pipe[0]) ?
stderr_pipe[0] : stdout_pipe[0];
res = waitpid(pid, &status, WNOHANG);
while (res <= 0) {
if (res < 0) {
if (errno != EINTR) {
pr_log_debug(DEBUG2, MOD_TLS_VERSION
": passphrase provider error: unable to wait for pid %u: %s",
(unsigned int) pid, strerror(errno));
status = -1;
break;
} else {
pr_signals_handle();
}
}
/* Check the time elapsed since we started. */
if ((time(NULL) - start_time) > TLS_PASSPHRASE_TIMEOUT) {
/* Send TERM, the first time, to be polite. */
if (send_sigterm) {
send_sigterm = 0;
pr_log_debug(DEBUG6, MOD_TLS_VERSION
": '%s' has exceeded the timeout (%lu seconds), sending "
"SIGTERM (signal %d)", tls_passphrase_provider,
(unsigned long) TLS_PASSPHRASE_TIMEOUT, SIGTERM);
kill(pid, SIGTERM);
} else {
/* The child is still around? Terminate with extreme prejudice. */
pr_log_debug(DEBUG6, MOD_TLS_VERSION
": '%s' has exceeded the timeout (%lu seconds), sending "
"SIGKILL (signal %d)", tls_passphrase_provider,
(unsigned long) TLS_PASSPHRASE_TIMEOUT, SIGKILL);
kill(pid, SIGKILL);
}
}
/* Select on the pipe read fds, to see if the child has anything
* to tell us.
*/
FD_ZERO(&readfds);
FD_SET(stdout_pipe[0], &readfds);
FD_SET(stderr_pipe[0], &readfds);
/* Note: this delay should be configurable somehow. */
tv.tv_sec = 2L;
tv.tv_usec = 0L;
fds = select(maxfd + 1, &readfds, NULL, NULL, &tv);
if (fds == -1 &&
errno == EINTR)
pr_signals_handle();
if (fds > 0) {
/* The child sent us something. How thoughtful. */
if (FD_ISSET(stdout_pipe[0], &readfds)) {
res = read(stdout_pipe[0], buf, buflen);
if (res > 0) {
while (res && (buf[res-1] == '\r' || buf[res-1] == '\n'))
res--;
buf[res] = '\0';
pr_trace_msg(trace_channel, 18,
"read passphrase from '%s'", tls_passphrase_provider);
} else if (res < 0) {
int xerrno = errno;
pr_trace_msg(trace_channel, 3,
"error reading stdout from '%s': %s",
tls_passphrase_provider, strerror(xerrno));
pr_log_debug(DEBUG2, MOD_TLS_VERSION
": error reading stdout from '%s': %s",
tls_passphrase_provider, strerror(xerrno));
}
}
if (FD_ISSET(stderr_pipe[0], &readfds)) {
int stderrlen;
char stderrbuf[PIPE_BUF];
memset(stderrbuf, '\0', sizeof(stderrbuf));
stderrlen = read(stderr_pipe[0], stderrbuf, sizeof(stderrbuf)-1);
if (stderrlen > 0) {
while (stderrlen &&
(stderrbuf[stderrlen-1] == '\r' ||
stderrbuf[stderrlen-1] == '\n'))
stderrlen--;
stderrbuf[stderrlen] = '\0';
pr_log_debug(DEBUG5, MOD_TLS_VERSION
": stderr from '%s': %s", tls_passphrase_provider,
stderrbuf);
} else if (res < 0) {
pr_log_debug(DEBUG2, MOD_TLS_VERSION
": error reading stderr from '%s': %s",
tls_passphrase_provider, strerror(errno));
}
}
}
res = waitpid(pid, &status, WNOHANG);
}
}
/* Restore the previous signal actions. */
if (sigaction(SIGINT, &sa_intr, NULL) < 0)
return -1;
if (sigaction(SIGQUIT, &sa_quit, NULL) < 0)
return -1;
if (sigprocmask(SIG_SETMASK, &set_save, NULL) < 0)
return -1;
if (WIFSIGNALED(status)) {
pr_log_debug(DEBUG2, MOD_TLS_VERSION
": '%s' died from signal %d", tls_passphrase_provider,
WTERMSIG(status));
errno = EPERM;
return -1;
}
return 0;
}
static int tls_passphrase_cb(char *buf, int buflen, int rwflag, void *d) {
static int need_banner = TRUE;
struct tls_pkey_data *pdata = d;
if (!tls_passphrase_provider) {
register unsigned int attempt;
int pwlen = 0;
tls_log("requesting passphrase from admin");
/* Similar to Apache's mod_ssl, we want to be nice, and display an
* informative message to the proftpd admin, telling them for what
* server they are being requested to provide a passphrase.
*/
if (need_banner) {
fprintf(stderr, "\nPlease provide passphrases for these encrypted certificate keys:\n");
need_banner = FALSE;
}
/* You get three attempts at entering the passphrase correctly. */
for (attempt = 0; attempt < 3; attempt++) {
int res;
/* Always handle signals in a loop. */
pr_signals_handle();
res = EVP_read_pw_string(buf, buflen, pdata->prompt, TRUE);
/* A return value of zero from EVP_read_pw_string() means success; -1
* means a system error occurred, and 1 means user interaction problems.
*/
if (res != 0) {
fprintf(stderr, "\nPassphrases do not match. Please try again.\n");
continue;
}
pwlen = strlen(buf);
if (pwlen < 1) {
fprintf(stderr, "Error: passphrase must be at least one character\n");
} else {
sstrncpy(pdata->buf, buf, pdata->bufsz);
pdata->buflen = pwlen;
return pwlen;
}
}
} else {
tls_log("requesting passphrase from '%s'", tls_passphrase_provider);
if (tls_exec_passphrase_provider(pdata->s, buf, buflen, pdata->flags) < 0) {
tls_log("error obtaining passphrase from '%s': %s",
tls_passphrase_provider, strerror(errno));
} else {
sstrncpy(pdata->buf, buf, pdata->bufsz);
pdata->buflen = strlen(buf);
return pdata->buflen;
}
}
#if OPENSSL_VERSION_NUMBER < 0x00908001
PEMerr(PEM_F_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
#else
PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
#endif
pr_memscrub(buf, buflen);
return -1;
}
static int prompt_fd = -1;
static void set_prompt_fds(void) {
/* Reconnect stderr to the term because proftpd connects stderr, earlier,
* to the general stderr logfile.
*/
prompt_fd = open("/dev/null", O_WRONLY);
if (prompt_fd == -1)
/* This is an arbitrary, meaningless placeholder number. */
prompt_fd = 76;
dup2(STDERR_FILENO, prompt_fd);
dup2(STDOUT_FILENO, STDERR_FILENO);
}
static void restore_prompt_fds(void) {
dup2(prompt_fd, STDERR_FILENO);
close(prompt_fd);
prompt_fd = -1;
}
static int tls_get_pkcs12_passwd(server_rec *s, FILE *fp, const char *prompt,
char *buf, size_t bufsz, int flags, struct tls_pkey_data *pdata) {
EVP_PKEY *pkey = NULL;
X509 *cert = NULL;
PKCS12 *p12 = NULL;
char *passwd = NULL;
int res, ok = FALSE;
p12 = d2i_PKCS12_fp(fp, NULL);
if (p12 != NULL) {
/* Check if a password is needed. */
res = PKCS12_verify_mac(p12, NULL, 0);
if (res == 1) {
passwd = NULL;
} else if (res == 0) {
res = PKCS12_verify_mac(p12, "", 0);
if (res == 1) {
passwd = "";
}
}
if (res == 0) {
register unsigned int attempt;
/* This PKCS12 file is password-protected; need to get the password
* from the admin.
*/
for (attempt = 0; attempt < 3; attempt++) {
int len = -1;
/* Always handle signals in a loop. */
pr_signals_handle();
len = tls_passphrase_cb(buf, bufsz, 0, pdata);
if (len > 0) {
res = PKCS12_verify_mac(p12, buf, -1);
if (res == 1) {
#if OPENSSL_VERSION_NUMBER >= 0x000905000L
/* Use the obtained password as additional entropy, ostensibly
* unknown to attackers who may be watching the network, for
* OpenSSL's PRNG.
*
* Human language gives about 2-3 bits of entropy per byte
* (as per RFC1750).
*/
RAND_add(buf, pdata->buflen, pdata->buflen * 0.25);
#endif
res = PKCS12_parse(p12, buf, &pkey, &cert, NULL);
if (res != 1) {
PKCS12_free(p12);
return -1;
}
ok = TRUE;
break;
}
}
ERR_clear_error();
fprintf(stderr, "\nWrong password for this PKCS12 file. Please try again.\n");
}
} else {
res = PKCS12_parse(p12, passwd, &pkey, &cert, NULL);
if (res != 1) {
PKCS12_free(p12);
return -1;
}
ok = TRUE;
}
} else {
fprintf(stderr, "\nUnable to read PKCS12 file.\n");
return -1;
}
/* Now we should have an EVP_PKEY (which may or may not need a passphrase),
* and a cert. We don't really care about the cert right now. But we
* DO need to get the passphrase for the private key. Do this by writing
* the key to a BIO, then calling tls_get_passphrase() for that BIO.
*
* It looks like OpenSSL's pkcs12 command-line tool does not allow
* passphrase-protected keys to be written into a PKCS12 structure;
* the key is decrypted first (hence, probably, the password protection
* for the entire PKCS12 structure). Can the same be assumed to be true
* for PKCS12 files created via other applications?
*
* For now, assume yes, that all PKCS12 files will have private keys which
* are not encrypted. If this is found to NOT be the case, then we
* will need to write the obtained private key out to a BIO somehow,
* then call tls_get_passphrase() on that BIO, rather than on a path.
*/
if (cert)
X509_free(cert);
if (pkey)
EVP_PKEY_free(pkey);
if (p12)
PKCS12_free(p12);
if (!ok) {
#if OPENSSL_VERSION_NUMBER < 0x00908001
PEMerr(PEM_F_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
#else
PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
#endif
return -1;
}
ERR_clear_error();
return res;
}
static int tls_get_passphrase(server_rec *s, const char *path,
const char *prompt, char *buf, size_t bufsz, int flags) {
FILE *keyf = NULL;
EVP_PKEY *pkey = NULL;
struct tls_pkey_data pdata;
register unsigned int attempt;
if (path) {
int fd, res;
/* Open an fp on the cert file. */
PRIVS_ROOT
fd = open(path, O_RDONLY);
PRIVS_RELINQUISH
if (fd < 0) {
SYSerr(SYS_F_FOPEN, errno);
return -1;
}
/* Make sure the fd isn't one of the big three. */
res = pr_fs_get_usable_fd(fd);
if (res >= 0) {
fd = res;
}
keyf = fdopen(fd, "r");
if (keyf == NULL) {
SYSerr(SYS_F_FOPEN, errno);
return -1;
}
}
pdata.s = s;
pdata.flags = flags;
pdata.buf = buf;
pdata.buflen = 0;
pdata.bufsz = bufsz;
pdata.prompt = prompt;
set_prompt_fds();
if (flags & TLS_PASSPHRASE_FL_PKCS12_PASSWD) {
int res;
res = tls_get_pkcs12_passwd(s, keyf, prompt, buf, bufsz, flags, &pdata);
if (keyf)
fclose(keyf);
/* Restore the normal stderr logging. */
restore_prompt_fds();
return res;
}
/* The user gets three tries to enter the correct passphrase. */
for (attempt = 0; attempt < 3; attempt++) {
/* Always handle signals in a loop. */
pr_signals_handle();
pkey = PEM_read_PrivateKey(keyf, NULL, tls_passphrase_cb, &pdata);
if (pkey)
break;
if (keyf)
fseek(keyf, 0, SEEK_SET);
ERR_clear_error();
fprintf(stderr, "\nWrong passphrase for this key. Please try again.\n");
}
if (keyf)
fclose(keyf);
/* Restore the normal stderr logging. */
restore_prompt_fds();
if (pkey == NULL)
return -1;
EVP_PKEY_free(pkey);
#if OPENSSL_VERSION_NUMBER >= 0x000905000L
/* Use the obtained passphrase as additional entropy, ostensibly
* unknown to attackers who may be watching the network, for
* OpenSSL's PRNG.
*
* Human language gives about 2-3 bits of entropy per byte (RFC1750).
*/
RAND_add(buf, pdata.buflen, pdata.buflen * 0.25);
#endif
#ifdef HAVE_MLOCK
PRIVS_ROOT
if (mlock(buf, bufsz) < 0)
pr_log_debug(DEBUG1, MOD_TLS_VERSION
": error locking passphrase into memory: %s", strerror(errno));
else
pr_log_debug(DEBUG1, MOD_TLS_VERSION ": passphrase locked into memory");
PRIVS_RELINQUISH
#endif
return 0;
}
static int tls_handshake_timeout_cb(CALLBACK_FRAME) {
tls_handshake_timed_out = TRUE;
return 0;
}
static tls_pkey_t *tls_lookup_pkey(void) {
tls_pkey_t *k, *pkey = NULL;
for (k = tls_pkey_list; k; k = k->next) {
/* If this pkey matches the current server_rec, mark it and move on. */
if (k->server == main_server) {
#ifdef HAVE_MLOCK
/* mlock() the passphrase memory areas again; page locks are not
* inherited across forks.
*/
PRIVS_ROOT
if (k->rsa_pkey) {
if (mlock(k->rsa_pkey, k->pkeysz) < 0)
tls_log("error locking passphrase into memory: %s", strerror(errno));
}
if (k->dsa_pkey) {
if (mlock(k->dsa_pkey, k->pkeysz) < 0)
tls_log("error locking passphrase into memory: %s", strerror(errno));
}
if (k->pkcs12_passwd) {
if (mlock(k->pkcs12_passwd, k->pkeysz) < 0)
tls_log("error locking password into memory: %s", strerror(errno));
}
PRIVS_RELINQUISH
#endif /* HAVE_MLOCK */
pkey = k;
continue;
}
/* Otherwise, scrub the passphrase's memory areas. */
if (k->rsa_pkey) {
pr_memscrub(k->rsa_pkey, k->pkeysz);
free(k->rsa_pkey_ptr);
k->rsa_pkey = k->rsa_pkey_ptr = NULL;
}
if (k->dsa_pkey) {
pr_memscrub(k->dsa_pkey, k->pkeysz);
free(k->dsa_pkey_ptr);
k->dsa_pkey = k->dsa_pkey_ptr = NULL;
}
if (k->pkcs12_passwd) {
pr_memscrub(k->pkcs12_passwd, k->pkeysz);
free(k->pkcs12_passwd_ptr);
k->pkcs12_passwd = k->pkcs12_passwd_ptr = NULL;
}
}
return pkey;
}
static int tls_pkey_cb(char *buf, int buflen, int rwflag, void *data) {
tls_pkey_t *k;
if (!data)
return 0;
k = (tls_pkey_t *) data;
if ((k->flags & TLS_PKEY_USE_RSA) && k->rsa_pkey) {
strncpy(buf, k->rsa_pkey, buflen);
buf[buflen - 1] = '\0';
return strlen(buf);
}
if ((k->flags & TLS_PKEY_USE_DSA) && k->dsa_pkey) {
strncpy(buf, k->dsa_pkey, buflen);
buf[buflen - 1] = '\0';
return strlen(buf);
}
return 0;
}
static void tls_scrub_pkeys(void) {
tls_pkey_t *k;
/* Scrub and free all passphrases in memory. */
if (tls_pkey_list) {
pr_log_debug(DEBUG5, MOD_TLS_VERSION
": scrubbing %u %s from memory",
tls_npkeys, tls_npkeys != 1 ? "passphrases" : "passphrase");
} else {
return;
}
for (k = tls_pkey_list; k; k = k->next) {
if (k->rsa_pkey) {
pr_memscrub(k->rsa_pkey, k->pkeysz);
free(k->rsa_pkey_ptr);
k->rsa_pkey = k->rsa_pkey_ptr = NULL;
}
if (k->dsa_pkey) {
pr_memscrub(k->dsa_pkey, k->pkeysz);
free(k->dsa_pkey_ptr);
k->dsa_pkey = k->dsa_pkey_ptr = NULL;
}
if (k->pkcs12_passwd) {
pr_memscrub(k->pkcs12_passwd, k->pkeysz);
free(k->pkcs12_passwd_ptr);
k->pkcs12_passwd = k->pkcs12_passwd_ptr = NULL;
}
}
tls_pkey_list = NULL;
tls_npkeys = 0;
}
#if OPENSSL_VERSION_NUMBER > 0x000907000L
static int tls_renegotiate_timeout_cb(CALLBACK_FRAME) {
if ((tls_flags & TLS_SESS_ON_CTRL) &&
(tls_flags & TLS_SESS_CTRL_RENEGOTIATING)) {
if (!SSL_renegotiate_pending(ctrl_ssl)) {
tls_log("%s", "control channel TLS session renegotiated");
tls_flags &= ~TLS_SESS_CTRL_RENEGOTIATING;
} else if (tls_renegotiate_required) {
tls_log("%s", "requested TLS renegotiation timed out on control channel");
tls_log("%s", "shutting down control channel TLS session");
tls_end_sess(ctrl_ssl, PR_NETIO_STRM_CTRL, 0);
tls_ctrl_rd_nstrm->strm_data = tls_ctrl_wr_nstrm->strm_data =
ctrl_ssl = NULL;
}
}
if ((tls_flags & TLS_SESS_ON_DATA) &&
(tls_flags & TLS_SESS_DATA_RENEGOTIATING)) {
if (!SSL_renegotiate_pending((SSL *) tls_data_wr_nstrm->strm_data)) {
tls_log("%s", "data channel TLS session renegotiated");
tls_flags &= ~TLS_SESS_DATA_RENEGOTIATING;
} else if (tls_renegotiate_required) {
tls_log("%s", "requested TLS renegotiation timed out on data channel");
tls_log("%s", "shutting down data channel TLS session");
tls_end_sess((SSL *) tls_data_wr_nstrm->strm_data, PR_NETIO_STRM_DATA, 0);
tls_data_rd_nstrm->strm_data = tls_data_wr_nstrm->strm_data = NULL;
}
}
return 0;
}
static int tls_ctrl_renegotiate_cb(CALLBACK_FRAME) {
if (tls_flags & TLS_SESS_ON_CTRL) {
if (TRUE
#if OPENSSL_VERSION_NUMBER >= 0x009080cfL
/* In OpenSSL-0.9.8l and later, SSL session renegotiations
* (both client- and server-initiated) are automatically disabled.
* Unless the admin explicitly configured support for
* client-initiated renegotations via the AllowClientRenegotiations
* TLSOption, we can't request renegotiations ourselves.
*/
&& (tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS)
#endif
) {
tls_flags |= TLS_SESS_CTRL_RENEGOTIATING;
tls_log("requesting TLS renegotiation on control channel "
"(%lu sec renegotiation interval)", p1);
SSL_renegotiate(ctrl_ssl);
/* SSL_do_handshake(ctrl_ssl); */
pr_timer_add(tls_renegotiate_timeout, -1, &tls_module,
tls_renegotiate_timeout_cb, "SSL/TLS renegotiation");
/* Restart the timer. */
return 1;
}
}
return 0;
}
#endif
static DH *tls_dh_cb(SSL *ssl, int is_export, int keylength) {
FILE *fp = NULL;
if (tls_tmp_dh) {
return tls_tmp_dh;
}
if (tls_dhparam_file) {
fp = fopen(tls_dhparam_file, "r");
if (fp) {
tls_tmp_dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
fclose(fp);
if (tls_tmp_dh) {
return tls_tmp_dh;
}
} else {
pr_log_debug(DEBUG3, MOD_TLS_VERSION
": unable to open TLSDHParamFile '%s': %s", tls_dhparam_file,
strerror(errno));
}
}
switch (keylength) {
case 512:
tls_tmp_dh = get_dh512();
break;
case 768:
tls_tmp_dh = get_dh768();
break;
case 1024:
tls_tmp_dh = get_dh1024();
break;
case 1536:
tls_tmp_dh = get_dh1536();
break;
case 2048:
tls_tmp_dh = get_dh2048();
break;
default:
tls_log("unsupported DH key length %d requested, returning 1024 bits",
keylength);
tls_tmp_dh = get_dh1024();
break;
}
return tls_tmp_dh;
}
/* Post 0.9.7a, RSA blinding is turned on by default, so there is no need to
* do this manually.
*/
#if OPENSSL_VERSION_NUMBER < 0x0090702fL
static void tls_blinding_on(SSL *ssl) {
EVP_PKEY *pkey = NULL;
RSA *rsa = NULL;
/* RSA keys are subject to timing attacks. To attempt to make such
* attacks harder, use RSA blinding.
*/
pkey = SSL_get_privatekey(ssl);
if (pkey)
rsa = EVP_PKEY_get1_RSA(pkey);
if (rsa) {
if (RSA_blinding_on(rsa, NULL) != 1)
tls_log("error setting RSA blinding: %s",
ERR_error_string(ERR_get_error(), NULL));
else
tls_log("set RSA blinding on");
/* Now, "free" the RSA pointer, to properly decrement the reference
* counter.
*/
RSA_free(rsa);
} else {
/* The administrator may have configured DSA keys rather than RSA keys.
* In this case, there is nothing to do.
*/
}
return;
}
#endif
static int tls_init_ctx(void) {
config_rec *c;
int ssl_opts = tls_ssl_opts;
long ssl_mode = 0;
if (pr_define_exists("TLS_USE_FIPS") &&
ServerType == SERVER_INETD) {
#ifdef OPENSSL_FIPS
if (!FIPS_mode()) {
/* Make sure OpenSSL is set to use the default RNG, as per an email
* discussion on the OpenSSL developer list:
*
* "The internal FIPS logic uses the default RNG to see the FIPS RNG
* as part of the self test process..."
*/
RAND_set_rand_method(NULL);
if (!FIPS_mode_set(1)) {
const char *errstr;
errstr = tls_get_errors();
tls_log("unable to use FIPS mode: %s", errstr);
pr_log_pri(PR_LOG_ERR, MOD_TLS_VERSION
": unable to use FIPS mode: %s", errstr);
errno = EPERM;
return -1;
} else {
pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION ": FIPS mode enabled");
}
} else {
pr_log_pri(PR_LOG_DEBUG, MOD_TLS_VERSION ": FIPS mode already enabled");
}
#else
pr_log_pri(PR_LOG_WARNING, MOD_TLS_VERSION ": FIPS mode requested, but " OPENSSL_VERSION_TEXT " not built with FIPS support");
#endif /* OPENSSL_FIPS */
}
#ifdef ZLIB
{
COMP_METHOD *cm = COMP_zlib();
if (cm != NULL && cm->type != NID_undef) {
SSL_COMP_add_compression_method(0xe0, cm); /* Eric Young's ZLIB ID */
}
}
#endif /* ZLIB */
if (ssl_ctx != NULL) {
SSL_CTX_free(ssl_ctx);
ssl_ctx = NULL;
}
ssl_ctx = SSL_CTX_new(SSLv23_server_method());
if (ssl_ctx == NULL) {
pr_log_debug(DEBUG0, MOD_TLS_VERSION ": error: SSL_CTX_new(): %s",
tls_get_errors());
return -1;
}
#if OPENSSL_VERSION_NUMBER > 0x000906000L
/* The SSL_MODE_AUTO_RETRY mode was added in 0.9.6. */
ssl_mode |= SSL_MODE_AUTO_RETRY;
#endif
#if OPENSSL_VERSION_NUMBER >= 0x1000001fL
/* The SSL_MODE_RELEASE_BUFFERS mode was added in 1.0.0a. */
ssl_mode |= SSL_MODE_RELEASE_BUFFERS;
#endif
if (ssl_mode != 0) {
SSL_CTX_set_mode(ssl_ctx, ssl_mode);
}
/* If using OpenSSL-0.9.7 or greater, prevent session resumptions on
* renegotiations (more secure).
*/
#if OPENSSL_VERSION_NUMBER > 0x000907000L
ssl_opts |= SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION;
#endif
/* Disable SSL tickets, for now. */
#ifdef SSL_OP_NO_TICKET
ssl_opts |= SSL_OP_NO_TICKET;
#endif
SSL_CTX_set_options(ssl_ctx, ssl_opts);
/* Set up session caching. */
SSL_CTX_set_session_id_context(ssl_ctx, (unsigned char *) MOD_TLS_VERSION,
strlen(MOD_TLS_VERSION));
c = find_config(main_server->conf, CONF_PARAM, "TLSSessionCache", FALSE);
if (c) {
const char *provider;
long timeout;
/* Look up and initialize the configured session cache provider. */
provider = c->argv[0];
timeout = *((long *) c->argv[2]);
if (strncmp(provider, "internal", 9) != 0) {
tls_sess_cache = tls_sess_cache_get_cache(provider);
pr_log_debug(DEBUG8, MOD_TLS_VERSION ": opening '%s' TLSSessionCache",
provider);
if (tls_sess_cache_open(c->argv[1], timeout) == 0) {
long cache_mode, cache_flags;
cache_mode = SSL_SESS_CACHE_SERVER;
/* We could force OpenSSL to use ONLY the configured external session
* caching mechanism by using the SSL_SESS_CACHE_NO_INTERNAL mode flag
* (available in OpenSSL 0.9.6h and later).
*
* However, consider the case where the serialized session data is
* too large for the external cache, or the external cache refuses
* to add the session for some reason. If OpenSSL is using only our
* external cache, that session is lost (which could cause problems
* e.g. for later protected data transfers, which require that the
* SSL session from the control connection be reused).
*
* If the external cache can be reasonably sure that session data
* can be added, then the NO_INTERNAL flag is a good idea; it keeps
* OpenSSL from allocating more memory than necessary. Having both
* an internal and an external cache of the same data is a bit
* unresourceful. Thus we ask the external cache mechanism what
* additional cache mode flags to use.
*/
cache_flags = tls_sess_cache_get_cache_mode();
cache_mode |= cache_flags;
SSL_CTX_set_session_cache_mode(ssl_ctx, cache_mode);
SSL_CTX_set_timeout(ssl_ctx, timeout);
SSL_CTX_sess_set_new_cb(ssl_ctx, tls_sess_cache_add_sess_cb);
SSL_CTX_sess_set_get_cb(ssl_ctx, tls_sess_cache_get_sess_cb);
SSL_CTX_sess_set_remove_cb(ssl_ctx, tls_sess_cache_delete_sess_cb);
} else {
pr_log_debug(DEBUG1, MOD_TLS_VERSION
": error opening '%s' TLSSessionCache: %s", provider,
strerror(errno));
/* Default to using OpenSSL's own internal session caching. */
SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_SERVER);
}
} else {
/* Default to using OpenSSL's own internal session caching. */
SSL_CTX_set_session_cache_mode(ssl_ctx, SSL_SESS_CACHE_SERVER);
SSL_CTX_set_timeout(ssl_ctx, timeout);
}
}
SSL_CTX_set_tmp_dh_callback(ssl_ctx, tls_dh_cb);
if (tls_seed_prng() < 0) {
pr_log_debug(DEBUG1, MOD_TLS_VERSION ": unable to properly seed PRNG");
}
return 0;
}
static int tls_init_server(void) {
#if OPENSSL_VERSION_NUMBER > 0x000907000L
config_rec *c = NULL;
#endif
char *tls_ca_cert = NULL, *tls_ca_path = NULL, *tls_ca_chain = NULL;
X509 *server_dsa_cert = NULL, *server_rsa_cert = NULL;
int verify_mode = SSL_VERIFY_PEER;
if ((tls_protocol & TLS_PROTO_SSL_V3) &&
(tls_protocol & TLS_PROTO_TLS_V1)) {
/* This is the default, so there is no need to do anything. */
pr_log_debug(DEBUG8, MOD_TLS_VERSION ": supporting SSLv3, TLSv1 protocols");
} else if (tls_protocol & TLS_PROTO_SSL_V3) {
SSL_CTX_set_ssl_version(ssl_ctx, SSLv3_server_method());
pr_log_debug(DEBUG8, MOD_TLS_VERSION ": supporting SSLv3 protocol only");
} else if (tls_protocol & TLS_PROTO_TLS_V1) {
SSL_CTX_set_ssl_version(ssl_ctx, TLSv1_server_method());
pr_log_debug(DEBUG8, MOD_TLS_VERSION ": supporting TLSv1 protocol only");
}
tls_ca_cert = get_param_ptr(main_server->conf, "TLSCACertificateFile", FALSE);
tls_ca_path = get_param_ptr(main_server->conf, "TLSCACertificatePath", FALSE);
if (tls_ca_cert || tls_ca_path) {
/* Set the locations used for verifying certificates. */
PRIVS_ROOT
if (SSL_CTX_load_verify_locations(ssl_ctx, tls_ca_cert, tls_ca_path) != 1) {
PRIVS_RELINQUISH
tls_log("unable to set CA verification using file '%s' or "
"directory '%s': %s", tls_ca_cert ? tls_ca_cert : "(none)",
tls_ca_path ? tls_ca_path : "(none)",
ERR_error_string(ERR_get_error(), NULL));
return -1;
}
PRIVS_RELINQUISH
} else {
/* Default to using locations set in the OpenSSL config file.
*/
tls_log("%s", "using default OpenSSL verification locations "
"(see $SSL_CERT_DIR environment variable)");
if (SSL_CTX_set_default_verify_paths(ssl_ctx) != 1) {
tls_log("error setting default verification locations: %s",
tls_get_errors());
}
}
if (tls_flags & TLS_SESS_VERIFY_CLIENT) {
/* If we are verifying clients, make sure the client sends a cert;
* the protocol allows for the client to disregard a request for
* its cert by the server.
*/
verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
if (tls_opts & TLS_OPT_NO_CERT_REQUEST) {
/* Warn about the incompatibility of using "TLSVerifyClient on" and
* "TLSOption NoCertRequest" at the same time.
*/
tls_log("TLSVerifyClient in effect, ignoring NoCertRequest TLSOption");
}
} else if (tls_opts & TLS_OPT_NO_CERT_REQUEST) {
verify_mode = 0;
}
if (verify_mode != 0) {
SSL_CTX_set_verify(ssl_ctx, verify_mode, tls_verify_cb);
/* Note: we add one to the configured depth purposefully. As noted
* in the OpenSSL man pages, the verification process will silently
* stop at the configured depth, and the error messages ensuing will
* be that of an incomplete certificate chain, rather than the
* "chain too long" error that might be expected. To log the "chain
* too long" condition, we add one to the configured depth, and catch,
* in the verify callback, the exceeding of the actual depth.
*/
SSL_CTX_set_verify_depth(ssl_ctx, tls_verify_depth + 1);
}
if (tls_ca_cert) {
STACK_OF(X509_NAME) *sk;
/* Use SSL_load_client_CA_file() to load all of the CA certs (since
* there can be more than one) from the TLSCACertificateFile. The
* entire list of CAs in that file will be present to the client as
* the "acceptable client CA" list, assuming that
* TLSOptions NoCertRequest" is not in use.
*/
PRIVS_ROOT
sk = SSL_load_client_CA_file(tls_ca_cert);
PRIVS_RELINQUISH
if (sk) {
SSL_CTX_set_client_CA_list(ssl_ctx, sk);
} else {
tls_log("unable to read certificates in '%s': %s", tls_ca_cert,
tls_get_errors());
}
if (tls_ca_path) {
DIR *cacertdir = NULL;
PRIVS_ROOT
cacertdir = opendir(tls_ca_path);
PRIVS_RELINQUISH
if (cacertdir) {
struct dirent *cadent = NULL;
pool *tmp_pool = make_sub_pool(permanent_pool);
while ((cadent = readdir(cacertdir)) != NULL) {
FILE *cacertf;
char *cacertname;
pr_signals_handle();
/* Skip dot directories. */
if (is_dotdir(cadent->d_name)) {
continue;
}
cacertname = pdircat(tmp_pool, tls_ca_path, cadent->d_name, NULL);
PRIVS_ROOT
cacertf = fopen(cacertname, "r");
PRIVS_RELINQUISH
if (cacertf) {
X509 *x509 = PEM_read_X509(cacertf, NULL, NULL, NULL);
if (x509) {
if (SSL_CTX_add_client_CA(ssl_ctx, x509) != 1) {
tls_log("error adding '%s' to client CA list: %s", cacertname,
tls_get_errors());
}
} else {
tls_log("unable to read '%s': %s", cacertname, tls_get_errors());
}
fclose(cacertf);
} else {
tls_log("unable to open '%s': %s", cacertname, strerror(errno));
}
}
destroy_pool(tmp_pool);
closedir(cacertdir);
} else {
tls_log("unable to add CAs in '%s': %s", tls_ca_path,
strerror(errno));
}
}
}
/* Assume that, if no separate key files are configured, the keys are
* in the same file as the corresponding certificate.
*/
if (!tls_rsa_key_file)
tls_rsa_key_file = tls_rsa_cert_file;
if (!tls_dsa_key_file)
tls_dsa_key_file = tls_dsa_cert_file;
PRIVS_ROOT
if (tls_rsa_cert_file) {
FILE *fh = NULL;
int res;
X509 *cert = NULL;
fh = fopen(tls_rsa_cert_file, "r");
if (fh == NULL) {
PRIVS_RELINQUISH
tls_log("error reading TLSRSACertificateFile '%s': %s", tls_rsa_cert_file,
strerror(errno));
return -1;
}
cert = PEM_read_X509(fh, NULL, ssl_ctx->default_passwd_callback,
ssl_ctx->default_passwd_callback_userdata);
if (cert == NULL) {
PRIVS_RELINQUISH
tls_log("error reading TLSRSACertificateFile '%s': %s", tls_rsa_cert_file,
tls_get_errors());
return -1;
}
fclose(fh);
/* SSL_CTX_use_certificate() will increment the refcount on cert, so we
* can safely call X509_free() on it. However, we need to keep that
* pointer around until after the handling of a cert chain file.
*/
res = SSL_CTX_use_certificate(ssl_ctx, cert);
if (res <= 0) {
PRIVS_RELINQUISH
tls_log("error loading TLSRSACertificateFile '%s': %s", tls_rsa_cert_file,
tls_get_errors());
return -1;
}
SSL_CTX_set_tmp_rsa_callback(ssl_ctx, tls_rsa_cb);
server_rsa_cert = cert;
}
if (tls_rsa_key_file) {
int res;
if (tls_pkey) {
tls_pkey->flags |= TLS_PKEY_USE_RSA;
tls_pkey->flags &= ~TLS_PKEY_USE_DSA;
}
res = SSL_CTX_use_PrivateKey_file(ssl_ctx, tls_rsa_key_file,
X509_FILETYPE_PEM);
if (res <= 0) {
PRIVS_RELINQUISH
tls_log("error loading TLSRSACertificateKeyFile '%s': %s",
tls_rsa_key_file, tls_get_errors());
return -1;
}
}
if (tls_dsa_cert_file) {
FILE *fh = NULL;
int res;
X509 *cert = NULL;
fh = fopen(tls_dsa_cert_file, "r");
if (fh == NULL) {
PRIVS_RELINQUISH
tls_log("error reading TLSDSACertificateFile '%s': %s", tls_dsa_cert_file,
strerror(errno));
return -1;
}
cert = PEM_read_X509(fh, NULL, ssl_ctx->default_passwd_callback,
ssl_ctx->default_passwd_callback_userdata);
if (cert == NULL) {
PRIVS_RELINQUISH
tls_log("error reading TLSDSACertificateFile '%s': %s", tls_dsa_cert_file,
tls_get_errors());
return -1;
}
fclose(fh);
/* SSL_CTX_use_certificate() will increment the refcount on cert, so we
* can safely call X509_free() on it. However, we need to keep that
* pointer around until after the handling of a cert chain file.
*/
res = SSL_CTX_use_certificate(ssl_ctx, cert);
if (res <= 0) {
PRIVS_RELINQUISH
tls_log("error loading TLSDSACertificateFile '%s': %s", tls_dsa_cert_file,
tls_get_errors());
return -1;
}
server_dsa_cert = cert;
}
if (tls_dsa_key_file) {
int res;
if (tls_pkey) {
tls_pkey->flags |= TLS_PKEY_USE_DSA;
tls_pkey->flags &= ~TLS_PKEY_USE_RSA;
}
res = SSL_CTX_use_PrivateKey_file(ssl_ctx, tls_dsa_key_file,
X509_FILETYPE_PEM);
if (res <= 0) {
PRIVS_RELINQUISH
tls_log("error loading TLSDSACertificateKeyFile '%s': %s",
tls_dsa_key_file, tls_get_errors());
return -1;
}
}
if (tls_pkcs12_file) {
int res;
FILE *fp;
X509 *cert = NULL;
EVP_PKEY *pkey = NULL;
PKCS12 *p12 = NULL;
char *passwd = "";
if (tls_pkey) {
passwd = tls_pkey->pkcs12_passwd;
}
fp = fopen(tls_pkcs12_file, "r");
if (fp == NULL) {
int xerrno = errno;
PRIVS_RELINQUISH
tls_log("error opening TLSPKCS12File '%s': %s", tls_pkcs12_file,
strerror(xerrno));
return -1;
}
/* Note that this should NOT fail; we will have already parsed the
* PKCS12 file already, in order to get the password and key passphrases.
*/
p12 = d2i_PKCS12_fp(fp, NULL);
if (p12 == NULL) {
tls_log("error reading TLSPKCS12File '%s': %s", tls_pkcs12_file,
tls_get_errors());
fclose(fp);
return -1;
}
fclose(fp);
/* XXX Need to add support for any CA certs contained in the PKCS12 file. */
if (PKCS12_parse(p12, passwd, &pkey, &cert, NULL) != 1) {
tls_log("error parsing info in TLSPKCS12File '%s': %s", tls_pkcs12_file,
tls_get_errors());
PKCS12_free(p12);
return -1;
}
res = SSL_CTX_use_certificate(ssl_ctx, cert);
if (res <= 0) {
PRIVS_RELINQUISH
tls_log("error loading certificate from TLSPKCS12File '%s' %s",
tls_pkcs12_file, tls_get_errors());
PKCS12_free(p12);
if (cert)
X509_free(cert);
if (pkey)
EVP_PKEY_free(pkey);
return -1;
}
if (pkey &&
tls_pkey) {
switch (EVP_PKEY_type(pkey->type)) {
case EVP_PKEY_RSA:
tls_pkey->flags |= TLS_PKEY_USE_RSA;
tls_pkey->flags &= ~TLS_PKEY_USE_DSA;
break;
case EVP_PKEY_DSA:
tls_pkey->flags |= TLS_PKEY_USE_DSA;
tls_pkey->flags &= ~TLS_PKEY_USE_RSA;
break;
}
}
res = SSL_CTX_use_PrivateKey(ssl_ctx, pkey);
if (res <= 0) {
PRIVS_RELINQUISH
tls_log("error loading key from TLSPKCS12File '%s' %s", tls_pkcs12_file,
tls_get_errors());
PKCS12_free(p12);
if (cert)
X509_free(cert);
if (pkey)
EVP_PKEY_free(pkey);
return -1;
}
/* SSL_CTX_use_certificate() will increment the refcount on cert, so we
* can safely call X509_free() on it. However, we need to keep that
* pointer around until after the handling of a cert chain file.
*/
if (pkey != NULL) {
switch (EVP_PKEY_type(pkey->type)) {
case EVP_PKEY_RSA:
server_rsa_cert = cert;
break;
case EVP_PKEY_DSA:
server_dsa_cert = cert;
break;
}
}
if (pkey)
EVP_PKEY_free(pkey);
if (p12)
PKCS12_free(p12);
}
/* Log a warning if the server was badly misconfigured, and has no server
* certs at all. The client will probably see this situation as something
* like:
*
* error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure
*
* And the TLSLog will show the error as:
*
* error:1408A0C1:SSL routines:SSL3_GET_CLIENT_HELLO:no shared cipher
*/
if (tls_rsa_cert_file == NULL &&
tls_dsa_cert_file == NULL &&
tls_pkcs12_file == NULL) {
tls_log("no TLSRSACertificateFile, TLSDSACertificateFile, or TLSPKCS12File "
"configured; unable to handle SSL/TLS connections");
pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
": no TLSRSACertificateFile, TLSDSACertificateFile, or TLSPKCS12File "
"configured; unable to handle SSL/TLS connections");
}
/* Handle a CertificateChainFile. We need to do this here, after the
* server cert has been loaded, so that we can decide whether the
* CertificateChainFile contains another copy of the server cert (or not).
*/
tls_ca_chain = get_param_ptr(main_server->conf, "TLSCertificateChainFile",
FALSE);
if (tls_ca_chain) {
BIO *bio;
X509 *cert;
/* Ideally we would use OpenSSL's SSL_CTX_use_certificate_chain()
* function. However, that function automatically assumes that the
* first cert contained in the chain file is to be used as the server
* cert. This may or may not be the case. So instead, we read through
* the chain and add the extra certs ourselves.
*/
bio = BIO_new_file(tls_ca_chain, "r");
if (bio) {
unsigned int count = 0;
int res;
cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
while (cert != NULL) {
pr_signals_handle();
if (server_rsa_cert != NULL) {
/* Skip this cert if it is the same as the configured RSA
* server cert.
*/
if (X509_cmp(server_rsa_cert, cert) == 0) {
cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
continue;
}
}
if (server_dsa_cert != NULL) {
/* Skip this cert if it is the same as the configured RSA
* server cert.
*/
if (X509_cmp(server_dsa_cert, cert) == 0) {
cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
continue;
}
}
res = SSL_CTX_add_extra_chain_cert(ssl_ctx, cert);
if (res != 1) {
tls_log("error adding cert to certificate chain: %s",
tls_get_errors());
X509_free(cert);
break;
}
count++;
cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
}
BIO_free(bio);
tls_log("added %u certs from '%s' to certificate chain", count,
tls_ca_chain);
} else {
tls_log("unable to read certificate chain '%s': %s", tls_ca_chain,
tls_get_errors());
}
}
/* Done with the server cert pointers now. */
if (server_rsa_cert != NULL) {
X509_free(server_rsa_cert);
server_rsa_cert = NULL;
}
if (server_dsa_cert != NULL) {
X509_free(server_dsa_cert);
server_dsa_cert = NULL;
}
/* Set up the CRL. */
if (tls_crl_file || tls_crl_path) {
tls_crl_store = X509_STORE_new();
if (tls_crl_store == NULL) {
tls_log("error creating CRL store: %s", tls_get_errors());
return -1;
}
if (X509_STORE_load_locations(tls_crl_store, tls_crl_file,
tls_crl_path) == 0) {
if (tls_crl_file && !tls_crl_path) {
tls_log("error loading TLSCARevocationFile '%s': %s",
tls_crl_file, tls_get_errors());
} else if (!tls_crl_file && tls_crl_path) {
tls_log("error loading TLSCARevocationPath '%s': %s",
tls_crl_path, tls_get_errors());
} else {
tls_log("error loading TLSCARevocationFile '%s', "
"TLSCARevocationPath '%s': %s", tls_crl_file, tls_crl_path,
tls_get_errors());
}
}
}
PRIVS_RELINQUISH
SSL_CTX_set_cipher_list(ssl_ctx, tls_cipher_suite);
#if OPENSSL_VERSION_NUMBER > 0x000907000L
/* Lookup/process any configured TLSRenegotiate parameters. */
c = find_config(main_server->conf, CONF_PARAM, "TLSRenegotiate", FALSE);
if (c) {
if (c->argc == 0) {
/* Disable all server-side requested renegotiations; clients can
* still request renegotiations.
*/
tls_ctrl_renegotiate_timeout = 0;
tls_data_renegotiate_limit = 0;
tls_renegotiate_timeout = 0;
tls_renegotiate_required = FALSE;
} else {
int ctrl_timeout = *((int *) c->argv[0]);
off_t data_limit = *((off_t *) c->argv[1]);
int renegotiate_timeout = *((int *) c->argv[2]);
unsigned char renegotiate_required = *((unsigned char *) c->argv[3]);
if (data_limit)
tls_data_renegotiate_limit = data_limit;
if (renegotiate_timeout)
tls_renegotiate_timeout = renegotiate_timeout;
tls_renegotiate_required = renegotiate_required;
/* Set any control channel renegotiation timers, if need be. */
pr_timer_add(ctrl_timeout ? ctrl_timeout : tls_ctrl_renegotiate_timeout,
-1, &tls_module, tls_ctrl_renegotiate_cb, "SSL/TLS renegotiation");
}
}
#endif
return 0;
}
static int tls_get_block(conn_t *conn) {
int flags;
flags = fcntl(conn->rfd, F_GETFL);
if (flags & O_NONBLOCK) {
return FALSE;
}
return TRUE;
}
static int tls_accept(conn_t *conn, unsigned char on_data) {
int blocking, res = 0, xerrno = 0;
char *subj = NULL;
static unsigned char logged_data = FALSE;
SSL *ssl = NULL;
BIO *rbio = NULL, *wbio = NULL;
if (!ssl_ctx) {
tls_log("%s", "unable to start session: null SSL_CTX");
return -1;
}
ssl = SSL_new(ssl_ctx);
if (ssl == NULL) {
tls_log("error: unable to start session: %s",
ERR_error_string(ERR_get_error(), NULL));
return -2;
}
blocking = tls_get_block(conn);
if (blocking) {
/* Put the connection in non-blocking mode for the duration of the
* SSL handshake. This lets us handle EGAIN/retries better (i.e.
* without spinning in a tight loop and consuming the CPU).
*/
pr_inet_set_nonblock(conn->pool, conn);
}
/* This works with either rfd or wfd (I hope) */
rbio = BIO_new_socket(conn->rfd, FALSE);
wbio = BIO_new_socket(conn->rfd, FALSE);
SSL_set_bio(ssl, rbio, wbio);
/* If configured, set a timer for the handshake. */
if (tls_handshake_timeout) {
tls_handshake_timer_id = pr_timer_add(tls_handshake_timeout, -1,
&tls_module, tls_handshake_timeout_cb, "SSL/TLS handshake");
}
retry:
pr_signals_handle();
res = SSL_accept(ssl);
if (res == -1) {
xerrno = errno;
}
if (blocking) {
/* Return the connection to blocking mode. */
pr_inet_set_block(conn->pool, conn);
}
if (res < 1) {
const char *msg = "unable to accept TLS connection";
int errcode = SSL_get_error(ssl, res);
pr_signals_handle();
if (tls_handshake_timed_out) {
tls_log("TLS negotiation timed out (%u seconds)", tls_handshake_timeout);
tls_end_sess(ssl, on_data ? PR_NETIO_STRM_DATA : PR_NETIO_STRM_CTRL, 0);
return -4;
}
switch (errcode) {
case SSL_ERROR_WANT_READ:
tls_readmore(conn->rfd);
goto retry;
case SSL_ERROR_WANT_WRITE:
tls_writemore(conn->rfd);
goto retry;
case SSL_ERROR_ZERO_RETURN:
tls_log("%s: TLS connection closed", msg);
break;
case SSL_ERROR_WANT_X509_LOOKUP:
tls_log("%s: needs X509 lookup", msg);
break;
case SSL_ERROR_SYSCALL: {
/* Check to see if the OpenSSL error queue has info about this. */
int xerrcode = ERR_get_error();
if (xerrcode == 0) {
/* The OpenSSL error queue doesn't have any more info, so we'll
* examine the SSL_accept() return value itself.
*/
if (res == 0) {
/* EOF */
tls_log("%s: received EOF that violates protocol", msg);
} else if (res == -1) {
/* Check errno */
tls_log("%s: system call error: [%d] %s", msg, xerrno,
strerror(xerrno));
}
} else {
tls_log("%s: system call error: %s", msg, tls_get_errors());
}
break;
}
case SSL_ERROR_SSL:
tls_log("%s: protocol error: %s", msg, tls_get_errors());
break;
}
tls_end_sess(ssl, on_data ? PR_NETIO_STRM_DATA : PR_NETIO_STRM_CTRL, 0);
return -3;
}
/* Disable the handshake timer. */
pr_timer_remove(tls_handshake_timer_id, &tls_module);
/* Manually update the raw bytes counters with the network IO from the
* SSL handshake.
*/
session.total_raw_in += (BIO_number_read(rbio) +
BIO_number_read(wbio));
session.total_raw_out += (BIO_number_written(rbio) +
BIO_number_written(wbio));
/* Stash the SSL object in the pointers of the correct NetIO streams. */
if (conn == session.c) {
pr_buffer_t *strm_buf;
ctrl_ssl = ssl;
tls_ctrl_rd_nstrm->strm_data = tls_ctrl_wr_nstrm->strm_data = (void *) ssl;
#if OPENSSL_VERSION_NUMBER >= 0x009080dfL
if (SSL_get_secure_renegotiation_support(ssl) == 1) {
/* If the peer indicates that it can support secure renegotiations, log
* this fact for reference.
*
* Note that while we could use this fact to automatically enable the
* AllowClientRenegotiations TLSOption, in light of CVE-2011-1473
* (where malicious SSL/TLS clients can abuse the fact that session
* renegotiations are more computationally intensive for servers than
* for clients and repeatedly request renegotiations to create a
* denial of service attach), we won't enable AllowClientRenegotiations
* programmatically. The admin will still need to explicitly configure
* that.
*/
tls_log("%s", "client supports secure renegotiations");
}
#endif /* OpenSSL 0.9.8m and later */
/* Clear any data from the NetIO stream buffers which may have been read
* in before the SSL/TLS handshake occurred (Bug#3624).
*/
strm_buf = tls_ctrl_rd_nstrm->strm_buf;
if (strm_buf != NULL) {
strm_buf->current = NULL;
strm_buf->remaining = strm_buf->buflen;
}
} else if (conn == session.d) {
pr_buffer_t *strm_buf;
tls_data_rd_nstrm->strm_data = tls_data_wr_nstrm->strm_data = (void *) ssl;
/* Clear any data from the NetIO stream buffers which may have been read
* in before the SSL/TLS handshake occurred (Bug#3624).
*/
strm_buf = tls_data_rd_nstrm->strm_buf;
if (strm_buf != NULL) {
strm_buf->current = NULL;
strm_buf->remaining = strm_buf->buflen;
}
}
#if OPENSSL_VERSION_NUMBER == 0x009080cfL
/* In OpenSSL-0.9.8l, SSL session renegotiations are automatically
* disabled. Thus if the admin explicitly configured support for
* client-initiated renegotations via the AllowClientRenegotiations
* TLSOption, then we need to do some hackery to enable renegotiations.
*/
if (tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS) {
ssl->s3->flags |= SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
}
#endif
/* TLS handshake on the control channel... */
if (!on_data) {
int reused;
subj = tls_get_subj_name();
if (subj)
tls_log("Client: %s", subj);
if (!(tls_opts & TLS_OPT_NO_CERT_REQUEST)) {
/* NOTE: should probably use SSL_get_verify_result() as a last
* sanity check.
*/
/* Now we can go on with our post-handshake, application level
* requirement checks.
*/
if (!tls_check_client_cert(ssl, conn)) {
return -1;
}
}
tls_log("%s connection accepted, using cipher %s (%d bits)",
SSL_get_cipher_version(ssl), SSL_get_cipher_name(ssl),
SSL_get_cipher_bits(ssl, NULL));
/* Setup the TLS environment variables, if requested. */
tls_setup_environ(ssl);
reused = SSL_session_reused(ssl);
if (reused > 0) {
pr_log_writefile(tls_logfd, MOD_TLS_VERSION, "%s",
"client reused previous SSL session for control connection");
}
/* TLS handshake on the data channel... */
} else {
/* We won't check for session reuse for data connections when either
* a) the NoSessionReuseRequired TLSOption has been configured, or
* b) the CCC command has been used (Bug#3465).
*/
if (!(tls_opts & TLS_OPT_NO_SESSION_REUSE_REQUIRED) &&
!(tls_flags & TLS_SESS_HAVE_CCC)) {
int reused;
SSL_SESSION *ctrl_sess;
/* Ensure that the following conditions are met:
*
* 1. The client reused an existing SSL session
* 2. The reused SSL session matches the SSL session from the control
* connection.
*
* Shutdown the SSL session unless the conditions are met. By
* requiring these conditions, we make sure that the client which is
* talking to us on the control connection is indeed the same client
* that is using this data connection. Without this checks, a
* malicious client might be able to hijack/steal the data transfer.
*/
reused = SSL_session_reused(ssl);
if (reused != 1) {
tls_log("client did not reuse SSL session, rejecting data connection "
"(see the NoSessionReuseRequired TLSOptions parameter)");
tls_end_sess(ssl, PR_NETIO_STRM_DATA, 0);
tls_data_rd_nstrm->strm_data = tls_data_wr_nstrm->strm_data = NULL;
return -1;
} else {
tls_log("%s", "client reused SSL session for data connection");
}
ctrl_sess = SSL_get_session(ctrl_ssl);
if (ctrl_sess != NULL) {
SSL_SESSION *data_sess;
data_sess = SSL_get_session(ssl);
if (data_sess != NULL) {
#if OPENSSL_VERSION_NUMBER < 0x000907000L
/* In the OpenSSL source code, SSL_SESSION_cmp() ultimately uses
* memcmp(3) to check, and thus returns memcmp(3)'s return value.
*/
if (SSL_SESSION_cmp(ctrl_sess, data_sess) != 0) {
#else
unsigned char *sess_id;
unsigned int sess_id_len;
# if OPENSSL_VERSION_NUMBER > 0x000908000L
sess_id = (unsigned char *) SSL_SESSION_get_id(data_sess,
&sess_id_len);
# else
/* XXX Directly accessing these fields cannot be a Good Thing. */
sess_id = data_sess->session_id;
sess_id_len = data_sess->session_id_length;
# endif
if (SSL_has_matching_session_id(ctrl_ssl, sess_id,
sess_id_len) == 0) {
#endif
tls_log("Client did not reuse SSL session from control channel, "
"rejecting data connection (see the NoSessionReuseRequired "
"TLSOptions parameter)");
tls_end_sess(ssl, PR_NETIO_STRM_DATA, 0);
tls_data_rd_nstrm->strm_data = tls_data_wr_nstrm->strm_data = NULL;
return -1;
} else {
long sess_created, sess_expires;
time_t now;
/* The SSL session ID for data and control channels matches.
*
* Many sites are using mod_tls such that OpenSSL's internal
* session caching is being used. And by default, that
* cache expires sessions after 300 secs (5 min). It's possible
* that the control channel SSL session will expire soon;
* unless the client renegotiates that session, the internal
* cache will expire the cached session, and the next data
* transfer could fail (since mod_tls won't allow that session ID
* to be reused again, as it will no longer be in the session
* cache).
*
* Try to warn if this is about to happen.
*/
sess_created = SSL_SESSION_get_time(ctrl_sess);
sess_expires = SSL_SESSION_get_timeout(ctrl_sess);
now = time(NULL);
if ((sess_created + sess_expires) >= now) {
unsigned long remaining;
remaining = (unsigned long) ((sess_created + sess_expires) - now);
if (remaining <= 60) {
tls_log("control channel SSL session expires in %lu secs (%lu session cache expiration)", remaining, sess_expires);
tls_log("%s","Consider using 'TLSSessionCache internal:' to increase the session cache expiration if necessary, or renegotiate the control channel SSL session");
}
}
}
} else {
/* This should never happen, so log if it does. */
tls_log("BUG: unable to determine whether client reused SSL session: SSL_get_session() for control connection return NULL");
tls_log("rejecting data connection (see TLSOption NoSessionReuseRequired)");
tls_end_sess(ssl, PR_NETIO_STRM_DATA, 0);
tls_data_rd_nstrm->strm_data = tls_data_wr_nstrm->strm_data = NULL;
return -1;
}
} else {
/* This should never happen, so log if it does. */
tls_log("BUG: unable to determine whether client reused SSL session: SSL_get_session() for control connection return NULL");
tls_log("rejecting data connection (see TLSOption NoSessionReuseRequired)");
tls_end_sess(ssl, PR_NETIO_STRM_DATA, 0);
tls_data_rd_nstrm->strm_data = tls_data_wr_nstrm->strm_data = NULL;
return -1;
}
}
/* Only be verbose with the first TLS data connection, otherwise there
* might be too much noise.
*/
if (!logged_data) {
tls_log("%s data connection accepted, using cipher %s (%d bits)",
SSL_get_cipher_version(ssl), SSL_get_cipher_name(ssl),
SSL_get_cipher_bits(ssl, NULL));
logged_data = TRUE;
}
}
return 0;
}
static void tls_cleanup(int flags) {
tls_sess_cache_close();
#if OPENSSL_VERSION_NUMBER > 0x000907000L
if (tls_crypto_device) {
ENGINE_cleanup();
tls_crypto_device = NULL;
}
#endif
if (tls_crl_store) {
X509_STORE_free(tls_crl_store);
tls_crl_store = NULL;
}
if (ssl_ctx) {
SSL_CTX_free(ssl_ctx);
ssl_ctx = NULL;
}
if (tls_tmp_dh) {
DH_free(tls_tmp_dh);
tls_tmp_dh = NULL;
}
if (tls_tmp_rsa) {
RSA_free(tls_tmp_rsa);
tls_tmp_rsa = NULL;
}
if (!(flags & TLS_CLEANUP_FL_SESS_INIT)) {
ERR_free_strings();
#if OPENSSL_VERSION_NUMBER >= 0x10000001L
/* The ERR_remove_state(0) usage is deprecated due to thread ID
* differences among platforms; see the OpenSSL-1.0.0 CHANGES file
* for details. So for new enough OpenSSL installations, use the
* proper way to clear the error queue state.
*/
ERR_remove_thread_state(NULL);
#else
ERR_remove_state(0);
#endif /* OpenSSL prior to 1.0.0-beta1 */
EVP_cleanup();
} else {
/* Only call EVP_cleanup() et al if other OpenSSL-using modules are not
* present. If we called EVP_cleanup() here during session
* initialization, and other modules want to use OpenSSL, we may
* be depriving those modules of OpenSSL functionality.
*
* At the moment, the modules known to use OpenSSL are mod_ldap,
* mod_sftp, mod_sql, and mod_sql_passwd.
*/
if (pr_module_get("mod_ldap.c") == NULL &&
pr_module_get("mod_sftp.c") == NULL &&
pr_module_get("mod_sql.c") == NULL &&
pr_module_get("mod_sql_passwd.c") == NULL) {
ERR_free_strings();
#if OPENSSL_VERSION_NUMBER >= 0x10000001L
/* The ERR_remove_state(0) usage is deprecated due to thread ID
* differences among platforms; see the OpenSSL-1.0.0c CHANGES file
* for details. So for new enough OpenSSL installations, use the
* proper way to clear the error queue state.
*/
ERR_remove_thread_state(NULL);
#else
ERR_remove_state(0);
#endif /* OpenSSL prior to 1.0.0-beta1 */
EVP_cleanup();
}
}
}
static void tls_end_sess(SSL *ssl, int strms, int flags) {
int res = 0;
int shutdown_state;
BIO *rbio, *wbio;
int bread, bwritten;
unsigned long rbio_rbytes, rbio_wbytes, wbio_rbytes, wbio_wbytes;
if (!ssl)
return;
rbio = SSL_get_rbio(ssl);
rbio_rbytes = BIO_number_read(rbio);
rbio_wbytes = BIO_number_written(rbio);
wbio = SSL_get_wbio(ssl);
wbio_rbytes = BIO_number_read(wbio);
wbio_wbytes = BIO_number_written(wbio);
/* A 'close_notify' alert (SSL shutdown message) may have been previously
* sent to the client via tls_netio_shutdown_cb().
*/
shutdown_state = SSL_get_shutdown(ssl);
if (!(shutdown_state & SSL_SENT_SHUTDOWN)) {
errno = 0;
/* 'close_notify' not already sent; send it now. */
res = SSL_shutdown(ssl);
}
if (res == 0) {
/* Now call SSL_shutdown() again, but only if necessary. */
if (flags & TLS_SHUTDOWN_BIDIRECTIONAL) {
shutdown_state = SSL_get_shutdown(ssl);
res = 1;
if (!(shutdown_state & SSL_RECEIVED_SHUTDOWN)) {
errno = 0;
res = SSL_shutdown(ssl);
}
}
if (res == 0) {
long err_code;
err_code = SSL_get_error(ssl, res);
switch (err_code) {
case SSL_ERROR_WANT_READ:
tls_log("SSL_shutdown error: WANT_READ");
pr_log_debug(DEBUG0, MOD_TLS_VERSION
": SSL_shutdown error: WANT_READ");
break;
case SSL_ERROR_WANT_WRITE:
tls_log("SSL_shutdown error: WANT_WRITE");
pr_log_debug(DEBUG0, MOD_TLS_VERSION
": SSL_shutdown error: WANT_WRITE");
break;
case SSL_ERROR_ZERO_RETURN:
/* Clean shutdown, nothing we need to do. */
break;
case SSL_ERROR_SYSCALL:
if (errno != 0 &&
errno != EOF &&
errno != EBADF &&
errno != EPIPE &&
errno != EPERM &&
errno != ENOSYS) {
tls_log("SSL_shutdown syscall error: %s", strerror(errno));
}
break;
default:
tls_log("SSL_shutdown error [%ld]: %s", err_code, tls_get_errors());
pr_log_debug(DEBUG0, MOD_TLS_VERSION
": SSL_shutdown error [%ld]: %s", err_code, tls_get_errors());
break;
}
}
} else if (res < 0) {
long err_code;
err_code = SSL_get_error(ssl, res);
switch (err_code) {
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_ZERO_RETURN:
/* Clean shutdown, nothing we need to do. The WANT_READ/WANT_WRITE
* error codes crept into OpenSSL 0.9.8m, with changes to make
* SSL_shutdown() work properly for non-blocking sockets. And
* handling these error codes for older OpenSSL versions won't break
* things.
*/
break;
case SSL_ERROR_SYSCALL:
if (errno != 0 &&
errno != EOF &&
errno != EBADF &&
errno != EPIPE &&
errno != EPERM &&
errno != ENOSYS) {
tls_log("SSL_shutdown syscall error: %s", strerror(errno));
}
break;
default:
tls_fatal_error(err_code, __LINE__);
break;
}
}
bread = (BIO_number_read(rbio) - rbio_rbytes) +
(BIO_number_read(wbio) - wbio_rbytes);
bwritten = (BIO_number_written(rbio) - rbio_wbytes) +
(BIO_number_written(wbio) - wbio_wbytes);
/* Manually update session.total_raw_in/out, in order to have %I/%O be
* accurately represented for the raw traffic.
*/
if (bread > 0) {
session.total_raw_in += bread;
}
if (bwritten > 0) {
session.total_raw_out += bwritten;
}
SSL_free(ssl);
}
static const char *tls_get_errors(void) {
unsigned int count = 0;
unsigned long e = ERR_get_error();
BIO *bio = NULL;
char *data = NULL;
long datalen;
const char *str = "(unknown)";
/* Use ERR_print_errors() and a memory BIO to build up a string with
* all of the error messages from the error queue.
*/
if (e)
bio = BIO_new(BIO_s_mem());
while (e) {
pr_signals_handle();
BIO_printf(bio, "\n (%u) %s", ++count, ERR_error_string(e, NULL));
e = ERR_get_error();
}
datalen = BIO_get_mem_data(bio, &data);
if (data) {
data[datalen] = '\0';
str = pstrdup(main_server->pool, data);
}
if (bio)
BIO_free(bio);
return str;
}
/* Return a page-aligned pointer to memory of at least the given size.
*/
static char *tls_get_page(size_t sz, void **ptr) {
void *d;
long pagesz = tls_get_pagesz(), p;
d = calloc(1, sz + (pagesz-1));
if (d == NULL) {
pr_log_pri(PR_LOG_ERR, "Out of memory!");
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_NOMEM, NULL);
}
*ptr = d;
p = ((long) d + (pagesz-1)) &~ (pagesz-1);
return ((char *) p);
}
/* Return the size of a page on this architecture.
*/
static size_t tls_get_pagesz(void) {
long pagesz;
#if defined(_SC_PAGESIZE)
pagesz = sysconf(_SC_PAGESIZE);
#elif defined(_SC_PAGE_SIZE)
pagesz = sysconf(_SC_PAGE_SIZE);
#else
/* Default to using OpenSSL's defined buffer size for PEM files. */
pagesz = PEM_BUFSIZE;
#endif /* !_SC_PAGESIZE and !_SC_PAGE_SIZE */
return pagesz;
}
static char *tls_get_subj_name(void) {
X509 *cert = SSL_get_peer_certificate(ctrl_ssl);
if (cert) {
char *name = tls_x509_name_oneline(X509_get_subject_name(cert));
X509_free(cert);
return name;
}
return NULL;
}
static void tls_fatal_error(long error, int lineno) {
switch (error) {
case SSL_ERROR_NONE:
return;
case SSL_ERROR_SSL:
tls_log("panic: SSL_ERROR_SSL, line %d: %s", lineno, tls_get_errors());
break;
case SSL_ERROR_WANT_READ:
tls_log("panic: SSL_ERROR_WANT_READ, line %d", lineno);
break;
case SSL_ERROR_WANT_WRITE:
tls_log("panic: SSL_ERROR_WANT_WRITE, line %d", lineno);
break;
case SSL_ERROR_WANT_X509_LOOKUP:
tls_log("panic: SSL_ERROR_WANT_X509_LOOKUP, line %d", lineno);
break;
case SSL_ERROR_SYSCALL: {
long xerrcode = ERR_get_error();
if (errno == ECONNRESET)
return;
/* Check to see if the OpenSSL error queue has info about this. */
if (xerrcode == 0) {
/* The OpenSSL error queue doesn't have any more info, so we'll
* examine the error value itself.
*/
if (errno == EOF) {
tls_log("panic: SSL_ERROR_SYSCALL, line %d: "
"EOF that violates protocol", lineno);
} else {
/* Check errno */
tls_log("panic: SSL_ERROR_SYSCALL, line %d: system error: %s", lineno,
strerror(errno));
}
} else {
tls_log("panic: SSL_ERROR_SYSCALL, line %d: %s", lineno,
tls_get_errors());
}
break;
}
case SSL_ERROR_ZERO_RETURN:
tls_log("panic: SSL_ERROR_ZERO_RETURN, line %d", lineno);
break;
case SSL_ERROR_WANT_CONNECT:
tls_log("panic: SSL_ERROR_WANT_CONNECT, line %d", lineno);
break;
default:
tls_log("panic: SSL_ERROR %ld, line %d", error, lineno);
break;
}
tls_log("%s", "unexpected OpenSSL error, disconnecting");
pr_log_pri(PR_LOG_ERR, "%s", MOD_TLS_VERSION
": unexpected OpenSSL error, disconnecting");
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION, NULL);
}
/* This function checks if the client's cert is in the ~/.tlslogin file
* of the "user".
*/
static unsigned char tls_dotlogin_allow(const char *user) {
char buf[512] = {'\0'}, *home = NULL;
FILE *fp = NULL;
X509 *client_cert = NULL, *file_cert = NULL;
struct passwd *pwd = NULL;
pool *tmp_pool = NULL;
unsigned char allow_user = FALSE;
if (!(tls_flags & TLS_SESS_ON_CTRL) ||
!ctrl_ssl ||
!user)
return FALSE;
tmp_pool = make_sub_pool(permanent_pool);
PRIVS_ROOT
pwd = pr_auth_getpwnam(tmp_pool, user);
PRIVS_RELINQUISH
if (!pwd) {
destroy_pool(tmp_pool);
return FALSE;
}
/* Handle the case where the user's home directory is a symlink. */
PRIVS_USER
home = dir_realpath(tmp_pool, pwd->pw_dir);
PRIVS_RELINQUISH
snprintf(buf, sizeof(buf), "%s/.tlslogin", home ? home : pwd->pw_dir);
buf[sizeof(buf)-1] = '\0';
/* No need for the temporary pool any more. */
destroy_pool(tmp_pool);
tmp_pool = NULL;
PRIVS_ROOT
fp = fopen(buf, "r");
PRIVS_RELINQUISH
if (!fp) {
tls_log(".tlslogin check: unable to open '%s': %s", buf, strerror(errno));
return FALSE;
}
client_cert = SSL_get_peer_certificate(ctrl_ssl);
if (!client_cert) {
fclose(fp);
return FALSE;
}
while ((file_cert = PEM_read_X509(fp, NULL, NULL, NULL))) {
if (!M_ASN1_BIT_STRING_cmp(client_cert->signature, file_cert->signature))
allow_user = TRUE;
X509_free(file_cert);
if (allow_user)
break;
}
X509_free(client_cert);
fclose(fp);
return allow_user;
}
/* This is unused...for now. */
#if 0
static char *tls_cert_to_user(pool *cert_pool, X509 *cert) {
if (!cert_pool || !cert)
return FALSE;
/* NOTE: insert cert->user translation code here. Possibly add
* TLSOptions that affect this mapping process.
*/
return NULL;
}
#endif
static int tls_readmore(int rfd) {
fd_set rfds;
struct timeval tv;
FD_ZERO(&rfds);
FD_SET(rfd, &rfds);
/* Use a timeout of 15 seconds */
tv.tv_sec = 15;
tv.tv_usec = 0;
return select(rfd + 1, &rfds, NULL, NULL, &tv);
}
static int tls_writemore(int wfd) {
fd_set wfds;
struct timeval tv;
FD_ZERO(&wfds);
FD_SET(wfd, &wfds);
/* Use a timeout of 15 seconds */
tv.tv_sec = 15;
tv.tv_usec = 0;
return select(wfd + 1, NULL, &wfds, NULL, &tv);
}
static ssize_t tls_read(SSL *ssl, void *buf, size_t len) {
ssize_t count;
retry:
pr_signals_handle();
count = SSL_read(ssl, buf, len);
if (count < 0) {
long err = SSL_get_error(ssl, count);
/* read(2) returns only the generic error number -1 */
count = -1;
switch (err) {
case SSL_ERROR_WANT_READ:
/* OpenSSL needs more data from the wire to finish the current block,
* so we wait a little while for it.
*/
err = tls_readmore(SSL_get_fd(ssl));
if (err > 0) {
goto retry;
} else if (err == 0) {
/* Still missing data after timeout. Simulate an EINTR and return.
*/
errno = EINTR;
/* If err < 0, i.e. some error from the select(), everything is
* already in place; errno is properly set and this function
* returns -1.
*/
break;
}
case SSL_ERROR_WANT_WRITE:
/* OpenSSL needs to write more data to the wire to finish the current
* block, so we wait a little while for it.
*/
err = tls_writemore(SSL_get_fd(ssl));
if (err > 0) {
goto retry;
} else if (err == 0) {
/* Still missing data after timeout. Simulate an EINTR and return.
*/
errno = EINTR;
/* If err < 0, i.e. some error from the select(), everything is
* already in place; errno is properly set and this function
* returns -1.
*/
break;
}
case SSL_ERROR_ZERO_RETURN:
tls_log("read EOF from client");
break;
default:
tls_fatal_error(err, __LINE__);
break;
}
}
return count;
}
static RSA *tls_rsa_cb(SSL *ssl, int is_export, int keylength) {
BIGNUM *e = NULL;
if (tls_tmp_rsa) {
return tls_tmp_rsa;
}
#if OPENSSL_VERSION_NUMBER > 0x000908000L
e = BN_new();
if (e == NULL) {
return NULL;
}
if (BN_set_word(e, RSA_F4) != 1) {
BN_free(e);
return NULL;
}
if (RSA_generate_key_ex(tls_tmp_rsa, keylength, e, NULL) != 1) {
BN_free(e);
return NULL;
}
#else
tls_tmp_rsa = RSA_generate_key(keylength, RSA_F4, NULL, NULL);
#endif /* OpenSSL version 0.9.8 and later */
if (e != NULL) {
BN_free(e);
}
return tls_tmp_rsa;
}
static int tls_seed_prng(void) {
char *heapdata, stackdata[1024];
static char rand_file[300];
FILE *fp = NULL;
#if OPENSSL_VERSION_NUMBER >= 0x00905100L
if (RAND_status() == 1)
/* PRNG already well-seeded. */
return 0;
#endif
tls_log("PRNG not seeded with enough data, looking for entropy sources");
/* If the device '/dev/urandom' is present, OpenSSL uses it by default.
* Check if it's present, else we have to make random data ourselves.
*/
fp = fopen("/dev/urandom", "r");
if (fp) {
fclose(fp);
tls_log("device /dev/urandom is present, assuming OpenSSL will use that "
"for PRNG data");
return 0;
}
/* Lookup any configured TLSRandomSeed. */
tls_rand_file = get_param_ptr(main_server->conf, "TLSRandomSeed", FALSE);
if (!tls_rand_file) {
/* The ftpd's random file is (openssl-dir)/.rnd */
memset(rand_file, '\0', sizeof(rand_file));
snprintf(rand_file, sizeof(rand_file)-1, "%s/.rnd",
X509_get_default_cert_area());
tls_rand_file = rand_file;
}
#if OPENSSL_VERSION_NUMBER >= 0x00905100L
/* In OpenSSL 0.9.5 and later, specifying -1 here means "read the entire
* file", which is exactly what we want.
*/
if (RAND_load_file(tls_rand_file, -1) == 0) {
#else
/* In versions of OpenSSL prior to 0.9.5, we have to specify the amount of
* bytes to read in. Since RAND_write_file(3) typically writes 1K of data
* out, we will read 1K bytes in.
*/
if (RAND_load_file(tls_rand_file, 1024) != 1024) {
#endif
time_t now;
pid_t pid;
#if OPENSSL_VERSION_NUMBER >= 0x00905100L
tls_log("unable to load PRNG seed data from '%s': %s", tls_rand_file,
tls_get_errors());
#else
tls_log("unable to load 1024 bytes of PRNG seed data from '%s': %s",
tls_rand_file, tls_get_errors());
#endif
/* No random file found, create new seed. */
now = time(NULL);
RAND_seed(&now, sizeof(time_t));
pid = getpid();
RAND_seed(&pid, sizeof(pid_t));
RAND_seed(stackdata, sizeof(stackdata));
heapdata = malloc(sizeof(stackdata));
if (heapdata != NULL) {
RAND_seed(heapdata, sizeof(stackdata));
free(heapdata);
}
} else {
tls_log("loaded PRNG seed data from '%s'", tls_rand_file);
}
#if OPENSSL_VERSION_NUMBER >= 0x00905100L
if (RAND_status() == 0) {
/* PRNG still badly seeded. */
return -1;
}
#endif
return 0;
}
/* Note: these mappings should probably be added to the mod_tls docs.
*/
static void tls_setup_cert_ext_environ(const char *env_prefix, X509 *cert) {
/* NOTE: in the future, add ways of adding subjectAltName (and other
* extensions?) to the environment.
*/
#if 0
int nexts = 0;
nexts = X509_get_ext_count(cert);
if (nexts > 0) {
register unsigned int i = 0;
for (i = 0; i < nexts; i++) {
X509_EXTENSION *ext = X509_get_ext(cert, i);
const char *extstr = OBJ_nid2sn(OBJ_obj2nid(
X509_EXTENSION_get_object(ext)));
}
}
#endif
return;
}
/* Note: these mappings should probably be added to the mod_tls docs.
*
* Name Short Name NID
* ---- ---------- ---
* countryName C NID_countryName
* commonName CN NID_commonName
* description D NID_description
* givenName G NID_givenName
* initials I NID_initials
* localityName L NID_localityName
* organizationName O NID_organizationName
* organizationalUnitName OU NID_organizationalUnitName
* stateOrProvinceName ST NID_stateOrProvinceName
* surname S NID_surname
* title T NID_title
* uniqueIdentifer UID NID_x500UniqueIdentifier
* (or NID_uniqueIdentifier, depending
* on OpenSSL version)
* email Email NID_pkcs9_emailAddress
*/
static void tls_setup_cert_dn_environ(const char *env_prefix, X509_NAME *name) {
register unsigned int i = 0;
char *k, *v;
for (i = 0; i < sk_X509_NAME_ENTRY_num(name->entries); i++) {
X509_NAME_ENTRY *entry = sk_X509_NAME_ENTRY_value(name->entries, i);
int nid = OBJ_obj2nid(entry->object);
switch (nid) {
case NID_countryName:
k = pstrcat(main_server->pool, env_prefix, "C", NULL);
v = pstrndup(main_server->pool, (const char *) entry->value->data,
entry->value->length);
pr_env_set(main_server->pool, k, v);
break;
case NID_commonName:
k = pstrcat(main_server->pool, env_prefix, "CN", NULL);
v = pstrndup(main_server->pool, (const char *) entry->value->data,
entry->value->length);
pr_env_set(main_server->pool, k, v);
break;
case NID_description:
k = pstrcat(main_server->pool, env_prefix, "D", NULL);
v = pstrndup(main_server->pool, (const char *) entry->value->data,
entry->value->length);
pr_env_set(main_server->pool, k, v);
break;
case NID_givenName:
k = pstrcat(main_server->pool, env_prefix, "G", NULL);
v = pstrndup(main_server->pool, (const char *) entry->value->data,
entry->value->length);
pr_env_set(main_server->pool, k, v);
break;
case NID_initials:
k = pstrcat(main_server->pool, env_prefix, "I", NULL);
v = pstrndup(main_server->pool, (const char *) entry->value->data,
entry->value->length);
pr_env_set(main_server->pool, k, v);
break;
case NID_localityName:
k = pstrcat(main_server->pool, env_prefix, "L", NULL);
v = pstrndup(main_server->pool, (const char *) entry->value->data,
entry->value->length);
pr_env_set(main_server->pool, k, v);
break;
case NID_organizationName:
k = pstrcat(main_server->pool, env_prefix, "O", NULL);
v = pstrndup(main_server->pool, (const char *) entry->value->data,
entry->value->length);
pr_env_set(main_server->pool, k, v);
break;
case NID_organizationalUnitName:
k = pstrcat(main_server->pool, env_prefix, "OU", NULL);
v = pstrndup(main_server->pool, (const char *) entry->value->data,
entry->value->length);
pr_env_set(main_server->pool, k, v);
break;
case NID_stateOrProvinceName:
k = pstrcat(main_server->pool, env_prefix, "ST", NULL);
v = pstrndup(main_server->pool, (const char *) entry->value->data,
entry->value->length);
pr_env_set(main_server->pool, k, v);
break;
case NID_surname:
k = pstrcat(main_server->pool, env_prefix, "S", NULL);
v = pstrndup(main_server->pool, (const char *) entry->value->data,
entry->value->length);
pr_env_set(main_server->pool, k, v);
break;
case NID_title:
k = pstrcat(main_server->pool, env_prefix, "T", NULL);
v = pstrndup(main_server->pool, (const char *) entry->value->data,
entry->value->length);
pr_env_set(main_server->pool, k, v);
break;
#if OPENSSL_VERSION_NUMBER >= 0x00907000L
case NID_x500UniqueIdentifier:
#else
case NID_uniqueIdentifier:
#endif
k = pstrcat(main_server->pool, env_prefix, "UID", NULL);
v = pstrndup(main_server->pool, (const char *) entry->value->data,
entry->value->length);
pr_env_set(main_server->pool, k, v);
break;
case NID_pkcs9_emailAddress:
k = pstrcat(main_server->pool, env_prefix, "Email", NULL);
v = pstrndup(main_server->pool, (const char *) entry->value->data,
entry->value->length);
pr_env_set(main_server->pool, k, v);
break;
default:
break;
}
}
}
static void tls_setup_cert_environ(const char *env_prefix, X509 *cert) {
char *data = NULL, *k, *v;
long datalen = 0;
BIO *bio = NULL;
if (tls_opts & TLS_OPT_STD_ENV_VARS) {
char buf[80] = {'\0'};
ASN1_INTEGER *serial = X509_get_serialNumber(cert);
memset(buf, '\0', sizeof(buf));
snprintf(buf, sizeof(buf) - 1, "%lu", X509_get_version(cert) + 1);
buf[sizeof(buf)-1] = '\0';
k = pstrcat(main_server->pool, env_prefix, "M_VERSION", NULL);
v = pstrdup(main_server->pool, buf);
pr_env_set(main_server->pool, k, v);
if (serial->length < 4) {
memset(buf, '\0', sizeof(buf));
snprintf(buf, sizeof(buf) - 1, "%lu", ASN1_INTEGER_get(serial));
buf[sizeof(buf)-1] = '\0';
k = pstrcat(main_server->pool, env_prefix, "M_SERIAL", NULL);
v = pstrdup(main_server->pool, buf);
pr_env_set(main_server->pool, k, v);
} else {
/* NOTE: actually, the number is printable, I'm just being lazy. This
* case is much harder to deal with, and not really worth the effort.
*/
tls_log("%s", "certificate serial number not printable");
}
k = pstrcat(main_server->pool, env_prefix, "S_DN", NULL);
v = pstrdup(main_server->pool,
tls_x509_name_oneline(X509_get_subject_name(cert)));
pr_env_set(main_server->pool, k, v);
tls_setup_cert_dn_environ(pstrcat(main_server->pool, env_prefix, "S_DN_",
NULL), X509_get_subject_name(cert));
k = pstrcat(main_server->pool, env_prefix, "I_DN", NULL);
v = pstrdup(main_server->pool,
tls_x509_name_oneline(X509_get_issuer_name(cert)));
pr_env_set(main_server->pool, k, v);
tls_setup_cert_dn_environ(pstrcat(main_server->pool, env_prefix, "I_DN_",
NULL), X509_get_issuer_name(cert));
tls_setup_cert_ext_environ(pstrcat(main_server->pool, env_prefix, "EXT_",
NULL), cert);
bio = BIO_new(BIO_s_mem());
ASN1_TIME_print(bio, X509_get_notBefore(cert));
datalen = BIO_get_mem_data(bio, &data);
data[datalen] = '\0';
k = pstrcat(main_server->pool, env_prefix, "V_START", NULL);
v = pstrdup(main_server->pool, data);
pr_env_set(main_server->pool, k, v);
BIO_free(bio);
bio = BIO_new(BIO_s_mem());
ASN1_TIME_print(bio, X509_get_notAfter(cert));
datalen = BIO_get_mem_data(bio, &data);
data[datalen] = '\0';
k = pstrcat(main_server->pool, env_prefix, "V_END", NULL);
v = pstrdup(main_server->pool, data);
pr_env_set(main_server->pool, k, v);
BIO_free(bio);
bio = BIO_new(BIO_s_mem());
i2a_ASN1_OBJECT(bio, cert->cert_info->signature->algorithm);
datalen = BIO_get_mem_data(bio, &data);
data[datalen] = '\0';
k = pstrcat(main_server->pool, env_prefix, "A_SIG", NULL);
v = pstrdup(main_server->pool, data);
pr_env_set(main_server->pool, k, v);
BIO_free(bio);
bio = BIO_new(BIO_s_mem());
i2a_ASN1_OBJECT(bio, cert->cert_info->key->algor->algorithm);
datalen = BIO_get_mem_data(bio, &data);
data[datalen] = '\0';
k = pstrcat(main_server->pool, env_prefix, "A_KEY", NULL);
v = pstrdup(main_server->pool, data);
pr_env_set(main_server->pool, k, v);
BIO_free(bio);
}
bio = BIO_new(BIO_s_mem());
PEM_write_bio_X509(bio, cert);
datalen = BIO_get_mem_data(bio, &data);
data[datalen] = '\0';
k = pstrcat(main_server->pool, env_prefix, "CERT", NULL);
v = pstrdup(main_server->pool, data);
pr_env_set(main_server->pool, k, v);
BIO_free(bio);
}
static void tls_setup_environ(SSL *ssl) {
X509 *cert = NULL;
STACK_OF(X509) *sk_cert_chain = NULL;
char *k, *v;
if (!(tls_opts & TLS_OPT_EXPORT_CERT_DATA) &&
!(tls_opts & TLS_OPT_STD_ENV_VARS))
return;
if (tls_opts & TLS_OPT_STD_ENV_VARS) {
SSL_CIPHER *cipher = NULL;
SSL_SESSION *ssl_session = NULL;
k = pstrdup(main_server->pool, "FTPS");
v = pstrdup(main_server->pool, "1");
pr_env_set(main_server->pool, k, v);
k = pstrdup(main_server->pool, "TLS_PROTOCOL");
v = pstrdup(main_server->pool, SSL_get_cipher_version(ssl));
pr_env_set(main_server->pool, k, v);
/* Process the SSL session-related environ variable. */
ssl_session = SSL_get_session(ssl);
if (ssl_session) {
char buf[SSL_MAX_SSL_SESSION_ID_LENGTH*2+1];
register unsigned int i = 0;
/* Have to obtain a stringified session ID the hard way. */
memset(buf, '\0', sizeof(buf));
for (i = 0; i < ssl_session->session_id_length; i++) {
snprintf(&(buf[i*2]), sizeof(buf) - (i*2) - 1, "%02X",
ssl_session->session_id[i]);
}
buf[sizeof(buf)-1] = '\0';
k = pstrdup(main_server->pool, "TLS_SESSION_ID");
v = pstrdup(main_server->pool, buf);
pr_env_set(main_server->pool, k, v);
}
/* Process the SSL cipher-related environ variables. */
cipher = (SSL_CIPHER *) SSL_get_current_cipher(ssl);
if (cipher) {
char buf[10] = {'\0'};
int cipher_bits_used = 0, cipher_bits_possible = 0;
k = pstrdup(main_server->pool, "TLS_CIPHER");
v = pstrdup(main_server->pool, SSL_CIPHER_get_name(cipher));
pr_env_set(main_server->pool, k, v);
cipher_bits_used = SSL_CIPHER_get_bits(cipher, &cipher_bits_possible);
if (cipher_bits_used < 56) {
k = pstrdup(main_server->pool, "TLS_CIPHER_EXPORT");
v = pstrdup(main_server->pool, "1");
pr_env_set(main_server->pool, k, v);
}
memset(buf, '\0', sizeof(buf));
snprintf(buf, sizeof(buf), "%d", cipher_bits_possible);
buf[sizeof(buf)-1] = '\0';
k = pstrdup(main_server->pool, "TLS_CIPHER_KEYSIZE_POSSIBLE");
v = pstrdup(main_server->pool, buf);
pr_env_set(main_server->pool, k, v);
memset(buf, '\0', sizeof(buf));
snprintf(buf, sizeof(buf), "%d", cipher_bits_used);
buf[sizeof(buf)-1] = '\0';
k = pstrdup(main_server->pool, "TLS_CIPHER_KEYSIZE_USED");
v = pstrdup(main_server->pool, buf);
pr_env_set(main_server->pool, k, v);
}
k = pstrdup(main_server->pool, "TLS_LIBRARY_VERSION");
v = pstrdup(main_server->pool, OPENSSL_VERSION_TEXT);
pr_env_set(main_server->pool, k, v);
}
sk_cert_chain = SSL_get_peer_cert_chain(ssl);
if (sk_cert_chain) {
char *data = NULL;
long datalen = 0;
register unsigned int i = 0;
BIO *bio = NULL;
/* Adding TLS_CLIENT_CERT_CHAIN environ variables. */
for (i = 0; i < sk_X509_num(sk_cert_chain); i++) {
size_t klen = 256;
k = pcalloc(main_server->pool, klen);
snprintf(k, klen - 1, "%s%u", "TLS_CLIENT_CERT_CHAIN", i + 1);
bio = BIO_new(BIO_s_mem());
PEM_write_bio_X509(bio, sk_X509_value(sk_cert_chain, i));
datalen = BIO_get_mem_data(bio, &data);
data[datalen] = '\0';
v = pstrdup(main_server->pool, data);
pr_env_set(main_server->pool, k, v);
BIO_free(bio);
}
}
/* Note: SSL_get_certificate() does NOT increment a reference counter,
* so we do not call X509_free() on it.
*/
cert = SSL_get_certificate(ssl);
if (cert) {
tls_setup_cert_environ("TLS_SERVER_", cert);
} else {
tls_log("unable to set server certificate environ variables: "
"Server certificate unavailable");
}
cert = SSL_get_peer_certificate(ssl);
if (cert) {
tls_setup_cert_environ("TLS_CLIENT_", cert);
X509_free(cert);
} else {
tls_log("unable to set client certificate environ variables: "
"Client certificate unavailable");
}
return;
}
static int tls_verify_cb(int ok, X509_STORE_CTX *ctx) {
config_rec *c;
/* We can configure the server to skip the peer's cert verification */
if (!(tls_flags & TLS_SESS_VERIFY_CLIENT))
return 1;
c = find_config(main_server->conf, CONF_PARAM, "TLSVerifyOrder", FALSE);
if (c) {
register unsigned int i;
for (i = 0; i < c->argc; i++) {
char *mech = c->argv[i];
if (strncasecmp(mech, "crl", 4) == 0) {
ok = tls_verify_crl(ok, ctx);
if (!ok) {
break;
}
} else if (strncasecmp(mech, "ocsp", 5) == 0) {
ok = tls_verify_ocsp(ok, ctx);
if (!ok) {
break;
}
}
}
} else {
/* If no TLSVerifyOrder was specified, default to the old behavior of
* always checking CRLs, if configured, and not paying attention to
* any AIA attributes (i.e. no use of OCSP).
*/
ok = tls_verify_crl(ok, ctx);
}
if (!ok) {
X509 *cert = X509_STORE_CTX_get_current_cert(ctx);
int depth = X509_STORE_CTX_get_error_depth(ctx);
tls_log("error: unable to verify certificate at depth %d", depth);
tls_log("error: cert subject: %s", tls_x509_name_oneline(
X509_get_subject_name(cert)));
tls_log("error: cert issuer: %s", tls_x509_name_oneline(
X509_get_issuer_name(cert)));
/* Catch a too long certificate chain here. */
if (depth > tls_verify_depth)
X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_CHAIN_TOO_LONG);
switch (ctx->error) {
case X509_V_ERR_CERT_CHAIN_TOO_LONG:
case X509_V_ERR_CERT_HAS_EXPIRED:
case X509_V_ERR_CERT_REVOKED:
case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
case X509_V_ERR_APPLICATION_VERIFICATION:
tls_log("client certificate failed verification: %s",
X509_verify_cert_error_string(ctx->error));
ok = 0;
break;
case X509_V_ERR_INVALID_PURPOSE: {
register unsigned int i;
int count = X509_PURPOSE_get_count();
tls_log("client certificate failed verification: %s",
X509_verify_cert_error_string(ctx->error));
for (i = 0; i < count; i++) {
X509_PURPOSE *purp = X509_PURPOSE_get0(i);
tls_log(" purpose #%d: %s", i+1, X509_PURPOSE_get0_name(purp));
}
ok = 0;
break;
}
case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
/* XXX this is strange. we get this error for certain clients
* (i.e. Jeff Altman's kftp) when all is ok. I think it's because the
* client is actually sending the whole CA cert. This must be figured
* out, but we let it pass for now. If the CA cert isn't available
* locally, we will fail anyway.
*/
tls_log("%s", X509_verify_cert_error_string(ctx->error));
ok = 1;
break;
default:
tls_log("error verifying client certificate: [%d] %s",
ctx->error, X509_verify_cert_error_string(ctx->error));
ok = 0;
break;
}
}
return ok;
}
/* This routine is (very much!) based on the work by Ralf S. Engelschall
* <rse@engelshall.com>. Comments by Ralf.
*/
static int tls_verify_crl(int ok, X509_STORE_CTX *ctx) {
X509_OBJECT obj;
X509_NAME *subject = NULL, *issuer = NULL;
X509 *xs = NULL;
X509_CRL *crl = NULL;
X509_STORE_CTX store_ctx;
int n, res;
register int i = 0;
/* Unless a revocation store for CRLs was created we cannot do any
* CRL-based verification, of course.
*/
if (!tls_crl_store) {
return ok;
}
tls_log("CRL store present, checking client certificate against configured "
"CRLs");
/* Determine certificate ingredients in advance.
*/
xs = X509_STORE_CTX_get_current_cert(ctx);
subject = X509_get_subject_name(xs);
pr_trace_msg(trace_channel, 15,
"verifying cert: subject = '%s'", tls_x509_name_oneline(subject));
issuer = X509_get_issuer_name(xs);
pr_trace_msg(trace_channel, 15,
"verifying cert: issuer = '%s'", tls_x509_name_oneline(issuer));
/* OpenSSL provides the general mechanism to deal with CRLs but does not
* use them automatically when verifying certificates, so we do it
* explicitly here. We will check the CRL for the currently checked
* certificate, if there is such a CRL in the store.
*
* We come through this procedure for each certificate in the certificate
* chain, starting with the root-CA's certificate. At each step we've to
* both verify the signature on the CRL (to make sure it's a valid CRL)
* and its revocation list (to make sure the current certificate isn't
* revoked). But because to check the signature on the CRL we need the
* public key of the issuing CA certificate (which was already processed
* one round before), we've a little problem. But we can both solve it and
* at the same time optimize the processing by using the following
* verification scheme (idea and code snippets borrowed from the GLOBUS
* project):
*
* 1. We'll check the signature of a CRL in each step when we find a CRL
* through the _subject_ name of the current certificate. This CRL
* itself will be needed the first time in the next round, of course.
* But we do the signature processing one round before this where the
* public key of the CA is available.
*
* 2. We'll check the revocation list of a CRL in each step when
* we find a CRL through the _issuer_ name of the current certificate.
* This CRLs signature was then already verified one round before.
*
* This verification scheme allows a CA to revoke its own certificate as
* well, of course.
*/
/* Try to retrieve a CRL corresponding to the _subject_ of
* the current certificate in order to verify its integrity.
*/
memset(&obj, 0, sizeof(obj));
#if OPENSSL_VERSION_NUMBER > 0x000907000L
if (X509_STORE_CTX_init(&store_ctx, tls_crl_store, NULL, NULL) <= 0) {
tls_log("error initializing CRL store context: %s", tls_get_errors());
return ok;
}
#else
X509_STORE_CTX_init(&store_ctx, tls_crl_store, NULL, NULL);
#endif
res = X509_STORE_get_by_subject(&store_ctx, X509_LU_CRL, subject, &obj);
crl = obj.data.crl;
if (res > 0 &&
crl != NULL) {
EVP_PKEY *pubkey;
char buf[512];
int len;
BIO *b = BIO_new(BIO_s_mem());
BIO_printf(b, "CA CRL: Issuer: ");
X509_NAME_print(b, issuer, 0);
BIO_printf(b, ", lastUpdate: ");
ASN1_UTCTIME_print(b, crl->crl->lastUpdate);
BIO_printf(b, ", nextUpdate: ");
ASN1_UTCTIME_print(b, crl->crl->nextUpdate);
len = BIO_read(b, buf, sizeof(buf) - 1);
if (len >= sizeof(buf)) {
len = sizeof(buf)-1;
}
buf[len] = '\0';
BIO_free(b);
tls_log("%s", buf);
pubkey = X509_get_pubkey(xs);
/* Verify the signature on this CRL */
res = X509_CRL_verify(crl, pubkey);
if (pubkey) {
EVP_PKEY_free(pubkey);
}
if (res <= 0) {
tls_log("invalid signature on CRL: %s", tls_get_errors());
X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_SIGNATURE_FAILURE);
X509_OBJECT_free_contents(&obj);
X509_STORE_CTX_cleanup(&store_ctx);
return FALSE;
}
/* Check date of CRL to make sure it's not expired */
i = X509_cmp_current_time(X509_CRL_get_nextUpdate(crl));
if (i == 0) {
tls_log("CRL has invalid nextUpdate field: %s", tls_get_errors());
X509_STORE_CTX_set_error(ctx, X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD);
X509_OBJECT_free_contents(&obj);
X509_STORE_CTX_cleanup(&store_ctx);
return FALSE;
}
if (i < 0) {
/* XXX This is a bit draconian, rejecting all certificates if the CRL
* has expired. See also Bug#3216, about automatically reloading
* the CRL file when it has expired.
*/
tls_log("%s", "CRL is expired, revoking all certificates until an "
"updated CRL is obtained");
X509_STORE_CTX_set_error(ctx, X509_V_ERR_CRL_HAS_EXPIRED);
X509_OBJECT_free_contents(&obj);
X509_STORE_CTX_cleanup(&store_ctx);
return FALSE;
}
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(&obj, 0, sizeof(obj));
res = X509_STORE_get_by_subject(&store_ctx, X509_LU_CRL, issuer, &obj);
crl = obj.data.crl;
if (res > 0 &&
crl != NULL) {
/* 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++) {
X509_REVOKED *revoked;
ASN1_INTEGER *sn;
revoked = sk_X509_REVOKED_value(X509_CRL_get_REVOKED(crl), i);
sn = revoked->serialNumber;
if (ASN1_INTEGER_cmp(sn, X509_get_serialNumber(xs)) == 0) {
long serial = ASN1_INTEGER_get(sn);
char *cp = tls_x509_name_oneline(issuer);
tls_log("certificate with serial number %ld (0x%lX) revoked per CRL "
"from issuer '%s'", serial, serial, cp ? cp : "(ERROR)");
X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_REVOKED);
X509_OBJECT_free_contents(&obj);
X509_STORE_CTX_cleanup(&store_ctx);
return FALSE;
}
}
X509_OBJECT_free_contents(&obj);
}
X509_STORE_CTX_cleanup(&store_ctx);
return ok;
}
#if OPENSSL_VERSION_NUMBER > 0x000907000L
static int tls_verify_ocsp_url(X509_STORE_CTX *ctx, X509 *cert,
const char *url) {
BIO *conn;
X509 *issuing_cert = NULL;
X509_NAME *subj = NULL;
const char *subj_name;
char *host = NULL, *port = NULL, *uri = NULL;
int ok = FALSE, res = 0 , use_ssl = 0, ocsp_status, ocsp_cert_status,
ocsp_reason;
OCSP_REQUEST *req = NULL;
OCSP_CERTID *cert_id = NULL;
OCSP_RESPONSE *resp = NULL;
OCSP_BASICRESP *basic_resp = NULL;
SSL_CTX *ocsp_ssl_ctx = NULL;
if (cert == NULL ||
url == NULL) {
return FALSE;
}
subj = X509_get_subject_name(cert);
subj_name = tls_x509_name_oneline(subj);
tls_log("checking OCSP URL '%s' for client cert '%s'", url, subj_name);
if (OCSP_parse_url((char *) url, &host, &port, &uri, &use_ssl) != 1) {
tls_log("error parsing OCSP URL '%s': %s", url, tls_get_errors());
return FALSE;
}
/* XXX Need to check for NULL host, uri. */
if (port == NULL) {
if (use_ssl == 1) {
#ifdef OPENSSL_strdup
port = OPENSSL_strdup("443");
#else
port = OPENSSL_malloc(4);
sstrncpy(port, "443", 3);
#endif /* OPENSSL_strdup */
} else {
#ifdef OPENSSL_strdup
port = OPENSSL_strdup("80");
#else
port = OPENSSL_malloc(3);
sstrncpy(port, "80", 2);
#endif /* OPENSSL_strdup */
}
}
tls_log("connecting to OCSP responder at host '%s', port '%s', URI '%s'%s",
host, port, uri, use_ssl ? ", using SSL/TLS" : "");
/* Connect to the OCSP responder indicated */
conn = BIO_new_connect(host);
if (conn == NULL) {
tls_log("error creating connection BIO: %s", tls_get_errors());
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(uri);
return FALSE;
}
BIO_set_conn_port(conn, port);
/* If use_ssl is true, we need to a) create an SSL_CTX object to use, and
* push it onto the BIO chain so that SSL/TLS actually happens.
* When doing so, what version of SSL/TLS should we use?
*/
if (use_ssl == 1) {
BIO *ocsp_ssl_bio = NULL;
/* Note: this code used openssl/apps/ocsp.c as a model. */
ocsp_ssl_ctx = SSL_CTX_new(SSLv23_client_method());
if (ocsp_ssl_ctx != NULL) {
SSL_CTX_set_mode(ocsp_ssl_ctx, SSL_MODE_AUTO_RETRY);
ocsp_ssl_bio = BIO_new_ssl(ocsp_ssl_ctx, 1);
BIO_push(ocsp_ssl_bio, conn);
} else {
tls_log("error allocating SSL_CTX object for OCSP verification: %s",
tls_get_errors());
}
}
res = BIO_do_connect(conn);
if (res != 1) {
tls_log("error connecting to OCSP URL '%s': %s", url, tls_get_errors());
if (ocsp_ssl_ctx != NULL) {
SSL_CTX_free(ocsp_ssl_ctx);
}
BIO_free_all(conn);
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(uri);
/* XXX Should we give the client the benefit of the doubt, and allow
* it to connect even though we can't talk to its OCSP responder? Or
* do we fail-close, and penalize the client if the OCSP responder is
* down (e.g. for maintenance)?
*/
return FALSE;
}
/* XXX Why are we querying the OCSP responder about the client cert's
* issuing CA, rather than querying about the client cert itself?
*/
res = X509_STORE_CTX_get1_issuer(&issuing_cert, ctx, cert);
if (res != 1) {
tls_log("error retrieving issuing cert for client cert '%s': %s",
subj_name, tls_get_errors());
if (ocsp_ssl_ctx != NULL) {
SSL_CTX_free(ocsp_ssl_ctx);
}
BIO_free_all(conn);
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(uri);
return FALSE;
}
/* Note that the cert_id value will be freed when the request is freed. */
cert_id = OCSP_cert_to_id(NULL, cert, issuing_cert);
if (cert_id == NULL) {
const char *issuer_subj_name = tls_x509_name_oneline(
X509_get_subject_name(issuing_cert));
tls_log("error converting client cert '%s' and its issuing cert '%s' "
"to an OCSP cert ID: %s", subj_name, issuer_subj_name, tls_get_errors());
if (ocsp_ssl_ctx != NULL) {
SSL_CTX_free(ocsp_ssl_ctx);
}
X509_free(issuing_cert);
BIO_free_all(conn);
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(uri);
return FALSE;
}
req = OCSP_REQUEST_new();
if (req == NULL) {
tls_log("unable to allocate OCSP request: %s", tls_get_errors());
if (ocsp_ssl_ctx != NULL) {
SSL_CTX_free(ocsp_ssl_ctx);
}
X509_free(issuing_cert);
BIO_free_all(conn);
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(uri);
return FALSE;
}
if (OCSP_request_add0_id(req, cert_id) == NULL) {
tls_log("error adding cert ID to OCSP request: %s", tls_get_errors());
if (ocsp_ssl_ctx != NULL) {
SSL_CTX_free(ocsp_ssl_ctx);
}
OCSP_REQUEST_free(req);
X509_free(issuing_cert);
BIO_free_all(conn);
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(uri);
return FALSE;
}
# if 0
/* XXX ideally we would set the requestor name to the subject name of the
* cert configured via TLS{DSA,RSA}CertificateFile here.
*/
if (OCSP_request_set1_name(req, /* server cert X509_NAME subj name */) != 1) {
tls_log("error adding requestor name '%s' to OCSP request: %s",
requestor_name, tls_get_errors());
if (ocsp_ssl_ctx != NULL) {
SSL_CTX_free(ocsp_ssl_ctx);
}
OCSP_REQUEST_free(req);
X509_free(issuing_cert);
BIO_free_all(conn);
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(uri);
return FALSE;
}
# endif
res = OCSP_request_add1_nonce(req, NULL, 0);
if (res != 1) {
tls_log("error adding nonce to OCSP request: %s", tls_get_errors());
if (ocsp_ssl_ctx != NULL) {
SSL_CTX_free(ocsp_ssl_ctx);
}
OCSP_REQUEST_free(req);
X509_free(issuing_cert);
BIO_free_all(conn);
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(uri);
return FALSE;
}
if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
BIO *bio;
bio = BIO_new(BIO_s_mem());
if (bio != NULL) {
if (OCSP_REQUEST_print(bio, req, 0) == 1) {
char *data = NULL;
long datalen;
datalen = BIO_get_mem_data(bio, &data);
if (data != NULL) {
data[datalen] = '\0';
tls_log("sending OCSP request (%ld bytes):\n%s", datalen, data);
}
}
BIO_free(bio);
}
}
resp = OCSP_sendreq_bio(conn, uri, req);
if (resp == NULL) {
tls_log("error receiving response from OCSP responder at '%s': %s", url,
tls_get_errors());
if (ocsp_ssl_ctx != NULL) {
SSL_CTX_free(ocsp_ssl_ctx);
}
OCSP_REQUEST_free(req);
X509_free(issuing_cert);
BIO_free_all(conn);
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(uri);
return FALSE;
}
if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
BIO *bio;
bio = BIO_new(BIO_s_mem());
if (bio != NULL) {
if (OCSP_RESPONSE_print(bio, resp, 0) == 1) {
char *data = NULL;
long datalen;
datalen = BIO_get_mem_data(bio, &data);
if (data != NULL) {
data[datalen] = '\0';
tls_log("received OCSP response (%ld bytes):\n%s", datalen, data);
}
}
BIO_free(bio);
}
}
tls_log("checking response from OCSP responder at URL '%s' for client cert "
"'%s'", url, subj_name);
basic_resp = OCSP_response_get1_basic(resp);
if (basic_resp == NULL) {
tls_log("error retrieving basic response from OCSP responder at '%s': %s",
url, tls_get_errors());
if (ocsp_ssl_ctx != NULL) {
SSL_CTX_free(ocsp_ssl_ctx);
}
OCSP_RESPONSE_free(resp);
OCSP_REQUEST_free(req);
X509_free(issuing_cert);
BIO_free_all(conn);
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(uri);
return FALSE;
}
res = OCSP_check_nonce(req, basic_resp);
if (res != 1) {
tls_log("unable to use response from OCSP responder at '%s': bad nonce",
url);
if (ocsp_ssl_ctx != NULL) {
SSL_CTX_free(ocsp_ssl_ctx);
}
OCSP_BASICRESP_free(basic_resp);
OCSP_RESPONSE_free(resp);
OCSP_REQUEST_free(req);
X509_free(issuing_cert);
BIO_free_all(conn);
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(uri);
return FALSE;
}
res = OCSP_basic_verify(basic_resp, NULL, ctx->ctx, 0);
if (res != 1) {
tls_log("error verifying basic response from OCSP responder at '%s': %s",
url, tls_get_errors());
if (ocsp_ssl_ctx != NULL) {
SSL_CTX_free(ocsp_ssl_ctx);
}
OCSP_REQUEST_free(req);
OCSP_BASICRESP_free(basic_resp);
OCSP_RESPONSE_free(resp);
X509_free(issuing_cert);
BIO_free_all(conn);
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(uri);
return FALSE;
}
/* Now that we have verified the response, we can check the response status.
* If we only looked at the status first, then a malicious responder
* could be tricking us, e.g.:
*
* http://www.thoughtcrime.org/papers/ocsp-attack.pdf
*/
ocsp_status = OCSP_response_status(resp);
if (ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
tls_log("unable to verify client cert '%s' via OCSP responder at '%s': "
"response status '%s' (%d)", subj_name, url,
OCSP_response_status_str(ocsp_status), ocsp_status);
if (ocsp_ssl_ctx != NULL) {
SSL_CTX_free(ocsp_ssl_ctx);
}
OCSP_REQUEST_free(req);
OCSP_BASICRESP_free(basic_resp);
OCSP_RESPONSE_free(resp);
X509_free(issuing_cert);
BIO_free_all(conn);
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(uri);
switch (ocsp_status) {
case OCSP_RESPONSE_STATUS_MALFORMEDREQUEST:
case OCSP_RESPONSE_STATUS_INTERNALERROR:
case OCSP_RESPONSE_STATUS_SIGREQUIRED:
case OCSP_RESPONSE_STATUS_UNAUTHORIZED:
case OCSP_RESPONSE_STATUS_TRYLATER:
/* XXX For now, for the above OCSP response reasons, give the client
* the benefit of the doubt, since all of the above non-success
* response codes indicate either a) an issue with the OCSP responder
* outside of the client's control, or b) an issue with our OCSP
* implementation (e.g. SIGREQUIRED, UNAUTHORIZED).
*/
ok = TRUE;
break;
default:
ok = FALSE;
}
return ok;
}
res = OCSP_resp_find_status(basic_resp, cert_id, &ocsp_cert_status,
&ocsp_reason, NULL, NULL, NULL);
if (res != 1) {
tls_log("unable to retrieve cert status from OCSP response: %s",
tls_get_errors());
if (ocsp_ssl_ctx != NULL) {
SSL_CTX_free(ocsp_ssl_ctx);
}
OCSP_REQUEST_free(req);
OCSP_BASICRESP_free(basic_resp);
OCSP_RESPONSE_free(resp);
X509_free(issuing_cert);
BIO_free_all(conn);
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(uri);
return FALSE;
}
tls_log("client cert '%s' has '%s' (%d) status according to OCSP responder "
"at '%s'", subj_name, OCSP_cert_status_str(ocsp_cert_status),
ocsp_cert_status, url);
switch (ocsp_cert_status) {
case V_OCSP_CERTSTATUS_GOOD:
ok = TRUE;
break;
case V_OCSP_CERTSTATUS_REVOKED:
tls_log("client cert '%s' has '%s' status due to: %s", subj_name,
OCSP_cert_status_str(ocsp_status), OCSP_crl_reason_str(ocsp_reason));
ok = FALSE;
break;
case V_OCSP_CERTSTATUS_UNKNOWN:
/* If the client cert points to an OCSP responder which claims not to
* know about the client cert, then we shouldn't trust that client
* cert. Otherwise, a client could present a cert pointing to an
* OCSP responder which they KNOW won't know about the client cert,
* and could then slip through the verification process.
*/
ok = FALSE;
break;
default:
ok = FALSE;
}
if (ocsp_ssl_ctx != NULL) {
SSL_CTX_free(ocsp_ssl_ctx);
}
OCSP_REQUEST_free(req);
OCSP_BASICRESP_free(basic_resp);
OCSP_RESPONSE_free(resp);
X509_free(issuing_cert);
BIO_free_all(conn);
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(uri);
return ok;
}
#endif
static int tls_verify_ocsp(int ok, X509_STORE_CTX *ctx) {
#if OPENSSL_VERSION_NUMBER > 0x000907000L
register unsigned int i;
X509 *cert;
const char *subj;
STACK_OF(ACCESS_DESCRIPTION) *descs;
pool *tmp_pool = NULL;
array_header *ocsp_urls = NULL;
/* Set a default verification error here; it will be superceded as needed
* later during the verification process.
*/
X509_STORE_CTX_set_error(ctx, X509_V_ERR_APPLICATION_VERIFICATION);
cert = X509_STORE_CTX_get_current_cert(ctx);
if (cert == NULL) {
return ok;
}
subj = tls_x509_name_oneline(X509_get_subject_name(cert));
descs = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
if (descs == NULL) {
tls_log("Client cert '%s' contained no AuthorityInfoAccess attribute, "
"unable to verify via OCSP", subj);
return ok;
}
for (i = 0; i < sk_ACCESS_DESCRIPTION_num(descs); i++) {
ACCESS_DESCRIPTION *desc = sk_ACCESS_DESCRIPTION_value(descs, i);
if (OBJ_obj2nid(desc->method) == NID_ad_OCSP) {
/* Found an OCSP AuthorityInfoAccess attribute */
if (desc->location->type != GEN_URI) {
/* Not a valid URI, ignore it. */
continue;
}
/* Add this URL to the list of OCSP URLs to check. */
if (ocsp_urls == NULL) {
tmp_pool = make_sub_pool(session.pool);
ocsp_urls = make_array(tmp_pool, 1, sizeof(char *));
}
*((char **) push_array(ocsp_urls)) = pstrdup(tmp_pool,
(char *) desc->location->d.uniformResourceIdentifier->data);
}
}
if (ocsp_urls == NULL) {
tls_log("found no OCSP URLs in AuthorityInfoAccess attribute for client "
"cert '%s', unable to verify via OCSP", subj);
AUTHORITY_INFO_ACCESS_free(descs);
return ok;
}
tls_log("found %u OCSP %s in AuthorityInfoAccess attribute for client cert "
"'%s'", ocsp_urls->nelts, ocsp_urls->nelts != 1 ? "URLs" : "URL", subj);
/* Check each of the URLs. */
for (i = 0; i < ocsp_urls->nelts; i++) {
char *url = ((char **) ocsp_urls->elts)[i];
ok = tls_verify_ocsp_url(ctx, cert, url);
if (ok)
break;
}
destroy_pool(tmp_pool);
AUTHORITY_INFO_ACCESS_free(descs);
return ok;
#else
return ok;
#endif
}
static ssize_t tls_write(SSL *ssl, const void *buf, size_t len) {
ssize_t count;
count = SSL_write(ssl, buf, len);
if (count < 0) {
long err = SSL_get_error(ssl, count);
/* write(2) returns only the generic error number -1 */
count = -1;
switch (err) {
case SSL_ERROR_WANT_WRITE:
/* Simulate an EINTR in case OpenSSL wants to write more. */
errno = EINTR;
break;
default:
tls_fatal_error(err, __LINE__);
break;
}
}
return count;
}
static char *tls_x509_name_oneline(X509_NAME *x509_name) {
static char buf[1024] = {'\0'};
/* If we are using OpenSSL 0.9.6 or newer, we want to use
* X509_NAME_print_ex() instead of X509_NAME_oneline().
*/
#if OPENSSL_VERSION_NUMBER < 0x000906000L
memset(&buf, '\0', sizeof(buf));
return X509_NAME_oneline(x509_name, buf, sizeof(buf)-1);
#else
/* Sigh...do it the hard way. */
BIO *mem = BIO_new(BIO_s_mem());
char *data = NULL;
long datalen = 0;
int ok;
ok = X509_NAME_print_ex(mem, x509_name, 0, XN_FLAG_ONELINE);
if (ok) {
datalen = BIO_get_mem_data(mem, &data);
if (data) {
memset(&buf, '\0', sizeof(buf));
if (datalen >= sizeof(buf)) {
datalen = sizeof(buf)-1;
}
memcpy(buf, data, datalen);
buf[datalen] = '\0';
buf[sizeof(buf)-1] = '\0';
BIO_free(mem);
return buf;
}
}
BIO_free(mem);
return NULL;
#endif /* OPENSSL_VERSION_NUMBER >= 0x000906000 */
}
/* Session cache API */
struct tls_scache {
struct tls_scache *next, *prev;
const char *name;
tls_sess_cache_t *cache;
};
static pool *tls_sess_cache_pool = NULL;
static struct tls_scache *tls_sess_caches = NULL;
static unsigned int tls_sess_ncaches = 0;
int tls_sess_cache_register(const char *name, tls_sess_cache_t *cache) {
struct tls_scache *sc;
if (name == NULL ||
cache == NULL) {
errno = EINVAL;
return -1;
}
if (tls_sess_cache_pool == NULL) {
tls_sess_cache_pool = make_sub_pool(permanent_pool);
pr_pool_tag(tls_sess_cache_pool, "TLS Session Cache API Pool");
}
/* Make sure this cache has not already been registered. */
if (tls_sess_cache_get_cache(name) != NULL) {
errno = EEXIST;
return -1;
}
sc = pcalloc(tls_sess_cache_pool, sizeof(struct tls_scache));
/* XXX Should this name string be dup'd from the tls_sess_cache_pool? */
sc->name = name;
cache->cache_name = pstrdup(tls_sess_cache_pool, name);
sc->cache = cache;
if (tls_sess_caches) {
sc->next = tls_sess_caches;
} else {
sc->next = NULL;
}
tls_sess_caches = sc;
tls_sess_ncaches++;
return 0;
}
int tls_sess_cache_unregister(const char *name) {
struct tls_scache *sc;
if (name == NULL) {
errno = EINVAL;
return -1;
}
for (sc = tls_sess_caches; sc; sc = sc->next) {
if (strcmp(sc->name, name) == 0) {
if (sc->prev) {
sc->prev->next = sc->next;
} else {
/* If prev is NULL, this is the head of the list. */
tls_sess_caches = sc->next;
}
if (sc->next)
sc->next->prev = sc->prev;
sc->next = sc->prev = NULL;
tls_sess_ncaches--;
/* NOTE: a counter should be kept of the number of unregistrations,
* as the memory for a registration is not freed on unregistration.
*/
return 0;
}
}
errno = ENOENT;
return -1;
}
static tls_sess_cache_t *tls_sess_cache_get_cache(const char *name) {
struct tls_scache *sc;
if (name == NULL) {
errno = EINVAL;
return NULL;
}
for (sc = tls_sess_caches; sc; sc = sc->next) {
if (strcmp(sc->name, name) == 0) {
return sc->cache;
}
}
errno = ENOENT;
return NULL;
}
static long tls_sess_cache_get_cache_mode(void) {
if (tls_sess_cache == NULL) {
return 0;
}
return tls_sess_cache->cache_mode;
}
static int tls_sess_cache_open(char *info, long timeout) {
int res;
if (tls_sess_cache == NULL) {
errno = ENOSYS;
return -1;
}
res = (tls_sess_cache->open)(tls_sess_cache, info, timeout);
return res;
}
static int tls_sess_cache_close(void) {
int res;
if (tls_sess_cache == NULL) {
errno = ENOSYS;
return -1;
}
res = (tls_sess_cache->close)(tls_sess_cache);
return res;
}
#ifdef PR_USE_CTRLS
static int tls_sess_cache_clear(void) {
int res;
if (tls_sess_cache == NULL) {
errno = ENOSYS;
return -1;
}
res = (tls_sess_cache->clear)(tls_sess_cache);
return res;
}
static int tls_sess_cache_remove(void) {
int res;
if (tls_sess_cache == NULL) {
errno = ENOSYS;
return -1;
}
res = (tls_sess_cache->remove)(tls_sess_cache);
return res;
}
static void sess_cache_printf(void *ctrl, const char *fmt, ...) {
char buf[PR_TUNABLE_BUFFER_SIZE];
va_list msg;
memset(buf, '\0', sizeof(buf));
va_start(msg, fmt);
vsnprintf(buf, sizeof(buf), fmt, msg);
va_end(msg);
buf[sizeof(buf)-1] = '\0';
pr_ctrls_add_response(ctrl, "%s", buf);
}
static int tls_sess_cache_status(pr_ctrls_t *ctrl, int flags) {
int res = 0;
if (tls_sess_cache != NULL) {
res = (tls_sess_cache->status)(tls_sess_cache, sess_cache_printf, ctrl,
flags);
return res;
}
pr_ctrls_add_response(ctrl, "No TLSSessionCache configured");
return res;
}
static int tls_handle_clear(pr_ctrls_t *ctrl, int reqargc, char **reqargv) {
int res;
res = tls_sess_cache_clear();
if (res < 0) {
pr_ctrls_add_response(ctrl,
"tls sesscache: error clearing session cache: %s", strerror(errno));
} else {
pr_ctrls_add_response(ctrl, "tls sesscache: cleared %d %s from '%s' "
"session cache", res, res != 1 ? "sessions" : "session",
tls_sess_cache->cache_name);
res = 0;
}
return res;
}
static int tls_handle_info(pr_ctrls_t *ctrl, int reqargc, char **reqargv) {
int flags = 0, optc, res;
const char *opts = "v";
pr_getopt_reset();
while ((optc = getopt(reqargc, reqargv, opts)) != -1) {
switch (optc) {
case 'v':
flags = TLS_SESS_CACHE_STATUS_FL_SHOW_SESSIONS;
break;
case '?':
pr_ctrls_add_response(ctrl,
"tls sesscache: unsupported parameter: '%s'", reqargv[1]);
return -1;
}
}
res = tls_sess_cache_status(ctrl, flags);
if (res < 0) {
pr_ctrls_add_response(ctrl,
"tls sesscache: error obtaining session cache status: %s",
strerror(errno));
} else {
res = 0;
}
return res;
}
static int tls_handle_remove(pr_ctrls_t *ctrl, int reqargc, char **reqargv) {
int res;
res = tls_sess_cache_remove();
if (res < 0) {
pr_ctrls_add_response(ctrl,
"tls sesscache: error removing session cache: %s", strerror(errno));
} else {
pr_ctrls_add_response(ctrl, "tls sesscache: removed '%s' session cache",
tls_sess_cache->cache_name);
res = 0;
}
return res;
}
static int tls_handle_sesscache(pr_ctrls_t *ctrl, int reqargc, char **reqargv) {
/* Sanity check */
if (reqargc == 0 ||
reqargv == NULL) {
pr_ctrls_add_response(ctrl, "tls sesscache: missing required parameters");
return -1;
}
if (strncmp(reqargv[0], "info", 5) == 0) {
/* Check the ACLs. */
if (!pr_ctrls_check_acl(ctrl, tls_acttab, "info")) {
pr_ctrls_add_response(ctrl, "access denied");
return -1;
}
return tls_handle_info(ctrl, reqargc, reqargv);
} else if (strncmp(reqargv[0], "clear", 6) == 0) {
/* Check the ACLs. */
if (!pr_ctrls_check_acl(ctrl, tls_acttab, "clear")) {
pr_ctrls_add_response(ctrl, "access denied");
return -1;
}
return tls_handle_clear(ctrl, reqargc, reqargv);
} else if (strncmp(reqargv[0], "remove", 7) == 0) {
/* Check the ACLs. */
if (!pr_ctrls_check_acl(ctrl, tls_acttab, "remove")) {
pr_ctrls_add_response(ctrl, "access denied");
return -1;
}
return tls_handle_remove(ctrl, reqargc, reqargv);
}
pr_ctrls_add_response(ctrl, "tls sesscache: unknown sesscache action: '%s'",
reqargv[0]);
return -1;
}
/* Our main ftpdctl action handler */
static int tls_handle_tls(pr_ctrls_t *ctrl, int reqargc, char **reqargv) {
/* Sanity check */
if (reqargc == 0 ||
reqargv == NULL) {
pr_ctrls_add_response(ctrl, "tls: missing required parameters");
return -1;
}
if (strncmp(reqargv[0], "sesscache", 10) == 0) {
/* Check the ACLs. */
if (!pr_ctrls_check_acl(ctrl, tls_acttab, "sesscache")) {
pr_ctrls_add_response(ctrl, "access denied");
return -1;
}
return tls_handle_sesscache(ctrl, --reqargc, ++reqargv);
}
pr_ctrls_add_response(ctrl, "tls: unknown tls action: '%s'", reqargv[0]);
return -1;
}
#endif
static int tls_sess_cache_add_sess_cb(SSL *ssl, SSL_SESSION *sess) {
unsigned char *sess_id;
unsigned int sess_id_len;
int res;
long expires;
if (tls_sess_cache == NULL) {
tls_log("unable to add session to session cache: %s", strerror(ENOSYS));
SSL_SESSION_free(sess);
return 1;
}
SSL_set_timeout(sess, tls_sess_cache->cache_timeout);
#if OPENSSL_VERSION_NUMBER > 0x000908000L
sess_id = (unsigned char *) SSL_SESSION_get_id(sess, &sess_id_len);
#else
/* XXX Directly accessing these fields cannot be a Good Thing. */
sess_id = sess->session_id;
sess_id_len = sess->session_id_length;
#endif
/* The expiration timestamp stored in the session cache is the
* Unix epoch time, not an interval.
*/
expires = SSL_SESSION_get_time(sess) + tls_sess_cache->cache_timeout;
res = (tls_sess_cache->add)(tls_sess_cache, sess_id, sess_id_len, expires,
sess);
if (res < 0) {
long cache_mode;
tls_log("error adding session to '%s' cache: %s",
tls_sess_cache->cache_name, strerror(errno));
cache_mode = tls_sess_cache_get_cache_mode();
#ifdef SSL_SESS_CACHE_NO_INTERNAL
if (cache_mode & SSL_SESS_CACHE_NO_INTERNAL) {
/* Call SSL_SESSION_free() here, and return 1. We told OpenSSL that we
* are the only cache, so failing to call SSL_SESSION_free() could
* result in a memory leak.
*/
SSL_SESSION_free(sess);
return 1;
}
#endif /* !SSL_SESS_CACHE_NO_INTERNAL */
}
/* Return zero to indicate to OpenSSL that we have not called
* SSL_SESSION_free().
*/
return 0;
}
static SSL_SESSION *tls_sess_cache_get_sess_cb(SSL *ssl,
unsigned char *sess_id, int sess_id_len, int *do_copy) {
SSL_SESSION *sess;
/* Indicate to OpenSSL that the ref count should not be incremented
* by setting the do_copy pointer to zero.
*/
*do_copy = 0;
/* The actual session_id_length field in the OpenSSL SSL_SESSION struct
* is unsigned, not signed. But for some reason, the expected callback
* signature uses 'int', not 'unsigned int'. Hopefully the implicit
* cast below (our callback uses 'unsigned int') won't cause problems.
* Just to be sure, check if OpenSSL is giving us a negative ID length.
*/
if (sess_id_len <= 0) {
tls_log("OpenSSL invoked SSL session cache 'get' callback with session "
"ID length %d, returning null", sess_id_len);
return NULL;
}
if (tls_sess_cache == NULL) {
tls_log("unable to get session from session cache: %s", strerror(ENOSYS));
return NULL;
}
sess = (tls_sess_cache->get)(tls_sess_cache, sess_id, sess_id_len);
if (sess == NULL) {
tls_log("error retrieving session from '%s' cache: %s",
tls_sess_cache->cache_name, strerror(errno));
}
return sess;
}
static void tls_sess_cache_delete_sess_cb(SSL_CTX *ctx, SSL_SESSION *sess) {
unsigned char *sess_id;
unsigned int sess_id_len;
int res;
if (tls_sess_cache == NULL) {
tls_log("unable to remove session from session cache: %s",
strerror(ENOSYS));
return;
}
#if OPENSSL_VERSION_NUMBER > 0x000908000L
sess_id = (unsigned char *) SSL_SESSION_get_id(sess, &sess_id_len);
#else
/* XXX Directly accessing these fields cannot be a Good Thing. */
sess_id = sess->session_id;
sess_id_len = sess->session_id_length;
#endif
res = (tls_sess_cache->delete)(tls_sess_cache, sess_id, sess_id_len);
if (res < 0) {
tls_log("error removing session from '%s' cache: %s",
tls_sess_cache->cache_name, strerror(errno));
}
return;
}
/* NetIO callbacks
*/
static void tls_netio_abort_cb(pr_netio_stream_t *nstrm) {
nstrm->strm_flags |= PR_NETIO_SESS_ABORT;
}
static int tls_netio_close_cb(pr_netio_stream_t *nstrm) {
int res = 0;
if (nstrm->strm_data) {
if (nstrm->strm_type == PR_NETIO_STRM_CTRL &&
nstrm->strm_mode == PR_NETIO_IO_WR) {
tls_end_sess((SSL *) nstrm->strm_data, nstrm->strm_type, 0);
tls_ctrl_rd_nstrm->strm_data = tls_ctrl_wr_nstrm->strm_data =
nstrm->strm_data = NULL;
tls_ctrl_netio = NULL;
tls_flags &= ~TLS_SESS_ON_CTRL;
}
if (nstrm->strm_type == PR_NETIO_STRM_DATA &&
nstrm->strm_mode == PR_NETIO_IO_WR) {
tls_end_sess((SSL *) nstrm->strm_data, nstrm->strm_type, 0);
tls_data_rd_nstrm->strm_data = tls_data_wr_nstrm->strm_data =
nstrm->strm_data = NULL;
tls_data_netio = NULL;
tls_flags &= ~TLS_SESS_ON_DATA;
}
}
res = close(nstrm->strm_fd);
nstrm->strm_fd = -1;
return res;
}
static pr_netio_stream_t *tls_netio_open_cb(pr_netio_stream_t *nstrm, int fd,
int mode) {
nstrm->strm_fd = fd;
nstrm->strm_mode = mode;
/* Cache a pointer to this stream. */
if (nstrm->strm_type == PR_NETIO_STRM_CTRL) {
if (nstrm->strm_mode == PR_NETIO_IO_RD)
tls_ctrl_rd_nstrm = nstrm;
if (nstrm->strm_mode == PR_NETIO_IO_WR)
tls_ctrl_wr_nstrm = nstrm;
} else if (nstrm->strm_type == PR_NETIO_STRM_DATA) {
if (nstrm->strm_mode == PR_NETIO_IO_RD)
tls_data_rd_nstrm = nstrm;
if (nstrm->strm_mode == PR_NETIO_IO_WR)
tls_data_wr_nstrm = nstrm;
/* Note: from the FTP-TLS Draft 9.2:
*
* It is quite reasonable for the server to insist that the data
* connection uses a TLS cached session. This might be a cache of a
* previous data connection or of the control connection. If this is
* the reason for the the refusal to allow the data transfer then the
* '522' reply should indicate this.
*
* and, from 10.4:
*
* If a server needs to have the connection protected then it will
* reply to the STOR/RETR/NLST/... command with a '522' indicating
* that the current state of the data connection protection level is
* not sufficient for that data transfer at that time.
*
* This points out the need for a module to be able to influence
* command response codes in a more flexible manner...
*/
}
return nstrm;
}
static int tls_netio_poll_cb(pr_netio_stream_t *nstrm) {
fd_set rfds, wfds;
struct timeval tval;
FD_ZERO(&rfds);
FD_ZERO(&wfds);
if (nstrm->strm_mode == PR_NETIO_IO_RD) {
FD_SET(nstrm->strm_fd, &rfds);
} else {
FD_SET(nstrm->strm_fd, &wfds);
}
tval.tv_sec = (nstrm->strm_flags & PR_NETIO_SESS_INTR) ?
nstrm->strm_interval : 10;
tval.tv_usec = 0;
return select(nstrm->strm_fd + 1, &rfds, &wfds, NULL, &tval);
}
static int tls_netio_postopen_cb(pr_netio_stream_t *nstrm) {
/* If this is a data stream, and it's for writing, and TLS is required,
* then do a TLS handshake.
*/
if (nstrm->strm_type == PR_NETIO_STRM_DATA &&
nstrm->strm_mode == PR_NETIO_IO_WR) {
/* Enforce the "data" part of TLSRequired, if configured. */
if (tls_required_on_data == 1 ||
(tls_flags & TLS_SESS_NEED_DATA_PROT)) {
X509 *ctrl_cert = NULL, *data_cert = NULL;
tls_log("%s", "starting TLS negotiation on data connection");
if (tls_accept(session.d, TRUE) < 0) {
tls_log("%s", "unable to open data connection: TLS negotiation failed");
session.d->xerrno = EPERM;
return -1;
}
/* Make sure that the certificate used, if any, for this data channel
* handshake is the same as that used for the control channel handshake.
* This may be too strict of a requirement, though.
*/
ctrl_cert = SSL_get_peer_certificate(ctrl_ssl);
data_cert = SSL_get_peer_certificate((SSL *) nstrm->strm_data);
if (ctrl_cert && data_cert) {
if (X509_cmp(ctrl_cert, data_cert)) {
X509_free(ctrl_cert);
X509_free(data_cert);
/* Properly shutdown the SSL session. */
tls_end_sess((SSL *) nstrm->strm_data, nstrm->strm_type, 0);
tls_data_rd_nstrm->strm_data = tls_data_wr_nstrm->strm_data =
nstrm->strm_data = NULL;
tls_log("%s", "unable to open data connection: control/data "
"certificate mismatch");
session.d->xerrno = EPERM;
return -1;
}
}
#if OPENSSL_VERSION_NUMBER < 0x0090702fL
/* Make sure blinding is turned on. (For some reason, this only seems
* to be allowed on SSL objects, not on SSL_CTX objects. Bummer).
*/
tls_blinding_on((SSL *) nstrm->strm_data);
#endif
if (ctrl_cert)
X509_free(ctrl_cert);
if (data_cert)
X509_free(data_cert);
tls_flags |= TLS_SESS_ON_DATA;
}
}
return 0;
}
static int tls_netio_read_cb(pr_netio_stream_t *nstrm, char *buf,
size_t buflen) {
if (nstrm->strm_data) {
SSL *ssl;
BIO *rbio, *wbio;
int bread = 0, bwritten = 0;
ssize_t res = 0;
unsigned long rbio_rbytes, rbio_wbytes, wbio_rbytes, wbio_wbytes;
ssl = nstrm->strm_data;
rbio = SSL_get_rbio(ssl);
rbio_rbytes = BIO_number_read(rbio);
rbio_wbytes = BIO_number_written(rbio);
wbio = SSL_get_wbio(ssl);
wbio_rbytes = BIO_number_read(wbio);
wbio_wbytes = BIO_number_written(wbio);
res = tls_read(ssl, buf, buflen);
bread = (BIO_number_read(rbio) - rbio_rbytes) +
(BIO_number_read(wbio) - wbio_rbytes);
bwritten = (BIO_number_written(rbio) - rbio_wbytes) +
(BIO_number_written(wbio) - wbio_wbytes);
/* Manually update session.total_raw_in with the difference between
* the raw bytes read in versus the non-SSL bytes read in, in order to
* have %I be accurately represented for the raw traffic.
*/
session.total_raw_in += (bread - res);
/* Manually update session.total_raw_out, in order to have %O be
* accurately represented for the raw traffic.
*/
if (bwritten > 0) {
session.total_raw_out += bwritten;
}
return res;
}
return read(nstrm->strm_fd, buf, buflen);
}
static pr_netio_stream_t *tls_netio_reopen_cb(pr_netio_stream_t *nstrm, int fd,
int mode) {
if (nstrm->strm_fd != -1)
close(nstrm->strm_fd);
nstrm->strm_fd = fd;
nstrm->strm_mode = mode;
/* NOTE: a no-op? */
return nstrm;
}
static int tls_netio_shutdown_cb(pr_netio_stream_t *nstrm, int how) {
if (how == 1 ||
how == 2) {
/* Closing this stream for writing; we need to send the 'close_notify'
* alert first, so that the client knows, at the application layer,
* that the SSL/TLS session is shutting down.
*/
if (nstrm->strm_mode == PR_NETIO_IO_WR &&
(nstrm->strm_type == PR_NETIO_STRM_CTRL ||
nstrm->strm_type == PR_NETIO_STRM_DATA)) {
SSL *ssl;
ssl = nstrm->strm_data;
if (ssl) {
BIO *rbio, *wbio;
int bread = 0, bwritten = 0;
unsigned long rbio_rbytes, rbio_wbytes, wbio_rbytes, wbio_wbytes;
rbio = SSL_get_rbio(ssl);
rbio_rbytes = BIO_number_read(rbio);
rbio_wbytes = BIO_number_written(rbio);
wbio = SSL_get_wbio(ssl);
wbio_rbytes = BIO_number_read(wbio);
wbio_wbytes = BIO_number_written(wbio);
if (!(SSL_get_shutdown(ssl) & SSL_SENT_SHUTDOWN)) {
/* We haven't sent a 'close_notify' alert yet; do so now. */
SSL_shutdown(ssl);
}
bread = (BIO_number_read(rbio) - rbio_rbytes) +
(BIO_number_read(wbio) - wbio_rbytes);
bwritten = (BIO_number_written(rbio) - rbio_wbytes) +
(BIO_number_written(wbio) - wbio_wbytes);
/* Manually update session.total_raw_in/out, in order to have %I/%O be
* accurately represented for the raw traffic.
*/
if (bread > 0) {
session.total_raw_in += bread;
}
if (bwritten > 0) {
session.total_raw_out += bwritten;
}
}
}
}
return shutdown(nstrm->strm_fd, how);
}
static int tls_netio_write_cb(pr_netio_stream_t *nstrm, char *buf,
size_t buflen) {
if (nstrm->strm_data) {
SSL *ssl;
BIO *rbio, *wbio;
int bread = 0, bwritten = 0;
ssize_t res = 0;
unsigned long rbio_rbytes, rbio_wbytes, wbio_rbytes, wbio_wbytes;
ssl = nstrm->strm_data;
rbio = SSL_get_rbio(ssl);
rbio_rbytes = BIO_number_read(rbio);
rbio_wbytes = BIO_number_written(rbio);
wbio = SSL_get_wbio(ssl);
wbio_rbytes = BIO_number_read(wbio);
wbio_wbytes = BIO_number_written(wbio);
#if OPENSSL_VERSION_NUMBER > 0x000907000L
if (tls_data_renegotiate_limit &&
session.xfer.total_bytes >= tls_data_renegotiate_limit
#if OPENSSL_VERSION_NUMBER >= 0x009080cfL
/* In OpenSSL-0.9.8l and later, SSL session renegotiations
* (both client- and server-initiated) are automatically disabled.
* Unless the admin explicitly configured support for
* client-initiated renegotations via the AllowClientRenegotiations
* TLSOption, we can't request renegotiations ourselves.
*/
&& (tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS)
#endif
) {
tls_flags |= TLS_SESS_DATA_RENEGOTIATING;
tls_log("requesting TLS renegotiation on data channel "
"(%" PR_LU " KB data limit)",
(pr_off_t) (tls_data_renegotiate_limit / 1024));
SSL_renegotiate(ssl);
/* SSL_do_handshake(ssl); */
pr_timer_add(tls_renegotiate_timeout, -1, &tls_module,
tls_renegotiate_timeout_cb, "SSL/TLS renegotiation");
}
#endif
res = tls_write(ssl, buf, buflen);
bread = (BIO_number_read(rbio) - rbio_rbytes) +
(BIO_number_read(wbio) - wbio_rbytes);
bwritten = (BIO_number_written(rbio) - rbio_wbytes) +
(BIO_number_written(wbio) - wbio_wbytes);
/* Manually update session.total_raw_in, in order to have %I be
* accurately represented for the raw traffic.
*/
if (bread > 0) {
session.total_raw_in += bread;
}
/* Manually update session.total_raw_out with the difference between
* the raw bytes written out versus the non-SSL bytes written out,
* in order to have %) be accurately represented for the raw traffic.
*/
session.total_raw_out += (bwritten - res);
return res;
}
return write(nstrm->strm_fd, buf, buflen);
}
static void tls_netio_install_ctrl(void) {
pr_netio_t *netio;
if (tls_ctrl_netio) {
/* If we already have our ctrl netio, then it's been registered, and
* we don't need to do anything more.
*/
return;
}
tls_ctrl_netio = netio = pr_alloc_netio(permanent_pool);
netio->abort = tls_netio_abort_cb;
netio->close = tls_netio_close_cb;
netio->open = tls_netio_open_cb;
netio->poll = tls_netio_poll_cb;
netio->postopen = tls_netio_postopen_cb;
netio->read = tls_netio_read_cb;
netio->reopen = tls_netio_reopen_cb;
netio->shutdown = tls_netio_shutdown_cb;
netio->write = tls_netio_write_cb;
pr_unregister_netio(PR_NETIO_STRM_CTRL);
if (pr_register_netio(netio, PR_NETIO_STRM_CTRL) < 0)
pr_log_pri(PR_LOG_INFO, MOD_TLS_VERSION ": error registering netio: %s",
strerror(errno));
}
static void tls_netio_install_data(void) {
pr_netio_t *netio = tls_data_netio ? tls_data_netio :
(tls_data_netio = pr_alloc_netio(session.pool ? session.pool :
permanent_pool));
netio->abort = tls_netio_abort_cb;
netio->close = tls_netio_close_cb;
netio->open = tls_netio_open_cb;
netio->poll = tls_netio_poll_cb;
netio->postopen = tls_netio_postopen_cb;
netio->read = tls_netio_read_cb;
netio->reopen = tls_netio_reopen_cb;
netio->shutdown = tls_netio_shutdown_cb;
netio->write = tls_netio_write_cb;
pr_unregister_netio(PR_NETIO_STRM_DATA);
if (pr_register_netio(netio, PR_NETIO_STRM_DATA) < 0)
pr_log_pri(PR_LOG_INFO, MOD_TLS_VERSION ": error registering netio: %s",
strerror(errno));
}
/* Logging functions
*/
static void tls_closelog(void) {
/* Sanity check */
if (tls_logfd != -1) {
close(tls_logfd);
tls_logfd = -1;
tls_logname = NULL;
}
return;
}
int tls_log(const char *fmt, ...) {
va_list msg;
int res;
/* Sanity check */
if (!tls_logname)
return 0;
va_start(msg, fmt);
res = pr_log_vwritefile(tls_logfd, MOD_TLS_VERSION, fmt, msg);
va_end(msg);
return res;
}
static int tls_openlog(void) {
int res = 0;
/* Sanity checks */
tls_logname = get_param_ptr(main_server->conf, "TLSLog", FALSE);
if (tls_logname == NULL)
return 0;
if (strncasecmp(tls_logname, "none", 5) == 0) {
tls_logname = NULL;
return 0;
}
pr_signals_block();
PRIVS_ROOT
res = pr_log_openfile(tls_logname, &tls_logfd, 0600);
PRIVS_RELINQUISH
pr_signals_unblock();
return res;
}
/* Authentication handlers
*/
/* This function does the main authentication work, and is called in the
* normal course of events:
*
* cmd->argv[0]: user name
* cmd->argv[1]: cleartext password
*/
MODRET tls_authenticate(cmd_rec *cmd) {
if (!tls_engine)
return PR_DECLINED(cmd);
/* Possible authentication combinations:
*
* TLS handshake + passwd (default)
* TLS handshake + .tlslogin (passwd ignored)
*/
if ((tls_flags & TLS_SESS_ON_CTRL) &&
(tls_opts & TLS_OPT_ALLOW_DOT_LOGIN)) {
if (tls_dotlogin_allow(cmd->argv[0])) {
tls_log("TLS/X509 .tlslogin check successful for user '%s'",
cmd->argv[0]);
pr_log_auth(PR_LOG_NOTICE, "USER %s: TLS/X509 .tlslogin authentication "
"successful", cmd->argv[0]);
session.auth_mech = "mod_tls.c";
return mod_create_data(cmd, (void *) PR_AUTH_RFC2228_OK);
} else
tls_log("TLS/X509 .tlslogin check failed for user '%s'",
cmd->argv[0]);
}
return PR_DECLINED(cmd);
}
/* This function is called only when UserPassword is involved, used to
* override the configured password for a user.
*
* cmd->argv[0]: hashed password (from proftpd.conf)
* cmd->argv[1]: user name
* cmd->argv[2]: cleartext password
*/
MODRET tls_auth_check(cmd_rec *cmd) {
if (!tls_engine)
return PR_DECLINED(cmd);
/* Possible authentication combinations:
*
* TLS handshake + passwd (default)
* TLS handshake + .tlslogin (passwd ignored)
*/
if ((tls_flags & TLS_SESS_ON_CTRL) &&
(tls_opts & TLS_OPT_ALLOW_DOT_LOGIN)) {
if (tls_dotlogin_allow(cmd->argv[1])) {
tls_log("TLS/X509 .tlslogin check successful for user '%s'",
cmd->argv[0]);
pr_log_auth(PR_LOG_NOTICE, "USER %s: TLS/X509 .tlslogin authentication "
"successful", cmd->argv[1]);
session.auth_mech = "mod_tls.c";
return mod_create_data(cmd, (void *) PR_AUTH_RFC2228_OK);
} else
tls_log("TLS/X509 .tlslogin check failed for user '%s'",
cmd->argv[1]);
}
return PR_DECLINED(cmd);
}
/* Command handlers
*/
MODRET tls_any(cmd_rec *cmd) {
if (!tls_engine)
return PR_DECLINED(cmd);
/* Some commands need not be hindered. */
if (pr_cmd_cmp(cmd, PR_CMD_SYST_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_AUTH_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_FEAT_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_QUIT_ID) == 0) {
return PR_DECLINED(cmd);
}
if (tls_required_on_auth == 1 &&
!(tls_flags & TLS_SESS_ON_CTRL)) {
if (!(tls_opts & TLS_OPT_ALLOW_PER_USER)) {
if (pr_cmd_cmp(cmd, PR_CMD_USER_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_PASS_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_ACCT_ID) == 0) {
tls_log("SSL/TLS required but absent for authentication, "
"denying %s command", cmd->argv[0]);
pr_response_add_err(R_550,
_("SSL/TLS required on the control channel"));
return PR_ERROR(cmd);
}
}
}
if (tls_required_on_ctrl == 1 &&
!(tls_flags & TLS_SESS_ON_CTRL)) {
if (!(tls_opts & TLS_OPT_ALLOW_PER_USER)) {
tls_log("SSL/TLS required but absent on control channel, "
"denying %s command", cmd->argv[0]);
pr_response_add_err(R_550, _("SSL/TLS required on the control channel"));
return PR_ERROR(cmd);
} else {
if (tls_authenticated &&
*tls_authenticated == TRUE) {
tls_log("SSL/TLS required but absent on control channel, "
"denying %s command", cmd->argv[0]);
pr_response_add_err(R_550,
_("SSL/TLS required on the control channel"));
return PR_ERROR(cmd);
}
}
}
/* TLSRequired checks */
if (tls_required_on_data == 1) {
/* TLSRequired encompasses all data transfers for this session, the
* client did not specify an appropriate PROT, and the command is one
* which will trigger a data transfer...
*/
if (!(tls_flags & TLS_SESS_NEED_DATA_PROT)) {
if (pr_cmd_cmp(cmd, PR_CMD_APPE_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_LIST_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_MLSD_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_NLST_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_RETR_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_STOR_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_STOU_ID) == 0) {
tls_log("SSL/TLS required but absent on data channel, "
"denying %s command", cmd->argv[0]);
pr_response_add_err(R_550, _("SSL/TLS required on the data channel"));
return PR_ERROR(cmd);
}
}
} else {
/* TLSRequired is not in effect for all data transfers for this session.
* If this command will trigger a data transfer, check the current
* context to see if there's a directory-level TLSRequired for data
* transfers.
*
* XXX ideally, rather than using the current directory location, we'd
* do the lookup based on the target location.
*/
if (pr_cmd_cmp(cmd, PR_CMD_APPE_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_LIST_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_MLSD_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_NLST_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_RETR_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_STOR_ID) == 0 ||
pr_cmd_cmp(cmd, PR_CMD_STOU_ID) == 0) {
config_rec *c;
c = find_config(CURRENT_CONF, CONF_PARAM, "TLSRequired", FALSE);
if (c) {
int tls_required;
tls_required = *((int *) c->argv[1]);
if (tls_required == TRUE &&
!(tls_flags & TLS_SESS_NEED_DATA_PROT)) {
tls_log("%s command denied by TLSRequired in directory '%s'",
cmd->argv[0], session.dir_config ? session.dir_config->name :
session.anon_config ? session.anon_config->name :
main_server->ServerName);
pr_response_add_err(R_550, _("SSL/TLS required on the data channel"));
return PR_ERROR(cmd);
}
}
}
}
return PR_DECLINED(cmd);
}
MODRET tls_auth(cmd_rec *cmd) {
register unsigned int i = 0;
if (!tls_engine)
return PR_DECLINED(cmd);
/* If we already have protection on the control channel (i.e. AUTH has
* already been sent by the client and handled), then reject this second
* AUTH. Clients that want to renegotiate can either use SSL/TLS's
* renegotiation facilities, or disconnect and start over.
*/
if (tls_flags & TLS_SESS_ON_CTRL) {
tls_log("Unwilling to accept AUTH after AUTH for this session");
pr_response_add_err(R_503, _("Unwilling to accept second AUTH"));
return PR_ERROR(cmd);
}
if (cmd->argc < 2) {
pr_response_add_err(R_504, _("AUTH requires at least one argument"));
return PR_ERROR(cmd);
}
if (tls_flags & TLS_SESS_HAVE_CCC) {
tls_log("Unwilling to accept AUTH after CCC for this session");
pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
return PR_ERROR(cmd);
}
/* Convert the parameter to upper case */
for (i = 0; i < strlen(cmd->argv[1]); i++)
(cmd->argv[1])[i] = toupper((cmd->argv[1])[i]);
if (strncmp(cmd->argv[1], "TLS", 4) == 0 ||
strncmp(cmd->argv[1], "TLS-C", 6) == 0) {
pr_response_send(R_234, _("AUTH %s successful"), cmd->argv[1]);
tls_log("%s", "TLS/TLS-C requested, starting TLS handshake");
if (tls_accept(session.c, FALSE) < 0) {
tls_log("%s", "TLS/TLS-C negotiation failed on control channel");
if (tls_required_on_ctrl == 1) {
pr_response_send(R_550, _("TLS handshake failed"));
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
"TLSRequired");
}
/* If we reach this point, the debug logging may show gibberish
* commands from the client. In reality, this gibberish is probably
* more encrypted data from the client.
*/
pr_response_send(R_550, _("TLS handshake failed"));
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION,
NULL);
}
#if OPENSSL_VERSION_NUMBER < 0x0090702fL
/* Make sure blinding is turned on. (For some reason, this only seems
* to be allowed on SSL objects, not on SSL_CTX objects. Bummer).
*/
tls_blinding_on(ctrl_ssl);
#endif
tls_flags |= TLS_SESS_ON_CTRL;
} else if (strncmp(cmd->argv[1], "SSL", 4) == 0 ||
strncmp(cmd->argv[1], "TLS-P", 6) == 0) {
pr_response_send(R_234, _("AUTH %s successful"), cmd->argv[1]);
tls_log("%s", "SSL/TLS-P requested, starting TLS handshake");
if (tls_accept(session.c, FALSE) < 0) {
tls_log("%s", "SSL/TLS-P negotiation failed on control channel");
if (tls_required_on_ctrl == 1) {
pr_response_send(R_550, _("TLS handshake failed"));
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
"TLSRequired");
}
/* If we reach this point, the debug logging may show gibberish
* commands from the client. In reality, this gibberish is probably
* more encrypted data from the client.
*/
pr_response_send(R_550, _("TLS handshake failed"));
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION,
NULL);
}
#if OPENSSL_VERSION_NUMBER < 0x0090702fL
/* Make sure blinding is turned on. (For some reason, this only seems
* to be allowed on SSL objects, not on SSL_CTX objects. Bummer).
*/
tls_blinding_on(ctrl_ssl);
#endif
tls_flags |= TLS_SESS_ON_CTRL;
tls_flags |= TLS_SESS_NEED_DATA_PROT;
} else {
tls_log("AUTH %s unsupported, declining", cmd->argv[1]);
/* Allow other RFC2228 modules a chance a handling this command. */
return PR_DECLINED(cmd);
}
pr_session_set_protocol("ftps");
session.rfc2228_mech = "TLS";
return PR_HANDLED(cmd);
}
MODRET tls_ccc(cmd_rec *cmd) {
if (!tls_engine ||
!session.rfc2228_mech ||
strncmp(session.rfc2228_mech, "TLS", 4) != 0)
return PR_DECLINED(cmd);
if (!(tls_flags & TLS_SESS_ON_CTRL)) {
pr_response_add_err(R_533,
_("CCC not allowed on insecure control connection"));
return PR_ERROR(cmd);
}
if (tls_required_on_ctrl == 1) {
pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
tls_log("%s: unwilling to accept security parameters: "
"TLSRequired setting does not allow for unprotected control channel",
cmd->argv[0]);
return PR_ERROR(cmd);
}
/* Check for <Limit> restrictions. */
if (!dir_check(cmd->tmp_pool, cmd, G_NONE, session.cwd, NULL)) {
pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
tls_log("%s: unwilling to accept security parameters", cmd->argv[0]);
return PR_ERROR(cmd);
}
tls_log("received CCC, clearing control channel protection");
/* Send the OK response asynchronously; the spec dictates that the
* response be sent prior to performing the SSL session shutdown.
*/
pr_response_send_async(R_200, _("Clearing control channel protection"));
/* Close the SSL session, but only one the control channel.
* The data channel, if protected, should remain so.
*/
tls_end_sess(ctrl_ssl, PR_NETIO_STRM_CTRL, TLS_SHUTDOWN_BIDIRECTIONAL);
ctrl_ssl = tls_ctrl_rd_nstrm->strm_data = tls_ctrl_wr_nstrm->strm_data = NULL;
/* Remove our NetIO for the control channel. */
pr_unregister_netio(PR_NETIO_STRM_CTRL);
tls_flags &= ~TLS_SESS_ON_CTRL;
tls_flags |= TLS_SESS_HAVE_CCC;
return PR_HANDLED(cmd);
}
MODRET tls_pbsz(cmd_rec *cmd) {
if (!tls_engine ||
!session.rfc2228_mech ||
strncmp(session.rfc2228_mech, "TLS", 4) != 0)
return PR_DECLINED(cmd);
CHECK_CMD_ARGS(cmd, 2);
if (!(tls_flags & TLS_SESS_ON_CTRL)) {
pr_response_add_err(R_503,
_("PBSZ not allowed on insecure control connection"));
return PR_ERROR(cmd);
}
/* We expect "PBSZ 0" */
if (strncmp(cmd->argv[1], "0", 2) == 0) {
pr_response_add(R_200, _("PBSZ 0 successful"));
} else {
pr_response_add(R_200, _("PBSZ=0 successful"));
}
tls_flags |= TLS_SESS_PBSZ_OK;
return PR_HANDLED(cmd);
}
MODRET tls_post_pass(cmd_rec *cmd) {
config_rec *protocols_config;
if (!tls_engine)
return PR_DECLINED(cmd);
/* At this point, we can look up the Protocols config if the client has been
* authenticated, which may have been tweaked via mod_ifsession's
* user/group/class-specific sections.
*/
protocols_config = find_config(main_server->conf, CONF_PARAM, "Protocols",
FALSE);
if (!(tls_opts & TLS_OPT_ALLOW_PER_USER) &&
protocols_config == NULL) {
return PR_DECLINED(cmd);
}
tls_authenticated = get_param_ptr(cmd->server->conf, "authenticated", FALSE);
if (tls_authenticated &&
*tls_authenticated == TRUE) {
config_rec *c;
c = find_config(TOPLEVEL_CONF, CONF_PARAM, "TLSRequired", FALSE);
if (c) {
/* Lookup the TLSRequired directive again in this context (which could be
* <Anonymous>, for example, or modified by mod_ifsession).
*/
tls_required_on_ctrl = *((int *) c->argv[0]);
tls_required_on_data = *((int *) c->argv[1]);
tls_required_on_auth = *((int *) c->argv[2]);
/* We cannot return PR_ERROR for the PASS command at this point, since
* this is a POST_CMD handler. Instead, we will simply check the
* TLSRequired policy, and if the current session does not make the
* cut, well, then the session gets cut.
*/
if ((tls_required_on_ctrl == 1 ||
tls_required_on_auth == 1) &&
(!tls_flags & TLS_SESS_ON_CTRL)) {
tls_log("SSL/TLS required but absent on control channel, "
"disconnecting");
pr_response_send(R_530, "%s", _("Login incorrect."));
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
"TLSRequired");
}
}
if (protocols_config) {
register unsigned int i;
int allow_ftps = FALSE;
array_header *protocols;
char **elts;
protocols = protocols_config->argv[0];
elts = protocols->elts;
/* We only want to check for 'ftps' in the configured Protocols list
* if the RFC2228 mechanism is "TLS".
*/
if (session.rfc2228_mech != NULL &&
strncmp(session.rfc2228_mech, "TLS", 4) == 0) {
for (i = 0; i < protocols->nelts; i++) {
char *proto;
proto = elts[i];
if (proto != NULL) {
if (strncasecmp(proto, "ftps", 5) == 0) {
allow_ftps = TRUE;
break;
}
}
}
}
if (!allow_ftps) {
tls_log("ftps protocol denied by Protocols config");
pr_response_send(R_530, "%s", _("Login incorrect."));
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_CONFIG_ACL,
"Denied by Protocols setting");
}
}
}
return PR_DECLINED(cmd);
}
MODRET tls_prot(cmd_rec *cmd) {
if (!tls_engine ||
!session.rfc2228_mech ||
strncmp(session.rfc2228_mech, "TLS", 4) != 0)
return PR_DECLINED(cmd);
CHECK_CMD_ARGS(cmd, 2);
if (!(tls_flags & TLS_SESS_ON_CTRL) &&
!(tls_flags & TLS_SESS_HAVE_CCC)) {
pr_response_add_err(R_503,
_("PROT not allowed on insecure control connection"));
return PR_ERROR(cmd);
}
if (!(tls_flags & TLS_SESS_PBSZ_OK)) {
pr_response_add_err(R_503,
_("You must issue the PBSZ command prior to PROT"));
return PR_ERROR(cmd);
}
/* Check for <Limit> restrictions. */
if (!dir_check(cmd->tmp_pool, cmd, G_NONE, session.cwd, NULL)) {
pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
tls_log("%s: denied by <Limit> configuration", cmd->argv[0]);
return PR_ERROR(cmd);
}
/* Only PROT C or PROT P is valid with respect to SSL/TLS. */
if (strncmp(cmd->argv[1], "C", 2) == 0) {
char *mesg = "Protection set to Clear";
if (tls_required_on_data != 1) {
/* Only accept this if SSL/TLS is not required, by policy, on data
* connections.
*/
tls_flags &= ~TLS_SESS_NEED_DATA_PROT;
pr_response_add(R_200, "%s", mesg);
tls_log("%s", mesg);
} else {
pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
tls_log("%s: TLSRequired requires protection for data transfers",
cmd->argv[0]);
tls_log("%s: unwilling to accept security parameter (%s)", cmd->argv[0],
cmd->argv[1]);
return PR_ERROR(cmd);
}
} else if (strncmp(cmd->argv[1], "P", 2) == 0) {
char *mesg = "Protection set to Private";
if (tls_required_on_data != -1) {
/* Only accept this if SSL/TLS is allowed, by policy, on data
* connections.
*/
tls_flags |= TLS_SESS_NEED_DATA_PROT;
pr_response_add(R_200, "%s", mesg);
tls_log("%s", mesg);
} else {
pr_response_add_err(R_534, _("Unwilling to accept security parameters"));
tls_log("%s: TLSRequired does not allow protection for data transfers",
cmd->argv[0]);
tls_log("%s: unwilling to accept security parameter (%s)", cmd->argv[0],
cmd->argv[1]);
return PR_ERROR(cmd);
}
} else if (strncmp(cmd->argv[1], "S", 2) == 0 ||
strncmp(cmd->argv[1], "E", 2) == 0) {
pr_response_add_err(R_536, _("PROT %s unsupported"), cmd->argv[1]);
/* By the time the logic reaches this point, there must have been
* an SSL/TLS session negotiated; other AUTH mechanisms will handle
* things differently, and when they do, the logic of this handler
* would not reach this point. This means that it would not be impolite
* to return ERROR here, rather than DECLINED: it shows that mod_tls
* is handling the security mechanism, and that this module does not
* allow for the unsupported PROT levels.
*/
return PR_ERROR(cmd);
} else {
pr_response_add_err(R_504, _("PROT %s unsupported"), cmd->argv[1]);
return PR_ERROR(cmd);
}
return PR_HANDLED(cmd);
}
/* Configuration handlers
*/
/* usage: TLSCACertificateFile file */
MODRET set_tlscacertfile(cmd_rec *cmd) {
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
if (!file_exists(cmd->argv[1]))
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", cmd->argv[1],
"' does not exist", NULL));
if (*cmd->argv[1] != '/')
CONF_ERROR(cmd, "parameter must be an absolute path");
add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
return PR_HANDLED(cmd);
}
/* usage: TLSCACertificatePath path */
MODRET set_tlscacertpath(cmd_rec *cmd) {
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
if (!dir_exists(cmd->argv[1]))
CONF_ERROR(cmd, "parameter must be a directory path");
if (*cmd->argv[1] != '/')
CONF_ERROR(cmd, "parameter must be an absolute path");
add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
return PR_HANDLED(cmd);
}
/* usage: TLSCARevocationFile file */
MODRET set_tlscacrlfile(cmd_rec *cmd) {
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
if (!file_exists(cmd->argv[1]))
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", cmd->argv[1],
"' does not exist", NULL));
if (*cmd->argv[1] != '/')
CONF_ERROR(cmd, "parameter must be an absolute path");
add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
return PR_HANDLED(cmd);
}
/* usage: TLSCARevocationPath path */
MODRET set_tlscacrlpath(cmd_rec *cmd) {
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
if (!dir_exists(cmd->argv[1]))
CONF_ERROR(cmd, "parameter must be a directory path");
if (*cmd->argv[1] != '/')
CONF_ERROR(cmd, "parameter must be an absolute path");
add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
return PR_HANDLED(cmd);
}
/* usage: TLSCertificateChainFile file */
MODRET set_tlscertchain(cmd_rec *cmd) {
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
if (!file_exists(cmd->argv[1]))
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", cmd->argv[1],
"' does not exist", NULL));
if (*cmd->argv[1] != '/')
CONF_ERROR(cmd, "parameter must be an absolute path");
add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
return PR_HANDLED(cmd);
}
/* usage: TLSCipherSuite string */
MODRET set_tlsciphersuite(cmd_rec *cmd) {
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
return PR_HANDLED(cmd);
}
/* usage: TLSControlsACLs actions|all allow|deny user|group list */
MODRET set_tlsctrlsacls(cmd_rec *cmd) {
#ifdef PR_USE_CTRLS
char *bad_action = NULL, **actions = NULL;
CHECK_ARGS(cmd, 4);
CHECK_CONF(cmd, CONF_ROOT);
/* We can cheat here, and use the ctrls_parse_acl() routine to
* separate the given string...
*/
actions = ctrls_parse_acl(cmd->tmp_pool, cmd->argv[1]);
/* Check the second parameter to make sure it is "allow" or "deny" */
if (strncmp(cmd->argv[2], "allow", 6) != 0 &&
strncmp(cmd->argv[2], "deny", 5) != 0)
CONF_ERROR(cmd, "second parameter must be 'allow' or 'deny'");
/* Check the third parameter to make sure it is "user" or "group" */
if (strncmp(cmd->argv[3], "user", 5) != 0 &&
strncmp(cmd->argv[3], "group", 6) != 0)
CONF_ERROR(cmd, "third parameter must be 'user' or 'group'");
bad_action = pr_ctrls_set_module_acls(tls_acttab, tls_act_pool, actions,
cmd->argv[2], cmd->argv[3], cmd->argv[4]);
if (bad_action != NULL)
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": unknown action: '",
bad_action, "'", NULL));
return PR_HANDLED(cmd);
#else
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0],
" directive requires Controls support (--enable-ctrls)", NULL));
#endif /* PR_USE_CTRLS */
}
/* usage: TLSCryptoDevice driver|"ALL" */
MODRET set_tlscryptodevice(cmd_rec *cmd) {
#if OPENSSL_VERSION_NUMBER > 0x000907000L
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
(void) add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
return PR_HANDLED(cmd);
#else /* OpenSSL is too old for ENGINE support */
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "The ", cmd->argv[0],
"directive cannot be used on the system, as the OpenSSL version is too old",
NULL));
#endif
}
/* usage: TLSDHParamFile file */
MODRET set_tlsdhparamfile(cmd_rec *cmd) {
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
if (!file_exists(cmd->argv[1]))
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", cmd->argv[1],
"' does not exist", NULL));
if (*cmd->argv[1] != '/')
CONF_ERROR(cmd, "parameter must be an absolute path");
add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
return PR_HANDLED(cmd);
}
/* usage: TLSDSACertificateFile file */
MODRET set_tlsdsacertfile(cmd_rec *cmd) {
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
if (!file_exists(cmd->argv[1])) {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", cmd->argv[1],
"' does not exist", NULL));
}
if (*cmd->argv[1] != '/')
CONF_ERROR(cmd, "parameter must be an absolute path");
add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
return PR_HANDLED(cmd);
}
/* usage: TLSDSACertificateKeyFile file */
MODRET set_tlsdsakeyfile(cmd_rec *cmd) {
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
if (!file_exists(cmd->argv[1])) {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", cmd->argv[1],
"' does not exist", NULL));
}
if (*cmd->argv[1] != '/')
CONF_ERROR(cmd, "parameter must be an absolute path");
add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
return PR_HANDLED(cmd);
}
/* usage: TLSEngine on|off */
MODRET set_tlsengine(cmd_rec *cmd) {
int bool = -1;
config_rec *c = NULL;
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
bool = get_boolean(cmd, 1);
if (bool == -1)
CONF_ERROR(cmd, "expected Boolean parameter");
c = add_config_param(cmd->argv[0], 1, NULL);
c->argv[0] = pcalloc(c->pool, sizeof(unsigned char));
*((unsigned char *) c->argv[0]) = bool;
return PR_HANDLED(cmd);
}
/* usage: TLSLog file */
MODRET set_tlslog(cmd_rec *cmd) {
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
return PR_HANDLED(cmd);
}
/* usage: TLSOptions opt1 opt2 ... */
MODRET set_tlsoptions(cmd_rec *cmd) {
config_rec *c = NULL;
register unsigned int i = 0;
unsigned long opts = 0UL;
if (cmd->argc-1 == 0)
CONF_ERROR(cmd, "wrong number of parameters");
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
c = add_config_param(cmd->argv[0], 1, NULL);
for (i = 1; i < cmd->argc; i++) {
if (strcmp(cmd->argv[i], "AllowDotLogin") == 0) {
opts |= TLS_OPT_ALLOW_DOT_LOGIN;
} else if (strcmp(cmd->argv[i], "AllowPerUser") == 0) {
opts |= TLS_OPT_ALLOW_PER_USER;
} else if (strcmp(cmd->argv[i], "AllowClientRenegotiation") == 0 ||
strcmp(cmd->argv[i], "AllowClientRenegotiations") == 0) {
opts |= TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS;
} else if (strcmp(cmd->argv[i], "EnableDiags") == 0) {
opts |= TLS_OPT_ENABLE_DIAGS;
} else if (strcmp(cmd->argv[i], "ExportCertData") == 0) {
opts |= TLS_OPT_EXPORT_CERT_DATA;
} else if (strcmp(cmd->argv[i], "NoCertRequest") == 0) {
opts |= TLS_OPT_NO_CERT_REQUEST;
} else if (strcmp(cmd->argv[i], "NoEmptyFragments") == 0) {
/* Unlike the other TLSOptions, this option is handled slightly
* differently, due to the fact that option affects the creation
* of the SSL_CTX.
*
*/
tls_ssl_opts |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
} else if (strcmp(cmd->argv[i], "NoSessionReuseRequired") == 0) {
opts |= TLS_OPT_NO_SESSION_REUSE_REQUIRED;
} else if (strcmp(cmd->argv[i], "StdEnvVars") == 0) {
opts |= TLS_OPT_STD_ENV_VARS;
} else if (strcmp(cmd->argv[i], "dNSNameRequired") == 0) {
opts |= TLS_OPT_VERIFY_CERT_FQDN;
} else if (strcmp(cmd->argv[i], "iPAddressRequired") == 0) {
opts |= TLS_OPT_VERIFY_CERT_IP_ADDR;
} else if (strcmp(cmd->argv[i], "UseImplicitSSL") == 0) {
opts |= TLS_OPT_USE_IMPLICIT_SSL;
} else if (strcmp(cmd->argv[i], "CommonNameRequired") == 0) {
opts |= TLS_OPT_VERIFY_CERT_CN;
} else {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, ": unknown TLSOption '",
cmd->argv[i], "'", NULL));
}
}
c->argv[0] = pcalloc(c->pool, sizeof(unsigned long));
*((unsigned long *) c->argv[0]) = opts;
return PR_HANDLED(cmd);
}
/* usage: TLSPassPhraseProvider path */
MODRET set_tlspassphraseprovider(cmd_rec *cmd) {
struct stat st;
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT);
if (*cmd->argv[1] != '/')
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "must be a full path: '",
cmd->argv[1], "'", NULL));
if (stat(cmd->argv[1], &st) < 0)
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error checking '",
cmd->argv[1], "': ", strerror(errno), NULL));
if (!S_ISREG(st.st_mode))
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unable to use '",
cmd->argv[1], ": Not a regular file", NULL));
tls_passphrase_provider = pstrdup(permanent_pool, cmd->argv[1]);
return PR_HANDLED(cmd);
}
/* usage: TLSPKCS12File file */
MODRET set_tlspkcs12file(cmd_rec *cmd) {
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
if (!file_exists(cmd->argv[1])) {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", cmd->argv[1],
"' does not exist", NULL));
}
if (*cmd->argv[1] != '/')
CONF_ERROR(cmd, "parameter must be an absolute path");
add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
return PR_HANDLED(cmd);
}
/* usage: TLSProtocol version1 ... versionN */
MODRET set_tlsprotocol(cmd_rec *cmd) {
register unsigned int i;
if (cmd->argc-1 == 0)
CONF_ERROR(cmd, "wrong number of parameters");
CHECK_CONF(cmd, CONF_ROOT);
tls_protocol = 0;
for (i = 1; i < cmd->argc; i++) {
if (strncasecmp(cmd->argv[i], "SSLv23", 7) == 0) {
tls_protocol |= TLS_PROTO_SSL_V3;
tls_protocol |= TLS_PROTO_TLS_V1;
} else if (strncasecmp(cmd->argv[i], "SSLv3", 6) == 0) {
tls_protocol |= TLS_PROTO_SSL_V3;
} else if (strncasecmp(cmd->argv[i], "TLSv1", 6) == 0) {
tls_protocol |= TLS_PROTO_TLS_V1;
} else {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "unknown protocol: '",
cmd->argv[i], "'", NULL));
}
}
return PR_HANDLED(cmd);
}
/* usage: TLSRandomSeed file */
MODRET set_tlsrandseed(cmd_rec *cmd) {
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
return PR_HANDLED(cmd);
}
/* usage: TLSRenegotiate [ctrl nsecs] [data nbytes] */
MODRET set_tlsrenegotiate(cmd_rec *cmd) {
#if OPENSSL_VERSION_NUMBER > 0x000907000L
register unsigned int i = 0;
config_rec *c = NULL;
if (cmd->argc-1 < 1 || cmd->argc-1 > 8)
CONF_ERROR(cmd, "wrong number of parameters");
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
if (strncasecmp(cmd->argv[1], "none", 5) == 0) {
add_config_param(cmd->argv[0], 0);
return PR_HANDLED(cmd);
}
c = add_config_param(cmd->argv[0], 4, NULL, NULL, NULL, NULL);
c->argv[0] = pcalloc(c->pool, sizeof(int));
*((int *) c->argv[0]) = 0;
c->argv[1] = pcalloc(c->pool, sizeof(off_t));
*((off_t *) c->argv[1]) = 0;
c->argv[2] = pcalloc(c->pool, sizeof(int));
*((int *) c->argv[2]) = 0;
c->argv[3] = pcalloc(c->pool, sizeof(unsigned char));
*((unsigned char *) c->argv[3]) = TRUE;
for (i = 1; i < cmd->argc;) {
if (strcmp(cmd->argv[i], "ctrl") == 0) {
int secs = atoi(cmd->argv[i+1]);
if (secs > 0) {
*((int *) c->argv[0]) = secs;
} else {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[i],
" must be greater than zero: '", cmd->argv[i+1], "'", NULL));
}
i += 2;
} else if (strcmp(cmd->argv[i], "data") == 0) {
char *tmp = NULL;
unsigned long kbytes = strtoul(cmd->argv[i+1], &tmp, 10);
if (!(tmp && *tmp)) {
*((off_t *) c->argv[1]) = (off_t) kbytes * 1024;
} else {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[i],
" must be greater than zero: '", cmd->argv[i+1], "'", NULL));
}
i += 2;
} else if (strcmp(cmd->argv[i], "required") == 0) {
int bool = get_boolean(cmd, i+1);
if (bool != -1) {
*((unsigned char *) c->argv[3]) = bool;
} else {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[i],
" must be a Boolean value: '", cmd->argv[i+1], "'", NULL));
}
i += 2;
} else if (strcmp(cmd->argv[i], "timeout") == 0) {
int secs = atoi(cmd->argv[i+1]);
if (secs > 0) {
*((int *) c->argv[2]) = secs;
} else {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[i],
" must be greater than zero: '", cmd->argv[i+1], "'", NULL));
}
i += 2;
} else {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
": unknown TLSRenegotiate argument '", cmd->argv[i], "'", NULL));
}
}
return PR_HANDLED(cmd);
#else
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, " requires OpenSSL-0.9.7 or greater",
NULL));
#endif
}
/* usage: TLSRequired on|off|both|control|ctrl|[!]data|auth|auth+data */
MODRET set_tlsrequired(cmd_rec *cmd) {
int bool = -1;
int on_auth = 0, on_ctrl = 0, on_data = 0;
config_rec *c = NULL;
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON|CONF_DIR|
CONF_DYNDIR);
bool = get_boolean(cmd, 1);
if (bool == -1) {
if (strcmp(cmd->argv[1], "control") == 0 ||
strcmp(cmd->argv[1], "ctrl") == 0) {
on_auth = 1;
on_ctrl = 1;
} else if (strcmp(cmd->argv[1], "data") == 0) {
on_data = 1;
} else if (strcmp(cmd->argv[1], "!data") == 0) {
on_data = -1;
} else if (strcmp(cmd->argv[1], "both") == 0 ||
strcmp(cmd->argv[1], "ctrl+data") == 0) {
on_auth = 1;
on_ctrl = 1;
on_data = 1;
} else if (strcmp(cmd->argv[1], "ctrl+!data") == 0) {
on_auth = 1;
on_ctrl = 1;
on_data = -1;
} else if (strcmp(cmd->argv[1], "auth") == 0) {
on_auth = 1;
} else if (strcmp(cmd->argv[1], "auth+data") == 0) {
on_auth = 1;
on_data = 1;
} else if (strcmp(cmd->argv[1], "auth+!data") == 0) {
on_auth = 1;
on_data = -1;
} else
CONF_ERROR(cmd, "bad parameter");
} else {
if (bool == TRUE) {
on_auth = 1;
on_ctrl = 1;
on_data = 1;
}
}
c = add_config_param(cmd->argv[0], 3, NULL, NULL, NULL);
c->argv[0] = pcalloc(c->pool, sizeof(int));
*((int *) c->argv[0]) = on_ctrl;
c->argv[1] = pcalloc(c->pool, sizeof(int));
*((int *) c->argv[1]) = on_data;
c->argv[2] = pcalloc(c->pool, sizeof(int));
*((int *) c->argv[2]) = on_auth;
c->flags |= CF_MERGEDOWN;
return PR_HANDLED(cmd);
}
/* usage: TLSRSACertificateFile file */
MODRET set_tlsrsacertfile(cmd_rec *cmd) {
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
if (!file_exists(cmd->argv[1])) {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", cmd->argv[1],
"' does not exist", NULL));
}
if (*cmd->argv[1] != '/')
CONF_ERROR(cmd, "parameter must be an absolute path");
add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
return PR_HANDLED(cmd);
}
/* usage: TLSRSACertificateKeyFile file */
MODRET set_tlsrsakeyfile(cmd_rec *cmd) {
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
if (!file_exists(cmd->argv[1])) {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", cmd->argv[1],
"' does not exist", NULL));
}
if (*cmd->argv[1] != '/')
CONF_ERROR(cmd, "parameter must be an absolute path");
add_config_param_str(cmd->argv[0], 1, cmd->argv[1]);
return PR_HANDLED(cmd);
}
/* usage: TLSSessionCache type:/info [timeout] */
MODRET set_tlssessioncache(cmd_rec *cmd) {
char *provider, *info, *ptr;
config_rec *c;
long timeout = -1;
if (cmd->argc < 2 ||
cmd->argc > 3) {
CONF_ERROR(cmd, "wrong number of parameters");
}
CHECK_CONF(cmd, CONF_ROOT);
/* Separate the type/info parameter into pieces. */
ptr = strchr(cmd->argv[1], ':');
if (ptr == NULL) {
CONF_ERROR(cmd, "badly formatted parameter");
}
*ptr = '\0';
provider = cmd->argv[1];
info = ptr + 1;
/* Verify that the requested cache type has been registered. */
if (strncmp(provider, "internal", 9) != 0) {
if (tls_sess_cache_get_cache(provider) == NULL) {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "session cache type '",
provider, "' not available", NULL));
}
}
if (cmd->argc == 3) {
ptr = NULL;
timeout = strtol(cmd->argv[2], &ptr, 10);
if (ptr && *ptr) {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "'", cmd->argv[2],
"' is not a valid timeout value", NULL));
}
if (timeout < 1) {
CONF_ERROR(cmd, "timeout be greater than 1");
}
} else {
/* Default timeout is 30 min (1800 secs). */
timeout = 1800;
}
c = add_config_param(cmd->argv[0], 3, NULL, NULL, NULL);
c->argv[0] = pstrdup(c->pool, provider);
c->argv[1] = pstrdup(c->pool, info);
c->argv[2] = palloc(c->pool, sizeof(long));
*((long *) c->argv[2]) = timeout;
return PR_HANDLED(cmd);
}
/* usage: TLSTimeoutHandshake <secs> */
MODRET set_tlstimeouthandshake(cmd_rec *cmd) {
int timeout = -1;
config_rec *c = NULL;
char *tmp = NULL;
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
timeout = (int) strtol(cmd->argv[1], &tmp, 10);
if ((tmp && *tmp) || timeout < 0 || timeout > 65535)
CONF_ERROR(cmd, "timeout value must be between 0 and 65535");
c = add_config_param(cmd->argv[0], 1, NULL);
c->argv[0] = pcalloc(c->pool, sizeof(unsigned int));
*((unsigned int *) c->argv[0]) = timeout;
return PR_HANDLED(cmd);
}
/* usage: TLSVerifyClient on|off */
MODRET set_tlsverifyclient(cmd_rec *cmd) {
int bool = -1;
config_rec *c = NULL;
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
bool = get_boolean(cmd, 1);
if (bool == -1)
CONF_ERROR(cmd, "expected Boolean parameter");
c = add_config_param(cmd->argv[0], 1, NULL);
c->argv[0] = pcalloc(c->pool, sizeof(unsigned char));
*((unsigned char *) c->argv[0]) = bool;
return PR_HANDLED(cmd);
}
/* usage: TLSVerifyDepth depth */
MODRET set_tlsverifydepth(cmd_rec *cmd) {
int depth = -1;
config_rec *c = NULL;
CHECK_ARGS(cmd, 1);
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
depth = atoi(cmd->argv[1]);
if (depth < 0)
CONF_ERROR(cmd, "depth must be zero or greater");
c = add_config_param(cmd->argv[0], 1, NULL);
c->argv[0] = pcalloc(c->pool, sizeof(int));
*((int *) c->argv[0]) = depth;
return PR_HANDLED(cmd);
}
/* usage: TLSVerifyOrder mech1 ... */
MODRET set_tlsverifyorder(cmd_rec *cmd) {
register unsigned int i = 0;
config_rec *c = NULL;
/* We only support two client cert verification mechanisms at the moment:
* CRLs and OCSP.
*/
if (cmd->argc-1 < 1 ||
cmd->argc-1 > 2) {
CONF_ERROR(cmd, "wrong number of parameters");
}
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL);
for (i = 1; i < cmd->argc; i++) {
char *mech = cmd->argv[i];
if (strncasecmp(mech, "crl", 4) != 0
#if OPENSSL_VERSION_NUMBER > 0x000907000L
&& strncasecmp(mech, "ocsp", 5) != 0) {
#else
) {
#endif
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool,
"unsupported verification mechanism '", mech, "' requested", NULL));
}
}
c = add_config_param(cmd->argv[0], cmd->argc-1, NULL, NULL);
for (i = 1; i < cmd->argc; i++) {
char *mech = cmd->argv[i];
if (strncasecmp(mech, "crl", 4) == 0) {
c->argv[i-1] = pstrdup(c->pool, "crl");
#if OPENSSL_VERSION_NUMBER > 0x000907000L
} else if (strncasecmp(mech, "ocsp", 5) == 0) {
c->argv[i-1] = pstrdup(c->pool, "ocsp");
#endif
}
}
return PR_HANDLED(cmd);
}
/* Event handlers
*/
#if defined(PR_SHARED_MODULE)
static void tls_mod_unload_ev(const void *event_data, void *user_data) {
if (strcmp("mod_tls.c", (const char *) event_data) == 0) {
/* Unregister ourselves from all events. */
pr_event_unregister(&tls_module, NULL, NULL);
# ifdef PR_USE_CTRLS
/* Unregister any control actions. */
pr_ctrls_unregister(&tls_module, "tls");
destroy_pool(tls_act_pool);
tls_act_pool = NULL;
# endif /* PR_USE_CTRLS */
/* Cleanup the OpenSSL stuff. */
tls_cleanup(0);
/* Unregister our NetIO handler for the control channel. */
pr_unregister_netio(PR_NETIO_STRM_CTRL);
if (tls_ctrl_netio) {
destroy_pool(tls_ctrl_netio->pool);
tls_ctrl_netio = NULL;
}
if (tls_data_netio) {
destroy_pool(tls_data_netio->pool);
tls_data_netio = NULL;
}
close(tls_logfd);
tls_logfd = -1;
}
}
#endif /* PR_SHARED_MODULE */
/* Daemon PID */
extern pid_t mpid;
static void tls_shutdown_ev(const void *event_data, void *user_data) {
if (mpid == getpid()) {
tls_scrub_pkeys();
}
/* Write out a new RandomSeed file, for use later. */
if (tls_rand_file) {
int res;
res = RAND_write_file(tls_rand_file);
if (res < 0) {
pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
": error writing PRNG seed data to '%s': %s", tls_rand_file,
tls_get_errors());
} else {
pr_log_debug(DEBUG2, MOD_TLS_VERSION
": wrote %d bytes of PRNG seed data to '%s'", res, tls_rand_file);
}
}
RAND_cleanup();
}
static void tls_restart_ev(const void *event_data, void *user_data) {
#ifdef PR_USE_CTRLS
register unsigned int i;
#endif /* PR_USE_CTRLS */
tls_scrub_pkeys();
#ifdef PR_USE_CTRLS
if (tls_act_pool) {
destroy_pool(tls_act_pool);
tls_act_pool = NULL;
}
tls_act_pool = make_sub_pool(permanent_pool);
pr_pool_tag(tls_act_pool, "TLS Controls Pool");
/* Re-create the controls ACLs. */
for (i = 0; tls_acttab[i].act_action; i++) {
tls_acttab[i].act_acl = palloc(tls_act_pool, sizeof(ctrls_acl_t));
pr_ctrls_init_acl(tls_acttab[i].act_acl);
}
#endif /* PR_USE_CTRLS */
tls_closelog();
}
static void tls_exit_ev(const void *event_data, void *user_data) {
/* If diags are enabled, log some OpenSSL stats. */
if (ssl_ctx != NULL &&
(tls_opts & TLS_OPT_ENABLE_DIAGS)) {
long res;
res = SSL_CTX_sess_accept(ssl_ctx);
tls_log("[stat]: SSL sessions attempted: %ld", res);
res = SSL_CTX_sess_accept_good(ssl_ctx);
tls_log("[stat]: SSL sessions established: %ld", res);
res = SSL_CTX_sess_accept_renegotiate(ssl_ctx);
tls_log("[stat]: SSL sessions renegotiated: %ld", res);
res = SSL_CTX_sess_hits(ssl_ctx);
tls_log("[stat]: SSL sessions resumed: %ld", res);
res = SSL_CTX_sess_number(ssl_ctx);
tls_log("[stat]: SSL sessions in cache: %ld", res);
res = SSL_CTX_sess_cb_hits(ssl_ctx);
tls_log("[stat]: SSL session cache hits: %ld", res);
res = SSL_CTX_sess_misses(ssl_ctx);
tls_log("[stat]: SSL session cache misses: %ld", res);
res = SSL_CTX_sess_timeouts(ssl_ctx);
tls_log("[stat]: SSL session cache timeouts: %ld", res);
res = SSL_CTX_sess_cache_full(ssl_ctx);
tls_log("[stat]: SSL session cache size exceeded: %ld", res);
}
/* OpenSSL cleanup */
tls_cleanup(0);
/* Done with the NetIO objects. Note that we only really need to
* destroy the data channel NetIO object; the control channel NetIO
* object is allocated out of the permanent pool, in the daemon process,
* and thus we have a read-only copy.
*/
if (tls_ctrl_netio) {
pr_unregister_netio(PR_NETIO_STRM_CTRL);
destroy_pool(tls_ctrl_netio->pool);
tls_ctrl_netio = NULL;
}
if (tls_data_netio) {
pr_unregister_netio(PR_NETIO_STRM_DATA);
destroy_pool(tls_data_netio->pool);
tls_data_netio = NULL;
}
if (mpid != getpid())
tls_scrub_pkeys();
tls_closelog();
return;
}
static void tls_timeout_ev(const void *event_data, void *user_data) {
if (session.c &&
ctrl_ssl != NULL &&
(tls_flags & TLS_SESS_ON_CTRL)) {
/* Try to properly close the SSL session down on the control channel,
* if there is one.
*/
tls_end_sess(ctrl_ssl, PR_NETIO_STRM_CTRL, 0);
tls_ctrl_rd_nstrm->strm_data = tls_ctrl_wr_nstrm->strm_data =
ctrl_ssl = NULL;
}
}
static void tls_get_passphrases(void) {
server_rec *s = NULL;
char buf[256];
for (s = (server_rec *) server_list->xas_list; s; s = s->next) {
config_rec *rsa = NULL, *dsa = NULL, *pkcs12 = NULL;
tls_pkey_t *k = NULL;
/* Find any TLS*CertificateKeyFile directives. If they aren't present,
* look for TLS*CertificateFile directives (when appropriate).
*/
rsa = find_config(s->conf, CONF_PARAM, "TLSRSACertificateKeyFile", FALSE);
if (rsa == NULL)
rsa = find_config(s->conf, CONF_PARAM, "TLSRSACertificateFile", FALSE);
dsa = find_config(s->conf, CONF_PARAM, "TLSDSACertificateKeyFile", FALSE);
if (dsa == NULL)
dsa = find_config(s->conf, CONF_PARAM, "TLSDSACertificateFile", FALSE);
pkcs12 = find_config(s->conf, CONF_PARAM, "TLSPKCS12File", FALSE);
if (rsa == NULL &&
dsa == NULL &&
pkcs12 == NULL) {
continue;
}
k = pcalloc(s->pool, sizeof(tls_pkey_t));
k->pkeysz = PEM_BUFSIZE;
k->server = s;
if (rsa) {
snprintf(buf, sizeof(buf)-1, "RSA key for the %s#%d (%s) server: ",
pr_netaddr_get_ipstr(s->addr), s->ServerPort, s->ServerName);
buf[sizeof(buf)-1] = '\0';
k->rsa_pkey = tls_get_page(PEM_BUFSIZE, &k->rsa_pkey_ptr);
if (k->rsa_pkey == NULL) {
pr_log_pri(PR_LOG_ERR, "Out of memory!");
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_NOMEM, NULL);
}
if (tls_get_passphrase(s, rsa->argv[0], buf, k->rsa_pkey,
k->pkeysz, TLS_PASSPHRASE_FL_RSA_KEY) < 0) {
pr_log_debug(DEBUG0, MOD_TLS_VERSION
": error reading RSA passphrase: %s", tls_get_errors());
pr_log_pri(PR_LOG_ERR, MOD_TLS_VERSION ": unable to use "
"RSA certificate key in '%s', exiting", (char *) rsa->argv[0]);
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION,
NULL);
}
}
if (dsa) {
snprintf(buf, sizeof(buf)-1, "DSA key for the %s#%d (%s) server: ",
pr_netaddr_get_ipstr(s->addr), s->ServerPort, s->ServerName);
buf[sizeof(buf)-1] = '\0';
k->dsa_pkey = tls_get_page(PEM_BUFSIZE, &k->dsa_pkey_ptr);
if (k->dsa_pkey == NULL) {
pr_log_pri(PR_LOG_ERR, "out of memory!");
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_NOMEM, NULL);
}
if (tls_get_passphrase(s, dsa->argv[0], buf, k->dsa_pkey,
k->pkeysz, TLS_PASSPHRASE_FL_DSA_KEY) < 0) {
pr_log_debug(DEBUG0, MOD_TLS_VERSION
": error reading DSA passphrase: %s", tls_get_errors());
pr_log_pri(PR_LOG_ERR, MOD_TLS_VERSION ": unable to use "
"DSA certificate key '%s', exiting", (char *) dsa->argv[0]);
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION,
NULL);
}
}
if (pkcs12) {
snprintf(buf, sizeof(buf)-1,
"PKCS12 password for the %s#%d (%s) server: ",
pr_netaddr_get_ipstr(s->addr), s->ServerPort, s->ServerName);
buf[sizeof(buf)-1] = '\0';
k->pkcs12_passwd = tls_get_page(PEM_BUFSIZE, &k->pkcs12_passwd_ptr);
if (k->pkcs12_passwd == NULL) {
pr_log_pri(PR_LOG_ERR, "out of memory!");
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_NOMEM, NULL);
}
if (tls_get_passphrase(s, pkcs12->argv[0], buf, k->pkcs12_passwd,
k->pkeysz, TLS_PASSPHRASE_FL_PKCS12_PASSWD) < 0) {
pr_log_debug(DEBUG0, MOD_TLS_VERSION
": error reading PKCS12 password: %s", tls_get_errors());
pr_log_pri(PR_LOG_ERR, MOD_TLS_VERSION ": unable to use "
"PKCS12 certificate '%s', exiting", (char *) pkcs12->argv[0]);
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION,
NULL);
}
}
k->next = tls_pkey_list;
tls_pkey_list = k;
tls_npkeys++;
}
}
static void tls_postparse_ev(const void *event_data, void *user_data) {
server_rec *s = NULL;
/* Check for incompatible configurations. For example, configuring:
*
* TLSOptions AllowPerUser
* TLSRequired auth
*
* cannot be supported; the AllowPerUser means that the requirement of
* SSL/TLS protection during authentication cannot be enforced.
*/
for (s = (server_rec *) server_list->xas_list; s; s = s->next) {
unsigned long *opts;
config_rec *toplevel_c = NULL, *other_c = NULL;
int toplevel_auth_requires_ssl = FALSE, other_auth_requires_ssl = TRUE;
opts = get_param_ptr(s->conf, "TLSOptions", FALSE);
if (opts == NULL) {
continue;
}
/* The purpose of this check is to watch for configurations such as:
*
* <IfModule mod_tls.c>
* ...
* TLSRequired on
* ...
* TLSOptions AllowPerUser
* ...
* </IfModule>
*
* This policy cannot be enforced; we cannot require use of SSL/TLS
* (specifically at authentication time, when we do NOT know the user)
* AND also allow per-user SSL/TLS requirements. It's a chicken-and-egg
* problem.
*
* However, we DO want to allow configurations like:
*
* <IfModule mod_tls.c>
* ...
* TLSRequired on
* ...
* TLSOptions AllowPerUser
* ...
* </IfModule>
*
* <Anonymous ...>
* ...
* <IfModule mod_tls.c>
* TLSRequired off
* </IfModule>
* </Anonymous>
*
* Thus this check is a bit tricky. We look first in this server_rec's
* config list for a top-level TLSRequired setting. If it is 'on' AND
* if the AllowPerUser TLSOption is set, AND we find no other TLSRequired
* configs deeper in the server_rec whose value is 'off', then log the
* error and quit. Otherwise, let things proceed.
*
* If the mod_ifsession module is present, skip this check as well; we
* will not be able to suss out any TLSRequired settings which are
* lurking in mod_ifsession's grasp until authentication time.
*
* I still regret adding support for the AllowPerUser TLSOption. Users
* just cannot seem to wrap their minds around the fact that the user
* is not known at the time when the SSL/TLS session is done. Sigh.
*/
if (pr_module_exists("mod_ifsession.c")) {
continue;
}
toplevel_c = find_config(s->conf, CONF_PARAM, "TLSRequired", FALSE);
if (toplevel_c) {
toplevel_auth_requires_ssl = *((int *) toplevel_c->argv[2]);
}
/* If this toplevel TLSRequired value is 'off', then we need check no
* further.
*/
if (!toplevel_auth_requires_ssl) {
continue;
}
/* This time, we recurse deeper into the server_rec's configs.
* We need only pay attention to settings we find in the CONF_DIR or
* CONF_ANON config contexts. And we need only look until we find such
* a setting does not require SSL/TLS during authentication, for at that
* point we know it is not a misconfiguration.
*/
find_config_set_top(NULL);
other_c = find_config(s->conf, CONF_PARAM, "TLSRequired", TRUE);
while (other_c) {
int auth_requires_ssl;
pr_signals_handle();
if (other_c->parent == NULL ||
(other_c->parent->config_type != CONF_ANON &&
other_c->parent->config_type != CONF_DIR)) {
/* Not what we're looking for; continue on. */
other_c = find_config_next(other_c, other_c->next, CONF_PARAM,
"TLSRequired", TRUE);
continue;
}
auth_requires_ssl = *((int *) other_c->argv[2]);
if (!auth_requires_ssl) {
other_auth_requires_ssl = FALSE;
break;
}
other_c = find_config_next(other_c, other_c->next, CONF_PARAM,
"TLSRequired", TRUE);
}
if ((*opts & TLS_OPT_ALLOW_PER_USER) &&
toplevel_auth_requires_ssl == TRUE &&
other_auth_requires_ssl == TRUE) {
pr_log_pri(PR_LOG_ERR, MOD_TLS_VERSION ": Server %s: cannot enforce "
"both 'TLSRequired auth' and 'TLSOptions AllowPerUser' at the "
"same time", s->ServerName);
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BAD_CONFIG, NULL);
}
}
/* Initialize the OpenSSL context. */
if (tls_init_ctx() < 0) {
pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
": error initialising OpenSSL context");
pr_session_disconnect(&tls_module, PR_SESS_DISCONNECT_BY_APPLICATION, NULL);
}
/* We can only get the passphrases from certs once OpenSSL has been
* initialized.
*/
tls_get_passphrases();
/* Install our control channel NetIO handlers. This is done here
* specifically because we need to cache a pointer to the nstrm that
* is passed to the open callback(). Ideally we'd only install our
* custom NetIO handlers if the appropriate AUTH command was given.
* But by then, the open() callback will have already been called, and
* we will not have a chance to get that nstrm pointer.
*/
tls_netio_install_ctrl();
}
/* Initialization routines
*/
static int tls_init(void) {
/* Check that the OpenSSL headers used match the version of the
* OpenSSL library used.
*
* For now, we only log if there is a difference.
*/
if (SSLeay() != OPENSSL_VERSION_NUMBER) {
pr_log_pri(PR_LOG_ERR, MOD_TLS_VERSION
": compiled using OpenSSL version '%s' headers, but linked to "
"OpenSSL version '%s' library", OPENSSL_VERSION_TEXT,
SSLeay_version(SSLEAY_VERSION));
tls_log("compiled using OpenSSL version '%s' headers, but linked to "
"OpenSSL version '%s' library", OPENSSL_VERSION_TEXT,
SSLeay_version(SSLEAY_VERSION));
}
pr_log_debug(DEBUG2, MOD_TLS_VERSION ": using " OPENSSL_VERSION_TEXT);
#if defined(PR_SHARED_MODULE)
pr_event_register(&tls_module, "core.module-unload", tls_mod_unload_ev, NULL);
#endif /* PR_SHARED_MODULE */
pr_event_register(&tls_module, "core.postparse", tls_postparse_ev, NULL);
pr_event_register(&tls_module, "core.restart", tls_restart_ev, NULL);
pr_event_register(&tls_module, "core.shutdown", tls_shutdown_ev, NULL);
SSL_load_error_strings();
SSL_library_init();
/* It looks like calling OpenSSL_add_all_algorithms() is necessary for
* handling some algorithms (e.g. PKCS12 files) which are NOT added by
* just calling SSL_library_init().
*/
OpenSSL_add_all_algorithms();
#ifdef PR_USE_CTRLS
if (pr_ctrls_register(&tls_module, "tls", "query/tune mod_tls settings",
tls_handle_tls) < 0) {
pr_log_pri(PR_LOG_INFO, MOD_TLS_VERSION
": error registering 'tls' control: %s", strerror(errno));
} else {
register unsigned int i;
tls_act_pool = make_sub_pool(permanent_pool);
pr_pool_tag(tls_act_pool, "TLS Controls Pool");
for (i = 0; tls_acttab[i].act_action; i++) {
tls_acttab[i].act_acl = palloc(tls_act_pool, sizeof(ctrls_acl_t));
pr_ctrls_init_acl(tls_acttab[i].act_acl);
}
}
#endif /* PR_USE_CTRLS */
return 0;
}
static int tls_sess_init(void) {
int res = 0;
unsigned char *tmp = NULL;
unsigned long *opts = NULL;
config_rec *c = NULL;
/* First, check to see whether mod_tls is even enabled. */
tmp = get_param_ptr(main_server->conf, "TLSEngine", FALSE);
if (tmp != NULL &&
*tmp == TRUE) {
tls_engine = TRUE;
} else {
/* No need for this modules's control channel NetIO handlers
* anymore.
*/
pr_unregister_netio(PR_NETIO_STRM_CTRL);
/* No need for all the OpenSSL stuff in this process space, either.
*/
tls_cleanup(TLS_CLEANUP_FL_SESS_INIT);
tls_scrub_pkeys();
return 0;
}
tls_cipher_suite = get_param_ptr(main_server->conf, "TLSCipherSuite",
FALSE);
if (tls_cipher_suite == NULL)
tls_cipher_suite = TLS_DEFAULT_CIPHER_SUITE;
tls_crl_file = get_param_ptr(main_server->conf, "TLSCARevocationFile", FALSE);
tls_crl_path = get_param_ptr(main_server->conf, "TLSCARevocationPath", FALSE);
tls_dhparam_file = get_param_ptr(main_server->conf, "TLSDHParamFile", FALSE);
tls_dsa_cert_file = get_param_ptr(main_server->conf, "TLSDSACertificateFile",
FALSE);
tls_dsa_key_file = get_param_ptr(main_server->conf,
"TLSDSACertificateKeyFile", FALSE);
tls_pkcs12_file = get_param_ptr(main_server->conf, "TLSPKCS12File", FALSE);
tls_rsa_cert_file = get_param_ptr(main_server->conf, "TLSRSACertificateFile",
FALSE);
tls_rsa_key_file = get_param_ptr(main_server->conf,
"TLSRSACertificateKeyFile", FALSE);
opts = get_param_ptr(main_server->conf, "TLSOptions", FALSE);
if (opts != NULL)
tls_opts = *opts;
#if OPENSSL_VERSION_NUMBER > 0x009080cfL
/* The OpenSSL team realized that the flag added in 0.9.8l, the
* SSL3_FLAGS_ALLOW_UNSAFE_LEGACY_RENEGOTIATION flag, was a bad idea.
* So in later versions, it was changed to a context flag,
* SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION.
*/
if (tls_opts & TLS_OPT_ALLOW_CLIENT_RENEGOTIATIONS) {
int ssl_opts;
ssl_opts = SSL_CTX_get_options(ssl_ctx);
ssl_opts |= SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
SSL_CTX_set_options(ssl_ctx, ssl_opts);
}
#endif
tmp = get_param_ptr(main_server->conf, "TLSVerifyClient", FALSE);
if (tmp!= NULL &&
*tmp == TRUE) {
int *depth = NULL;
tls_flags |= TLS_SESS_VERIFY_CLIENT;
depth = get_param_ptr(main_server->conf, "TLSVerifyDepth", FALSE);
if (depth != NULL)
tls_verify_depth = *depth;
}
c = find_config(main_server->conf, CONF_PARAM, "TLSRequired", FALSE);
if (c) {
tls_required_on_ctrl = *((int *) c->argv[0]);
tls_required_on_data = *((int *) c->argv[1]);
tls_required_on_auth = *((int *) c->argv[2]);
}
c = find_config(main_server->conf, CONF_PARAM, "TLSTimeoutHandshake", FALSE);
if (c)
tls_handshake_timeout = *((unsigned int *) c->argv[0]);
/* Open the TLSLog, if configured */
res = tls_openlog();
if (res < 0) {
if (res == -1) {
pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
": notice: unable to open TLSLog: %s", strerror(errno));
} else if (res == PR_LOG_WRITABLE_DIR) {
pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
": notice: unable to open TLSLog: parent directory is world writable");
} else if (res == PR_LOG_SYMLINK) {
pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION
": notice: unable to open TLSLog: cannot log to a symbolic link");
}
}
/* If UseReverseDNS is set to off, disable TLS_OPT_VERIFY_CERT_FQDN. */
if (!ServerUseReverseDNS &&
((tls_opts & TLS_OPT_VERIFY_CERT_FQDN) ||
(tls_opts & TLS_OPT_VERIFY_CERT_CN))) {
if (tls_opts & TLS_OPT_VERIFY_CERT_FQDN) {
tls_opts &= ~TLS_OPT_VERIFY_CERT_FQDN;
tls_log("%s", "reverse DNS off, disabling TLSOption dNSNameRequired");
}
if (tls_opts & TLS_OPT_VERIFY_CERT_CN) {
tls_opts &= ~TLS_OPT_VERIFY_CERT_CN;
tls_log("%s", "reverse DNS off, disabling TLSOption CommonNameRequired");
}
}
/* We need to check for FIPS mode in the child process as well, in order
* to re-seed the FIPS PRNG for this process ID. Annoying, isn't it?
*/
if (pr_define_exists("TLS_USE_FIPS") &&
ServerType == SERVER_STANDALONE) {
#ifdef OPENSSL_FIPS
if (!FIPS_mode()) {
/* Make sure OpenSSL is set to use the default RNG, as per an email
* discussion on the OpenSSL developer list:
*
* "The internal FIPS logic uses the default RNG to see the FIPS RNG
* as part of the self test process..."
*/
RAND_set_rand_method(NULL);
if (!FIPS_mode_set(1)) {
const char *errstr;
errstr = tls_get_errors();
tls_log("unable to use FIPS mode: %s", errstr);
pr_log_pri(PR_LOG_ERR, MOD_TLS_VERSION ": unable to use FIPS mode: %s",
errstr);
errno = EPERM;
return -1;
} else {
tls_log("FIPS mode enabled");
pr_log_pri(PR_LOG_NOTICE, MOD_TLS_VERSION ": FIPS mode enabled");
}
} else {
tls_log("FIPS mode already enabled");
}
#else
pr_log_pri(PR_LOG_WARNING, MOD_TLS_VERSION ": FIPS mode requested, but " OPENSSL_VERSION_TEXT " not built with FIPS support");
#endif /* OPENSSL_FIPS */
}
/* Update the session ID context to use. This is important; it ensures
* that the session IDs for this particular vhost will differ from those
* for another vhost. An external SSL session cache will possibly
* cache sessions from all vhosts together, and we need to keep them
* separate.
*/
SSL_CTX_set_session_id_context(ssl_ctx, (unsigned char *) main_server,
sizeof(main_server));
/* Update the session ID context to use. This is important; it ensures
* that the session IDs for this particular vhost will differ from those
* for another vhost. An external SSL session cache will possibly
* cache sessions from all vhosts together, and we need to keep them
* separate.
*/
SSL_CTX_set_session_id_context(ssl_ctx, (unsigned char *) main_server,
sizeof(main_server));
/* Install our data channel NetIO handlers. */
tls_netio_install_data();
pr_event_register(&tls_module, "core.exit", tls_exit_ev, NULL);
/* There are several timeouts which can cause the client to be disconnected;
* register a listener for them which can politely/cleanly shut the SSL/TLS
* session down before the connection is closed.
*/
pr_event_register(&tls_module, "core.timeout-idle", tls_timeout_ev, NULL);
pr_event_register(&tls_module, "core.timeout-login", tls_timeout_ev, NULL);
pr_event_register(&tls_module, "core.timeout-no-transfer", tls_timeout_ev,
NULL);
pr_event_register(&tls_module, "core.timeout-session", tls_timeout_ev, NULL);
pr_event_register(&tls_module, "core.timeout-stalled", tls_timeout_ev, NULL);
/* Check to see if a passphrase has been entered for this server. */
tls_pkey = tls_lookup_pkey();
if (tls_pkey != NULL) {
SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_pkey_cb);
SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, (void *) tls_pkey);
}
/* We always install an info callback, in order to watch for
* client-initiated session renegotiations (Bug#3324). If EnableDiags
* is enabled, that info callback will also log the OpenSSL diagnostic
* information.
*/
SSL_CTX_set_info_callback(ssl_ctx, tls_diags_cb);
#if OPENSSL_VERSION_NUMBER > 0x000907000L
/* Install a callback for logging OpenSSL message information,
* if requested.
*/
if (tls_opts & TLS_OPT_ENABLE_DIAGS) {
tls_log("%s",
"TLSOption EnableDiags enabled, setting diagnostics callback");
SSL_CTX_set_msg_callback(ssl_ctx, tls_msg_cb);
}
#endif
#if OPENSSL_VERSION_NUMBER > 0x000907000L
/* Handle any requested crypto accelerators/drivers. */
c = find_config(main_server->conf, CONF_PARAM, "TLSCryptoDevice", FALSE);
if (c) {
tls_crypto_device = (const char *) c->argv[0];
if (strncasecmp(tls_crypto_device, "ALL", 4) == 0) {
/* Load all ENGINE implementations bundled with OpenSSL. */
ENGINE_load_builtin_engines();
ENGINE_register_all_complete();
tls_log("%s", "enabled all builtin crypto devices");
} else {
ENGINE *e;
/* Load all ENGINE implementations bundled with OpenSSL. */
ENGINE_load_builtin_engines();
e = ENGINE_by_id(tls_crypto_device);
if (e) {
if (ENGINE_init(e)) {
if (ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
ENGINE_finish(e);
ENGINE_free(e);
tls_log("using TLSCryptoDevice '%s'", tls_crypto_device);
} else {
/* The requested driver could not be used as the default for
* some odd reason.
*/
tls_log("unable to register TLSCryptoDevice '%s' as the "
"default: %s", tls_crypto_device, tls_get_errors());
ENGINE_finish(e);
ENGINE_free(e);
e = NULL;
tls_crypto_device = NULL;
}
} else {
/* The requested driver could not be initialized. */
tls_log("unable to initialize TLSCryptoDevice '%s': %s",
tls_crypto_device, tls_get_errors());
ENGINE_free(e);
e = NULL;
tls_crypto_device = NULL;
}
} else {
/* The requested driver is not available. */
tls_log("TLSCryptoDevice '%s' is not available", tls_crypto_device);
tls_crypto_device = NULL;
}
}
}
#endif
/* Initialize the OpenSSL context for this server's configuration. */
res = tls_init_server();
if (res < 0) {
/* NOTE: should we fail session init if TLS server init fails? */
tls_log("%s", "error initializing OpenSSL context for this session");
}
/* Add the additional features implemented by this module into the
* list, to be displayed in response to a FEAT command.
*/
pr_feat_add("AUTH TLS");
pr_feat_add("PBSZ");
pr_feat_add("PROT");
/* Add the commands handled by this module to the HELP list. */
pr_help_add(C_AUTH, _("<sp> base64-data"), TRUE);
pr_help_add(C_PBSZ, _("<sp> protection buffer size"), TRUE);
pr_help_add(C_PROT, _("<sp> protection code"), TRUE);
if (tls_opts & TLS_OPT_USE_IMPLICIT_SSL) {
tls_log("%s", "TLSOption UseImplicitSSL in effect, starting SSL/TLS "
"handshake");
if (tls_accept(session.c, FALSE) < 0) {
tls_log("%s", "implicit SSL/TLS negotiation failed on control channel");
errno = EACCES;
return -1;
}
tls_flags |= TLS_SESS_ON_CTRL;
pr_session_set_protocol("ftps");
session.rfc2228_mech = "TLS";
}
return 0;
}
#ifdef PR_USE_CTRLS
static ctrls_acttab_t tls_acttab[] = {
{ "clear", NULL, NULL, NULL },
{ "info", NULL, NULL, NULL },
{ "remove", NULL, NULL, NULL },
{ "sesscache", NULL, NULL, NULL },
{ NULL, NULL, NULL, NULL }
};
#endif /* PR_USE_CTRLS */
/* Module API tables
*/
static conftable tls_conftab[] = {
{ "TLSCACertificateFile", set_tlscacertfile, NULL },
{ "TLSCACertificatePath", set_tlscacertpath, NULL },
{ "TLSCARevocationFile", set_tlscacrlfile, NULL },
{ "TLSCARevocationPath", set_tlscacrlpath, NULL },
{ "TLSCertificateChainFile", set_tlscertchain, NULL },
{ "TLSCipherSuite", set_tlsciphersuite, NULL },
{ "TLSControlsACLs", set_tlsctrlsacls, NULL },
{ "TLSCryptoDevice", set_tlscryptodevice, NULL },
{ "TLSDHParamFile", set_tlsdhparamfile, NULL },
{ "TLSDSACertificateFile", set_tlsdsacertfile, NULL },
{ "TLSDSACertificateKeyFile", set_tlsdsakeyfile, NULL },
{ "TLSEngine", set_tlsengine, NULL },
{ "TLSLog", set_tlslog, NULL },
{ "TLSOptions", set_tlsoptions, NULL },
{ "TLSPassPhraseProvider", set_tlspassphraseprovider, NULL },
{ "TLSPKCS12File", set_tlspkcs12file, NULL },
{ "TLSProtocol", set_tlsprotocol, NULL },
{ "TLSRandomSeed", set_tlsrandseed, NULL },
{ "TLSRenegotiate", set_tlsrenegotiate, NULL },
{ "TLSRequired", set_tlsrequired, NULL },
{ "TLSRSACertificateFile", set_tlsrsacertfile, NULL },
{ "TLSRSACertificateKeyFile", set_tlsrsakeyfile, NULL },
{ "TLSSessionCache", set_tlssessioncache, NULL },
{ "TLSTimeoutHandshake", set_tlstimeouthandshake,NULL },
{ "TLSVerifyClient", set_tlsverifyclient, NULL },
{ "TLSVerifyDepth", set_tlsverifydepth, NULL },
{ "TLSVerifyOrder", set_tlsverifyorder, NULL },
{ NULL , NULL, NULL}
};
static cmdtable tls_cmdtab[] = {
{ PRE_CMD, C_ANY, G_NONE, tls_any, FALSE, FALSE },
{ CMD, C_AUTH, G_NONE, tls_auth, FALSE, FALSE, CL_SEC },
{ CMD, C_CCC, G_NONE, tls_ccc, FALSE, FALSE, CL_SEC },
{ CMD, C_PBSZ, G_NONE, tls_pbsz, FALSE, FALSE, CL_SEC },
{ CMD, C_PROT, G_NONE, tls_prot, FALSE, FALSE, CL_SEC },
{ POST_CMD, C_PASS, G_NONE, tls_post_pass, FALSE, FALSE, CL_SEC },
{ 0, NULL }
};
static authtable tls_authtab[] = {
{ 0, "auth", tls_authenticate },
{ 0, "check", tls_auth_check },
{ 0, "requires_pass", tls_authenticate },
{ 0, NULL }
};
module tls_module = {
/* Always NULL */
NULL, NULL,
/* Module API version */
0x20,
/* Module name */
"tls",
/* Module configuration handler table */
tls_conftab,
/* Module command handler table */
tls_cmdtab,
/* Module authentication handler table */
tls_authtab,
/* Module initialization */
tls_init,
/* Session initialization */
tls_sess_init,
/* Module version */
MOD_TLS_VERSION
};
|