1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137
|
/*
*
* auth_mellon_handler.c: an authentication apache module
* Copyright © 2003-2007 UNINETT (http://www.uninett.no/)
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "auth_mellon.h"
#ifdef APLOG_USE_MODULE
APLOG_USE_MODULE(auth_mellon);
#endif
/*
* Note:
*
* Information on PAOS ECP vs. Web SSO flow processing can be found in
* the ECP.rst file.
*/
/* This function generates optional metadata for a given element
*
* Parameters:
* apr_pool_t *p Pool to allocate memory from
* apr_hash_t *t Hash of lang -> strings
* const char *e Name of the element
*
* Returns:
* the metadata, or NULL if an error occured
*/
static char *am_optional_metadata_element(apr_pool_t *p,
apr_hash_t *h,
const char *e)
{
apr_hash_index_t *index;
char *data = "";
for (index = apr_hash_first(p, h); index; index = apr_hash_next(index)) {
char *lang;
char *value;
apr_ssize_t slen;
char *xmllang = "";
apr_hash_this(index, (const void **)&lang, &slen, (void *)&value);
if (*lang != '\0')
xmllang = apr_psprintf(p, " xml:lang=\"%s\"", lang);
data = apr_psprintf(p, "%s<%s%s>%s</%s>",
data, e, xmllang, value, e);
}
return data;
}
/* This function generates optinal metadata
*
* Parameters:
* request_rec *r The request we received.
*
* Returns:
* the metadata, or NULL if an error occured
*/
static char *am_optional_metadata(apr_pool_t *p, request_rec *r)
{
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
int count = 0;
char *org_data = NULL;
char *org_name = NULL;
char *org_display_name = NULL;
char *org_url = NULL;
count += apr_hash_count(cfg->sp_org_name);
count += apr_hash_count(cfg->sp_org_display_name);
count += apr_hash_count(cfg->sp_org_url);
if (count == 0)
return "";
org_name = am_optional_metadata_element(p, cfg->sp_org_name,
"OrganizationName");
org_display_name = am_optional_metadata_element(p, cfg->sp_org_display_name,
"OrganizationDisplayName");
org_url = am_optional_metadata_element(p, cfg->sp_org_url,
"OrganizationURL");
org_data = apr_psprintf(p, "<Organization>%s%s%s</Organization>",
org_name, org_display_name, org_url);
return org_data;
}
/* This function generates metadata
*
* Parameters:
* request_rec *r The request we received.
*
* Returns:
* the metadata, or NULL if an error occured
*/
static char *am_generate_metadata(apr_pool_t *p, request_rec *r)
{
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
char *url = am_get_endpoint_url(r);
char *cert = "";
const char *sp_entity_id;
am_diag_printf(r, "Generating SP metadata\n");
sp_entity_id = cfg->sp_entity_id ? cfg->sp_entity_id : url;
if (cfg->sp_cert_file && cfg->sp_cert_file->contents) {
char *sp_cert_file;
char *cp;
char *bp;
const char *begin = "-----BEGIN CERTIFICATE-----";
const char *end = "-----END CERTIFICATE-----";
/*
* Try to remove leading and trailing garbage, as it can
* wreak havoc XML parser if it contains [<>&]
*/
sp_cert_file = apr_pstrdup(p, cfg->sp_cert_file->contents);
cp = strstr(sp_cert_file, begin);
if (cp != NULL)
sp_cert_file = cp + strlen(begin);
cp = strstr(sp_cert_file, end);
if (cp != NULL)
*cp = '\0';
/*
* And remove any non printing char (CR, spaces...)
*/
bp = sp_cert_file;
for (cp = sp_cert_file; *cp; cp++) {
if (apr_isgraph(*cp))
*bp++ = *cp;
}
*bp = '\0';
cert = apr_psprintf(p,
"<KeyDescriptor use=\"signing\">"
"<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">"
"<ds:X509Data>"
"<ds:X509Certificate>%s</ds:X509Certificate>"
"</ds:X509Data>"
"</ds:KeyInfo>"
"</KeyDescriptor>"
"<KeyDescriptor use=\"encryption\">"
"<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">"
"<ds:X509Data>"
"<ds:X509Certificate>%s</ds:X509Certificate>"
"</ds:X509Data>"
"</ds:KeyInfo>"
"</KeyDescriptor>",
sp_cert_file,
sp_cert_file);
}
return apr_psprintf(p,
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n\
<EntityDescriptor\n\
entityID=\"%s%s\"\n\
xmlns=\"urn:oasis:names:tc:SAML:2.0:metadata\">\n\
<SPSSODescriptor\n\
AuthnRequestsSigned=\"true\"\n\
WantAssertionsSigned=\"true\"\n\
protocolSupportEnumeration=\"urn:oasis:names:tc:SAML:2.0:protocol\">\n\
%s\
<SingleLogoutService\n\
Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:SOAP\"\n\
Location=\"%slogout\" />\n\
<SingleLogoutService\n\
Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect\"\n\
Location=\"%slogout\" />\n\
<SingleLogoutService\n\
Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\"\n\
Location=\"%slogout\" />\n\
<NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:transient</NameIDFormat>\n\
<AssertionConsumerService\n\
index=\"0\"\n\
isDefault=\"true\"\n\
Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\"\n\
Location=\"%spostResponse\" />\n\
<AssertionConsumerService\n\
index=\"1\"\n\
Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact\"\n\
Location=\"%sartifactResponse\" />\n\
<AssertionConsumerService\n\
index=\"2\"\n\
Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:PAOS\"\n\
Location=\"%spaosResponse\" />\n\
</SPSSODescriptor>\n\
%s\n\
</EntityDescriptor>",
sp_entity_id, cfg->sp_entity_id ? "" : "metadata",
cert, url, url, url, url, url, url, am_optional_metadata(p, r));
}
/*
* This function loads all IdP metadata in a lasso server
*
* Parameters:
* am_dir_cfg_rec *cfg The server configuration.
* request_rec *r The request we received.
*
* Returns:
* number of loaded providers
*/
static guint am_server_add_providers(am_dir_cfg_rec *cfg, request_rec *r)
{
apr_size_t index;
if (cfg->idp_metadata->nelts == 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error, URI \"%s\" has no IdP's defined", r->uri);
return 0;
}
for (index = 0; index < cfg->idp_metadata->nelts; index++) {
const am_metadata_t *idp_metadata;
int error;
GList *loaded_idp = NULL;
idp_metadata = &( ((const am_metadata_t*)cfg->idp_metadata->elts) [index] );
am_diag_log_file_data(r, 0, idp_metadata->metadata,
"Loading IdP Metadata");
if (idp_metadata->chain) {
am_diag_log_file_data(r, 0, idp_metadata->chain,
"Loading IdP metadata chain");
}
error = lasso_server_load_metadata(cfg->server,
LASSO_PROVIDER_ROLE_IDP,
idp_metadata->metadata->path,
idp_metadata->chain ?
idp_metadata->chain->path : NULL,
cfg->idp_ignore,
&loaded_idp,
LASSO_SERVER_LOAD_METADATA_FLAG_DEFAULT);
if (error == 0) {
GList *idx;
for (idx = loaded_idp; idx != NULL; idx = idx->next) {
AM_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r,
"loaded IdP \"%s\" from \"%s\".",
(char *)idx->data, idp_metadata->metadata->path);
}
}
if (loaded_idp != NULL) {
for (GList *idx = loaded_idp; idx != NULL; idx = idx->next) {
g_free(idx->data);
}
g_list_free(loaded_idp);
}
if (error != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error adding metadata \"%s\" to "
"lasso server objects. Lasso error: [%i] %s",
idp_metadata->metadata->path, error, lasso_strerror(error));
}
}
return g_hash_table_size(cfg->server->providers);
}
static LassoServer *am_get_lasso_server(request_rec *r)
{
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
cfg = cfg->inherit_server_from;
apr_thread_mutex_lock(cfg->server_mutex);
if(cfg->server == NULL) {
if(cfg->sp_metadata_file == NULL) {
/*
* Try to generate missing metadata
*/
apr_pool_t *pool = r->server->process->pconf;
cfg->sp_metadata_file = am_file_data_new(pool, NULL);
cfg->sp_metadata_file->rv = APR_SUCCESS;
cfg->sp_metadata_file->generated = true;
cfg->sp_metadata_file->contents = am_generate_metadata(pool, r);
}
cfg->server = lasso_server_new_from_buffers(cfg->sp_metadata_file->contents,
cfg->sp_private_key_file ?
cfg->sp_private_key_file->contents : NULL,
NULL,
cfg->sp_cert_file ?
cfg->sp_cert_file->contents : NULL);
if (cfg->server == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error initializing lasso server object. Please"
" verify the following configuration directives:"
" MellonSPMetadataFile and MellonSPPrivateKeyFile.");
apr_thread_mutex_unlock(cfg->server_mutex);
return NULL;
}
if (am_server_add_providers(cfg, r) == 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error adding IdP to lasso server object. Please"
" verify the following configuration directive:"
" MellonIdPMetadataFile.");
lasso_server_destroy(cfg->server);
cfg->server = NULL;
apr_thread_mutex_unlock(cfg->server_mutex);
return NULL;
}
cfg->server->signature_method = CFG_VALUE(cfg, signature_method);
}
apr_thread_mutex_unlock(cfg->server_mutex);
return cfg->server;
}
/* Redirect to discovery service.
*
* Parameters:
* request_rec *r The request we received.
* const char *return_to The URL the user should be returned to after login.
*
* Returns:
* HTTP_SEE_OTHER on success, an error otherwise.
*/
static int am_start_disco(request_rec *r, const char *return_to)
{
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
const char *endpoint = am_get_endpoint_url(r);
LassoServer *server;
const char *sp_entity_id;
const char *sep;
const char *login_url;
const char *discovery_url;
server = am_get_lasso_server(r);
if(server == NULL) {
return HTTP_INTERNAL_SERVER_ERROR;
}
sp_entity_id = LASSO_PROVIDER(server)->ProviderID;
login_url = apr_psprintf(r->pool, "%slogin?ReturnTo=%s",
endpoint,
am_urlencode(r->pool, return_to));
AM_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r,
"login_url = %s", login_url);
/* If discovery URL already has a ? we append a & */
sep = (strchr(cfg->discovery_url, '?')) ? "&" : "?";
discovery_url = apr_psprintf(r->pool, "%s%sentityID=%s&"
"return=%s&returnIDParam=IdP",
cfg->discovery_url, sep,
am_urlencode(r->pool, sp_entity_id),
am_urlencode(r->pool, login_url));
AM_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r,
"discovery_url = %s", discovery_url);
apr_table_setn(r->headers_out, "Location", discovery_url);
return HTTP_SEE_OTHER;
}
/* This function returns the first configured IdP
*
* Parameters:
* request_rec *r The request we received.
*
* Returns:
* the providerID, or NULL if an error occured
*/
static const char *am_first_idp(request_rec *r)
{
LassoServer *server;
GList *idp_list;
const char *idp_providerid;
server = am_get_lasso_server(r);
if (server == NULL)
return NULL;
idp_list = g_hash_table_get_keys(server->providers);
if (idp_list == NULL)
return NULL;
idp_providerid = idp_list->data;
g_list_free(idp_list);
return idp_providerid;
}
/* This function selects an IdP and returns its provider_id
*
* Parameters:
* request_rec *r The request we received.
*
* Returns:
* the provider_id, or NULL if an error occured
*/
static const char *am_get_idp(request_rec *r)
{
LassoServer *server;
const char *idp_provider_id;
server = am_get_lasso_server(r);
if (server == NULL)
return NULL;
/*
* If we have a single IdP, return that one.
*/
if (g_hash_table_size(server->providers) == 1)
return am_first_idp(r);
/*
* If IdP discovery handed us an IdP, try to use it.
*/
idp_provider_id = am_extract_query_parameter(r->pool, r->args, "IdP");
if (idp_provider_id != NULL) {
int rc;
rc = am_urldecode((char *)idp_provider_id);
if (rc != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Could not urldecode IdP discovery value.");
idp_provider_id = NULL;
} else {
if (g_hash_table_lookup(server->providers, idp_provider_id) == NULL)
idp_provider_id = NULL;
}
/*
* If we do not know about it, fall back to default.
*/
if (idp_provider_id == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"IdP discovery returned unknown or inexistant IdP");
idp_provider_id = am_first_idp(r);
}
return idp_provider_id;
}
/*
* No IdP answered, use default
* Perhaps we should redirect to an error page instead.
*/
return am_first_idp(r);
}
/* This function stores dumps of the LassoIdentity and LassoSession objects
* for the given LassoProfile object. The dumps are stored in the session
* belonging to the current request.
*
* Parameters:
* request_rec *r The current request.
* am_cache_entry_t *session The session we are creating.
* LassoProfile *profile The profile object.
* char *saml_response The full SAML 2.0 response message.
*
* Returns:
* OK on success or HTTP_INTERNAL_SERVER_ERROR on failure.
*/
static int am_save_lasso_profile_state(request_rec *r,
am_cache_entry_t *session,
LassoProfile *profile,
char *saml_response)
{
LassoIdentity *lasso_identity;
LassoSession *lasso_session;
gchar *identity_dump;
gchar *session_dump;
int ret;
lasso_identity = lasso_profile_get_identity(profile);
if(lasso_identity == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r,
"The current LassoProfile object doesn't contain a"
" LassoIdentity object.");
identity_dump = NULL;
} else {
identity_dump = lasso_identity_dump(lasso_identity);
if(identity_dump == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Could not create a identity dump from the"
" LassoIdentity object.");
return HTTP_INTERNAL_SERVER_ERROR;
}
}
lasso_session = lasso_profile_get_session(profile);
if(lasso_session == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r,
"The current LassoProfile object doesn't contain a"
" LassoSession object.");
session_dump = NULL;
} else {
session_dump = lasso_session_dump(lasso_session);
if(session_dump == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Could not create a session dump from the"
" LassoSession object.");
if(identity_dump != NULL) {
g_free(identity_dump);
}
return HTTP_INTERNAL_SERVER_ERROR;
}
}
/* Save the profile state. */
ret = am_cache_set_lasso_state(session,
identity_dump,
session_dump,
saml_response);
if(identity_dump != NULL) {
g_free(identity_dump);
}
if(session_dump != NULL) {
g_free(session_dump);
}
return ret;
}
/* Use Lasso Logout to set the HTTP content & headers for HTTP-POST binding.
*
* Parameters:
* request_rec *r The request we are processing.
* LassoProfile *profile The Lasso profile(logout) message.
* char *post_data The post data (if present for POST logout)
*
* Returns:
* OK on success, or an error on failure.
*/
static int am_set_logout_response_post_content(request_rec *r,
LassoProfile *profile,
char *post_data)
{
char *url;
char *message;
char *relay_state = NULL;
char *output;
url = am_htmlencode(r, profile->msg_url);
message = am_htmlencode(r, profile->msg_body);
if (profile->msg_relayState != NULL) {
relay_state = am_htmlencode(r, profile->msg_relayState);
} else {
/* Try to get relayState from post_data (lasso seems not to initialize relayState from post logout) */
int rc = 0;
relay_state = am_extract_query_parameter(r->pool, post_data,
"RelayState");
if (relay_state) {
rc = am_urldecode(relay_state);
if (rc != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Could not urldecode RelayState value.");
relay_state = NULL;
}
}
}
if (relay_state) {
output = apr_psprintf(r->pool,
"<!DOCTYPE html>\n"
"<html>\n"
" <head>\n"
" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n"
" <title>POST data</title>\n"
" </head>\n"
" <body onload=\"document.forms[0].submit()\">\n"
" <noscript><p>\n"
" <strong>Note:</strong> Since your browser does not support JavaScript, you must press the button below once to proceed.\n"
" </p></noscript>\n"
" <form method=\"POST\" action=\"%s\">\n"
" <input type=\"hidden\" name=\"SAMLResponse\" value=\"%s\">\n"
" <input type=\"hidden\" name=\"RelayState\" value=\"%s\">\n"
" <noscript>\n"
" <input type=\"submit\" value=\"Proceed\">\n"
" </noscript>\n"
" </form>\n"
" </body>\n"
"</html>\n",
url, message, relay_state);
} else {
output = apr_psprintf(r->pool,
"<!DOCTYPE html>\n"
"<html>\n"
" <head>\n"
" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n"
" <title>POST data</title>\n"
" </head>\n"
" <body onload=\"document.forms[0].submit()\">\n"
" <noscript><p>\n"
" <strong>Note:</strong> Since your browser does not support JavaScript, you must press the button below once to proceed.\n"
" </p></noscript>\n"
" <form method=\"POST\" action=\"%s\">\n"
" <input type=\"hidden\" name=\"SAMLResponse\" value=\"%s\">\n"
" <noscript>\n"
" <input type=\"submit\" value=\"Proceed\">\n"
" </noscript>\n"
" </form>\n"
" </body>\n"
"</html>\n",
url, message);
}
ap_set_content_type(r, "text/html");
ap_rputs(output, r);
return OK;
}
/* Returns a SAML response
*
* Parameters:
* request_rec *r The current request.
* LassoProfile *profile The profile object.
* char *post_data The post data (if present for POST logout)
*
* Returns:
* HTTP_INTERNAL_SERVER_ERROR if an error occurs, HTTP_SEE_OTHER for the
* Redirect binding and OK for the SOAP binding.
*/
static int am_return_logout_response(request_rec *r,
LassoProfile *profile,
char *post_data)
{
if (profile->msg_url && profile->msg_body) {
/* POST binding response */
return am_set_logout_response_post_content(r, profile, post_data);
} else if (profile->msg_url) {
/* HTTP-Redirect binding response */
apr_table_setn(r->headers_out, "Location",
apr_pstrdup(r->pool, profile->msg_url));
return HTTP_SEE_OTHER;
} else if (profile->msg_body) {
/* SOAP binding response */
ap_set_content_type(r, "text/xml");
ap_rputs(profile->msg_body, r);
return OK;
} else {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error building logout response message."
" There is no content to return.");
return HTTP_INTERNAL_SERVER_ERROR;
}
}
/* This function restores dumps of a LassoIdentity object and a LassoSession
* object. The dumps are fetched from the session belonging to the current
* request and restored to the given LassoProfile object.
*
* Parameters:
* request_rec *r The current request.
* LassoProfile *profile The profile object.
* am_cache_entry_t *am_session The session structure.
*
* Returns:
* OK on success or HTTP_INTERNAL_SERVER_ERROR on failure.
*/
static void am_restore_lasso_profile_state(request_rec *r,
LassoProfile *profile,
am_cache_entry_t *am_session)
{
const char *identity_dump;
const char *session_dump;
int rc;
if(am_session == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Could not get auth_mellon session while attempting"
" to restore the lasso profile state.");
return;
}
identity_dump = am_cache_get_lasso_identity(am_session);
if(identity_dump != NULL) {
rc = lasso_profile_set_identity_from_dump(profile, identity_dump);
if(rc != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Could not restore identity from dump."
" Lasso error: [%i] %s", rc, lasso_strerror(rc));
am_release_request_session(r, am_session);
}
}
session_dump = am_cache_get_lasso_session(am_session);
if(session_dump != NULL) {
rc = lasso_profile_set_session_from_dump(profile, session_dump);
if(rc != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Could not restore session from dump."
" Lasso error: [%i] %s", rc, lasso_strerror(rc));
am_release_request_session(r, am_session);
}
}
am_diag_log_cache_entry(r, 0, am_session, "%s: Session Cache Entry", __func__);
am_diag_log_profile(r, 0, profile, "%s: Restored Profile", __func__);
}
/* This function handles an IdP initiated logout request.
*
* Parameters:
* request_rec *r The logout request.
* LassoLogout *logout A LassoLogout object initiated with
* the current session.
* char *msg The logout message to process.
* char *post_data The post data (if present for POST logout)
*
* Returns:
* OK on success, or an error if any of the steps fail.
*/
static int am_handle_logout_request(request_rec *r,
LassoLogout *logout,
char *msg,
char *post_data)
{
gint res = 0, rc = HTTP_OK;
am_cache_entry_t *session = NULL;
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
am_diag_printf(r, "enter function %s\n", __func__);
/* Process the logout message. Ignore missing signature. */
res = lasso_logout_process_request_msg(logout, msg);
if(res != 0 && res != LASSO_DS_ERROR_SIGNATURE_NOT_FOUND &&
logout->parent.remote_providerID != NULL) {
if (apr_hash_get(cfg->do_not_verify_logout_signature,
logout->parent.remote_providerID,
APR_HASH_KEY_STRING)) {
lasso_profile_set_signature_verify_hint(&logout->parent,
LASSO_PROFILE_SIGNATURE_VERIFY_HINT_IGNORE);
res = lasso_logout_process_request_msg(logout, msg);
}
}
if(res != 0 && res != LASSO_DS_ERROR_SIGNATURE_NOT_FOUND) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error processing logout request message."
" Lasso error: [%i] %s", res, lasso_strerror(res));
rc = HTTP_BAD_REQUEST;
goto exit;
}
/* Search session using NameID */
if (! LASSO_IS_SAML2_NAME_ID(logout->parent.nameIdentifier)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error processing logout request message."
" No NameID found");
rc = HTTP_BAD_REQUEST;
goto exit;
}
am_diag_printf(r, "%s name id %s\n", __func__,
((LassoSaml2NameID*)logout->parent.nameIdentifier)->content);
session = am_get_request_session_by_nameid(r,
((LassoSaml2NameID*)logout->parent.nameIdentifier)->content);
if (session == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error processing logout request message."
" No session found for NameID %s",
((LassoSaml2NameID*)logout->parent.nameIdentifier)->content);
}
am_diag_log_cache_entry(r, 0, session, "%s", __func__);
if (session == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error processing logout request message."
" No session found.");
} else {
am_restore_lasso_profile_state(r, &logout->parent, session);
}
/* Validate the logout message. Ignore missing signature. */
res = lasso_logout_validate_request(logout);
if(res != 0 &&
res != LASSO_DS_ERROR_SIGNATURE_NOT_FOUND &&
res != LASSO_PROFILE_ERROR_SESSION_NOT_FOUND) {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"Error validating logout request."
" Lasso error: [%i] %s", res, lasso_strerror(res));
rc = HTTP_INTERNAL_SERVER_ERROR;
goto exit;
}
/* We continue with the logout despite those errors. They could be
* caused by the IdP believing that we are logged in when we are not.
*/
if (session != NULL && res != LASSO_PROFILE_ERROR_SESSION_NOT_FOUND) {
/* We found a matching session -- delete it. */
am_delete_request_session(r, session);
session = NULL;
}
/* Create response message. */
res = lasso_logout_build_response_msg(logout);
if(res != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error building logout response message."
" Lasso error: [%i] %s", res, lasso_strerror(res));
rc = HTTP_INTERNAL_SERVER_ERROR;
goto exit;
}
rc = am_return_logout_response(r, &logout->parent, post_data);
exit:
if (session != NULL) {
am_release_request_session(r, session);
}
lasso_logout_destroy(logout);
return rc;
}
/* This function handles an IdP initiated logout request HTTP-POST.
*
* Parameters:
* request_rec *r The logout request.
* LassoLogout *logout A LassoLogout object initiated with
* the current session.
* char *post_data The post data (if present for POST logout)
*
* Returns:
* OK on success, or an error if any of the steps fail.
*/
static int am_handle_logout_request_POST(request_rec *r,
LassoLogout *logout,
char *post_data)
{
int rc = 0;
char *saml_request;
saml_request = am_extract_query_parameter(r->pool, post_data,
"SAMLRequest");
if (saml_request == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Could not find SAMLRequest field in POST data.");
return HTTP_BAD_REQUEST;
}
rc = am_urldecode(saml_request);
if (rc != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Could not urldecode SAMLRequest value.");
return rc;
}
return am_handle_logout_request(r, logout, saml_request, post_data);
}
/* This function handles an invalidate request.
*
* Parameters:
* request_rec *r The logout request.
*
* Returns:
* OK on success, or an error if any of the steps fail.
*/
static int am_handle_invalidate_request(request_rec *r)
{
gint res = 0, rc = HTTP_OK;
char *return_to;
am_cache_entry_t *session = am_get_request_session(r);
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
/* Check if the session invalidation endpoint is enabled. */
if (cfg->enabled_invalidation_session == 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Session Invalidation Endpoint is not enabled.");
rc = HTTP_BAD_REQUEST;
goto exit;
}
am_diag_printf(r, "enter function %s\n", __func__);
am_diag_log_cache_entry(r, 0, session, "%s\n", __func__);
return_to = am_extract_query_parameter(r->pool, r->args, "ReturnTo");
if (return_to == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"No ReturnTo parameter provided for invalidate handler.");
rc = HTTP_BAD_REQUEST;
goto exit;
}
/* Check for bad characters in ReturnTo. */
res = am_check_url(r, return_to);
if (res != OK) {
rc = HTTP_BAD_REQUEST;
goto exit;
}
res = am_urldecode(return_to);
if (res != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Could not urldecode ReturnTo value in invalidate"
" response.");
rc = HTTP_BAD_REQUEST;
goto exit;
}
/* Make sure that it is a valid redirect URL. */
res = am_validate_redirect_url(r, return_to);
if (res != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid target domain in invalidate response ReturnTo parameter.");
rc = HTTP_BAD_REQUEST;
goto exit;
}
if (session == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error processing invalidate request message."
" No session found.");
rc = HTTP_BAD_REQUEST;
goto exit;
}
am_delete_request_session(r, session);
apr_table_setn(r->headers_out, "Location", return_to);
rc = HTTP_SEE_OTHER;
exit:
if (session != NULL) {
am_release_request_session(r, session);
}
return rc;
}
/* This function handles a logout response message from the IdP. We get
* this message after we have sent a logout request to the IdP.
*
* Parameters:
* request_rec *r The logout response request.
* LassoLogout *logout A LassoLogout object initiated with
* the current session.
* input in POST case: url-decoded SAMLResponse parameter,
* in GET case: url-encoded query string.
* args Url-encoded parameters.
*
* Returns:
* OK on success, or an error if any of the steps fail.
*/
static int am_handle_logout_response_cmn(request_rec *r, LassoLogout *logout,
char *input, char *args)
{
gint res;
int rc;
am_cache_entry_t *session;
char *return_to;
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
res = lasso_logout_process_response_msg(logout, input);
am_diag_log_lasso_node(r, 0, LASSO_PROFILE(logout)->response,
"SAML Response (%s):", __func__);
if(res != 0 && res != LASSO_DS_ERROR_SIGNATURE_NOT_FOUND &&
logout->parent.remote_providerID != NULL) {
if (apr_hash_get(cfg->do_not_verify_logout_signature,
logout->parent.remote_providerID,
APR_HASH_KEY_STRING)) {
lasso_profile_set_signature_verify_hint(&logout->parent,
LASSO_PROFILE_SIGNATURE_VERIFY_HINT_IGNORE);
res = lasso_logout_process_response_msg(logout, input);
}
}
if(res != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Unable to process logout response."
" Lasso error: [%i] %s, SAML Response: %s",
res, lasso_strerror(res),
am_saml_response_status_str(r,
LASSO_PROFILE(logout)->response));
lasso_logout_destroy(logout);
return HTTP_BAD_REQUEST;
}
lasso_logout_destroy(logout);
/* Delete the session. */
session = am_get_request_session(r);
am_diag_log_cache_entry(r, 0, session, "%s\n", __func__);
if(session != NULL) {
am_delete_request_session(r, session);
}
return_to = am_extract_query_parameter(r->pool, args, "RelayState");
if(return_to == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"No RelayState parameter to logout response handler."
" It is possible that your IdP doesn't support the"
" RelayState parameter.");
return HTTP_BAD_REQUEST;
}
rc = am_urldecode(return_to);
if(rc != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Could not urldecode RelayState value in logout"
" response.");
return HTTP_BAD_REQUEST;
}
/* Check for bad characters in RelayState. */
rc = am_check_url(r, return_to);
if (rc != OK) {
return rc;
}
/* Make sure that it is a valid redirect URL. */
rc = am_validate_redirect_url(r, return_to);
if (rc != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid target domain in logout response RelayState parameter.");
return rc;
}
apr_table_setn(r->headers_out, "Location", return_to);
return HTTP_SEE_OTHER;
}
static int am_handle_logout_response_GET(request_rec *r, LassoLogout *logout)
{
return am_handle_logout_response_cmn(r, logout, r->args, r->args);
}
static int am_handle_logout_response_POST(request_rec *r, LassoLogout *logout,
char *post_data)
{
int rc = 0;
char *saml_response;
saml_response = am_extract_query_parameter(r->pool, post_data,
"SAMLResponse");
if (saml_response == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Could not find SAMLResponse field in POST data.");
return HTTP_BAD_REQUEST;
}
rc = am_urldecode(saml_response);
if (rc != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Could not urldecode SAMLResponse value.");
return rc;
}
return am_handle_logout_response_cmn(r, logout, saml_response,
post_data);
}
/* This function initiates a logout request and sends it to the IdP.
*
* Parameters:
* request_rec *r The logout response request.
* LassoLogout *logout A LassoLogout object initiated with
* the current session.
*
* Returns:
* OK on success, or an error if any of the steps fail.
*/
static int am_init_logout_request(request_rec *r, LassoLogout *logout)
{
char *return_to;
int rc;
am_cache_entry_t *mellon_session;
gint res;
char *redirect_to;
LassoProfile *profile;
LassoSession *session;
GList *assertion_list;
LassoNode *assertion_n;
LassoSaml2Assertion *assertion;
LassoSaml2AuthnStatement *authnStatement;
LassoSamlp2LogoutRequest *request;
return_to = am_extract_query_parameter(r->pool, r->args, "ReturnTo");
rc = am_urldecode(return_to);
if (rc != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Could not urldecode ReturnTo value.");
return HTTP_BAD_REQUEST;
}
rc = am_validate_redirect_url(r, return_to);
if (rc != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid target domain in logout request ReturnTo parameter.");
return rc;
}
/* Disable the the local session (in case the IdP doesn't respond). */
mellon_session = am_get_request_session(r);
if(mellon_session != NULL) {
am_restore_lasso_profile_state(r, &logout->parent, mellon_session);
mellon_session->logged_in = 0;
am_release_request_session(r, mellon_session);
}
/* Create the logout request message. */
res = lasso_logout_init_request(logout, NULL, LASSO_HTTP_METHOD_REDIRECT);
/* Early non failing return. */
if (res != 0) {
if(res == LASSO_PROFILE_ERROR_SESSION_NOT_FOUND) {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"User attempted to initiate logout without being"
" loggged in.");
} else if (res == LASSO_LOGOUT_ERROR_UNSUPPORTED_PROFILE || res == LASSO_PROFILE_ERROR_UNSUPPORTED_PROFILE) {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r, "Current identity provider "
"does not support single logout. Destroying local session only.");
} else if(res != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Unable to create logout request."
" Lasso error: [%i] %s", res, lasso_strerror(res));
lasso_logout_destroy(logout);
return HTTP_INTERNAL_SERVER_ERROR;
}
lasso_logout_destroy(logout);
/* Check for bad characters in ReturnTo. */
rc = am_check_url(r, return_to);
if (rc != OK) {
return rc;
}
/* Redirect to the page the user should be sent to after logout. */
apr_table_setn(r->headers_out, "Location", return_to);
return HTTP_SEE_OTHER;
}
profile = LASSO_PROFILE(logout);
/* Set the RelayState parameter to the return url (if we have one). */
if(return_to) {
profile->msg_relayState = g_strdup(return_to);
}
/* Serialize the request message into a url which we can redirect to. */
res = lasso_logout_build_request_msg(logout);
if(res != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Unable to serialize lasso logout message."
" Lasso error: [%i] %s", res, lasso_strerror(res));
lasso_logout_destroy(logout);
return HTTP_INTERNAL_SERVER_ERROR;
}
/* Set the redirect url. */
redirect_to = apr_pstrdup(r->pool, LASSO_PROFILE(logout)->msg_url);
/* Check if the lasso library added the RelayState. If lasso didn't add
* a RelayState parameter, then we add one ourself. This should hopefully
* be removed in the future.
*/
if(return_to != NULL
&& strstr(redirect_to, "&RelayState=") == NULL
&& strstr(redirect_to, "?RelayState=") == NULL) {
/* The url didn't contain the relaystate parameter. */
redirect_to = apr_pstrcat(
r->pool, redirect_to, "&RelayState=",
am_urlencode(r->pool, return_to),
NULL
);
}
apr_table_setn(r->headers_out, "Location", redirect_to);
lasso_logout_destroy(logout);
/* Redirect (without including POST data if this was a POST request. */
return HTTP_SEE_OTHER;
}
/* This function handles requests to the logout handler.
*
* Parameters:
* request_rec *r The request.
*
* Returns:
* OK on success, or an error if any of the steps fail.
*/
static int am_handle_logout(request_rec *r)
{
LassoServer *server;
LassoLogout *logout;
server = am_get_lasso_server(r);
if(server == NULL) {
return HTTP_INTERNAL_SERVER_ERROR;
}
logout = lasso_logout_new(server);
if(logout == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error creating lasso logout object.");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* Check which type of request to the logout handler this is.
* We have three types:
* - logout requests: The IdP sends a logout request to this service.
* it can be either through HTTP-Redirect or SOAP.
* - logout responses: We have sent a logout request to the IdP, and
* are receiving a response either via GET or POST.
* - We want to initiate a logout request.
*/
/*
* First check for POST method, which could be either IdP-initiated SOAP
* or HTTP-POST logout request or POST logout response from IdP.
*/
if ((r->args == NULL) && (r->method_number == M_POST)) {
int rc;
char *post_data;
const char *content_type;
/* Check Content-Type */
content_type = apr_table_get(r->headers_in, "Content-Type");
rc = am_read_post_data(r, &post_data, NULL);
if (rc != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Error reading POST data.");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (content_type != NULL &&
am_has_header(r, content_type, "application/x-www-form-urlencoded")) {
/* POST can be for a SAMLRequest (IDP request for SLO) or a SAMLResponse (IDP response for SLO) */
char *saml_param;
saml_param = am_extract_query_parameter(r->pool, post_data,
"SAMLResponse");
if (saml_param) {
return am_handle_logout_response_POST(r, logout, post_data);
}
}
/* HTTP-POST Request */
return am_handle_logout_request_POST(r, logout, post_data);
} else if(am_extract_query_parameter(r->pool, r->args,
"SAMLRequest") != NULL) {
/* SAMLRequest - logout request from the IdP. */
return am_handle_logout_request(r, logout, r->args, r->args);
} else if(am_extract_query_parameter(r->pool, r->args,
"SAMLResponse") != NULL) {
/* SAMLResponse - logout response from the IdP. */
return am_handle_logout_response_GET(r, logout);
} else if(am_extract_query_parameter(r->pool, r->args,
"ReturnTo") != NULL) {
/* RedirectTo - SP initiated logout. */
return am_init_logout_request(r, logout);
} else {
/* Unknown request to the logout handler. */
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"No known parameters passed to the logout"
" handler. Query string was \"%s\". To initiate"
" a logout, you need to pass a \"ReturnTo\""
" parameter with a url to the web page the user should"
" be redirected to after a successful logout.",
r->args);
return HTTP_BAD_REQUEST;
}
}
/* This function handles requests to the invalidate handler.
*
* Parameters:
* request_rec *r The request.
*
* Returns:
* OK on success, or an error if any of the steps fail.
*/
static int am_handle_invalidate(request_rec *r)
{
LassoServer *server;
server = am_get_lasso_server(r);
if (server == NULL) {
return HTTP_INTERNAL_SERVER_ERROR;
}
return am_handle_invalidate_request(r);
}
/* This function parses a timestamp for a SAML 2.0 condition.
*
* Parameters:
* request_rec *r The current request. Used for logging of errors.
* const char *timestamp The timestamp we should parse. Must be on
* the following format: "YYYY-MM-DDThh:mm:ssZ"
*
* Returns:
* An apr_time_t value with the timestamp, or 0 on error.
*/
static apr_time_t am_parse_timestamp(request_rec *r, const char *timestamp)
{
size_t len;
int i;
char c;
const char *expected;
apr_time_exp_t time_exp;
apr_time_t res;
apr_status_t rc;
len = strlen(timestamp);
/* Verify length of timestamp. */
if(len < 20){
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"Invalid length of timestamp: \"%s\".", timestamp);
}
/* Verify components of timestamp. */
for(i = 0; i < len - 1; i++) {
c = timestamp[i];
expected = NULL;
switch(i) {
case 4:
case 7:
/* Matches " - - " */
if(c != '-') {
expected = "'-'";
}
break;
case 10:
/* Matches " T " */
if(c != 'T') {
expected = "'T'";
}
break;
case 13:
case 16:
/* Matches " : : " */
if(c != ':') {
expected = "':'";
}
break;
case 19:
/* Matches " ." */
if (c != '.') {
expected = "'.'";
}
break;
default:
/* Matches "YYYY MM DD hh mm ss uuuuuu" */
if(c < '0' || c > '9') {
expected = "a digit";
}
break;
}
if(expected != NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid character in timestamp at position %i."
" Expected %s, got '%c'. Full timestamp: \"%s\"",
i, expected, c, timestamp);
return 0;
}
}
if (timestamp[len - 1] != 'Z') {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Timestamp wasn't in UTC (did not end with 'Z')."
" Full timestamp: \"%s\"",
timestamp);
return 0;
}
time_exp.tm_usec = 0;
if (len > 20) {
/* Subsecond precision. */
if (len > 27) {
/* Timestamp has more than microsecond precision. Just clip it to
* microseconds.
*/
len = 27;
}
len -= 1; /* Drop the 'Z' off the end. */
for (i = 20; i < len; i++) {
time_exp.tm_usec = time_exp.tm_usec * 10 + timestamp[i] - '0';
}
for (i = len; i < 26; i++) {
time_exp.tm_usec *= 10;
}
}
time_exp.tm_sec = (timestamp[17] - '0') * 10 + (timestamp[18] - '0');
time_exp.tm_min = (timestamp[14] - '0') * 10 + (timestamp[15] - '0');
time_exp.tm_hour = (timestamp[11] - '0') * 10 + (timestamp[12] - '0');
time_exp.tm_mday = (timestamp[8] - '0') * 10 + (timestamp[9] - '0');
time_exp.tm_mon = (timestamp[5] - '0') * 10 + (timestamp[6] - '0') - 1;
time_exp.tm_year = (timestamp[0] - '0') * 1000 +
(timestamp[1] - '0') * 100 + (timestamp[2] - '0') * 10 +
(timestamp[3] - '0') - 1900;
time_exp.tm_wday = 0; /* Unknown. */
time_exp.tm_yday = 0; /* Unknown. */
time_exp.tm_isdst = 0; /* UTC, no daylight savings time. */
time_exp.tm_gmtoff = 0; /* UTC, no offset from UTC. */
rc = apr_time_exp_gmt_get(&res, &time_exp);
if(rc != APR_SUCCESS) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Error converting timestamp \"%s\".",
timestamp);
return 0;
}
return res;
}
/* Validate the subject on an Assertion.
*
* request_rec *r The current request. Used to log
* errors.
* LassoSaml2Assertion *assertion The assertion we will validate.
* const char *url The current URL.
*
* Returns:
* OK on success, HTTP_BAD_REQUEST on failure.
*/
static int am_validate_subject(request_rec *r, LassoSaml2Assertion *assertion,
const char *url)
{
apr_time_t now;
apr_time_t t;
LassoSaml2SubjectConfirmation *sc;
LassoSaml2SubjectConfirmationData *scd;
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
if (assertion->Subject == NULL) {
/* No Subject to validate. */
return OK;
} else if (!LASSO_IS_SAML2_SUBJECT(assertion->Subject)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Wrong type of Subject node.");
return HTTP_BAD_REQUEST;
}
if (assertion->Subject->SubjectConfirmation == NULL) {
/* No SubjectConfirmation. */
return OK;
} else if (!LASSO_IS_SAML2_SUBJECT_CONFIRMATION(assertion->Subject->SubjectConfirmation)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Wrong type of SubjectConfirmation node.");
return HTTP_BAD_REQUEST;
}
sc = assertion->Subject->SubjectConfirmation;
if (sc->Method == NULL ||
strcmp(sc->Method, "urn:oasis:names:tc:SAML:2.0:cm:bearer")) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid Method in SubjectConfirmation.");
return HTTP_BAD_REQUEST;
}
scd = sc->SubjectConfirmationData;
if (scd == NULL) {
/* Nothing to verify. */
return OK;
} else if (!LASSO_IS_SAML2_SUBJECT_CONFIRMATION_DATA(scd)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Wrong type of SubjectConfirmationData node.");
return HTTP_BAD_REQUEST;
}
now = apr_time_now();
if (scd->NotBefore) {
t = am_parse_timestamp(r, scd->NotBefore);
if (t == 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid timestamp in NotBefore in SubjectConfirmationData.");
return HTTP_BAD_REQUEST;
}
if (t - 60000000 > now) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"NotBefore in SubjectConfirmationData was in the future.");
return HTTP_BAD_REQUEST;
}
}
if (scd->NotOnOrAfter) {
t = am_parse_timestamp(r, scd->NotOnOrAfter);
if (t == 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid timestamp in NotOnOrAfter in SubjectConfirmationData.");
return HTTP_BAD_REQUEST;
}
if (now >= t + 60000000) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"NotOnOrAfter in SubjectConfirmationData was in the past.");
return HTTP_BAD_REQUEST;
}
}
if (scd->Recipient) {
if (strcmp(scd->Recipient, url)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Wrong Recipient in SubjectConfirmationData. Current URL is: %s, Recipient is %s",
url, scd->Recipient);
return HTTP_BAD_REQUEST;
}
}
if (scd->Address && CFG_VALUE(cfg, subject_confirmation_data_address_check)) {
if (strcasecmp(scd->Address, am_compat_request_ip(r))) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Wrong Address in SubjectConfirmationData."
"Current address is \"%s\", but should have been \"%s\".",
am_compat_request_ip(r), scd->Address);
return HTTP_BAD_REQUEST;
}
}
return OK;
}
/* Validate the conditions on an Assertion.
*
* Parameters:
* request_rec *r The current request. Used to log
* errors.
* LassoSaml2Assertion *assertion The assertion we will validate.
* const char *providerID The providerID of the SP.
*
* Returns:
* OK on success, HTTP_BAD_REQUEST on failure.
*/
static int am_validate_conditions(request_rec *r,
LassoSaml2Assertion *assertion,
const char *providerID)
{
LassoSaml2Conditions *conditions;
apr_time_t now;
apr_time_t t;
GList *i;
LassoSaml2AudienceRestriction *ar;
conditions = assertion->Conditions;
if (conditions == NULL) {
/* An assertion without conditions -- nothing to validate. */
return OK;
}
if (!LASSO_IS_SAML2_CONDITIONS(conditions)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Wrong type of Conditions node.");
return HTTP_BAD_REQUEST;
}
if (conditions->Condition != NULL) {
/* This is a list of LassoSaml2ConditionAbstract - if it
* isn't empty, we have an unsupported condition.
*/
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Unsupported condition in Assertion.");
return HTTP_BAD_REQUEST;
}
now = apr_time_now();
if (conditions->NotBefore) {
t = am_parse_timestamp(r, conditions->NotBefore);
if (t == 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid timestamp in NotBefore in Condition.");
return HTTP_BAD_REQUEST;
}
if (t - 60000000 > now) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"NotBefore in Condition was in the future.");
return HTTP_BAD_REQUEST;
}
}
if (conditions->NotOnOrAfter) {
t = am_parse_timestamp(r, conditions->NotOnOrAfter);
if (t == 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid timestamp in NotOnOrAfter in Condition.");
return HTTP_BAD_REQUEST;
}
if (now >= t + 60000000) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"NotOnOrAfter in Condition was in the past.");
return HTTP_BAD_REQUEST;
}
}
for (i = g_list_first(conditions->AudienceRestriction); i != NULL;
i = g_list_next(i)) {
ar = i->data;
if (!LASSO_IS_SAML2_AUDIENCE_RESTRICTION(ar)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Wrong type of AudienceRestriction node.");
return HTTP_BAD_REQUEST;
}
if (ar->Audience == NULL || strcmp(ar->Audience, providerID)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid Audience in Conditions. Should be '%s', but was '%s'",
providerID, ar->Audience ? ar->Audience : "");
return HTTP_BAD_REQUEST;
}
}
return OK;
}
/* Validate that the ID of the Assertion has not been used.
*
* Parameters:
* request_rec *r The current request. Used to log
* errors.
* LassoSaml2Assertion *assertion The assertion we will validate.
*
* Returns:
* OK on success, HTTP_BAD_REQUEST on failure.
*/
static int am_validate_unique_assertion_id(request_rec *r,
LassoSaml2Assertion *assertion)
{
am_cache_entry_t *session = NULL;
if (assertion->ID == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Assertion ID is not present.");
return HTTP_BAD_REQUEST;
}
// Check if there is a session associate with the Assertion ID
session = am_get_request_session_by_assertionid(r, assertion->ID);
if (session != NULL) {
am_cache_unlock(r, session);
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Assertion ID %s has already been used.",
assertion->ID);
return HTTP_BAD_REQUEST;
}
return OK;
}
/* This function sets the session expire timestamp based on NotOnOrAfter
* attribute of a condition element.
*
* Parameters:
* request_rec *r The current request. Used to log
* errors.
* am_cache_entry_t *session The current session.
* LassoSaml2Assertion *assertion The assertion which we will extract
* the conditions from.
*
* Returns:
* Nothing.
*/
static void am_handle_session_expire(request_rec *r, am_cache_entry_t *session,
LassoSaml2Assertion *assertion)
{
GList *authn_itr;
LassoSaml2AuthnStatement *authn;
const char *not_on_or_after;
apr_time_t t;
for(authn_itr = g_list_first(assertion->AuthnStatement); authn_itr != NULL;
authn_itr = g_list_next(authn_itr)) {
authn = authn_itr->data;
if (!LASSO_IS_SAML2_AUTHN_STATEMENT(authn)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Wrong type of AuthnStatement node.");
continue;
}
/* Find timestamp. */
not_on_or_after = authn->SessionNotOnOrAfter;
if(not_on_or_after == NULL) {
am_diag_printf(r, "%s failed to find"
" Assertion.AuthnStatement.SessionNotOnOrAfter\n",
__func__);
continue;
}
/* Parse timestamp. */
t = am_parse_timestamp(r, not_on_or_after);
if(t == 0) {
continue;
}
am_diag_printf(r, "%s Assertion.AuthnStatement.SessionNotOnOrAfter:"
" %s\n",
__func__, am_diag_time_t_to_8601(r, t));
/* Updates the expires timestamp if this one is earlier than the
* previous timestamp.
*/
am_cache_update_expires(r, session, t);
}
}
/* Add all the attributes from an assertion to the session data for the
* current user.
*
* Parameters:
* am_cache_entry_t *s The current session.
* request_rec *r The current request.
* const char *name_id The name identifier we received from
* the IdP.
* LassoSaml2Assertion *assertion The assertion.
*
* Returns:
* HTTP_BAD_REQUEST if we couldn't find the session id of the user, or
* OK if no error occured.
*/
static int add_attributes(am_cache_entry_t *session, request_rec *r,
const char *name_id, LassoSaml2Assertion *assertion)
{
am_dir_cfg_rec *dir_cfg;
GList *atr_stmt_itr;
LassoSaml2AttributeStatement *atr_stmt;
GList *atr_itr;
LassoSaml2Attribute *attribute;
GList *value_itr;
LassoSaml2AttributeValue *value;
GList *any_itr;
char *content;
char *dump;
int ret;
dir_cfg = am_get_dir_cfg(r);
/* Set expires to whatever is set by MellonSessionLength. */
if(dir_cfg->session_length == -1) {
/* -1 means "use default. The current default is 86400 seconds. */
am_cache_update_expires(r, session, apr_time_now()
+ apr_time_make(86400, 0));
} else {
am_cache_update_expires(r, session, apr_time_now()
+ apr_time_make(dir_cfg->session_length, 0));
}
/* Set the idle timeout to whatever is set by MellonSessionIdleTimeout. */
am_cache_update_idle_timeout(r, session, dir_cfg->session_idle_timeout);
/* Save session NAME_ID information. */
ret = am_cache_env_append(session, "NAME_ID", name_id);
if(ret != OK) {
return ret;
}
/* Save session ASSERTION_ID information. */
ret = am_cache_env_append(session, "ASSERTION_ID", assertion->ID);
if(ret != OK) {
return ret;
}
/* Update expires timestamp of session. */
am_handle_session_expire(r, session, assertion);
/* assertion->AttributeStatement is a list of
* LassoSaml2AttributeStatement objects.
*/
for(atr_stmt_itr = g_list_first(assertion->AttributeStatement);
atr_stmt_itr != NULL;
atr_stmt_itr = g_list_next(atr_stmt_itr)) {
atr_stmt = atr_stmt_itr->data;
if (!LASSO_IS_SAML2_ATTRIBUTE_STATEMENT(atr_stmt)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Wrong type of AttributeStatement node.");
continue;
}
/* atr_stmt->Attribute is list of LassoSaml2Attribute objects. */
for(atr_itr = g_list_first(atr_stmt->Attribute);
atr_itr != NULL;
atr_itr = g_list_next(atr_itr)) {
attribute = atr_itr->data;
if (!LASSO_IS_SAML2_ATTRIBUTE(attribute)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Wrong type of Attribute node.");
continue;
}
if (attribute->Name == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"SAML 2.0 attribute without name.");
continue;
}
/* attribute->AttributeValue is a list of
* LassoSaml2AttributeValue objects.
*/
for(value_itr = g_list_first(attribute->AttributeValue);
value_itr != NULL;
value_itr = g_list_next(value_itr)) {
value = value_itr->data;
if (!LASSO_IS_SAML2_ATTRIBUTE_VALUE(value)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Wrong type of AttributeValue node.");
continue;
}
/* value->any is a list with the child nodes of the
* AttributeValue element.
*
* We assume that the list contains a single text node.
*/
if(value->any == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"AttributeValue element was empty.");
continue;
}
content = "";
for (any_itr = g_list_first(value->any);
any_itr != NULL;
any_itr = g_list_next(any_itr)) {
/* Verify that this is a LassoNode object. */
if(!LASSO_NODE(any_itr->data)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"AttributeValue element contained an "
" element which wasn't a Node.");
continue;
}
dump = lasso_node_dump(LASSO_NODE(any_itr->data));
if (!dump) {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"AttributeValue content dump failed.");
continue;
}
/* Use the request pool, no need to free results */
content = apr_pstrcat(r->pool, content, dump, NULL);
g_free(dump);
}
/* Decode and save the attribute. */
am_diag_printf(r, "%s name=%s value=%s\n",
__func__, attribute->Name, content);
ret = am_cache_env_append(session, attribute->Name, content);
if(ret != OK) {
return ret;
}
}
}
}
return OK;
}
/* This function validates that the received assertion verify the security level configured by
* MellonAuthnContextClassRef directives
*/
static int am_validate_authn_context_class_ref(request_rec *r,
LassoSaml2Assertion *assertion) {
int i = 0;
LassoSaml2AuthnStatement *authn_statement = NULL;
LassoSaml2AuthnContext *authn_context = NULL;
am_dir_cfg_rec *dir_cfg;
apr_array_header_t *refs;
dir_cfg = am_get_dir_cfg(r);
refs = dir_cfg->authn_context_class_ref;
if (! refs->nelts)
return OK;
if (! assertion->AuthnStatement) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Missing AuthnStatement in assertion, returning BadRequest.");
return HTTP_BAD_REQUEST;
}
/* we only consider the first AuthnStatement, I do not know of any idp
* sending more than one. */
authn_statement = g_list_first(assertion->AuthnStatement)->data;
if (! authn_statement->AuthnContext) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Missing AuthnContext in assertion, returning BadRequest.");
return HTTP_BAD_REQUEST;
}
authn_context = authn_statement->AuthnContext;
if (! authn_context->AuthnContextClassRef) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Missing AuthnContextClassRef in assertion, returning Forbidden.");
return HTTP_FORBIDDEN;
}
for (i = 0; i < refs->nelts; i++) {
const char *ref = ((char **)refs->elts)[i];
if (strcmp(ref, authn_context->AuthnContextClassRef) == 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r,
"AuthnContextClassRef (%s) matches the "
"MellonAuthnContextClassRef directive, "
"access can be granted.",
authn_context->AuthnContextClassRef);
return OK;
}
}
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"AuthnContextClassRef (%s) does not match the "
"MellonAuthnContextClassRef directive, returning "
"Forbidden.",
authn_context->AuthnContextClassRef);
return HTTP_FORBIDDEN;
}
/* This function finishes handling of a login response after it has been parsed
* by the HTTP-POST or HTTP-Artifact handler.
*
* Parameters:
* request_rec *r The current request.
* LassoLogin *login The login object which has been initialized with the
* data we have received from the IdP.
* char *relay_state The RelayState parameter from the POST data or from
* the request url. This parameter is urlencoded, and
* this function will urldecode it in-place. Therefore it
* must be possible to overwrite the data.
* is_paos If true then flow is PAOS ECP.
*
* Returns:
* A HTTP status code which should be returned to the client.
*/
static int am_handle_reply_common(request_rec *r, LassoLogin *login,
char *relay_state, char *saml_response,
bool is_paos)
{
char *url;
char *chr;
const char *name_id;
LassoSamlp2Response *response;
LassoSaml2Assertion *assertion;
const char *in_response_to;
am_dir_cfg_rec *dir_cfg;
am_cache_entry_t *session;
int rc;
const char *idp;
url = am_reconstruct_url(r);
chr = strchr(url, '?');
if (! chr) {
chr = strchr(url, ';');
}
if (chr) {
*chr = '\0';
}
dir_cfg = am_get_dir_cfg(r);
if(LASSO_PROFILE(login)->nameIdentifier == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"No acceptable name identifier found in"
" SAML 2.0 response.");
lasso_login_destroy(login);
return HTTP_BAD_REQUEST;
}
name_id = LASSO_SAML2_NAME_ID(LASSO_PROFILE(login)->nameIdentifier)
->content;
response = LASSO_SAMLP2_RESPONSE(LASSO_PROFILE(login)->response);
if (response->parent.Destination) {
if (strcmp(response->parent.Destination, url)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid Destination on Response. Should be '%s', but was '%s'",
url, response->parent.Destination);
lasso_login_destroy(login);
return HTTP_BAD_REQUEST;
}
}
if (g_list_length(response->Assertion) == 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"No Assertion in response.");
lasso_login_destroy(login);
return HTTP_BAD_REQUEST;
}
if (g_list_length(response->Assertion) > 1) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"More than one Assertion in response.");
lasso_login_destroy(login);
return HTTP_BAD_REQUEST;
}
assertion = g_list_first(response->Assertion)->data;
if (!LASSO_IS_SAML2_ASSERTION(assertion)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Wrong type of Assertion node.");
lasso_login_destroy(login);
return HTTP_BAD_REQUEST;
}
rc = am_validate_subject(r, assertion, url);
if (rc != OK) {
lasso_login_destroy(login);
return rc;
}
rc = am_validate_conditions(r, assertion,
LASSO_PROVIDER(LASSO_PROFILE(login)->server)->ProviderID);
if (rc != OK) {
lasso_login_destroy(login);
return rc;
}
rc = am_validate_unique_assertion_id(r, assertion);
if (rc != OK) {
lasso_login_destroy(login);
return rc;
}
in_response_to = response->parent.InResponseTo;
if (!is_paos) {
if(in_response_to != NULL) {
/* This is SP-initiated login. Check that we have a cookie. */
if(am_cookie_get(r) == NULL) {
/* Missing cookie. */
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"User has disabled cookies, or has lost"
" the cookie before returning from the SAML2"
" login server.");
if(dir_cfg->no_cookie_error_page != NULL) {
apr_table_setn(r->headers_out, "Location",
dir_cfg->no_cookie_error_page);
lasso_login_destroy(login);
return HTTP_SEE_OTHER;
} else {
/* Return 400 Bad Request when the user hasn't set a
* no-cookie error page.
*/
lasso_login_destroy(login);
return HTTP_BAD_REQUEST;
}
}
}
}
/* Check AuthnContextClassRef */
rc = am_validate_authn_context_class_ref(r, assertion);
if (rc != OK) {
lasso_login_destroy(login);
return rc;
}
/* Create a new session. */
session = am_new_request_session(r);
if(session == NULL) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL,
"am_new_request_session() failed");
return HTTP_INTERNAL_SERVER_ERROR;
}
rc = add_attributes(session, r, name_id, assertion);
if(rc != OK) {
am_release_request_session(r, session);
lasso_login_destroy(login);
return rc;
}
/* If requested, save the IdP ProviderId */
if(dir_cfg->idpattr != NULL) {
idp = LASSO_PROFILE(login)->remote_providerID;
if(idp != NULL) {
rc = am_cache_env_append(session, dir_cfg->idpattr, idp);
if(rc != OK) {
am_release_request_session(r, session);
lasso_login_destroy(login);
return rc;
}
}
}
rc = lasso_login_accept_sso(login);
if(rc != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Unable to accept SSO message."
" Lasso error: [%i] %s", rc, lasso_strerror(rc));
am_release_request_session(r, session);
lasso_login_destroy(login);
return HTTP_INTERNAL_SERVER_ERROR;
}
/* Save the profile state. */
rc = am_save_lasso_profile_state(r, session, LASSO_PROFILE(login),
saml_response);
if(rc != OK) {
am_release_request_session(r, session);
lasso_login_destroy(login);
return rc;
}
/* Mark user as logged in. */
session->logged_in = 1;
am_release_request_session(r, session);
lasso_login_destroy(login);
/* No RelayState - we don't know what to do. Use default login path. */
if(relay_state == NULL || strlen(relay_state) == 0) {
dir_cfg = am_get_dir_cfg(r);
apr_table_setn(r->headers_out, "Location", dir_cfg->login_path);
return HTTP_SEE_OTHER;
}
rc = am_urldecode(relay_state);
if (rc != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Could not urldecode RelayState value.");
return HTTP_BAD_REQUEST;
}
/* Check for bad characters in RelayState. */
rc = am_check_url(r, relay_state);
if (rc != OK) {
return rc;
}
rc = am_validate_redirect_url(r, relay_state);
if (rc != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid target domain in logout response RelayState parameter.");
return rc;
}
apr_table_setn(r->headers_out, "Location",
relay_state);
/* HTTP_SEE_OTHER should be a redirect where the browser doesn't repeat
* the POST data to the new page.
*/
return HTTP_SEE_OTHER;
}
/* This function handles responses to login requests received with the
* HTTP-POST binding.
*
* Parameters:
* request_rec *r The request we received.
*
* Returns:
* HTTP_SEE_OTHER on success, or an error on failure.
*/
static int am_handle_post_reply(request_rec *r)
{
int rc;
char *post_data;
char *saml_response;
LassoServer *server;
LassoLogin *login;
char *relay_state;
am_dir_cfg_rec *dir_cfg = am_get_dir_cfg(r);
int i, err;
am_diag_printf(r, "enter function %s\n", __func__);
/* Make sure that this is a POST request. */
if(r->method_number != M_POST) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Expected POST request for HTTP-POST endpoint."
" Got a %s request instead.", r->method);
/* According to the documentation for request_rec, a handler which
* doesn't handle a request method, should set r->allowed to the
* methods it handles, and return DECLINED.
* However, the default handler handles GET-requests, so for GET
* requests the handler should return HTTP_METHOD_NOT_ALLOWED.
*/
r->allowed = M_POST;
if(r->method_number == M_GET) {
return HTTP_METHOD_NOT_ALLOWED;
} else {
return DECLINED;
}
}
/* Read POST-data. */
rc = am_read_post_data(r, &post_data, NULL);
if (rc != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Error reading POST data.");
return rc;
}
/* Extract the SAMLResponse-field from the data. */
saml_response = am_extract_query_parameter(r->pool, post_data,
"SAMLResponse");
if (saml_response == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Could not find SAMLResponse field in POST data.");
return HTTP_BAD_REQUEST;
}
rc = am_urldecode(saml_response);
if (rc != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Could not urldecode SAMLResponse value.");
return rc;
}
server = am_get_lasso_server(r);
if(server == NULL) {
return HTTP_INTERNAL_SERVER_ERROR;
}
login = lasso_login_new(server);
if (login == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Failed to initialize LassoLogin object.");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* Process login responce. */
rc = lasso_login_process_authn_response_msg(login, saml_response);
am_diag_log_lasso_node(r, 0, LASSO_PROFILE(login)->response,
"SAML Response (%s):", __func__);
if (rc != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error processing authn response."
" Lasso error: [%i] %s, SAML Response: %s",
rc, lasso_strerror(rc),
am_saml_response_status_str(r,
LASSO_PROFILE(login)->response));
lasso_login_destroy(login);
err = HTTP_BAD_REQUEST;
for (i = 0; auth_mellon_errormap[i].lasso_error != 0; i++) {
if (auth_mellon_errormap[i].lasso_error == rc) {
err = auth_mellon_errormap[i].http_error;
break;
}
}
if (err == HTTP_UNAUTHORIZED) {
if (dir_cfg->no_success_error_page != NULL) {
apr_table_setn(r->headers_out, "Location",
dir_cfg->no_success_error_page);
return HTTP_SEE_OTHER;
}
}
return err;
}
/* Extract RelayState parameter. */
relay_state = am_extract_query_parameter(r->pool, post_data,
"RelayState");
/* Finish handling the reply with the common handler. */
return am_handle_reply_common(r, login, relay_state, saml_response, false);
}
/* This function handles responses to login requests received with the
* PAOS binding.
*
* Parameters:
* request_rec *r The request we received.
*
* Returns:
* HTTP_SEE_OTHER on success, or an error on failure.
*/
static int am_handle_paos_reply(request_rec *r)
{
int rc;
char *post_data;
LassoServer *server;
LassoLogin *login;
char *relay_state = NULL;
int i, err;
am_diag_printf(r, "enter function %s\n", __func__);
/* Make sure that this is a POST request. */
if(r->method_number != M_POST) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Expected POST request for paosResponse endpoint."
" Got a %s request instead.", r->method);
/* According to the documentation for request_rec, a handler which
* doesn't handle a request method, should set r->allowed to the
* methods it handles, and return DECLINED.
* However, the default handler handles GET-requests, so for GET
* requests the handler should return HTTP_METHOD_NOT_ALLOWED.
*/
r->allowed = M_POST;
if(r->method_number == M_GET) {
return HTTP_METHOD_NOT_ALLOWED;
} else {
return DECLINED;
}
}
/* Read POST-data. */
rc = am_read_post_data(r, &post_data, NULL);
if (rc != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Error reading POST data.");
return rc;
}
server = am_get_lasso_server(r);
if(server == NULL) {
return HTTP_INTERNAL_SERVER_ERROR;
}
login = lasso_login_new(server);
if (login == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Failed to initialize LassoLogin object.");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* Process login response. */
rc = lasso_login_process_paos_response_msg(login, post_data);
am_diag_log_lasso_node(r, 0, LASSO_PROFILE(login)->response,
"SAML Response (%s):", __func__);
if (rc != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error processing ECP authn response."
" Lasso error: [%i] %s, SAML Response: %s",
rc, lasso_strerror(rc),
am_saml_response_status_str(r,
LASSO_PROFILE(login)->response));
lasso_login_destroy(login);
err = HTTP_BAD_REQUEST;
for (i = 0; auth_mellon_errormap[i].lasso_error != 0; i++) {
if (auth_mellon_errormap[i].lasso_error == rc) {
err = auth_mellon_errormap[i].http_error;
break;
}
}
return err;
}
/* Extract RelayState parameter. */
if (LASSO_PROFILE(login)->msg_relayState) {
relay_state = apr_pstrdup(r->pool, LASSO_PROFILE(login)->msg_relayState);
}
/* Finish handling the reply with the common handler. */
return am_handle_reply_common(r, login, relay_state, post_data, true);
}
/* This function handles responses to login requests which use the
* HTTP-Artifact binding.
*
* Parameters:
* request_rec *r The request we received.
*
* Returns:
* HTTP_SEE_OTHER on success, or an error on failure.
*/
static int am_handle_artifact_reply(request_rec *r)
{
int rc;
LassoServer *server;
LassoLogin *login;
char *response;
char *relay_state;
char *saml_art;
char *post_data;
am_diag_printf(r, "enter function %s\n", __func__);
/* Make sure that this is a GET request. */
if(r->method_number != M_GET && r->method_number != M_POST) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Expected GET or POST request for the HTTP-Artifact endpoint."
" Got a %s request instead.", r->method);
/* According to the documentation for request_rec, a handler which
* doesn't handle a request method, should set r->allowed to the
* methods it handles, and return DECLINED.
* However, the default handler handles GET-requests, so for GET
* requests the handler should return HTTP_METHOD_NOT_ALLOWED.
* This endpoints handles GET requests, so it isn't necessary to
* check for method_number == M_GET.
*/
r->allowed = M_GET;
return DECLINED;
}
server = am_get_lasso_server(r);
if(server == NULL) {
return HTTP_INTERNAL_SERVER_ERROR;
}
login = lasso_login_new(server);
if (login == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Failed to initialize LassoLogin object.");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* Parse artifact url. */
if (r->method_number == M_GET) {
rc = lasso_login_init_request(login, r->args,
LASSO_HTTP_METHOD_ARTIFACT_GET);
if(rc != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Failed to handle login response."
" Lasso error: [%i] %s", rc, lasso_strerror(rc));
lasso_login_destroy(login);
return HTTP_BAD_REQUEST;
}
} else {
rc = am_read_post_data(r, &post_data, NULL);
if (rc != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Error reading POST data.");
return HTTP_BAD_REQUEST;
}
saml_art = am_extract_query_parameter(r->pool, post_data, "SAMLart");
if (saml_art == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, rc, r,
"Error reading POST data missing SAMLart form parameter.");
return HTTP_BAD_REQUEST;
}
ap_unescape_url(saml_art);
rc = lasso_login_init_request(login, saml_art, LASSO_HTTP_METHOD_ARTIFACT_POST);
if(rc != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Failed to handle login response."
" Lasso error: [%i] %s", rc, lasso_strerror(rc));
lasso_login_destroy(login);
return HTTP_BAD_REQUEST;
}
}
/* Prepare SOAP request. */
rc = lasso_login_build_request_msg(login);
if(rc != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Failed to prepare SOAP message for HTTP-Artifact"
" resolution."
" Lasso error: [%i] %s", rc, lasso_strerror(rc));
lasso_login_destroy(login);
return HTTP_INTERNAL_SERVER_ERROR;
}
/* Do the SOAP request. */
rc = am_httpclient_post_str(
r,
LASSO_PROFILE(login)->msg_url,
LASSO_PROFILE(login)->msg_body,
"text/xml",
(void**)&response,
NULL
);
if(rc != OK) {
lasso_login_destroy(login);
return HTTP_INTERNAL_SERVER_ERROR;
}
rc = lasso_login_process_response_msg(login, response);
am_diag_log_lasso_node(r, 0, LASSO_PROFILE(login)->response,
"SAML Response (%s):", __func__);
if(rc != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Failed to handle HTTP-Artifact response data."
" Lasso error: [%i] %s, SAML Response: %s",
rc, lasso_strerror(rc),
am_saml_response_status_str(r,
LASSO_PROFILE(login)->response));
lasso_login_destroy(login);
return HTTP_INTERNAL_SERVER_ERROR;
}
/* Extract the RelayState parameter. */
if (r->method_number == M_GET) {
relay_state = am_extract_query_parameter(r->pool, r->args,
"RelayState");
} else {
relay_state = am_extract_query_parameter(r->pool, post_data,
"RelayState");
}
/* Finish handling the reply with the common handler. */
return am_handle_reply_common(r, login, relay_state, "", false);
}
/* This function builds web form inputs for a saved POST request,
* in multipart/form-data format.
*
* Parameters:
* request_rec *r The request
* const char *post_data The savec POST request
*
* Returns:
* The web form fragment, or NULL on failure.
*/
const char *am_post_mkform_multipart(request_rec *r, const char *post_data)
{
const char *mime_part;
const char *boundary;
char *l1;
char *post_form = "";
/* Replace CRLF by LF */
post_data = am_strip_cr(r, post_data);
if ((boundary = am_xstrtok(r, post_data, "\n", &l1)) == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Cannot figure initial boundary");
return NULL;
}
for (mime_part = am_xstrtok(r, post_data, boundary, &l1); mime_part;
mime_part = am_xstrtok(r, NULL, boundary, &l1)) {
const char *hdr;
const char *name = NULL;
const char *value = NULL;
const char *input_item;
/* End of MIME data */
if (strcmp(mime_part, "--\n") == 0)
break;
/* Remove leading CRLF */
if (strstr(mime_part, "\n") == mime_part)
mime_part += 1;
/* Empty part */
if (*mime_part == '\0')
continue;
/* Find Content-Disposition header
* Looking for
* Content-Disposition: form-data; name="the_name"\n
*/
hdr = am_get_mime_header(r, mime_part, "Content-Disposition");
if (hdr == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"No Content-Disposition header in MIME section,");
continue;
}
name = am_get_header_attr(r, hdr, "form-data", "name");
if (name == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Unexpected Content-Disposition header: \"%s\"", hdr);
continue;
}
if ((value = am_get_mime_body(r, mime_part)) == NULL)
value = "";
input_item = apr_psprintf(r->pool,
" <input type=\"hidden\" name=\"%s\" value=\"%s\">\n",
am_htmlencode(r, name), am_htmlencode(r, value));
post_form = apr_pstrcat(r->pool, post_form, input_item, NULL);
}
return post_form;
}
/* This function builds web form inputs for a saved POST request,
* in application/x-www-form-urlencoded format
*
* Parameters:
* request_rec *r The request
* const char *post_data The savec POST request
*
* Returns:
* The web form fragment, or NULL on failure.
*/
const char *am_post_mkform_urlencoded(request_rec *r, const char *post_data)
{
const char *item;
char *last;
char *post_form = "";
char empty_value[] = "";
for (item = am_xstrtok(r, post_data, "&", &last); item;
item = am_xstrtok(r, NULL, "&", &last)) {
char *l1;
char *name;
char *value;
const char *input_item;
name = (char *)am_xstrtok(r, item, "=", &l1);
value = (char *)am_xstrtok(r, NULL, "=", &l1);
if (name == NULL)
continue;
if (value == NULL)
value = empty_value;
if (am_urldecode(name) != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"urldecode(\"%s\") failed", name);
return NULL;
}
if (am_urldecode(value) != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"urldecode(\"%s\") failed", value);
return NULL;
}
input_item = apr_psprintf(r->pool,
" <input type=\"hidden\" name=\"%s\" value=\"%s\">\n",
am_htmlencode(r, name), am_htmlencode(r, value));
post_form = apr_pstrcat(r->pool, post_form, input_item, NULL);
}
return post_form;
}
/* This function handles responses to repost request
*
* Parameters:
* request_rec *r The request we received.
*
* Returns:
* OK on success, or an error on failure.
*/
static int am_handle_repost(request_rec *r)
{
am_mod_cfg_rec *mod_cfg;
const char *query;
const char *enctype;
char *charset;
char *psf_id;
char *cp;
am_file_data_t *file_data;
const char *post_data;
const char *post_form;
char *output;
char *return_url;
const char *(*post_mkform)(request_rec *, const char *);
int rc;
am_diag_printf(r, "enter function %s\n", __func__);
if (am_cookie_get(r) == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Repost query without a session");
return HTTP_FORBIDDEN;
}
mod_cfg = am_get_mod_cfg(r->server);
if (!mod_cfg->post_dir) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Repost query without MellonPostDirectory.");
return HTTP_NOT_FOUND;
}
query = r->parsed_uri.query;
enctype = am_extract_query_parameter(r->pool, query, "enctype");
if (enctype == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Bad repost query: missing enctype");
return HTTP_BAD_REQUEST;
}
if (strcmp(enctype, "urlencoded") == 0) {
enctype = "application/x-www-form-urlencoded";
post_mkform = am_post_mkform_urlencoded;
} else if (strcmp(enctype, "multipart") == 0) {
enctype = "multipart/form-data";
post_mkform = am_post_mkform_multipart;
} else {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Bad repost query: invalid enctype \"%s\".", enctype);
return HTTP_BAD_REQUEST;
}
charset = am_extract_query_parameter(r->pool, query, "charset");
if (charset != NULL) {
if (am_urldecode(charset) != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Bad repost query: invalid charset \"%s\"", charset);
return HTTP_BAD_REQUEST;
}
/* Check that charset is sane */
for (cp = charset; *cp; cp++) {
if (!apr_isalnum(*cp) && (*cp != '-') && (*cp != '_')) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Bad repost query: invalid charset \"%s\"", charset);
return HTTP_BAD_REQUEST;
}
}
}
psf_id = am_extract_query_parameter(r->pool, query, "id");
if (psf_id == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Bad repost query: missing id");
return HTTP_BAD_REQUEST;
}
/* Check that Id is sane */
for (cp = psf_id; *cp; cp++) {
if (!apr_isalnum(*cp)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Bad repost query: invalid id \"%s\"", psf_id);
return HTTP_BAD_REQUEST;
}
}
return_url = am_extract_query_parameter(r->pool, query, "ReturnTo");
if (return_url == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid or missing query ReturnTo parameter.");
return HTTP_BAD_REQUEST;
}
if (am_urldecode(return_url) != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r, "Bad repost query: return");
return HTTP_BAD_REQUEST;
}
rc = am_validate_redirect_url(r, return_url);
if (rc != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid target domain in repost request ReturnTo parameter.");
return rc;
}
if ((file_data = am_file_data_new(r->pool, NULL)) == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"Bad repost query: cannot allocate file_data");
apr_table_setn(r->headers_out, "Location", return_url);
return HTTP_SEE_OTHER;
}
file_data->path = apr_psprintf(file_data->pool, "%s/%s",
mod_cfg->post_dir, psf_id);
rc = am_file_read(file_data);
if (rc != APR_SUCCESS) {
/* Unable to load repost data. Just redirect us instead. */
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"Bad repost query: %s", file_data->strerror);
apr_table_setn(r->headers_out, "Location", return_url);
return HTTP_SEE_OTHER;
} else {
post_data = file_data->contents;
}
if ((post_form = (*post_mkform)(r, post_data)) == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r, "am_post_mkform() failed");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (charset != NULL) {
ap_set_content_type(r, apr_psprintf(r->pool,
"text/html; charset=\"%s\"", charset));
charset = apr_psprintf(r->pool, " accept-charset=\"%s\"", charset);
} else {
ap_set_content_type(r, "text/html");
charset = (char *)"";
}
output = apr_psprintf(r->pool,
"<!DOCTYPE html>\n"
"<html>\n"
" <head>\n"
" <title>SAML rePOST request</title>\n"
" </head>\n"
" <body onload=\"document.forms[0].submit()\">\n"
" <noscript>\n"
" <strong>Note:</strong> Since your browser does not support JavaScript, you must press the button below once to proceed.\n"
" </noscript>\n"
" <form method=\"POST\" action=\"%s\" enctype=\"%s\"%s>\n%s"
" <noscript>\n"
" <input type=\"submit\" value=\"Proceed\">\n"
" </noscript>\n"
" </form>\n"
" </body>\n"
"</html>\n",
am_htmlencode(r, return_url), enctype, charset, post_form);
ap_rputs(output, r);
return OK;
}
/* This function handles responses to metadata request
*
* Parameters:
* request_rec *r The request we received.
*
* Returns:
* OK on success, or an error on failure.
*/
static int am_handle_metadata(request_rec *r)
{
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
LassoServer *server;
const char *data;
am_diag_printf(r, "enter function %s\n", __func__);
server = am_get_lasso_server(r);
if(server == NULL)
return HTTP_INTERNAL_SERVER_ERROR;
cfg = cfg->inherit_server_from;
data = cfg->sp_metadata_file ? cfg->sp_metadata_file->contents : NULL;
if (data == NULL)
return HTTP_INTERNAL_SERVER_ERROR;
ap_set_content_type(r, "application/samlmetadata+xml");
ap_rputs(data, r);
return OK;
}
/* Use Lasso Login to set the HTTP content & headers for HTTP-Redirect binding.
*
* Parameters:
* request_rec *r
* LassoLogin *login
*
* Returns:
* HTTP_SEE_OTHER on success, or an error on failure.
*/
static int am_set_authn_request_redirect_content(request_rec *r, LassoLogin *login)
{
char *redirect_to;
/* The URL we should send the message to. */
redirect_to = apr_pstrdup(r->pool, LASSO_PROFILE(login)->msg_url);
/* Check if the lasso library added the RelayState. If lasso didn't add
* a RelayState parameter, then we add one ourself. This should hopefully
* be removed in the future.
*/
if(strstr(redirect_to, "&RelayState=") == NULL
&& strstr(redirect_to, "?RelayState=") == NULL) {
/* The url didn't contain the relaystate parameter. */
redirect_to = apr_pstrcat(
r->pool, redirect_to, "&RelayState=",
am_urlencode(r->pool, LASSO_PROFILE(login)->msg_relayState),
NULL
);
}
apr_table_setn(r->headers_out, "Location", redirect_to);
/* We don't want to include POST data (in case this was a POST request). */
return HTTP_SEE_OTHER;
}
/* Use Lasso Login to set the HTTP content & headers for HTTP-POST binding.
*
* Parameters:
* request_rec *r The request we are processing.
* LassoLogin *login The login message.
*
* Returns:
* OK on success, or an error on failure.
*/
static int am_set_authn_request_post_content(request_rec *r, LassoLogin *login)
{
char *url;
char *message;
char *relay_state;
char *output;
url = am_htmlencode(r, LASSO_PROFILE(login)->msg_url);
message = am_htmlencode(r, LASSO_PROFILE(login)->msg_body);
relay_state = am_htmlencode(r, LASSO_PROFILE(login)->msg_relayState);
output = apr_psprintf(r->pool,
"<!DOCTYPE html>\n"
"<html>\n"
" <head>\n"
" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n"
" <title>POST data</title>\n"
" </head>\n"
" <body onload=\"document.forms[0].submit()\">\n"
" <noscript><p>\n"
" <strong>Note:</strong> Since your browser does not support JavaScript, you must press the button below once to proceed.\n"
" </p></noscript>\n"
" <form method=\"POST\" action=\"%s\">\n"
" <input type=\"hidden\" name=\"SAMLRequest\" value=\"%s\">\n"
" <input type=\"hidden\" name=\"RelayState\" value=\"%s\">\n"
" <noscript>\n"
" <input type=\"submit\" value=\"Proceed\">\n"
" </noscript>\n"
" </form>\n"
" </body>\n"
"</html>\n",
url, message, relay_state);
ap_set_content_type(r, "text/html");
ap_rputs(output, r);
return OK;
}
/* Use Lasso Login to set the HTTP content & headers for PAOS binding.
*
* Parameters:
* request_rec *r The request we are processing.
* LassoLogin *login The login message.
*
* Returns:
* OK on success, or an error on failure.
*/
static int am_set_authn_request_paos_content(request_rec *r, LassoLogin *login)
{
ap_set_content_type(r, MEDIA_TYPE_PAOS);
ap_rputs(LASSO_PROFILE(login)->msg_body, r);
return OK;
}
/*
* Create and initialize LassoLogin object
*
* This function creates a LassoLogin object and initializes it to the
* greatest extent possible to allow it to be shared by multiple
* callers. There are two return values. The function return is an
* error code, the login_return parameter is a pointer in which to
* receive the LassoLogin object. The caller MUST free the returned
* login object using lasso_login_destroy() in all cases (even when
* this function returns an error), the only execption is if the
* returned LassoLogin is NULL.
*
* Parameters:
* r The request we are processing.
* login_return The returned LassoLogin object (caller must free)
* idp The provider id of remote Idp
* [optional, may be NULL]
* http_method Specifies the SAML profile to use
* destination_url If the idp parameter is non-NULL this should be
* the URL of the IdP endpoint the message is being sent to
* [optional, may be NULL]
* assertion_consumer_service_url
* The URL of this SP's endpoint which will receive the
* SAML assertion
* return_to_url Used to initialize the RelayState value
* is_passive The SAML IsPassive flag
*
* Returns:
* OK on success, HTTP error code otherwise
*
*/
static int am_init_authn_request_common(request_rec *r,
LassoLogin **login_return,
const char *idp,
LassoHttpMethod http_method,
const char *destination_url,
const char *assertion_consumer_service_url,
const char *return_to_url,
int is_passive)
{
gint ret;
am_dir_cfg_rec *dir_cfg;
LassoServer *server;
LassoLogin *login;
LassoSamlp2AuthnRequest *request;
const char *sp_name;
*login_return = NULL;
dir_cfg = am_get_dir_cfg(r);
server = am_get_lasso_server(r);
if (server == NULL) {
return HTTP_INTERNAL_SERVER_ERROR;
}
login = lasso_login_new(server);
if(login == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error creating LassoLogin object from LassoServer.");
return HTTP_INTERNAL_SERVER_ERROR;
}
*login_return = login;
ret = lasso_login_init_authn_request(login, idp, http_method);
if(ret != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error creating login request."
" Lasso error: [%i] %s", ret, lasso_strerror(ret));
return HTTP_INTERNAL_SERVER_ERROR;
}
request = LASSO_SAMLP2_AUTHN_REQUEST(LASSO_PROFILE(login)->request);
if (request->NameIDPolicy == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error creating login request. Please verify the "
"MellonSPMetadataFile directive.");
return HTTP_INTERNAL_SERVER_ERROR;
}
/*
* Make sure the Destination attribute is set to the IdP
* SingleSignOnService endpoint. This is required for
* Shibboleth 2 interoperability, and older versions of
* lasso (at least up to 2.2.91) did not do it.
*/
if (destination_url &&
LASSO_SAMLP2_REQUEST_ABSTRACT(request)->Destination == NULL) {
lasso_assign_string(LASSO_SAMLP2_REQUEST_ABSTRACT(request)->Destination,
destination_url);
}
if (assertion_consumer_service_url) {
lasso_assign_string(request->AssertionConsumerServiceURL,
assertion_consumer_service_url);
/* Can't set request->ProtocolBinding (which is usually set along side
* AssertionConsumerServiceURL) as there is no immediate function
* like lasso_provider_get_assertion_consumer_service_url to get them.
* So leave that empty for now, it is not strictly required */
}
request->ForceAuthn = FALSE;
request->IsPassive = is_passive;
request->NameIDPolicy->AllowCreate = TRUE;
sp_name = am_get_config_langstring(dir_cfg->sp_org_display_name, NULL);
if (sp_name) {
lasso_assign_string(request->ProviderName, sp_name);
}
LASSO_SAMLP2_REQUEST_ABSTRACT(request)->Consent
= g_strdup(LASSO_SAML2_CONSENT_IMPLICIT);
/* Add AuthnContextClassRef */
if (dir_cfg->authn_context_class_ref->nelts) {
apr_array_header_t *refs = dir_cfg->authn_context_class_ref;
int i = 0;
LassoSamlp2RequestedAuthnContext *req_authn_context;
req_authn_context = (LassoSamlp2RequestedAuthnContext*)
lasso_samlp2_requested_authn_context_new();
request->RequestedAuthnContext = req_authn_context;
for (i = 0; i < refs->nelts; i++) {
const char *ref = ((char **)refs->elts)[i];
req_authn_context->AuthnContextClassRef =
g_list_append(req_authn_context->AuthnContextClassRef,
g_strdup(ref));
AM_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r,
"adding AuthnContextClassRef %s to the "
"AuthnRequest", ref);
}
if (dir_cfg->authn_context_comparison_type != NULL) {
lasso_assign_string(request->RequestedAuthnContext->Comparison,
dir_cfg->authn_context_comparison_type);
}
}
LASSO_PROFILE(login)->msg_relayState = g_strdup(return_to_url);
#ifdef HAVE_ECP
{
am_req_cfg_rec *req_cfg;
ECPServiceOptions unsupported_ecp_options;
req_cfg = am_get_req_cfg(r);
/*
* Currently we only support the WANT_AUTHN_SIGNED ECP option,
* if a client sends us anything else let them know it's not
* implemented.
*
* We do test for CHANNEL_BINDING below but that's because if
* and when we support it we don't want to forget channel
* bindings require the authn request to be signed.
*/
unsupported_ecp_options =
req_cfg->ecp_service_options &
~ECP_SERVICE_OPTION_WANT_AUTHN_SIGNED;
if (unsupported_ecp_options) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Unsupported ECP service options [%s]",
am_ecp_service_options_str(r->pool,
unsupported_ecp_options));
return HTTP_NOT_IMPLEMENTED;
}
/*
* The signature hint must be set prior to calling
* lasso_login_build_authn_request_msg
*/
if (req_cfg->ecp_service_options &
(ECP_SERVICE_OPTION_WANT_AUTHN_SIGNED |
ECP_SERVICE_OPTION_CHANNEL_BINDING)) {
/*
* authnRequest should be signed if the client requested it
* or if channel bindings are enabled.
*/
lasso_profile_set_signature_hint(LASSO_PROFILE(login),
LASSO_PROFILE_SIGNATURE_HINT_FORCE);
}
}
#endif
ret = lasso_login_build_authn_request_msg(login);
if (ret != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error building login request."
" Lasso error: [%i] %s", ret, lasso_strerror(ret));
return HTTP_INTERNAL_SERVER_ERROR;
}
return OK;
}
/* Use Lasso Login to set the HTTP content & headers for selected binding.
*
* Parameters:
* request_rec *r The request we are processing.
* LassoLogin *login The login message.
*
* Returns:
* HTTP response code
*/
static int am_set_authn_request_content(request_rec *r, LassoLogin *login)
{
am_diag_log_lasso_node(r, 0, LASSO_PROFILE(login)->request,
"SAML AuthnRequest: http_method=%s URL=%s",
am_diag_lasso_http_method_str(login->http_method),
LASSO_PROFILE(login)->msg_url);
switch (login->http_method) {
case LASSO_HTTP_METHOD_REDIRECT:
return am_set_authn_request_redirect_content(r, login);
case LASSO_HTTP_METHOD_POST:
return am_set_authn_request_post_content(r, login);
case LASSO_HTTP_METHOD_PAOS:
return am_set_authn_request_paos_content(r, login);
default:
/* We should never get here. */
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Unsupported http_method.");
return HTTP_INTERNAL_SERVER_ERROR;
}
}
#ifdef HAVE_ECP
/* Build an IDPList whose members have an endpoint supporing
* the protocol_type and http_method.
*/
static LassoNode *
am_get_idp_list(const LassoServer *server, LassoMdProtocolType protocol_type, LassoHttpMethod http_method)
{
GList *idp_entity_ids = NULL;
GList *entity_id = NULL;
GList *idp_entries = NULL;
LassoSamlp2IDPList *idp_list;
LassoSamlp2IDPEntry *idp_entry;
idp_list = LASSO_SAMLP2_IDP_LIST(lasso_samlp2_idp_list_new());
idp_entity_ids =
lasso_server_get_filtered_provider_list(server,
LASSO_PROVIDER_ROLE_IDP,
protocol_type, http_method);
for (entity_id = g_list_first(idp_entity_ids); entity_id != NULL;
entity_id = g_list_next(entity_id)) {
idp_entry = LASSO_SAMLP2_IDP_ENTRY(lasso_samlp2_idp_entry_new());
idp_entry->ProviderID = g_strdup(entity_id->data);
/* RFE: we should have a mechanism to obtain these values */
idp_entry->Name = NULL;
idp_entry->Loc = NULL;
idp_entries = g_list_append(idp_entries, idp_entry);
}
lasso_release_list_of_strings(idp_entity_ids);
idp_list->IDPEntry = idp_entries;
return LASSO_NODE(idp_list);
}
/* Send AuthnRequest using PAOS binding.
*
* Parameters:
* request_rec *r
*
* Returns:
* OK on success, or an error on failure.
*/
static int am_send_paos_authn_request(request_rec *r)
{
gint ret;
am_dir_cfg_rec *dir_cfg;
LassoServer *server;
LassoLogin *login;
const char *relay_state = NULL;
char *assertion_consumer_service_url;
int is_passive = FALSE;
dir_cfg = am_get_dir_cfg(r);
server = am_get_lasso_server(r);
if(server == NULL) {
return HTTP_INTERNAL_SERVER_ERROR;
}
relay_state = am_reconstruct_url(r);
assertion_consumer_service_url =
am_get_assertion_consumer_service_by_binding(LASSO_PROVIDER(server),
"PAOS");
ret = am_init_authn_request_common(r, &login,
NULL, LASSO_HTTP_METHOD_PAOS, NULL,
assertion_consumer_service_url,
relay_state, is_passive);
g_free(assertion_consumer_service_url);
if (ret != OK) {
if (login) {
lasso_login_destroy(login);
}
return ret;
}
if (CFG_VALUE(dir_cfg, ecp_send_idplist)) {
lasso_profile_set_idp_list(LASSO_PROFILE(login),
am_get_idp_list(LASSO_PROFILE(login)->server,
LASSO_MD_PROTOCOL_TYPE_SINGLE_SIGN_ON,
LASSO_HTTP_METHOD_SOAP));
}
ret = am_set_authn_request_content(r, login);
lasso_login_destroy(login);
return ret;
}
#endif /* HAVE_ECP */
/* Create and send an authentication request.
*
* Parameters:
* request_rec *r The request we are processing.
* const char *idp The entityID of the IdP.
* const char *return_to The URL we should redirect to when receiving the request.
* int is_passive The value of the IsPassive flag in <AuthnRequest>
*
* Returns:
* HTTP response code indicating success or failure.
*/
static int am_send_login_authn_request(request_rec *r, const char *idp,
const char *return_to_url,
int is_passive)
{
int ret;
LassoServer *server;
LassoProvider *provider;
LassoHttpMethod http_method;
char *destination_url;
char *assertion_consumer_service_url;
LassoLogin *login;
/* Add cookie for cookie test. We know that we should have
* a valid cookie when we return from the IdP after SP-initiated
* login.
* Ensure that SameSite is set to None for this cookie if SameSite
* is allowed to be set as the cookie otherwise gets lost on
* HTTP-POST binding messages.
*/
apr_table_setn(r->notes, AM_FORCE_SAMESITE_NONE_NOTE, "1");
am_cookie_set(r, "cookietest");
apr_table_unset(r->notes, AM_FORCE_SAMESITE_NONE_NOTE);
server = am_get_lasso_server(r);
if(server == NULL) {
return HTTP_INTERNAL_SERVER_ERROR;
}
/* Find our IdP. */
provider = lasso_server_get_provider(server, idp);
if (provider == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Could not find metadata for the IdP \"%s\".",
idp);
return HTTP_INTERNAL_SERVER_ERROR;
}
/* Determine what binding and endpoint we should use when
* sending the request.
*/
http_method = LASSO_HTTP_METHOD_REDIRECT;
destination_url = lasso_provider_get_metadata_one(
provider, "SingleSignOnService HTTP-Redirect");
if (destination_url == NULL) {
/* HTTP-Redirect unsupported - try HTTP-POST. */
http_method = LASSO_HTTP_METHOD_POST;
destination_url = lasso_provider_get_metadata_one(
provider, "SingleSignOnService HTTP-POST");
}
if (destination_url == NULL) {
/* Both HTTP-Redirect and HTTP-POST unsupported - give up. */
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Could not find a supported SingleSignOnService endpoint"
" for the IdP \"%s\".", idp);
return HTTP_INTERNAL_SERVER_ERROR;
}
assertion_consumer_service_url =
lasso_provider_get_assertion_consumer_service_url(
LASSO_PROVIDER(server), NULL);
ret = am_init_authn_request_common(r, &login, idp, http_method,
destination_url,
assertion_consumer_service_url,
return_to_url, is_passive);
g_free(destination_url);
g_free(assertion_consumer_service_url);
if (ret != OK) {
if (login) {
lasso_login_destroy(login);
}
return ret;
}
ret = am_set_authn_request_content(r, login);
lasso_login_destroy(login);
return ret;
}
/* Handle the "auth" endpoint.
*
* This endpoint is included for backwards-compatibility.
*
* Parameters:
* request_rec *r The request we received.
*
* Returns:
* OK or HTTP_SEE_OTHER on success, an error on failure.
*/
static int am_handle_auth(request_rec *r)
{
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
const char *relay_state;
am_diag_printf(r, "enter function %s\n", __func__);
relay_state = am_reconstruct_url(r);
/* Check if IdP discovery is in use and no IdP was selected yet */
if ((cfg->discovery_url != NULL) &&
(am_extract_query_parameter(r->pool, r->args, "IdP") == NULL)) {
return am_start_disco(r, relay_state);
}
/* If IdP discovery is in use and we have an IdP selected,
* set the relay_state
*/
if (cfg->discovery_url != NULL) {
char *return_url;
return_url = am_extract_query_parameter(r->pool, r->args, "ReturnTo");
if ((return_url != NULL) && am_urldecode((char *)return_url) == 0)
relay_state = return_url;
}
return am_send_login_authn_request(r, am_get_idp(r), relay_state, FALSE);
}
/* This function handles requests to the login handler.
*
* Parameters:
* request_rec *r The request.
*
* Returns:
* OK on success, or an error if any of the steps fail.
*/
static int am_handle_login(request_rec *r)
{
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
char *idp_param;
const char *idp;
char *return_to;
int is_passive;
int ret;
am_diag_printf(r, "enter function %s\n", __func__);
return_to = am_extract_query_parameter(r->pool, r->args, "ReturnTo");
if(return_to == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Missing required ReturnTo parameter.");
return HTTP_BAD_REQUEST;
}
ret = am_urldecode(return_to);
if(ret != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error urldecoding ReturnTo parameter.");
return ret;
}
ret = am_validate_redirect_url(r, return_to);
if(ret != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid target domain in login request ReturnTo parameter.");
return ret;
}
idp_param = am_extract_query_parameter(r->pool, r->args, "IdP");
if(idp_param != NULL) {
ret = am_urldecode(idp_param);
if(ret != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error urldecoding IdP parameter.");
return ret;
}
}
ret = am_get_boolean_query_parameter(r, "IsPassive", &is_passive, FALSE);
if (ret != OK) {
return ret;
}
if(idp_param != NULL) {
idp = idp_param;
} else if(cfg->discovery_url) {
if(is_passive) {
/* We cannot currently do discovery with passive authentication requests. */
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Discovery service with passive authentication request unsupported.");
return HTTP_INTERNAL_SERVER_ERROR;
}
return am_start_disco(r, return_to);
} else {
/* No discovery service -- just use the default IdP. */
idp = am_get_idp(r);
}
return am_send_login_authn_request(r, idp, return_to, is_passive);
}
/* This function probes an URL (HTTP GET)
*
* Parameters:
* request_rec *r The request.
* const char *url The URL
* int timeout Timeout in seconds
*
* Returns:
* OK on success, or an error if any of the steps fail.
*/
static int am_probe_url(request_rec *r, const char *url, int timeout)
{
void *dontcare;
apr_size_t len;
long status;
int error;
status = 0;
if ((error = am_httpclient_get(r, url, &dontcare, &len,
timeout, &status)) != OK)
return error;
if (status != HTTP_OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Probe on \"%s\" returned HTTP %ld",
url, status);
return status;
}
return OK;
}
/* This function handles requests to the probe discovery handler
*
* Parameters:
* request_rec *r The request.
*
* Returns:
* OK on success, or an error if any of the steps fail.
*/
static int am_handle_probe_discovery(request_rec *r) {
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
LassoServer *server;
const char *disco_idp = NULL;
int timeout;
char *return_to;
char *idp_param;
char *redirect_url;
int ret;
am_diag_printf(r, "enter function %s\n", __func__);
server = am_get_lasso_server(r);
if(server == NULL) {
return HTTP_INTERNAL_SERVER_ERROR;
}
/*
* If built-in IdP discovery is not configured, return error.
* For now we only have the get-metadata metadata method, so this
* information is not saved in configuration nor it is checked here.
*/
timeout = cfg->probe_discovery_timeout;
if (timeout == -1) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"probe discovery handler invoked but not "
"configured. Please set MellonProbeDiscoveryTimeout.");
return HTTP_INTERNAL_SERVER_ERROR;
}
/*
* Check for mandatory arguments early to avoid sending
* probles for nothing.
*/
return_to = am_extract_query_parameter(r->pool, r->args, "return");
if(return_to == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Missing required return parameter.");
return HTTP_BAD_REQUEST;
}
ret = am_urldecode(return_to);
if (ret != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, ret, r,
"Could not urldecode return value.");
return HTTP_BAD_REQUEST;
}
ret = am_validate_redirect_url(r, return_to);
if (ret != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid target domain in probe discovery return parameter.");
return ret;
}
idp_param = am_extract_query_parameter(r->pool, r->args, "returnIDParam");
if(idp_param == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Missing required returnIDParam parameter.");
return HTTP_BAD_REQUEST;
}
ret = am_urldecode(idp_param);
if (ret != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, ret, r,
"Could not urldecode returnIDParam value.");
return HTTP_BAD_REQUEST;
}
/*
* Proceed with built-in IdP discovery.
*
* First try sending probes to IdP configured for discovery.
* Second send probes for all configured IdP
* The first to answer is chosen.
* If none answer, use the first configured IdP
*/
if (!apr_is_empty_table(cfg->probe_discovery_idp)) {
const apr_array_header_t *header;
apr_table_entry_t *elts;
const char *url;
const char *idp;
int i;
header = apr_table_elts(cfg->probe_discovery_idp);
elts = (apr_table_entry_t *)header->elts;
for (i = 0; i < header->nelts; i++) {
idp = elts[i].key;
url = elts[i].val;
if (am_probe_url(r, url, timeout) == OK) {
disco_idp = idp;
break;
}
}
} else {
GList *iter;
GList *idp_list;
const char *idp;
idp_list = g_hash_table_get_keys(server->providers);
for (iter = idp_list; iter != NULL; iter = iter->next) {
idp = iter->data;
if (am_probe_url(r, idp, timeout) == OK) {
disco_idp = idp;
break;
}
}
g_list_free(idp_list);
}
/*
* On failure, fail if a MellonProbeDiscoveryIdP
* list was provided, otherwise try first IdP.
*/
if (disco_idp == NULL) {
if (!apr_is_empty_table(cfg->probe_discovery_idp)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"probeDiscovery failed and non empty "
"MellonProbeDiscoveryIdP was provided.");
return HTTP_INTERNAL_SERVER_ERROR;
}
disco_idp = am_first_idp(r);
if (disco_idp == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"probeDiscovery found no usable IdP.");
return HTTP_INTERNAL_SERVER_ERROR;
} else {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r, "probeDiscovery "
"failed, trying default IdP %s", disco_idp);
}
} else {
AM_LOG_RERROR(APLOG_MARK, APLOG_INFO, 0, r,
"probeDiscovery using %s", disco_idp);
}
redirect_url = apr_psprintf(r->pool, "%s%s%s=%s", return_to,
strchr(return_to, '?') ? "&" : "?",
am_urlencode(r->pool, idp_param),
am_urlencode(r->pool, disco_idp));
apr_table_setn(r->headers_out, "Location", redirect_url);
return HTTP_SEE_OTHER;
}
/* This function handles responses to request on our endpoint
*
* Parameters:
* request_rec *r The request we received.
*
* Returns:
* OK on success, or an error on failure.
*/
int am_handler(request_rec *r)
{
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
#ifdef HAVE_ECP
am_req_cfg_rec *req_cfg = am_get_req_cfg(r);
#endif /* HAVE_ECP */
const char *endpoint;
/*
* Normally this content handler is used to dispatch to the SAML
* endpoints implmented by mod_auth_mellon. SAML endpoint dispatch
* occurs when the URI begins with the SAML endpoint path.
*
* However, this handler is also responsible for generating ECP
* authn requests, in this case the URL will be a protected
* resource we're doing authtentication for. Early in the request
* processing pipeline we detected we were doing ECP authn and set
* a flag on the request. Here we test for that flag and if true
* respond with the ECP PAOS authn request.
*
* If the request is neither for a SAML endpoint nor one that
* requires generating an ECP authn we decline handling the request.
*/
#ifdef HAVE_ECP
if (req_cfg->ecp_authn_req) { /* Are we doing ECP? */
return am_send_paos_authn_request(r);
}
#endif /* HAVE_ECP */
/* Check if this is a request for one of our endpoints. We check if
* the uri starts with the path set with the MellonEndpointPath
* configuration directive.
*/
if(strstr(r->uri, cfg->endpoint_path) != r->uri)
return DECLINED;
endpoint = &r->uri[strlen(cfg->endpoint_path)];
if (!strcmp(endpoint, "metadata")) {
return am_handle_metadata(r);
} else if (!strcmp(endpoint, "repost")) {
return am_handle_repost(r);
} else if(!strcmp(endpoint, "postResponse")) {
return am_handle_post_reply(r);
} else if(!strcmp(endpoint, "artifactResponse")) {
return am_handle_artifact_reply(r);
} else if(!strcmp(endpoint, "paosResponse")) {
return am_handle_paos_reply(r);
} else if(!strcmp(endpoint, "auth")) {
return am_handle_auth(r);
} else if(!strcmp(endpoint, "logout")
|| !strcmp(endpoint, "logoutRequest")) {
/* logoutRequest is included for backwards-compatibility
* with version 0.0.6 and older.
*/
return am_handle_logout(r);
} else if(!strcmp(endpoint, "invalidate")) {
return am_handle_invalidate(r);
} else if(!strcmp(endpoint, "login")) {
return am_handle_login(r);
} else if(!strcmp(endpoint, "probeDisco")) {
return am_handle_probe_discovery(r);
} else {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Endpoint \"%s\" not handled by mod_auth_mellon.",
endpoint);
return HTTP_NOT_FOUND;
}
}
/**
* Trigger a login operation from a "normal" request.
*
* Parameters:
* request_rec *r The request we received.
*
* Returns:
* HTTP_SEE_OTHER on success, or an error on failure.
*/
static int am_start_auth(request_rec *r)
{
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
const char *endpoint = am_get_endpoint_url(r);
const char *return_to;
const char *idp;
const char *login_url;
am_diag_printf(r, "enter function %s\n", __func__);
return_to = am_reconstruct_url(r);
/* If this is a POST request, attempt to save it */
if (r->method_number == M_POST) {
if (CFG_VALUE(cfg, post_replay)) {
if (am_save_post(r, &return_to) != OK)
return HTTP_INTERNAL_SERVER_ERROR;
} else {
AM_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r,
"POST data dropped because we do not have a"
" MellonPostReplay is not enabled.");
}
}
/* Check if IdP discovery is in use. */
if (cfg->discovery_url) {
return am_start_disco(r, return_to);
}
idp = am_get_idp(r);
login_url = apr_psprintf(r->pool, "%slogin?ReturnTo=%s&IdP=%s",
endpoint,
am_urlencode(r->pool, return_to),
am_urlencode(r->pool, idp));
AM_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r,
"Redirecting to login URL: %s", login_url);
apr_table_setn(r->headers_out, "Location", login_url);
return HTTP_SEE_OTHER;
}
int am_auth_mellon_user(request_rec *r)
{
am_dir_cfg_rec *dir = am_get_dir_cfg(r);
int return_code = HTTP_UNAUTHORIZED;
am_cache_entry_t *session;
const char *ajax_header;
if (r->main) {
/* We are a subrequest. Trust the main request to have
* performed the authentication.
*/
return OK;
}
/* Check that the user has enabled authentication for this directory. */
if(dir->enable_mellon == am_enable_off
|| dir->enable_mellon == am_enable_default) {
return DECLINED;
}
am_diag_printf(r, "enter function %s\n", __func__);
/* Set defaut Cache-Control headers within this location */
if (CFG_VALUE(dir, send_cache_control_header)) {
am_set_cache_control_headers(r);
}
/* Check if this is a request for one of our endpoints. We check if
* the uri starts with the path set with the MellonEndpointPath
* configuration directive.
*/
if(strstr(r->uri, dir->endpoint_path) == r->uri) {
/* No access control on our internal endpoints. */
return OK;
}
/* Get the session of this request. */
session = am_get_request_session(r);
if(dir->enable_mellon == am_enable_auth) {
/* This page requires the user to be authenticated and authorized. */
if(session == NULL || !session->logged_in) {
/* We don't have a valid session. */
am_diag_printf(r, "%s am_enable_auth, no valid session\n",
__func__);
if(session) {
/* Release the session. */
am_release_request_session(r, session);
}
/*
* If this is an AJAX request, we cannot proceed to the IdP,
* Just fail early to save our resources
*/
ajax_header = apr_table_get(r->headers_in, "X-Requested-With");
if (ajax_header != NULL &&
strcmp(ajax_header, "XMLHttpRequest") == 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_INFO, 0, r,
"Deny unauthenticated X-Requested-With XMLHttpRequest "
"(AJAX) request");
return HTTP_FORBIDDEN;
}
#ifdef HAVE_ECP
/*
* If PAOS set a flag on the request indicating we're
* doing ECP and allow the request to proceed through the
* request handlers until we reach am_handler which then
* checks the flag and if True initiates an ECP transaction.
* See am_check_uid for detailed explanation.
*/
bool is_paos;
int error_code;
is_paos = am_is_paos_request(r, &error_code);
if (error_code) return HTTP_BAD_REQUEST;
if (is_paos) {
am_req_cfg_rec *req_cfg;
req_cfg = am_get_req_cfg(r);
req_cfg->ecp_authn_req = true;
return OK;
} else {
/* Send the user to the authentication page on the IdP. */
return am_start_auth(r);
}
#else /* HAVE_ECP */
/* Send the user to the authentication page on the IdP. */
return am_start_auth(r);
#endif /* HAVE_ECP */
}
am_diag_printf(r, "%s am_enable_auth, have valid session\n",
__func__);
/* Verify that the user has access to this resource. */
return_code = am_check_permissions(r, session);
if(return_code != OK) {
am_diag_printf(r, "%s failed am_check_permissions, status=%d\n",
__func__, return_code);
am_release_request_session(r, session);
return return_code;
}
/* Update the idle timeout to whatever is set by MellonSessionIdleTimeout. */
am_cache_update_idle_timeout(r, session, dir->session_idle_timeout);
/* The user has been authenticated, and we can now populate r->user
* and the r->subprocess_env with values from the session store.
*/
am_cache_env_populate(r, session);
/* Release the session. */
am_release_request_session(r, session);
return OK;
} else {
/* dir->enable_mellon == am_enable_info:
* We should pass information about the user to the web application
* if the user is authorized to access this resource.
* However, we shouldn't attempt to do any access control.
*/
if(session != NULL
&& session->logged_in
&& am_check_permissions(r, session) == OK) {
am_diag_printf(r, "%s am_enable_info, have valid session\n",
__func__);
/* Update the idle timeout to whatever is set by MellonSessionIdleTimeout. */
am_cache_update_idle_timeout(r, session, dir->session_idle_timeout);
/* The user is authenticated and has access to the resource.
* Now we populate the environment with information about
* the user.
*/
am_cache_env_populate(r, session);
} else {
am_diag_printf(r, "%s am_enable_info, no valid session\n",
__func__);
}
if(session != NULL) {
/* Release the session. */
am_release_request_session(r, session);
}
/* We shouldn't really do any access control, so we always return
* DECLINED.
*/
return DECLINED;
}
}
int am_check_uid(request_rec *r)
{
am_dir_cfg_rec *dir = am_get_dir_cfg(r);
am_cache_entry_t *session;
int return_code = HTTP_UNAUTHORIZED;
if (r->main) {
/* We are a subrequest. Trust the main request to have
* performed the authentication.
*/
if (r->main->user) {
/* Make sure that the username from the main request is
* available in the subrequest.
*/
r->user = apr_pstrdup(r->pool, r->main->user);
}
return OK;
}
/* Check that the user has enabled authentication for this directory. */
if(dir->enable_mellon == am_enable_off
|| dir->enable_mellon == am_enable_default) {
return DECLINED;
}
am_diag_printf(r, "enter function %s\n", __func__);
#ifdef HAVE_ECP
am_req_cfg_rec *req_cfg = am_get_req_cfg(r);
if (req_cfg->ecp_authn_req) {
AM_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r,
"am_check_uid is performing ECP authn request flow");
/*
* Normally when a protected resource requires authentication
* the request processing pipeline is exited early by
* responding with either a 401 or a redirect. But the flow
* for ECP is different, there will be a successful response
* (200) but instead of the response body containing the
* protected resource it will contain a SAML AuthnRequest
* with the Content-Type indicating it's PAOS ECP.
*
* In order to return a 200 Success with a PAOS body we have
* to reach the handler stage of the request processing
* pipeline. But this is a protected resource and we won't
* reach the handler stage unless authn and authz are
* satisfied. Therefore we lie and return results which
* indicate authn and authz are satisfied. This is OK because
* we're not actually going to respond with the protected
* resource, instead we'll be responsing with a SAML request.
*
* Apache's internal request logic
* (ap_process_request_internal) requires that after a
* successful return from the check_user_id authentication
* hook the r->user value be non-NULL. This makes sense
* because authentication establishes who the authenticated
* principal is. But with ECP flow there is no authenticated
* user at this point, we're just faking successful
* authentication in order to reach the handler stage. To get
* around this problem we set r-user to the empty string to
* keep Apache happy, otherwise it would throw an
* error. mod_shibboleth does the same thing.
*/
r->user = "";
return OK;
}
#endif /* HAVE_ECP */
/* Check if this is a request for one of our endpoints. We check if
* the uri starts with the path set with the MellonEndpointPath
* configuration directive.
*/
if(strstr(r->uri, dir->endpoint_path) == r->uri) {
/* No access control on our internal endpoints. */
r->user = ""; /* see above explanation */
return OK;
}
/* Get the session of this request. */
session = am_get_request_session(r);
/* If we don't have a session, then we can't authorize the user. */
if(session == NULL) {
am_diag_printf(r, "%s no session, return HTTP_UNAUTHORIZED\n",
__func__);
return HTTP_UNAUTHORIZED;
}
/* If the user isn't logged in, then we can't authorize the user. */
if(!session->logged_in) {
am_diag_printf(r, "%s session not logged in,"
" return HTTP_UNAUTHORIZED\n", __func__);
am_release_request_session(r, session);
return HTTP_UNAUTHORIZED;
}
/* Verify that the user has access to this resource. */
return_code = am_check_permissions(r, session);
if(return_code != OK) {
am_diag_printf(r, "%s failed am_check_permissions, status=%d\n",
__func__, return_code);
am_release_request_session(r, session);
return return_code;
}
/* The user has been authenticated, and we can now populate r->user
* and the r->subprocess_env with values from the session store.
*/
am_cache_env_populate(r, session);
/* Release the session. */
am_release_request_session(r, session);
return OK;
}
|