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
|
/*
* tls.c
*
* Version: $Id: 7cc5f032b4f78ee55792b7859cd1ea172a2148aa $
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
* Copyright 2001 hereUare Communications, Inc. <raghud@hereuare.com>
* Copyright 2003 Alan DeKok <aland@freeradius.org>
* Copyright 2006 The FreeRADIUS server project
*/
RCSID("$Id: 7cc5f032b4f78ee55792b7859cd1ea172a2148aa $")
USES_APPLE_DEPRECATED_API /* OpenSSL API has been deprecated by Apple */
#include <freeradius-devel/radiusd.h>
#include <freeradius-devel/process.h>
#include <freeradius-devel/rad_assert.h>
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_UTIME_H
#include <utime.h>
#endif
#include <ctype.h>
#ifdef WITH_TLS
# ifdef HAVE_OPENSSL_RAND_H
# include <openssl/rand.h>
# endif
# ifdef HAVE_OPENSSL_OCSP_H
# include <openssl/ocsp.h>
# endif
# ifdef HAVE_OPENSSL_EVP_H
# include <openssl/evp.h>
# endif
# include <openssl/ssl.h>
#define LOG_PREFIX "tls"
#ifdef ENABLE_OPENSSL_VERSION_CHECK
typedef struct libssl_defect {
uint64_t high;
uint64_t low;
char const *id;
char const *name;
char const *comment;
} libssl_defect_t;
/* Record critical defects in libssl here, new versions of OpenSSL to older versions of OpenSSL. */
static libssl_defect_t libssl_defects[] =
{
{
.low = 0x01010101f, /* 1.1.0a */
.high = 0x01010101f, /* 1.1.0a */
.id = "CVE-2016-6309",
.name = "OCSP status request extension",
.comment = "For more information see https://www.openssl.org/news/secadv/20160926.txt"
},
{
.low = 0x01010100f, /* 1.1.0 */
.high = 0x01010100f, /* 1.1.0 */
.id = "CVE-2016-6304",
.name = "OCSP status request extension",
.comment = "For more information see https://www.openssl.org/news/secadv/20160922.txt"
},
{
.low = 0x01000209f, /* 1.0.2i */
.high = 0x01000209f, /* 1.0.2i */
.id = "CVE-2016-7052",
.name = "OCSP status request extension",
.comment = "For more information see https://www.openssl.org/news/secadv/20160926.txt"
},
{
.low = 0x01000200f, /* 1.0.2 */
.high = 0x01000208f, /* 1.0.2h */
.id = "CVE-2016-6304",
.name = "OCSP status request extension",
.comment = "For more information see https://www.openssl.org/news/secadv/20160922.txt"
},
{
.low = 0x01000100f, /* 1.0.1 */
.high = 0x01000114f, /* 1.0.1t */
.id = "CVE-2016-6304",
.name = "OCSP status request extension",
.comment = "For more information see https://www.openssl.org/news/secadv/20160922.txt"
},
{
.low = 0x010001000, /* 1.0.1 */
.high = 0x01000106f, /* 1.0.1f */
.id = "CVE-2014-0160",
.name = "Heartbleed",
.comment = "For more information see http://heartbleed.com"
},
};
#endif /* ENABLE_OPENSSL_VERSION_CHECK */
FR_NAME_NUMBER const fr_tls_status_table[] = {
{ "invalid", FR_TLS_INVALID },
{ "request", FR_TLS_REQUEST },
{ "response", FR_TLS_RESPONSE },
{ "success", FR_TLS_SUCCESS },
{ "fail", FR_TLS_FAIL },
{ "noop", FR_TLS_NOOP },
{ "start", FR_TLS_START },
{ "ok", FR_TLS_OK },
{ "ack", FR_TLS_ACK },
{ "first fragment", FR_TLS_FIRST_FRAGMENT },
{ "more fragments", FR_TLS_MORE_FRAGMENTS },
{ "length included", FR_TLS_LENGTH_INCLUDED },
{ "more fragments with length", FR_TLS_MORE_FRAGMENTS_WITH_LENGTH },
{ "handled", FR_TLS_HANDLED },
{ NULL , -1},
};
/* index we use to store cached session VPs
* needs to be dynamic so we can supply a "free" function
*/
int fr_tls_ex_index_vps = -1;
int fr_tls_ex_index_certs = -1;
/* Session */
static void session_close(tls_session_t *ssn);
static void session_init(tls_session_t *ssn);
/* record */
static void record_init(record_t *buf);
static void record_close(record_t *buf);
static unsigned int record_plus(record_t *buf, void const *ptr,
unsigned int size);
static unsigned int record_minus(record_t *buf, void *ptr,
unsigned int size);
DIAG_OFF(format-nonliteral)
/** Print errors in the TLS thread local error stack
*
* Drains the thread local OpenSSL error queue, and prints out errors.
*
* @param[in] request The current request (may be NULL).
* @param[in] msg Error message describing the operation being attempted.
* @param[in] ap Arguments for msg.
* @return the number of errors drained from the stack.
*/
static int tls_verror_log(REQUEST *request, char const *msg, va_list ap)
{
unsigned long error;
char *p;
int in_stack = 0;
char buffer[256];
int line;
char const *file;
/*
* Pop the first error, so ERR_peek_error()
* can be used to determine if there are
* multiple errors.
*/
error = ERR_get_error_line(&file, &line);
if (msg) {
p = talloc_vasprintf(request, msg, ap);
/*
* Single line mode (there's only one error)
*/
if (error && !ERR_peek_error()) {
ERR_error_string_n(error, buffer, sizeof(buffer));
/* Extra verbose */
if ((request && RDEBUG_ENABLED3) || DEBUG_ENABLED3) {
ROPTIONAL(REDEBUG, ERROR, "%s: %s[%i]:%s", p, file, line, buffer);
} else {
ROPTIONAL(REDEBUG, ERROR, "%s: %s", p, buffer);
}
talloc_free(p);
return 1;
}
/*
* Print the error we were given, irrespective
* of whether there were any OpenSSL errors.
*/
ROPTIONAL(RERROR, ERROR, "%s", p);
talloc_free(p);
}
/*
* Stack mode (there are multiple errors)
*/
if (!error) return 0;
do {
ERR_error_string_n(error, buffer, sizeof(buffer));
/* Extra verbose */
if ((request && RDEBUG_ENABLED3) || DEBUG_ENABLED3) {
ROPTIONAL(REDEBUG, ERROR, "%s[%i]:%s", file, line, buffer);
} else {
ROPTIONAL(REDEBUG, ERROR, "%s", buffer);
}
in_stack++;
} while ((error = ERR_get_error_line(&file, &line)));
return in_stack;
}
DIAG_ON(format-nonliteral)
/** Print errors in the TLS thread local error stack
*
* Drains the thread local OpenSSL error queue, and prints out errors.
*
* @param[in] request The current request (may be NULL).
* @param[in] msg Error message describing the operation being attempted.
* @param[in] ... Arguments for msg.
* @return the number of errors drained from the stack.
*/
int tls_error_log(REQUEST *request, char const *msg, ...)
{
va_list ap;
int ret;
va_start(ap, msg);
ret = tls_verror_log(request, msg, ap);
va_end(ap);
return ret;
}
/** Print errors raised by OpenSSL I/O functions
*
* Drains the thread local OpenSSL error queue, and prints out errors
* based on the SSL handle and the return code of the I/O function.
*
* OpenSSL lists I/O functions to be:
* - SSL_connect
* - SSL_accept
* - SSL_do_handshake
* - SSL_read
* - SSL_peek
* - SSL_write
*
* @param request The current request (may be NULL).
* @param session The current tls_session.
* @param ret from the I/O operation.
* @param msg Error message describing the operation being attempted.
* @param ... Arguments for msg.
* @return
* - 0 TLS session cannot continue.
* - 1 TLS session may still be viable.
*/
int tls_error_io_log(REQUEST *request, tls_session_t *session, int ret, char const *msg, ...)
{
int error;
va_list ap;
if (ERR_peek_error()) {
va_start(ap, msg);
tls_verror_log(request, msg, ap);
va_end(ap);
}
error = SSL_get_error(session->ssl, ret);
switch (error) {
/*
* These seem to be harmless and already "dealt
* with" by our non-blocking environment. NB:
* "ZERO_RETURN" is the clean "error"
* indicating a successfully closed SSL
* tunnel. We let this happen because our IO
* loop should not appear to have broken on
* this condition - and outside the IO loop, the
* "shutdown" state is checked.
*
* Don't print anything if we ignore the error.
*/
case SSL_ERROR_NONE:
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_X509_LOOKUP:
case SSL_ERROR_ZERO_RETURN:
break;
/*
* These seem to be indications of a genuine
* error that should result in the SSL tunnel
* being regarded as "dead".
*/
case SSL_ERROR_SYSCALL:
ROPTIONAL(REDEBUG, ERROR, "System call (I/O) error (%i)", ret);
return 0;
case SSL_ERROR_SSL:
ROPTIONAL(REDEBUG, ERROR, "TLS protocol error (%i)", ret);
return 0;
/*
* For any other errors that (a) exist, and (b)
* crop up - we need to interpret what to do with
* them - so "politely inform" the caller that
* the code needs updating here.
*/
default:
ROPTIONAL(REDEBUG, ERROR, "TLS session error %i (%i)", error, ret);
return 0;
}
return 1;
}
#ifdef PSK_MAX_IDENTITY_LEN
static bool identity_is_safe(const char *identity)
{
char c;
if (!identity) return true;
while ((c = *(identity++)) != '\0') {
if (isalpha((int) c) || isdigit((int) c) || isspace((int) c) ||
(c == '@') || (c == '-') || (c == '_') || (c == '.')) {
continue;
}
return false;
}
return true;
}
/*
* When a client uses TLS-PSK to talk to a server, this callback
* is used by the server to determine the PSK to use.
*/
static unsigned int psk_server_callback(SSL *ssl, const char *identity,
unsigned char *psk,
unsigned int max_psk_len)
{
unsigned int psk_len = 0;
fr_tls_server_conf_t *conf;
REQUEST *request;
conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
FR_TLS_EX_INDEX_CONF);
if (!conf) return 0;
request = (REQUEST *)SSL_get_ex_data(ssl,
FR_TLS_EX_INDEX_REQUEST);
if (request && conf->psk_query) {
size_t hex_len;
VALUE_PAIR *vp;
char buffer[2 * PSK_MAX_PSK_LEN + 4]; /* allow for too-long keys */
/*
* The passed identity is weird. Deny it.
*/
if (!identity_is_safe(identity)) {
RWDEBUG("Invalid characters in PSK identity %s", identity);
return 0;
}
vp = pair_make_request("TLS-PSK-Identity", identity, T_OP_SET);
if (!vp) return 0;
hex_len = radius_xlat(buffer, sizeof(buffer), request, conf->psk_query,
NULL, NULL);
if (!hex_len) {
RWDEBUG("PSK expansion returned an empty string.");
return 0;
}
/*
* The returned key is truncated at MORE than
* OpenSSL can handle. That way we can detect
* the truncation, and complain about it.
*/
if (hex_len > (2 * max_psk_len)) {
RWDEBUG("Returned PSK is too long (%u > %u)",
(unsigned int) hex_len, 2 * max_psk_len);
return 0;
}
/*
* Leave the TLS-PSK-Identity in the request, and
* convert the expansion from printable string
* back to hex.
*/
return fr_hex2bin(psk, max_psk_len, buffer, hex_len);
}
if (!conf->psk_identity) {
DEBUG("No static PSK identity set. Rejecting the user");
return 0;
}
/*
* No REQUEST, or no dynamic query. Just look for a
* static identity.
*/
if (strcmp(identity, conf->psk_identity) != 0) {
ERROR("Supplied PSK identity %s does not match configuration. Rejecting.",
identity);
return 0;
}
psk_len = strlen(conf->psk_password);
if (psk_len > (2 * max_psk_len)) return 0;
return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
}
static unsigned int psk_client_callback(SSL *ssl, UNUSED char const *hint,
char *identity, unsigned int max_identity_len,
unsigned char *psk, unsigned int max_psk_len)
{
unsigned int psk_len;
fr_tls_server_conf_t *conf;
conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
FR_TLS_EX_INDEX_CONF);
if (!conf) return 0;
psk_len = strlen(conf->psk_password);
if (psk_len > (2 * max_psk_len)) return 0;
strlcpy(identity, conf->psk_identity, max_identity_len);
return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
}
#endif
#define MAX_SESSION_SIZE (256)
void tls_session_id(SSL_SESSION *ssn, char *buffer, size_t bufsize)
{
#if OPENSSL_VERSION_NUMBER < 0x10001000L
size_t size;
size = ssn->session_id_length;
if (size > bufsize) size = bufsize;
fr_bin2hex(buffer, ssn->session_id, size);
#else
unsigned int size;
uint8_t const *p;
p = SSL_SESSION_get_id(ssn, &size);
if (size > bufsize) size = bufsize;
fr_bin2hex(buffer, p, size);
#endif
}
static int _tls_session_free(tls_session_t *ssn)
{
/*
* Free any opaque TTLS or PEAP data.
*/
if ((ssn->opaque) && (ssn->free_opaque)) {
ssn->free_opaque(ssn->opaque);
ssn->opaque = NULL;
}
session_close(ssn);
return 0;
}
tls_session_t *tls_new_client_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, int fd)
{
int ret;
int verify_mode;
tls_session_t *ssn = NULL;
REQUEST *request;
ssn = talloc_zero(ctx, tls_session_t);
if (!ssn) return NULL;
talloc_set_destructor(ssn, _tls_session_free);
ssn->ctx = conf->ctx;
SSL_CTX_set_mode(ssn->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
ssn->ssl = SSL_new(ssn->ctx);
if (!ssn->ssl) {
talloc_free(ssn);
return NULL;
}
request = request_alloc(ssn);
SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
/*
* Add the message callback to identify what type of
* message/handshake is passed
*/
SSL_set_msg_callback(ssn->ssl, cbtls_msg);
SSL_set_msg_callback_arg(ssn->ssl, ssn);
SSL_set_info_callback(ssn->ssl, cbtls_info);
/*
* Always verify the peer certificate.
*/
DEBUG2("Requiring Server certificate");
verify_mode = SSL_VERIFY_PEER;
verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_SSN, (void *)ssn);
SSL_set_fd(ssn->ssl, fd);
ret = SSL_connect(ssn->ssl);
if (ret <= 0) {
tls_error_io_log(NULL, ssn, ret, "Failed in " STRINGIFY(__FUNCTION__) " (SSL_connect)");
talloc_free(ssn);
return NULL;
}
ssn->mtu = conf->fragment_size;
return ssn;
}
/** Create a new TLS session
*
* Configures a new TLS session, configuring options, setting callbacks etc...
*
* @param ctx to alloc session data in. Should usually be NULL unless the lifetime of the
* session is tied to another talloc'd object.
* @param conf to use to configure the tls session.
* @param request The current #REQUEST.
* @param client_cert Whether to require a client_cert.
* @return a new session on success, or NULL on error.
*/
tls_session_t *tls_new_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, REQUEST *request, bool client_cert)
{
tls_session_t *state = NULL;
SSL *new_tls = NULL;
int verify_mode = 0;
VALUE_PAIR *vp;
rad_assert(request != NULL);
RDEBUG2("Initiating new EAP-TLS session");
/*
* Manually flush the sessions every so often. If HALF
* of the session lifetime has passed since we last
* flushed, then flush it again.
*
* FIXME: Also do it every N sessions?
*/
if (/*conf->session_cache_enable*/0 &&
((conf->session_last_flushed + ((int)conf->session_timeout * 1800)) <= request->timestamp)){
RDEBUG2("Flushing SSL sessions (of #%ld)", SSL_CTX_sess_number(conf->ctx));
SSL_CTX_flush_sessions(conf->ctx, request->timestamp);
conf->session_last_flushed = request->timestamp;
}
new_tls = SSL_new(conf->ctx);
if (new_tls == NULL) {
tls_error_log(request, "Error creating new TLS session");
return NULL;
}
/* We use the SSL's "app_data" to indicate a call-back */
SSL_set_app_data(new_tls, NULL);
if ((state = talloc_zero(ctx, tls_session_t)) == NULL) {
RERROR("Error allocating memory for SSL state");
return NULL;
}
session_init(state);
talloc_set_destructor(state, _tls_session_free);
state->ctx = conf->ctx;
state->ssl = new_tls;
/*
* Initialize callbacks
*/
state->record_init = record_init;
state->record_close = record_close;
state->record_plus = record_plus;
state->record_minus = record_minus;
/*
* Create & hook the BIOs to handle the dirty side of the
* SSL. This is *very important* as we want to handle
* the transmission part. Now the only IO interface
* that SSL is aware of, is our defined BIO buffers.
*
* This means that all SSL IO is done to/from memory,
* and we can update those BIOs from the packets we've
* received.
*/
state->into_ssl = BIO_new(BIO_s_mem());
state->from_ssl = BIO_new(BIO_s_mem());
SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
/*
* Add the message callback to identify what type of
* message/handshake is passed
*/
SSL_set_msg_callback(new_tls, cbtls_msg);
SSL_set_msg_callback_arg(new_tls, state);
SSL_set_info_callback(new_tls, cbtls_info);
/*
* In Server mode we only accept.
*/
SSL_set_accept_state(state->ssl);
/*
* Verify the peer certificate, if asked.
*/
if (client_cert) {
RDEBUG2("Setting verify mode to require certificate from client");
verify_mode = SSL_VERIFY_PEER;
verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
verify_mode |= SSL_VERIFY_CLIENT_ONCE;
}
SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_SSN, (void *)state);
state->length_flag = conf->include_length;
/*
* We use default fragment size, unless the Framed-MTU
* tells us it's too big. Note that we do NOT account
* for the EAP-TLS headers if conf->fragment_size is
* large, because that config item looks to be confusing.
*
* i.e. it should REALLY be called MTU, and the code here
* should figure out what that means for TLS fragment size.
* asking the administrator to know the internal details
* of EAP-TLS in order to calculate fragment sizes is
* just too much.
*/
state->mtu = conf->fragment_size;
vp = fr_pair_find_by_num(request->packet->vps, PW_FRAMED_MTU, 0, TAG_ANY);
if (vp && (vp->vp_integer > 100) && (vp->vp_integer < state->mtu)) {
state->mtu = vp->vp_integer;
}
if (/*conf->session_cache_enable*/0) state->allow_session_resumption = true; /* otherwise it's false */
return state;
}
/*
* We are the server, we always get the dirty data
* (Handshake data is also considered as dirty data)
* During handshake, since SSL API handles itself,
* After clean-up, dirty_out will be filled with
* the data required for handshaking. So we check
* if dirty_out is empty then we simply send it back.
* As of now, if handshake is successful, then we keep going,
* otherwise we fail.
*
* Fill the Bio with the dirty data to clean it
* Get the cleaned data from SSL, if it is not Handshake data
*/
int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
{
int err;
if (ssn->invalid_hb_used) return 0;
err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
if (err != (int) ssn->dirty_in.used) {
REDEBUG("Failed writing %zd bytes to SSL BIO: %d", ssn->dirty_in.used, err);
record_init(&ssn->dirty_in);
return 0;
}
record_init(&ssn->dirty_in);
err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
sizeof(ssn->clean_out.data) - ssn->clean_out.used);
if (err > 0) {
ssn->clean_out.used += err;
return 1;
}
if (!tls_error_io_log(request, ssn, err, "Failed in " STRINGIFY(__FUNCTION__) " (SSL_read)")) return 0;
/* Some Extra STATE information for easy debugging */
if (SSL_is_init_finished(ssn->ssl)) RDEBUG2("SSL Connection Established");
if (SSL_in_init(ssn->ssl)) RDEBUG2("In SSL Handshake Phase");
if (SSL_in_before(ssn->ssl)) RDEBUG2("Before SSL Handshake Phase");
if (SSL_in_accept_init(ssn->ssl)) RDEBUG2("In SSL Accept mode");
if (SSL_in_connect_init(ssn->ssl)) RDEBUG2("In SSL Connect mode");
#if OPENSSL_VERSION_NUMBER >= 0x10001000L
/*
* Cache the SSL_SESSION pointer.
*/
if (!ssn->ssl_session && SSL_is_init_finished(ssn->ssl)) {
ssn->ssl_session = SSL_get_session(ssn->ssl);
if (!ssn->ssl_session) {
RDEBUG("Failed getting SSL session");
return 0;
}
}
#endif
err = BIO_ctrl_pending(ssn->from_ssl);
if (err > 0) {
err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
sizeof(ssn->dirty_out.data));
if (err > 0) {
ssn->dirty_out.used = err;
} else if (BIO_should_retry(ssn->from_ssl)) {
record_init(&ssn->dirty_in);
RDEBUG2("Asking for more data in tunnel");
return 1;
} else {
tls_error_log(NULL, NULL);
record_init(&ssn->dirty_in);
return 0;
}
} else {
RDEBUG2("SSL Application Data");
/* Its clean application data, do whatever we want */
record_init(&ssn->clean_out);
}
/* We are done with dirty_in, reinitialize it */
record_init(&ssn->dirty_in);
return 1;
}
/*
* Take cleartext user data, and encrypt it into the output buffer,
* to send to the client at the other end of the SSL connection.
*/
int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
{
int err;
/*
* If there's un-encrypted data in 'clean_in', then write
* that data to the SSL session, and then call the BIO function
* to get that encrypted data from the SSL session, into
* a buffer which we can then package into an EAP packet.
*
* Based on Server's logic this clean_in is expected to
* contain the data to send to the client.
*/
if (ssn->clean_in.used > 0) {
int written;
written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
record_minus(&ssn->clean_in, NULL, written);
/* Get the dirty data from Bio to send it */
err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
sizeof(ssn->dirty_out.data));
if (err > 0) {
ssn->dirty_out.used = err;
} else {
if (!tls_error_io_log(request, ssn, err,
"Failed in " STRINGIFY(__FUNCTION__) " (SSL_write)")) {
return 0;
}
}
}
return 1;
}
static void session_init(tls_session_t *ssn)
{
ssn->ssl = NULL;
ssn->into_ssl = ssn->from_ssl = NULL;
record_init(&ssn->clean_in);
record_init(&ssn->clean_out);
record_init(&ssn->dirty_in);
record_init(&ssn->dirty_out);
memset(&ssn->info, 0, sizeof(ssn->info));
ssn->mtu = 0;
ssn->fragment = false;
ssn->tls_msg_len = 0;
ssn->length_flag = false;
ssn->opaque = NULL;
ssn->free_opaque = NULL;
}
static void session_close(tls_session_t *ssn)
{
SSL_set_quiet_shutdown(ssn->ssl, 1);
SSL_shutdown(ssn->ssl);
if (ssn->ssl) {
SSL_free(ssn->ssl);
ssn->ssl = NULL;
}
record_close(&ssn->clean_in);
record_close(&ssn->clean_out);
record_close(&ssn->dirty_in);
record_close(&ssn->dirty_out);
session_init(ssn);
}
static void record_init(record_t *rec)
{
rec->used = 0;
}
static void record_close(record_t *rec)
{
rec->used = 0;
}
/*
* Copy data to the intermediate buffer, before we send
* it somewhere.
*/
static unsigned int record_plus(record_t *rec, void const *ptr,
unsigned int size)
{
unsigned int added = MAX_RECORD_SIZE - rec->used;
if(added > size)
added = size;
if(added == 0)
return 0;
memcpy(rec->data + rec->used, ptr, added);
rec->used += added;
return added;
}
/*
* Take data from the buffer, and give it to the caller.
*/
static unsigned int record_minus(record_t *rec, void *ptr,
unsigned int size)
{
unsigned int taken = rec->used;
if(taken > size)
taken = size;
if(taken == 0)
return 0;
if(ptr)
memcpy(ptr, rec->data, taken);
rec->used -= taken;
/*
* This is pretty bad...
*/
if (rec->used > 0) memmove(rec->data, rec->data + taken, rec->used);
return taken;
}
void tls_session_information(tls_session_t *tls_session)
{
char const *str_write_p, *str_version, *str_content_type = "";
char const *str_details1 = "", *str_details2= "";
REQUEST *request;
char buffer[32];
/*
* Don't print this out in the normal course of
* operations.
*/
if (rad_debug_lvl == 0) return;
str_write_p = tls_session->info.origin ? ">>> send" : "<<< recv";
switch (tls_session->info.version) {
case SSL2_VERSION:
str_version = "SSL 2.0 ";
break;
case SSL3_VERSION:
str_version = "SSL 3.0 ";
break;
case TLS1_VERSION:
str_version = "TLS 1.0 ";
break;
#ifdef TLS1_1_VERSION
case TLS1_1_VERSION:
str_version = "TLS 1.1 ";
break;
#endif
#ifdef TLS1_2_VERSION
case TLS1_2_VERSION:
str_version = "TLS 1.2 ";
break;
#endif
#ifdef TLS1_3_VERSON
case TLS1_3_VERSION:
str_version = "TLS 1.3 ";
break;
#endif
default:
sprintf(buffer, "UNKNOWN TLS VERSION ?%04X?", tls_session->info.version);
str_version = buffer;
break;
}
if (tls_session->info.version == SSL3_VERSION ||
tls_session->info.version == TLS1_VERSION) {
switch (tls_session->info.content_type) {
case SSL3_RT_CHANGE_CIPHER_SPEC:
str_content_type = "ChangeCipherSpec";
break;
case SSL3_RT_ALERT:
str_content_type = "Alert";
break;
case SSL3_RT_HANDSHAKE:
str_content_type = "Handshake";
break;
case SSL3_RT_APPLICATION_DATA:
str_content_type = "ApplicationData";
break;
default:
str_content_type = "UnknownContentType";
break;
}
if (tls_session->info.content_type == SSL3_RT_ALERT) {
str_details1 = ", ???";
if (tls_session->info.record_len == 2) {
switch (tls_session->info.alert_level) {
case SSL3_AL_WARNING:
str_details1 = ", warning";
break;
case SSL3_AL_FATAL:
str_details1 = ", fatal";
break;
}
str_details2 = " ???";
switch (tls_session->info.alert_description) {
case SSL3_AD_CLOSE_NOTIFY:
str_details2 = " close_notify";
break;
case SSL3_AD_UNEXPECTED_MESSAGE:
str_details2 = " unexpected_message";
break;
case SSL3_AD_BAD_RECORD_MAC:
str_details2 = " bad_record_mac";
break;
case TLS1_AD_DECRYPTION_FAILED:
str_details2 = " decryption_failed";
break;
case TLS1_AD_RECORD_OVERFLOW:
str_details2 = " record_overflow";
break;
case SSL3_AD_DECOMPRESSION_FAILURE:
str_details2 = " decompression_failure";
break;
case SSL3_AD_HANDSHAKE_FAILURE:
str_details2 = " handshake_failure";
break;
case SSL3_AD_BAD_CERTIFICATE:
str_details2 = " bad_certificate";
break;
case SSL3_AD_UNSUPPORTED_CERTIFICATE:
str_details2 = " unsupported_certificate";
break;
case SSL3_AD_CERTIFICATE_REVOKED:
str_details2 = " certificate_revoked";
break;
case SSL3_AD_CERTIFICATE_EXPIRED:
str_details2 = " certificate_expired";
break;
case SSL3_AD_CERTIFICATE_UNKNOWN:
str_details2 = " certificate_unknown";
break;
case SSL3_AD_ILLEGAL_PARAMETER:
str_details2 = " illegal_parameter";
break;
case TLS1_AD_UNKNOWN_CA:
str_details2 = " unknown_ca";
break;
case TLS1_AD_ACCESS_DENIED:
str_details2 = " access_denied";
break;
case TLS1_AD_DECODE_ERROR:
str_details2 = " decode_error";
break;
case TLS1_AD_DECRYPT_ERROR:
str_details2 = " decrypt_error";
break;
case TLS1_AD_EXPORT_RESTRICTION:
str_details2 = " export_restriction";
break;
case TLS1_AD_PROTOCOL_VERSION:
str_details2 = " protocol_version";
break;
case TLS1_AD_INSUFFICIENT_SECURITY:
str_details2 = " insufficient_security";
break;
case TLS1_AD_INTERNAL_ERROR:
str_details2 = " internal_error";
break;
case TLS1_AD_USER_CANCELLED:
str_details2 = " user_canceled";
break;
case TLS1_AD_NO_RENEGOTIATION:
str_details2 = " no_renegotiation";
break;
}
}
}
if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
str_details1 = "???";
if (tls_session->info.record_len > 0) switch (tls_session->info.handshake_type) {
case SSL3_MT_HELLO_REQUEST:
str_details1 = ", HelloRequest";
break;
case SSL3_MT_CLIENT_HELLO:
str_details1 = ", ClientHello";
break;
case SSL3_MT_SERVER_HELLO:
str_details1 = ", ServerHello";
break;
case SSL3_MT_CERTIFICATE:
str_details1 = ", Certificate";
break;
case SSL3_MT_SERVER_KEY_EXCHANGE:
str_details1 = ", ServerKeyExchange";
break;
case SSL3_MT_CERTIFICATE_REQUEST:
str_details1 = ", CertificateRequest";
break;
case SSL3_MT_SERVER_DONE:
str_details1 = ", ServerHelloDone";
break;
case SSL3_MT_CERTIFICATE_VERIFY:
str_details1 = ", CertificateVerify";
break;
case SSL3_MT_CLIENT_KEY_EXCHANGE:
str_details1 = ", ClientKeyExchange";
break;
case SSL3_MT_FINISHED:
str_details1 = ", Finished";
break;
}
}
}
snprintf(tls_session->info.info_description,
sizeof(tls_session->info.info_description),
"%s %s%s [length %04lx]%s%s\n",
str_write_p, str_version, str_content_type,
(unsigned long)tls_session->info.record_len,
str_details1, str_details2);
request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
ROPTIONAL(RDEBUG2, DEBUG2, "%s", tls_session->info.info_description);
}
static CONF_PARSER cache_config[] = {
{ "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, session_cache_enable), "no" },
{ "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_timeout), "24" },
{ "name", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_id_name), NULL },
{ "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_cache_size), "255" },
{ "persist_dir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_path), NULL },
CONF_PARSER_TERMINATOR
};
static CONF_PARSER verify_config[] = {
{ "skip_if_ocsp_ok", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, verify_skip_if_ocsp_ok), "no" },
{ "tmpdir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_tmp_dir), NULL },
{ "client", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_client_cert_cmd), NULL },
CONF_PARSER_TERMINATOR
};
#ifdef HAVE_OPENSSL_OCSP_H
static CONF_PARSER ocsp_config[] = {
{ "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_enable), "no" },
{ "override_cert_url", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_override_url), "no" },
{ "url", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_url), NULL },
{ "use_nonce", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_use_nonce), "yes" },
{ "timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ocsp_timeout), "yes" },
{ "softfail", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_softfail), "no" },
CONF_PARSER_TERMINATOR
};
#endif
static CONF_PARSER tls_server_config[] = {
{ "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
{ "CA_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_path), NULL },
{ "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
{ "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
{ "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
{ "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
{ "CA_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_file), NULL },
{ "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
{ "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
#ifdef PSK_MAX_IDENTITY_LEN
{ "psk_identity", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_identity), NULL },
{ "psk_hexphrase", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, psk_password), NULL },
{ "psk_query", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_query), NULL },
#endif
{ "dh_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, dh_file), NULL },
{ "random_file", FR_CONF_OFFSET(PW_TYPE_FILE_EXISTS, fr_tls_server_conf_t, random_file), NULL },
{ "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
{ "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
{ "auto_chain", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, auto_chain), "yes" },
{ "disable_single_dh_use", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_single_dh_use), NULL },
{ "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
#ifdef X509_V_FLAG_CRL_CHECK_ALL
{ "check_all_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_all_crl), "no" },
#endif
{ "allow_expired_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, allow_expired_crl), NULL },
{ "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
{ "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
{ "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
{ "require_client_cert", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, require_client_cert), NULL },
#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
#ifndef OPENSSL_NO_ECDH
{ "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
#endif
#endif
#ifdef SSL_OP_NO_TLSv1
{ "disable_tlsv1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1), NULL },
#endif
#ifdef SSL_OP_NO_TLSv1_1
{ "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
#endif
#ifdef SSL_OP_NO_TLSv1_2
{ "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
#endif
{ "cache", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) cache_config },
{ "verify", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) verify_config },
#ifdef HAVE_OPENSSL_OCSP_H
{ "ocsp", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) ocsp_config },
#endif
CONF_PARSER_TERMINATOR
};
static CONF_PARSER tls_client_config[] = {
{ "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
{ "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
{ "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
{ "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
{ "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
{ "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
{ "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
{ "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
{ "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
{ "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
{ "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
{ "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
{ "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
{ "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
{ "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
#ifndef OPENSSL_NO_ECDH
{ "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
#endif
#endif
#ifdef SSL_OP_NO_TLSv1
{ "disable_tlsv1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1), NULL },
#endif
#ifdef SSL_OP_NO_TLSv1_1
{ "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
#endif
#ifdef SSL_OP_NO_TLSv1_2
{ "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
#endif
CONF_PARSER_TERMINATOR
};
/*
* TODO: Check for the type of key exchange * like conf->dh_key
*/
static int load_dh_params(SSL_CTX *ctx, char *file)
{
DH *dh = NULL;
BIO *bio;
if (!file) return 0;
if ((bio = BIO_new_file(file, "r")) == NULL) {
ERROR(LOG_PREFIX ": Unable to open DH file - %s", file);
return -1;
}
dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
BIO_free(bio);
if (!dh) {
WARN(LOG_PREFIX ": Unable to set DH parameters. DH cipher suites may not work!");
WARN(LOG_PREFIX ": Fix this by running the OpenSSL command listed in eap.conf");
return 0;
}
if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
ERROR(LOG_PREFIX ": Unable to set DH parameters");
DH_free(dh);
return -1;
}
DH_free(dh);
return 0;
}
/*
* Print debugging messages, and free data.
*/
static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
{
char buffer[2 * MAX_SESSION_SIZE + 1];
fr_tls_server_conf_t *conf;
tls_session_id(sess, buffer, MAX_SESSION_SIZE);
conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
if (!conf) {
DEBUG(LOG_PREFIX ": Failed to find TLS configuration in session");
return;
}
{
int rv;
char filename[256];
DEBUG2(LOG_PREFIX ": Removing session %s from the cache", buffer);
/* remove session and any cached VPs */
snprintf(filename, sizeof(filename), "%s%c%s.asn1",
conf->session_cache_path, FR_DIR_SEP, buffer);
rv = unlink(filename);
if (rv != 0) {
DEBUG2(LOG_PREFIX ": Could not remove persisted session file %s: %s",
filename, fr_syserror(errno));
}
/* VPs might be absent; might not have been written to disk yet */
snprintf(filename, sizeof(filename), "%s%c%s.vps",
conf->session_cache_path, FR_DIR_SEP, buffer);
unlink(filename);
}
return;
}
static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
{
char buffer[2 * MAX_SESSION_SIZE + 1];
fr_tls_server_conf_t *conf;
unsigned char *sess_blob = NULL;
REQUEST *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
if (!conf) {
RWDEBUG("Failed to find TLS configuration in session");
return 0;
}
tls_session_id(sess, buffer, MAX_SESSION_SIZE);
{
int fd, rv, todo, blob_len;
char filename[256];
unsigned char *p;
RDEBUG2("Serialising session %s, and storing in cache", buffer);
/* find out what length data we need */
blob_len = i2d_SSL_SESSION(sess, NULL);
if (blob_len < 1) {
/* something went wrong */
RWDEBUG("Session serialisation failed, couldn't determine required buffer length");
return 0;
}
/* Do not convert to TALLOC - Thread safety */
/* alloc and convert to ASN.1 */
sess_blob = malloc(blob_len);
if (!sess_blob) {
RWDEBUG("Session serialisation failed, couldn't allocate buffer (%d bytes)", blob_len);
return 0;
}
/* openssl mutates &p */
p = sess_blob;
rv = i2d_SSL_SESSION(sess, &p);
if (rv != blob_len) {
RWDEBUG("Session serialisation failed");
goto error;
}
/* open output file */
snprintf(filename, sizeof(filename), "%s%c%s.asn1",
conf->session_cache_path, FR_DIR_SEP, buffer);
fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
if (fd < 0) {
RERROR("Session serialisation failed, failed opening session file %s: %s",
filename, fr_syserror(errno));
goto error;
}
todo = blob_len;
p = sess_blob;
while (todo > 0) {
rv = write(fd, p, todo);
if (rv < 1) {
RWDEBUG("Failed writing session: %s", fr_syserror(errno));
close(fd);
goto error;
}
p += rv;
todo -= rv;
}
close(fd);
RWDEBUG("Wrote session %s to %s (%d bytes)", buffer, filename, blob_len);
}
error:
free(sess_blob);
return 0;
}
static SSL_SESSION *cbtls_get_session(SSL *ssl, unsigned char *data, int len, int *copy)
{
size_t size;
char buffer[2 * MAX_SESSION_SIZE + 1];
fr_tls_server_conf_t *conf;
TALLOC_CTX *talloc_ctx;
SSL_SESSION *sess = NULL;
unsigned char *sess_data = NULL;
PAIR_LIST *pairlist = NULL;
REQUEST *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
rad_assert(request != NULL);
size = len;
if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
fr_bin2hex(buffer, data, size);
RDEBUG2("Peer requested cached session: %s", buffer);
*copy = 0;
conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
if (!conf) {
RWDEBUG("Failed to find TLS configuration in session");
return NULL;
}
talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
{
int rv, fd, todo;
char filename[256];
unsigned char const **o;
unsigned char **p;
uint8_t *q;
struct stat st;
VALUE_PAIR *vps = NULL;
/* read in the cached VPs from the .vps file */
snprintf(filename, sizeof(filename), "%s%c%s.vps",
conf->session_cache_path, FR_DIR_SEP, buffer);
rv = pairlist_read(talloc_ctx, filename, &pairlist, 1);
if (rv < 0) {
/* not safe to un-persist a session w/o VPs */
RWDEBUG("Failed loading persisted VPs for session %s", buffer);
goto err;
}
/* load the actual SSL session */
snprintf(filename, sizeof(filename), "%s%c%s.asn1", conf->session_cache_path, FR_DIR_SEP, buffer);
fd = open(filename, O_RDONLY);
if (fd < 0) {
RWDEBUG("No persisted session file %s: %s", filename, fr_syserror(errno));
goto err;
}
rv = fstat(fd, &st);
if (rv < 0) {
RWDEBUG("Failed stating persisted session file %s: %s", filename, fr_syserror(errno));
close(fd);
goto err;
}
sess_data = talloc_array(NULL, unsigned char, st.st_size);
if (!sess_data) {
RWDEBUG("Failed allocating buffer for persisted session (%d bytes)", (int) st.st_size);
close(fd);
goto err;
}
q = sess_data;
todo = st.st_size;
while (todo > 0) {
rv = read(fd, q, todo);
if (rv < 1) {
RWDEBUG("Failed reading persisted session: %s", fr_syserror(errno));
close(fd);
goto err;
}
todo -= rv;
q += rv;
}
close(fd);
/*
* OpenSSL mutates what's passed in, so we assign sess_data to q,
* so the value of q gets mutated, and not the value of sess_data.
*
* We then need a pointer to hold &q, but it can't be const, because
* clang complains about lack of consting in nested pointer types.
*
* So we memcpy the value of that pointer, to one that
* does have a const, which we then pass into d2i_SSL_SESSION *sigh*.
*/
q = sess_data;
p = &q;
memcpy(&o, &p, sizeof(o));
sess = d2i_SSL_SESSION(NULL, o, st.st_size);
if (!sess) {
RWDEBUG("Failed loading persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
goto err;
}
/* move the cached VPs into the session */
fr_pair_list_mcopy_by_num(talloc_ctx, &vps, &pairlist->reply, 0, 0, TAG_ANY);
SSL_SESSION_set_ex_data(sess, fr_tls_ex_index_vps, vps);
RWDEBUG("Successfully restored session %s", buffer);
rdebug_pair_list(L_DBG_LVL_2, request, vps, "reply:");
}
err:
if (sess_data) talloc_free(sess_data);
if (pairlist) pairlist_free(&pairlist);
return sess;
}
#ifdef HAVE_OPENSSL_OCSP_H
/** Extract components of OCSP responser URL from a certificate
*
* @param[in] cert to extract URL from.
* @param[out] host_out Portion of the URL (must be freed with free()).
* @param[out] port_out Port portion of the URL (must be freed with free()).
* @param[out] path_out Path portion of the URL (must be freed with free()).
* @param[out] is_https Whether the responder should be contacted using https.
* @return
* - 0 if no valid URL is contained in the certificate.
* - 1 if a URL was found and parsed.
* - -1 if at least one URL was found, but none could be parsed.
*/
static int ocsp_parse_cert_url(X509 *cert, char **host_out, char **port_out,
char **path_out, int *is_https)
{
int i;
bool found_uri = false;
AUTHORITY_INFO_ACCESS *aia;
ACCESS_DESCRIPTION *ad;
aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
ad = sk_ACCESS_DESCRIPTION_value(aia, i);
if (OBJ_obj2nid(ad->method) != NID_ad_OCSP) continue;
if (ad->location->type != GEN_URI) continue;
found_uri = true;
if (OCSP_parse_url((char *) ad->location->d.ia5->data, host_out,
port_out, path_out, is_https)) return 1;
}
return found_uri ? -1 : 0;
}
/*
* This function sends a OCSP request to a defined OCSP responder
* and checks the OCSP response for correctness.
*/
/* Maximum leeway in validity period: default 5 minutes */
#define MAX_VALIDITY_PERIOD (5 * 60)
typedef enum {
OCSP_STATUS_FAILED = 0,
OCSP_STATUS_OK = 1,
OCSP_STATUS_SKIPPED = 2,
} ocsp_status_t;
static ocsp_status_t ocsp_check(REQUEST *request, X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
fr_tls_server_conf_t *conf)
{
OCSP_CERTID *certid;
OCSP_REQUEST *req;
OCSP_RESPONSE *resp = NULL;
OCSP_BASICRESP *bresp = NULL;
char *host = NULL;
char *port = NULL;
char *path = NULL;
char hostheader[1024];
int use_ssl = -1;
long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
BIO *cbio, *bio_out;
ocsp_status_t ocsp_status = OCSP_STATUS_FAILED;
int status;
ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
int reason;
#if OPENSSL_VERSION_NUMBER >= 0x1000003f
OCSP_REQ_CTX *ctx;
int rc;
struct timeval now;
struct timeval when;
#endif
VALUE_PAIR *vp;
/*
* Create OCSP Request
*/
certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
req = OCSP_REQUEST_new();
OCSP_request_add0_id(req, certid);
if (conf->ocsp_use_nonce) OCSP_request_add1_nonce(req, NULL, 8);
/*
* Send OCSP Request and get OCSP Response
*/
/* Get OCSP responder URL */
if (conf->ocsp_override_url) {
char *url;
use_ocsp_url:
memcpy(&url, &conf->ocsp_url, sizeof(url));
/* Reading the libssl src, they do a strdup on the URL, so it could of been const *sigh* */
OCSP_parse_url(url, &host, &port, &path, &use_ssl);
if (!host || !port || !path) {
RWDEBUG("ocsp: Host or port or path missing from configured URL \"%s\". Not doing OCSP", url);
goto skipped;
}
} else {
int ret;
ret = ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
switch (ret) {
case -1:
RWDEBUG("ocsp: Invalid URL in certificate. Not doing OCSP");
break;
case 0:
if (conf->ocsp_url) {
RWDEBUG("ocsp: No OCSP URL in certificate, falling back to configured URL");
goto use_ocsp_url;
}
RWDEBUG("ocsp: No OCSP URL in certificate. Not doing OCSP");
goto skipped;
case 1:
break;
}
}
RDEBUG2("ocsp: Using responder URL \"http://%s:%s%s\"", host, port, path);
/* Check host and port length are sane, then create Host: HTTP header */
if ((strlen(host) + strlen(port) + 2) > sizeof(hostheader)) {
RWDEBUG("ocsp: Host and port too long");
goto skipped;
}
snprintf(hostheader, sizeof(hostheader), "%s:%s", host, port);
/* Setup BIO socket to OCSP responder */
cbio = BIO_new_connect(host);
bio_out = NULL;
if (rad_debug_lvl) {
if (default_log.dst == L_DST_STDOUT) {
bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
} else if (default_log.dst == L_DST_STDERR) {
bio_out = BIO_new_fp(stderr, BIO_NOCLOSE);
}
}
BIO_set_conn_port(cbio, port);
#if OPENSSL_VERSION_NUMBER < 0x1000003f
BIO_do_connect(cbio);
/* Send OCSP request and wait for response */
resp = OCSP_sendreq_bio(cbio, path, req);
if (!resp) {
REDEBUG("ocsp: Couldn't get OCSP response");
ocsp_status = OCSP_STATUS_SKIPPED;
goto ocsp_end;
}
#else
if (conf->ocsp_timeout)
BIO_set_nbio(cbio, 1);
rc = BIO_do_connect(cbio);
if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
REDEBUG("ocsp: Couldn't connect to OCSP responder");
ocsp_status = OCSP_STATUS_SKIPPED;
goto ocsp_end;
}
ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
if (!ctx) {
REDEBUG("ocsp: Couldn't create OCSP request");
ocsp_status = OCSP_STATUS_SKIPPED;
goto ocsp_end;
}
if (!OCSP_REQ_CTX_add1_header(ctx, "Host", hostheader)) {
REDEBUG("ocsp: Couldn't set Host header");
ocsp_status = OCSP_STATUS_SKIPPED;
goto ocsp_end;
}
if (!OCSP_REQ_CTX_set1_req(ctx, req)) {
REDEBUG("ocsp: Couldn't add data to OCSP request");
ocsp_status = OCSP_STATUS_SKIPPED;
goto ocsp_end;
}
gettimeofday(&when, NULL);
when.tv_sec += conf->ocsp_timeout;
do {
rc = OCSP_sendreq_nbio(&resp, ctx);
if (conf->ocsp_timeout) {
gettimeofday(&now, NULL);
if (!timercmp(&now, &when, <))
break;
}
} while ((rc == -1) && BIO_should_retry(cbio));
if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
REDEBUG("ocsp: Response timed out");
ocsp_status = OCSP_STATUS_SKIPPED;
goto ocsp_end;
}
OCSP_REQ_CTX_free(ctx);
if (rc == 0) {
REDEBUG("ocsp: Couldn't get OCSP response");
ocsp_status = OCSP_STATUS_SKIPPED;
goto ocsp_end;
}
#endif
/* Verify OCSP response status */
status = OCSP_response_status(resp);
if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
REDEBUG("ocsp: Response status: %s", OCSP_response_status_str(status));
goto ocsp_end;
}
bresp = OCSP_response_get1_basic(resp);
if (conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
REDEBUG("ocsp: Response has wrong nonce value");
goto ocsp_end;
}
if (OCSP_basic_verify(bresp, NULL, store, 0)!=1){
REDEBUG("ocsp: Couldn't verify OCSP basic response");
goto ocsp_end;
}
/* Verify OCSP cert status */
if (!OCSP_resp_find_status(bresp, certid, &status, &reason, &rev, &thisupd, &nextupd)) {
REDEBUG("ocsp: No Status found");
goto ocsp_end;
}
if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
if (bio_out) {
BIO_puts(bio_out, "WARNING: Status times invalid.\n");
ERR_print_errors(bio_out);
}
goto ocsp_end;
}
if (bio_out) {
BIO_puts(bio_out, "\tThis Update: ");
ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
BIO_puts(bio_out, "\n");
if (nextupd) {
BIO_puts(bio_out, "\tNext Update: ");
ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
BIO_puts(bio_out, "\n");
}
}
switch (status) {
case V_OCSP_CERTSTATUS_GOOD:
RDEBUG2("ocsp: Cert status: good");
vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
vp->vp_integer = 1; /* yes */
ocsp_status = OCSP_STATUS_OK;
break;
default:
/* REVOKED / UNKNOWN */
REDEBUG("ocsp: Cert status: %s", OCSP_cert_status_str(status));
if (reason != -1) REDEBUG("ocsp: Reason: %s", OCSP_crl_reason_str(reason));
if (bio_out) {
BIO_puts(bio_out, "\tRevocation Time: ");
ASN1_GENERALIZEDTIME_print(bio_out, rev);
BIO_puts(bio_out, "\n");
}
break;
}
ocsp_end:
/* Free OCSP Stuff */
OCSP_REQUEST_free(req);
OCSP_RESPONSE_free(resp);
free(host);
free(port);
free(path);
BIO_free_all(cbio);
if (bio_out) BIO_free(bio_out);
OCSP_BASICRESP_free(bresp);
switch (ocsp_status) {
case OCSP_STATUS_OK:
RDEBUG2("ocsp: Certificate is valid");
break;
case OCSP_STATUS_SKIPPED:
skipped:
vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
vp->vp_integer = 2; /* skipped */
if (conf->ocsp_softfail) {
RWDEBUG("ocsp: Unable to check certificate, assuming it's valid");
RWDEBUG("ocsp: This may be insecure");
/* Remove OpenSSL errors from queue or handshake will fail */
while (ERR_get_error());
ocsp_status = OCSP_STATUS_SKIPPED;
} else {
REDEBUG("ocsp: Unable to check certificate, failing");
ocsp_status = OCSP_STATUS_FAILED;
}
break;
default:
vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
vp->vp_integer = 0; /* no */
REDEBUG("ocsp: Certificate has been expired/revoked");
break;
}
return ocsp_status;
}
#endif /* HAVE_OPENSSL_OCSP_H */
/*
* For creating certificate attributes.
*/
static char const *cert_attr_names[8][2] = {
{ "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
{ "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
{ "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
{ "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
{ "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
{ "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" },
{ "TLS-Client-Cert-Subject-Alt-Name-Dns", "TLS-Cert-Subject-Alt-Name-Dns" },
{ "TLS-Client-Cert-Subject-Alt-Name-Upn", "TLS-Cert-Subject-Alt-Name-Upn" }
};
#define FR_TLS_SERIAL (0)
#define FR_TLS_EXPIRATION (1)
#define FR_TLS_SUBJECT (2)
#define FR_TLS_ISSUER (3)
#define FR_TLS_CN (4)
#define FR_TLS_SAN_EMAIL (5)
#define FR_TLS_SAN_DNS (6)
#define FR_TLS_SAN_UPN (7)
/*
* Before trusting a certificate, you must make sure that the
* certificate is 'valid'. There are several steps that your
* application can take in determining if a certificate is
* valid. Commonly used steps are:
*
* 1.Verifying the certificate's signature, and verifying that
* the certificate has been issued by a trusted Certificate
* Authority.
*
* 2.Verifying that the certificate is valid for the present date
* (i.e. it is being presented within its validity dates).
*
* 3.Verifying that the certificate has not been revoked by its
* issuing Certificate Authority, by checking with respect to a
* Certificate Revocation List (CRL).
*
* 4.Verifying that the credentials presented by the certificate
* fulfill additional requirements specific to the application,
* such as with respect to access control lists or with respect
* to OCSP (Online Certificate Status Processing).
*
* NOTE: This callback will be called multiple times based on the
* depth of the root certificate chain
*/
int cbtls_verify(int ok, X509_STORE_CTX *ctx)
{
char subject[1024]; /* Used for the subject name */
char issuer[1024]; /* Used for the issuer name */
char attribute[1024];
char value[1024];
char common_name[1024];
char cn_str[1024];
char buf[64];
X509 *client_cert;
#if OPENSSL_VERSION_NUMBER < 0x10100000L
X509_CINF *client_inf;
#endif
STACK_OF(X509_EXTENSION) *ext_list;
SSL *ssl;
int err, depth, lookup, loc;
fr_tls_server_conf_t *conf;
int my_ok = ok;
ASN1_INTEGER *sn = NULL;
ASN1_TIME *asn_time = NULL;
VALUE_PAIR **certs;
char **identity;
#ifdef HAVE_OPENSSL_OCSP_H
X509_STORE *ocsp_store = NULL;
X509 *issuer_cert;
bool do_verify = false;
#endif
VALUE_PAIR *vp;
TALLOC_CTX *talloc_ctx;
REQUEST *request;
client_cert = X509_STORE_CTX_get_current_cert(ctx);
err = X509_STORE_CTX_get_error(ctx);
depth = X509_STORE_CTX_get_error_depth(ctx);
lookup = depth;
/*
* Log client/issuing cert. If there's an error, log
* issuing cert.
*/
if ((lookup > 1) && !my_ok) lookup = 1;
/*
* Retrieve the pointer to the SSL of the connection currently treated
* and the application specific data stored into the SSL object.
*/
ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
if (!conf) return 1;
request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
rad_assert(request != NULL);
certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, fr_tls_ex_index_certs);
identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
#ifdef HAVE_OPENSSL_OCSP_H
ocsp_store = conf->ocsp_store;
#endif
talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
/*
* Get the Serial Number
*/
buf[0] = '\0';
sn = X509_get_serialNumber(client_cert);
RDEBUG2("Creating attributes from certificate OIDs");
RINDENT();
/*
* For this next bit, we create the attributes *only* if
* we're at the client or issuing certificate, AND we
* have a user identity. i.e. we don't create the
* attributes for RadSec connections.
*/
if (certs && identity &&
(lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
char *p = buf;
int i;
for (i = 0; i < sn->length; i++) {
sprintf(p, "%02x", (unsigned int)sn->data[i]);
p += 2;
}
vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
}
/*
* Get the Expiration Date
*/
buf[0] = '\0';
asn_time = X509_get_notAfter(client_cert);
if (certs && identity && (lookup <= 1) && asn_time &&
(asn_time->length < (int) sizeof(buf))) {
memcpy(buf, (char*) asn_time->data, asn_time->length);
buf[asn_time->length] = '\0';
vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
}
/*
* Get the Subject & Issuer
*/
subject[0] = issuer[0] = '\0';
X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
sizeof(subject));
subject[sizeof(subject) - 1] = '\0';
if (certs && identity && (lookup <= 1) && subject[0]) {
vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
}
X509_NAME_oneline(X509_get_issuer_name(client_cert), issuer,
sizeof(issuer));
issuer[sizeof(issuer) - 1] = '\0';
if (certs && identity && (lookup <= 1) && issuer[0]) {
vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
}
/*
* Get the Common Name, if there is a subject.
*/
X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
NID_commonName, common_name, sizeof(common_name));
common_name[sizeof(common_name) - 1] = '\0';
if (certs && identity && (lookup <= 1) && common_name[0] && subject[0]) {
vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
}
/*
* Get the RFC822 Subject Alternative Name
*/
loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
if (certs && (lookup <= 1) && (loc >= 0)) {
X509_EXTENSION *ext = NULL;
GENERAL_NAMES *names = NULL;
int i;
if ((ext = X509_get_ext(client_cert, loc)) &&
(names = X509V3_EXT_d2i(ext))) {
for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
switch (name->type) {
#ifdef GEN_EMAIL
case GEN_EMAIL:
vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
(char *) ASN1_STRING_data(name->d.rfc822Name), T_OP_SET);
rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
break;
#endif /* GEN_EMAIL */
#ifdef GEN_DNS
case GEN_DNS:
vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_DNS][lookup],
(char *) ASN1_STRING_data(name->d.dNSName), T_OP_SET);
rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
break;
#endif /* GEN_DNS */
#ifdef GEN_OTHERNAME
case GEN_OTHERNAME:
/* look for a MS UPN */
if (NID_ms_upn == OBJ_obj2nid(name->d.otherName->type_id)) {
/* we've got a UPN - Must be ASN1-encoded UTF8 string */
if (name->d.otherName->value->type == V_ASN1_UTF8STRING) {
vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_UPN][lookup],
(char *) ASN1_STRING_data(name->d.otherName->value->value.utf8string), T_OP_SET);
rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
break;
} else {
RWARN("Invalid UPN in Subject Alt Name (should be UTF-8)");
break;
}
}
break;
#endif /* GEN_OTHERNAME */
default:
/* XXX TODO handle other SAN types */
break;
}
}
}
if (names != NULL)
sk_GENERAL_NAME_free(names);
}
/*
* If the CRL has expired, that might still be OK.
*/
if (!my_ok &&
(conf->allow_expired_crl) &&
(err == X509_V_ERR_CRL_HAS_EXPIRED)) {
my_ok = 1;
X509_STORE_CTX_set_error( ctx, 0 );
}
if (!my_ok) {
char const *p = X509_verify_cert_error_string(err);
RERROR("SSL says error %d : %s", err, p);
REXDENT();
return my_ok;
}
if (lookup == 0) {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
ext_list = X509_get0_extensions(client_cert);
#else
client_inf = client_cert->cert_info;
ext_list = client_inf->extensions;
#endif
} else {
ext_list = NULL;
}
/*
* Grab the X509 extensions, and create attributes out of them.
* For laziness, we re-use the OpenSSL names
*/
if (certs && (sk_X509_EXTENSION_num(ext_list) > 0)) {
int i, len;
char *p;
BIO *out;
out = BIO_new(BIO_s_mem());
strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
ASN1_OBJECT *obj;
X509_EXTENSION *ext;
ext = sk_X509_EXTENSION_value(ext_list, i);
obj = X509_EXTENSION_get_object(ext);
i2a_ASN1_OBJECT(out, obj);
len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
if (len <= 0) continue;
attribute[16 + len] = '\0';
for (p = attribute + 16; *p != '\0'; p++) {
if (*p == ' ') *p = '-';
}
X509V3_EXT_print(out, ext, 0, 0);
len = BIO_read(out, value , sizeof(value) - 1);
if (len <= 0) continue;
value[len] = '\0';
vp = fr_pair_make(talloc_ctx, certs, attribute, value, T_OP_ADD);
if (!vp) {
RDEBUG3("Skipping %s += '%s'. Please check that both the "
"attribute and value are defined in the dictionaries",
attribute, value);
} else {
/*
* rdebug_pair_list indents (so pre REXDENT())
*/
REXDENT();
rdebug_pair_list(L_DBG_LVL_2, request, vp, NULL);
RINDENT();
}
}
BIO_free_all(out);
}
REXDENT();
switch (X509_STORE_CTX_get_error(ctx)) {
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
RERROR("issuer=%s", issuer);
break;
case X509_V_ERR_CERT_NOT_YET_VALID:
case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
RERROR("notBefore=");
#if 0
ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
#endif
break;
case X509_V_ERR_CERT_HAS_EXPIRED:
case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
RERROR("notAfter=");
#if 0
ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
#endif
break;
}
/*
* If we're at the actual client cert, apply additional
* checks.
*/
if (depth == 0) {
/*
* If the conf tells us to, check cert issuer
* against the specified value and fail
* verification if they don't match.
*/
if (conf->check_cert_issuer &&
(strcmp(issuer, conf->check_cert_issuer) != 0)) {
AUTH(LOG_PREFIX ": Certificate issuer (%s) does not match specified value (%s)!",
issuer, conf->check_cert_issuer);
my_ok = 0;
}
/*
* If the conf tells us to, check the CN in the
* cert against xlat'ed value, but only if the
* previous checks passed.
*/
if (my_ok && conf->check_cert_cn) {
if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
/* if this fails, fail the verification */
my_ok = 0;
} else {
RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
if (strcmp(cn_str, common_name) != 0) {
AUTH(LOG_PREFIX ": Certificate CN (%s) does not match specified value (%s)!",
common_name, cn_str);
my_ok = 0;
}
}
} /* check_cert_cn */
#ifdef HAVE_OPENSSL_OCSP_H
if (my_ok) {
/*
* No OCSP, allow external verification.
*/
if (!conf->ocsp_enable) {
do_verify = true;
} else {
RDEBUG2("Starting OCSP Request");
if ((X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert) != 1) ||
!issuer_cert) {
/*
* Allow for external verify.
*/
RERROR("Couldn't get issuer_cert for %s", common_name);
do_verify = true;
} else {
/*
* Do the full OCSP checks.
*
* If they fail, don't run the external verify. We don't want
* to allow admins to force authentication success for bad
* certificates.
*
* If the OCSP checks succeed, check whether we still want to
* run the external verification routine. If it's marked as
* "skip verify on OK", then we don't do verify.
*/
my_ok = ocsp_check(request, ocsp_store, issuer_cert, client_cert, conf);
if (my_ok != OCSP_STATUS_FAILED) {
do_verify = !conf->verify_skip_if_ocsp_ok;
}
}
}
}
#endif
if ((my_ok != OCSP_STATUS_FAILED)
#ifdef HAVE_OPENSSL_OCSP_H
&& do_verify
#endif
) while (conf->verify_client_cert_cmd) {
char filename[256];
int fd;
FILE *fp;
snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
conf->verify_tmp_dir, main_config.name);
fd = mkstemp(filename);
if (fd < 0) {
RDEBUG("Failed creating file in %s: %s",
conf->verify_tmp_dir, fr_syserror(errno));
break;
}
fp = fdopen(fd, "w");
if (!fp) {
close(fd);
RDEBUG("Failed opening file %s: %s",
filename, fr_syserror(errno));
break;
}
if (!PEM_write_X509(fp, client_cert)) {
fclose(fp);
RDEBUG("Failed writing certificate to file");
goto do_unlink;
}
fclose(fp);
if (!pair_make_request("TLS-Client-Cert-Filename",
filename, T_OP_SET)) {
RDEBUG("Failed creating TLS-Client-Cert-Filename");
goto do_unlink;
}
RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
if (radius_exec_program(request, NULL, 0, NULL, request, conf->verify_client_cert_cmd,
request->packet->vps,
true, true, EXEC_TIMEOUT) != 0) {
AUTH(LOG_PREFIX ": Certificate CN (%s) fails external verification!", common_name);
my_ok = 0;
} else {
RDEBUG("Client certificate CN %s passed external validation", common_name);
}
do_unlink:
unlink(filename);
break;
}
} /* depth == 0 */
if (certs && request && !my_ok) {
fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
}
if (RDEBUG_ENABLED3) {
RDEBUG3("chain-depth : %d", depth);
RDEBUG3("error : %d", err);
if (identity) RDEBUG3("identity : %s", *identity);
RDEBUG3("common name : %s", common_name);
RDEBUG3("subject : %s", subject);
RDEBUG3("issuer : %s", issuer);
RDEBUG3("verify return : %d", my_ok);
}
return (my_ok != 0);
}
#ifdef HAVE_OPENSSL_OCSP_H
/*
* Create Global X509 revocation store and use it to verify
* OCSP responses
*
* - Load the trusted CAs
* - Load the trusted issuer certificates
*/
static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
{
X509_STORE *store = NULL;
store = X509_STORE_new();
/* Load the CAs we trust */
if (conf->ca_file || conf->ca_path)
if (!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
tls_error_log(NULL, "Error reading Trusted root CA list \"%s\"", conf->ca_file);
return NULL;
}
#ifdef X509_V_FLAG_CRL_CHECK
if (conf->check_crl)
X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
#endif
#ifdef X509_V_FLAG_CRL_CHECK_ALL
if (conf->check_all_crl)
X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK_ALL);
#endif
return store;
}
#endif /* HAVE_OPENSSL_OCSP_H */
#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
#ifndef OPENSSL_NO_ECDH
static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve, bool disable_single_dh_use)
{
int nid;
EC_KEY *ecdh;
if (!ecdh_curve || !*ecdh_curve) return 0;
nid = OBJ_sn2nid(ecdh_curve);
if (!nid) {
ERROR(LOG_PREFIX ": Unknown ecdh_curve \"%s\"", ecdh_curve);
return -1;
}
ecdh = EC_KEY_new_by_curve_name(nid);
if (!ecdh) {
ERROR(LOG_PREFIX ": Unable to create new curve \"%s\"", ecdh_curve);
return -1;
}
SSL_CTX_set_tmp_ecdh(ctx, ecdh);
if (!disable_single_dh_use) {
SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
}
EC_KEY_free(ecdh);
return 0;
}
#endif
#endif
/*
* DIE OPENSSL DIE DIE DIE
*
* What a palaver, just to free some data attached the
* session. We need to do this because the "remove" callback
* is called when refcount > 0 sometimes, if another thread
* is using the session
*/
static void sess_free_vps(UNUSED void *parent, void *data_ptr,
UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
UNUSED long argl, UNUSED void *argp)
{
VALUE_PAIR *vp = data_ptr;
if (!vp) return;
DEBUG2(LOG_PREFIX ": Freeing cached session VPs");
fr_pair_list_free(&vp);
}
static void sess_free_certs(UNUSED void *parent, void *data_ptr,
UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
UNUSED long argl, UNUSED void *argp)
{
VALUE_PAIR **certs = data_ptr;
if (!certs) return;
DEBUG2(LOG_PREFIX ": Freeing cached session Certificates");
fr_pair_list_free(certs);
}
/** Add all the default ciphers and message digests reate our context.
*
* This should be called exactly once from main, before reading the main config
* or initialising any modules.
*/
void tls_global_init(void)
{
SSL_load_error_strings(); /* readable error messages (examples show call before library_init) */
SSL_library_init(); /* initialize library */
OpenSSL_add_all_algorithms(); /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
OPENSSL_config(NULL);
/*
* Initialize the index for the certificates.
*/
fr_tls_ex_index_certs = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_certs);
}
#ifdef ENABLE_OPENSSL_VERSION_CHECK
/** Check for vulnerable versions of libssl
*
* @param acknowledged The highest CVE number a user has confirmed is not present in the system's libssl.
* @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
*/
int tls_global_version_check(char const *acknowledged)
{
uint64_t v;
bool bad = false;
size_t i;
if (strcmp(acknowledged, "yes") == 0) return 0;
/* Check for bad versions */
v = (uint64_t) SSLeay();
for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
libssl_defect_t *defect = &libssl_defects[i];
if ((v >= defect->low) && (v <= defect->high)) {
/*
* If the CVE is acknowledged, allow it.
*/
if (!bad && (strcmp(acknowledged, defect->id) == 0)) return 0;
ERROR("Refusing to start with libssl version %s (in range %s)",
ssl_version(), ssl_version_range(defect->low, defect->high));
ERROR("Security advisory %s (%s)", defect->id, defect->name);
ERROR("%s", defect->comment);
/*
* Only warn about the first one...
*/
if (!bad) {
INFO("Once you have verified libssl has been correctly patched, "
"set security.allow_vulnerable_openssl = '%s'", defect->id);
bad = true;
}
}
}
if (bad) return -1;
return 0;
}
#endif
/** Free any memory alloced by libssl
*
*/
void tls_global_cleanup(void)
{
ERR_remove_state(0);
ENGINE_cleanup();
CONF_modules_unload(1);
ERR_free_strings();
EVP_cleanup();
CRYPTO_cleanup_all_ex_data();
}
/** Create SSL context
*
* - Load the trusted CAs
* - Load the Private key & the certificate
* - Set the Context options & Verify options
*/
SSL_CTX *tls_init_ctx(fr_tls_server_conf_t *conf, int client)
{
SSL_CTX *ctx;
X509_STORE *certstore;
int verify_mode = SSL_VERIFY_NONE;
int ctx_options = 0;
int ctx_tls_versions = 0;
int type;
/*
* SHA256 is in all versions of OpenSSL, but isn't
* initialized by default. It's needed for WiMAX
* certificates.
*/
#ifdef HAVE_OPENSSL_EVP_SHA256
EVP_add_digest(EVP_sha256());
#endif
ctx = SSL_CTX_new(SSLv23_method()); /* which is really "all known SSL / TLS methods". Idiots. */
if (!ctx) {
tls_error_log(NULL, "Failed creating TLS context");
return NULL;
}
/*
* Save the config on the context so that callbacks which
* only get SSL_CTX* e.g. session persistence, can get it
*/
SSL_CTX_set_app_data(ctx, conf);
/*
* Identify the type of certificates that needs to be loaded
*/
if (conf->file_type) {
type = SSL_FILETYPE_PEM;
} else {
type = SSL_FILETYPE_ASN1;
}
/*
* Set the password to load private key
*/
if (conf->private_key_password) {
#ifdef __APPLE__
/*
* We don't want to put the private key password in eap.conf, so check
* for our special string which indicates we should get the password
* programmatically.
*/
char const* special_string = "Apple:UseCertAdmin";
if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
char cmd[256];
char *password;
long const max_password_len = 128;
snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
conf->private_key_file);
DEBUG2(LOG_PREFIX ": Getting private key passphrase using command \"%s\"", cmd);
FILE* cmd_pipe = popen(cmd, "r");
if (!cmd_pipe) {
ERROR(LOG_PREFIX ": %s command failed: Unable to get private_key_password", cmd);
ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
return NULL;
}
rad_const_free(conf->private_key_password);
password = talloc_array(conf, char, max_password_len);
if (!password) {
ERROR(LOG_PREFIX ": Can't allocate space for private_key_password");
ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
pclose(cmd_pipe);
return NULL;
}
fgets(password, max_password_len, cmd_pipe);
pclose(cmd_pipe);
/* Get rid of newline at end of password. */
password[strlen(password) - 1] = '\0';
DEBUG3(LOG_PREFIX ": Password from command = \"%s\"", password);
conf->private_key_password = password;
}
#endif
{
char *password;
memcpy(&password, &conf->private_key_password, sizeof(password));
SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
}
}
#ifdef PSK_MAX_IDENTITY_LEN
if (!client) {
/*
* No dynamic query exists. There MUST be a
* statically configured identity and password.
*/
if (conf->psk_query && !*conf->psk_query) {
ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be empty");
return NULL;
}
/*
* Set the callback only if we can check things.
*/
if (conf->psk_identity || conf->psk_query) {
SSL_CTX_set_psk_server_callback(ctx, psk_server_callback);
}
} else if (conf->psk_query) {
ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be used for outgoing connections");
return NULL;
}
/*
* Now check that if PSK is being used, the config is valid.
*/
if ((conf->psk_identity && !conf->psk_password) ||
(!conf->psk_identity && conf->psk_password) ||
(conf->psk_identity && !*conf->psk_identity) ||
(conf->psk_password && !*conf->psk_password)) {
ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_identity or psk_password are empty");
return NULL;
}
if (conf->psk_identity) {
size_t psk_len, hex_len;
uint8_t buffer[PSK_MAX_PSK_LEN];
if (conf->certificate_file ||
conf->private_key_password || conf->private_key_file ||
conf->ca_file || conf->ca_path) {
ERROR(LOG_PREFIX ": When PSKs are used, No certificate configuration is permitted");
return NULL;
}
if (client) {
SSL_CTX_set_psk_client_callback(ctx,
psk_client_callback);
}
psk_len = strlen(conf->psk_password);
if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
ERROR(LOG_PREFIX ": psk_hexphrase is too long (max %d)", PSK_MAX_PSK_LEN);
return NULL;
}
/*
* Check the password now, so that we don't have
* errors at run-time.
*/
hex_len = fr_hex2bin(buffer, sizeof(buffer), conf->psk_password, psk_len);
if (psk_len != (2 * hex_len)) {
ERROR(LOG_PREFIX ": psk_hexphrase is not all hex");
return NULL;
}
goto post_ca;
}
#else
(void) client; /* -Wunused */
#endif
/*
* Load our keys and certificates
*
* If certificates are of type PEM then we can make use
* of cert chain authentication using openssl api call
* SSL_CTX_use_certificate_chain_file. Please see how
* the cert chain needs to be given in PEM from
* openSSL.org
*/
if (!conf->certificate_file) goto load_ca;
if (type == SSL_FILETYPE_PEM) {
if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
tls_error_log(NULL, "Failed reading certificate file \"%s\"",
conf->certificate_file);
return NULL;
}
} else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
tls_error_log(NULL, "Failed reading certificate file \"%s\"",
conf->certificate_file);
return NULL;
}
/* Load the CAs we trust */
load_ca:
if (conf->ca_file || conf->ca_path) {
if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
tls_error_log(NULL, "Failed reading Trusted root CA list \"%s\"",
conf->ca_file);
return NULL;
}
}
if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
if (conf->private_key_file) {
if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
tls_error_log(NULL, "Failed reading private key file \"%s\"",
conf->private_key_file);
return NULL;
}
/*
* Check if the loaded private key is the right one
*/
if (!SSL_CTX_check_private_key(ctx)) {
ERROR(LOG_PREFIX ": Private key does not match the certificate public key");
return NULL;
}
}
#ifdef PSK_MAX_IDENTITY_LEN
post_ca:
#endif
/*
* We never want SSLv2 or SSLv3.
*/
ctx_options |= SSL_OP_NO_SSLv2;
ctx_options |= SSL_OP_NO_SSLv3;
/*
* As of 3.0.5, we always allow TLSv1.1 and TLSv1.2.
* Though they can be *globally* disabled if necessary.x
*/
#ifdef SSL_OP_NO_TLSv1
if (conf->disable_tlsv1) ctx_options |= SSL_OP_NO_TLSv1;
ctx_tls_versions |= SSL_OP_NO_TLSv1;
#endif
#ifdef SSL_OP_NO_TLSv1_1
if (conf->disable_tlsv1_1) ctx_options |= SSL_OP_NO_TLSv1_1;
ctx_tls_versions |= SSL_OP_NO_TLSv1_1;
#endif
#ifdef SSL_OP_NO_TLSv1_2
if (conf->disable_tlsv1_2) ctx_options |= SSL_OP_NO_TLSv1_2;
ctx_tls_versions |= SSL_OP_NO_TLSv1_2;
#endif
if ((ctx_options & ctx_tls_versions) == ctx_tls_versions) {
ERROR(LOG_PREFIX ": You have disabled all available TLS versions. EAP will not work");
return NULL;
}
#ifdef SSL_OP_NO_TICKET
ctx_options |= SSL_OP_NO_TICKET;
#endif
if (!conf->disable_single_dh_use) {
/*
* SSL_OP_SINGLE_DH_USE must be used in order to prevent
* small subgroup attacks and forward secrecy. Always
* using SSL_OP_SINGLE_DH_USE has an impact on the
* computer time needed during negotiation, but it is not
* very large.
*/
ctx_options |= SSL_OP_SINGLE_DH_USE;
}
/*
* SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
* in Windows Vista client.
* http://www.openssl.org/~bodo/tls-cbc.txt
* http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
*/
ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
SSL_CTX_set_options(ctx, ctx_options);
/*
* TODO: Set the RSA & DH
* SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
* SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
*/
/*
* set the message callback to identify the type of
* message. For every new session, there can be a
* different callback argument.
*
* SSL_CTX_set_msg_callback(ctx, cbtls_msg);
*/
/*
* Set eliptical curve crypto configuration.
*/
#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
#ifndef OPENSSL_NO_ECDH
if (set_ecdh_curve(ctx, conf->ecdh_curve, conf->disable_single_dh_use) < 0) {
return NULL;
}
#endif
#endif
/*
* OpenSSL will automatically create certificate chains,
* unless we tell it to not do that. The problem is that
* it sometimes gets the chains right from a certificate
* signature view, but wrong from the clients view.
*/
if (!conf->auto_chain) {
SSL_CTX_set_mode(ctx, SSL_MODE_NO_AUTO_CHAIN);
}
/* Set Info callback */
SSL_CTX_set_info_callback(ctx, cbtls_info);
/*
* Callbacks, etc. for session resumption.
*/
if (/*conf->session_cache_enable*/0) {
/*
* Cache sessions on disk if requested.
*/
if (conf->session_cache_path) {
SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
}
SSL_CTX_set_quiet_shutdown(ctx, 1);
if (fr_tls_ex_index_vps < 0)
fr_tls_ex_index_vps = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
}
/*
* Check the certificates for revocation.
*/
#ifdef X509_V_FLAG_CRL_CHECK
if (conf->check_crl) {
certstore = SSL_CTX_get_cert_store(ctx);
if (certstore == NULL) {
tls_error_log(NULL, "Error reading Certificate Store");
return NULL;
}
X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
#ifdef X509_V_FLAG_CRL_CHECK_ALL
if (conf->check_all_crl)
X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK_ALL);
#endif
}
#endif
/*
* Set verify modes
* Always verify the peer certificate
*/
verify_mode |= SSL_VERIFY_PEER;
verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
verify_mode |= SSL_VERIFY_CLIENT_ONCE;
SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
if (conf->verify_depth) {
SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
}
/* Load randomness */
if (conf->random_file) {
if (!(RAND_load_file(conf->random_file, 1024*10))) {
tls_error_log(NULL, "Failed loading randomness");
return NULL;
}
}
/*
* Set the cipher list if we were told to
*/
if (conf->cipher_list) {
if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
tls_error_log(NULL, "Failed setting cipher list");
return NULL;
}
}
/*
* Setup session caching
*/
if (/*conf->session_cache_enable*/0) {
/*
* Create a unique context Id per EAP-TLS configuration.
*/
if (conf->session_id_name) {
snprintf(conf->session_context_id, sizeof(conf->session_context_id),
"FR eap %s", conf->session_id_name);
} else {
snprintf(conf->session_context_id, sizeof(conf->session_context_id),
"FR eap %p", conf);
}
/*
* Cache it, and DON'T auto-clear it.
*/
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
SSL_CTX_set_session_id_context(ctx,
(unsigned char *) conf->session_context_id,
(unsigned int) strlen(conf->session_context_id));
/*
* Our timeout is in hours, this is in seconds.
*/
SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
/*
* Set the maximum number of entries in the
* session cache.
*/
SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
} else {
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
}
return ctx;
}
/*
* Free TLS client/server config
* Should not be called outside this code, as a callback is
* added to automatically free the data when the CONF_SECTION
* is freed.
*/
static int _tls_server_conf_free(fr_tls_server_conf_t *conf)
{
if (conf->ctx) SSL_CTX_free(conf->ctx);
#ifdef HAVE_OPENSSL_OCSP_H
if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
conf->ocsp_store = NULL;
#endif
#ifndef NDEBUG
memset(conf, 0, sizeof(*conf));
#endif
return 0;
}
static fr_tls_server_conf_t *tls_server_conf_alloc(TALLOC_CTX *ctx)
{
fr_tls_server_conf_t *conf;
conf = talloc_zero(ctx, fr_tls_server_conf_t);
if (!conf) {
ERROR(LOG_PREFIX ": Out of memory");
return NULL;
}
talloc_set_destructor(conf, _tls_server_conf_free);
return conf;
}
fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
{
fr_tls_server_conf_t *conf;
/*
* If cs has already been parsed there should be a cached copy
* of conf already stored, so just return that.
*/
conf = cf_data_find(cs, "tls-conf");
if (conf) {
DEBUG(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
return conf;
}
conf = tls_server_conf_alloc(cs);
if (cf_section_parse(cs, conf, tls_server_config) < 0) {
error:
talloc_free(conf);
return NULL;
}
/*
* Save people from their own stupidity.
*/
if (conf->fragment_size < 100) conf->fragment_size = 100;
if (!conf->private_key_file) {
ERROR(LOG_PREFIX ": TLS Server requires a private key file");
goto error;
}
if (!conf->certificate_file) {
ERROR(LOG_PREFIX ": TLS Server requires a certificate file");
goto error;
}
/*
* Initialize TLS
*/
conf->ctx = tls_init_ctx(conf, 0);
if (conf->ctx == NULL) {
goto error;
}
#ifdef HAVE_OPENSSL_OCSP_H
/*
* Initialize OCSP Revocation Store
*/
if (conf->ocsp_enable) {
conf->ocsp_store = init_revocation_store(conf);
if (conf->ocsp_store == NULL) goto error;
}
#endif /*HAVE_OPENSSL_OCSP_H*/
{
char *dh_file;
memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
if (load_dh_params(conf->ctx, dh_file) < 0) {
goto error;
}
}
if (conf->verify_tmp_dir) {
if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
ERROR(LOG_PREFIX ": Failed changing permissions on %s: %s",
conf->verify_tmp_dir, fr_syserror(errno));
goto error;
}
}
if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
ERROR(LOG_PREFIX ": You MUST set the verify directory in order to use verify_client_cmd");
goto error;
}
#ifdef SSL_OP_NO_TLSv1_2
/*
* OpenSSL 1.0.1f and 1.0.1g get the MS-MPPE keys wrong.
*/
#if (OPENSSL_VERSION_NUMBER >= 0x10010060L) && (OPENSSL_VERSION_NUMBER < 0x10010060L)
conf->disable_tlsv1_2 = true;
WARN(LOG_PREFIX ": Disabling TLSv1.2 due to OpenSSL bugs");
#endif
#endif
/*
* Cache conf in cs in case we're asked to parse this again.
*/
cf_data_add(cs, "tls-conf", conf, NULL);
return conf;
}
fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
{
fr_tls_server_conf_t *conf;
conf = cf_data_find(cs, "tls-conf");
if (conf) {
DEBUG2(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
return conf;
}
conf = tls_server_conf_alloc(cs);
if (cf_section_parse(cs, conf, tls_client_config) < 0) {
error:
talloc_free(conf);
return NULL;
}
/*
* Save people from their own stupidity.
*/
if (conf->fragment_size < 100) conf->fragment_size = 100;
/*
* Initialize TLS
*/
conf->ctx = tls_init_ctx(conf, 1);
if (conf->ctx == NULL) {
goto error;
}
{
char *dh_file;
memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
if (load_dh_params(conf->ctx, dh_file) < 0) {
goto error;
}
}
cf_data_add(cs, "tls-conf", conf, NULL);
return conf;
}
int tls_success(tls_session_t *ssn, REQUEST *request)
{
VALUE_PAIR *vp, *vps = NULL;
fr_tls_server_conf_t *conf;
TALLOC_CTX *talloc_ctx;
conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
rad_assert(conf != NULL);
talloc_ctx = SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_TALLOC);
/*
* If there's no session resumption, delete the entry
* from the cache. This means either it's disabled
* globally for this SSL context, OR we were told to
* disable it for this user.
*
* This also means you can't turn it on just for one
* user.
*/
if ((!ssn->allow_session_resumption) ||
(((vp = fr_pair_find_by_num(request->config, PW_ALLOW_SESSION_RESUMPTION, 0, TAG_ANY)) != NULL) &&
(vp->vp_integer == 0))) {
SSL_CTX_remove_session(ssn->ctx,
ssn->ssl_session);
ssn->allow_session_resumption = false;
/*
* If we're in a resumed session and it's
* not allowed,
*/
if (SSL_session_reused(ssn->ssl)) {
RDEBUG("Forcibly stopping session resumption as it is not allowed");
return -1;
}
/*
* Else resumption IS allowed, so we store the
* user data in the cache.
*/
} else if (!SSL_session_reused(ssn->ssl)) {
VALUE_PAIR **certs;
char buffer[2 * MAX_SESSION_SIZE + 1];
tls_session_id(ssn->ssl_session, buffer, MAX_SESSION_SIZE);
vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
if (vp) fr_pair_add(&vps, vp);
vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
if (vp) fr_pair_add(&vps, vp);
vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_DOMAIN, 0, TAG_ANY);
if (vp) fr_pair_add(&vps, vp);
vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
if (vp) fr_pair_add(&vps, vp);
vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
if (vp) fr_pair_add(&vps, vp);
certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
/*
* Hmm... the certs should probably be session data.
*/
if (certs) {
/*
* @todo: some go into reply, others into
* request
*/
fr_pair_add(&vps, fr_pair_list_copy(talloc_ctx, *certs));
/*
* Save the certs in the packet, so that we can see them.
*/
fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
}
if (vps) {
SSL_SESSION_set_ex_data(ssn->ssl_session, fr_tls_ex_index_vps, vps);
rdebug_pair_list(L_DBG_LVL_2, request, vps, " caching ");
if (conf->session_cache_path) {
/* write the VPs to the cache file */
char filename[256], buf[1024];
FILE *vp_file;
RDEBUG2("Saving session %s in the disk cache", buffer);
snprintf(filename, sizeof(filename), "%s%c%s.vps", conf->session_cache_path,
FR_DIR_SEP, buffer);
vp_file = fopen(filename, "w");
if (vp_file == NULL) {
RWDEBUG("Could not write session VPs to persistent cache: %s",
fr_syserror(errno));
} else {
VALUE_PAIR *prev = NULL;
vp_cursor_t cursor;
/* generate a dummy user-style entry which is easy to read back */
fprintf(vp_file, "# SSL cached session\n");
fprintf(vp_file, "%s\n\t", buffer);
for (vp = fr_cursor_init(&cursor, &vps);
vp;
vp = fr_cursor_next(&cursor)) {
/*
* Terminate the previous line.
*/
if (prev) fprintf(vp_file, ",\n\t");
/*
* Write this one.
*/
vp_prints(buf, sizeof(buf), vp);
fputs(buf, vp_file);
prev = vp;
}
/*
* Terminate the final line.
*/
fprintf(vp_file, "\n");
fclose(vp_file);
}
} else {
RDEBUG("Failed to find 'persist_dir' in TLS configuration. Session will not be cached on disk.");
}
} else {
RDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
SSL_CTX_remove_session(ssn->ctx, ssn->ssl_session);
}
/*
* Else the session WAS allowed. Copy the cached reply.
*/
} else {
char buffer[2 * MAX_SESSION_SIZE + 1];
tls_session_id(ssn->ssl_session, buffer, MAX_SESSION_SIZE);
/*
* The "restore VPs from OpenSSL cache" code is
* now in eaptls_process()
*/
if (conf->session_cache_path) {
/* "touch" the cached session/vp file */
char filename[256];
snprintf(filename, sizeof(filename), "%s%c%s.asn1",
conf->session_cache_path, FR_DIR_SEP, buffer);
utime(filename, NULL);
snprintf(filename, sizeof(filename), "%s%c%s.vps",
conf->session_cache_path, FR_DIR_SEP, buffer);
utime(filename, NULL);
}
/*
* Mark the request as resumed.
*/
pair_make_request("EAP-Session-Resumed", "1", T_OP_SET);
}
return 0;
}
void tls_fail(tls_session_t *ssn)
{
/*
* Force the session to NOT be cached.
*/
SSL_CTX_remove_session(ssn->ctx, ssn->ssl_session);
}
fr_tls_status_t tls_application_data(tls_session_t *ssn, REQUEST *request)
{
int err;
VALUE_PAIR **certs;
/*
* Decrypt the complete record.
*/
err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
ssn->dirty_in.used);
if (err != (int) ssn->dirty_in.used) {
record_init(&ssn->dirty_in);
RDEBUG("Failed writing %zd bytes to SSL BIO: %d", ssn->dirty_in.used, err);
return FR_TLS_FAIL;
}
/*
* Clear the dirty buffer now that we are done with it
* and init the clean_out buffer to store decrypted data
*/
record_init(&ssn->dirty_in);
record_init(&ssn->clean_out);
/*
* Read (and decrypt) the tunneled data from the
* SSL session, and put it into the decrypted
* data buffer.
*/
err = SSL_read(ssn->ssl, ssn->clean_out.data, sizeof(ssn->clean_out.data));
if (err < 0) {
int code;
RDEBUG("SSL_read Error");
code = SSL_get_error(ssn->ssl, err);
switch (code) {
case SSL_ERROR_WANT_READ:
DEBUG("Error in fragmentation logic: SSL_WANT_READ");
return FR_TLS_MORE_FRAGMENTS;
case SSL_ERROR_WANT_WRITE:
DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
break;
default:
REDEBUG("Error in fragmentation logic");
tls_error_io_log(request, ssn, err,
"Failed in " STRINGIFY(__FUNCTION__) " (SSL_read)");
break;
}
return FR_TLS_FAIL;
}
if (err == 0) RWDEBUG("No data inside of the tunnel");
/*
* Passed all checks, successfully decrypted data
*/
ssn->clean_out.used = err;
/*
* Add the certificates to intermediate packets, so that
* the inner tunnel policies can use them.
*/
certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
if (certs) fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
return FR_TLS_OK;
}
/*
* Acknowledge received is for one of the following messages sent earlier
* 1. Handshake completed Message, so now send, EAP-Success
* 2. Alert Message, now send, EAP-Failure
* 3. Fragment Message, now send, next Fragment
*/
fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
{
if (ssn == NULL){
REDEBUG("Unexpected ACK received: No ongoing SSL session");
return FR_TLS_INVALID;
}
if (!ssn->info.initialized) {
RDEBUG("No SSL info available. Waiting for more SSL data");
return FR_TLS_REQUEST;
}
if ((ssn->info.content_type == handshake) && (ssn->info.origin == 0)) {
REDEBUG("Unexpected ACK received: We sent no previous messages");
return FR_TLS_INVALID;
}
switch (ssn->info.content_type) {
case alert:
RDEBUG2("Peer ACKed our alert");
return FR_TLS_FAIL;
case handshake:
if ((ssn->info.handshake_type == handshake_finished) && (ssn->dirty_out.used == 0)) {
RDEBUG2("Peer ACKed our handshake fragment. handshake is finished");
/*
* From now on all the content is
* application data set it here as nobody else
* sets it.
*/
ssn->info.content_type = application_data;
return FR_TLS_SUCCESS;
} /* else more data to send */
RDEBUG2("Peer ACKed our handshake fragment");
/* Fragmentation handler, send next fragment */
return FR_TLS_REQUEST;
case application_data:
RDEBUG2("Peer ACKed our application data fragment");
return FR_TLS_REQUEST;
/*
* For the rest of the conditions, switch over
* to the default section below.
*/
default:
REDEBUG("Invalid ACK received: %d", ssn->info.content_type);
return FR_TLS_INVALID;
}
}
#endif /* WITH_TLS */
|