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 | 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 19× 342× 2× 2× 19× 2× 19× 19× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 2× 7318× 7318× 7318× 3290× 4028× 4028× 4028× 4028× 3121× 2× 3004× 3004× 987× 3004× 3004× 2× 69179× 2× 3377× 1359× 630× 729× 2018× 2018× 2018× 2× 2× 2016× 1930× 1930× 1930× 54× 54× 54× 1× 1× 1× 30× 30× 30× 30× 30× 30× 30× 30× 1× 1× 2016× 2× 3228× 3228× 3228× 3228× 3228× 3228× 3228× 3215× 3215× 3215× 13× 13× 13× 3228× 3215× 13× 13× 13× 3228× 3228× 2× 1943× 1943× 1829× 1829× 114× 114× 114× 114× 114× 2× 3119× 3119× 3119× 3119× 3119× 3119× 3119× 3119× 3119× 3119× 3119× 3119× 3119× 3119× 3119× 3119× 3119× 2× 3491× 3491× 2151× 3491× 2× 2× 2× 3377× 3377× 3221× 3377× 3377× 3377× 3377× 72× 3377× 2× 3491× 3491× 3491× 3491× 3491× 3491× 3491× 3491× 3491× 3491× 3491× 3491× 2× 3491× 3491× 3491× 3491× 3491× 3491× 3491× 2× 3377× 3377× 3377× 2× 3377× 3377× 114× 3263× 3263× 3263× 3263× 3263× 3263× 3263× 3263× 2× 3377× 2× 3377× 2018× 1359× 2× 6754× 6694× 60× 60× 60× 60× 30× 60× 2× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 1× 3377× 3377× 3377× 3377× 3377× 2× 3377× 3377× 2× 3377× 3377× 3377× 3377× 3377× 3377× 47278× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 325× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 3377× 21× 21× 21× 21× 21× 21× 21× 21× 3377× 2018× 2018× 1359× 1359× 3377× 2× 2× 2554× 2554× 2554× 2554× 2554× 2554× 2554× 2554× 2554× 2554× 2554× 2554× 2554× 2554× 2554× 5× 2554× 2554× 2554× 2554× 2554× 2554× 2554× 2554× 2× 2554× 2554× 2554× 2554× 2554× 2554× 114× 114× 2554× 2× 2× 2× 2× 19× 2× 1829× 1829× 1829× 1829× 1829× 2× 2× 2× 1279× 1279× 1279× 23× 1279× 1279× 21× 21× 1279× 7674× 1279× 2× 943× 943× 943× 943× 3772× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 943× 861× 943× 239× 239× 704× 704× 704× 152× 152× 943× 21× 943× 943× 943× 943× 943× 943× 2× 2× 2× 1283× 1283× 2× 1283× 1283× 1283× 1283× 1283× 1283× 1283× 2× 3227× 1755× 1472× 1263× 209× 209× 209× 2× 4084× 4084× 4084× 4084× 2× 1810× 1810× 1810× 1810× 1810× 1810× 1810× 1810× 748× 1810× 1810× 1810× 1810× 1810× 1062× 1810× 247× 1928× 1810× 251× 3123× 1810× 1810× 748× 497× 251× 251× 1810× 2× 1799× 306× 1493× 1493× 1493× 1493× 2× 1829× 1829× 1829× 1829× 2× 3007× 2× 2988× 2988× 2988× 2988× 2988× 2988× 2988× 2988× 2988× 2988× 1829× 2988× 2988× 2988× 2× 1829× 1829× 329× 2× 1829× 1829× 1829× 2× 2535× 2535× 2535× 2× 800× 463× 337× 135× 202× 202× 2× 2201× 2201× 2× 1829× 1829× 1829× 1829× 30× 30× 30× 30× 1799× 306× 306× 306× 1799× 2× 957× 957× 669× 669× 14× 943× 943× 2× 718× 718× 718× 718× 718× 2× 206× 206× 206× 206× 206× 206× 206× 206× 206× 2× 239× 239× 239× 239× 239× 239× 239× 239× 2× 718× 718× 718× 2× 1829× 1829× 1829× 5487× 1829× 1829× 2× 2988× 30× 30× 2988× 198× 2× 1829× 1829× 1829× 1829× 1829× 1829× 1829× 1829× 1829× 1829× 1829× 1829× 1829× 1829× 1829× 1829× 1829× 1829× 317× 317× 17× 317× 317× 1829× 1829× 1829× 1829× 1829× 1829× 1829× 2× 1829× 1829× 1829× 497× 1829× 1829× 1829× 1829× 1828× 2× 2× 161× 161× 161× 161× 38× 161× 161× 2× 2× 2× 2× 2× 19× 19× 2× 2× 19× 19× 19× 19× 19× 2× 19× 19× 20× 19× 2× 2× 2× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 2× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 2× 2× 1159× 1159× 920× 920× 920× 33× 33× 920× 239× 239× 239× 2× 1159× 800× 359× 359× 359× 359× 359× 2× 1159× 1159× 2× 1176× 1176× 1176× 1176× 1176× 17× 17× 1159× 1159× 1159× 1159× 1159× 1159× 1159× 1159× 239× 1159× 1159× 1159× 1159× 1159× 1159× 1159× 490× 1159× 1159× 1159× 1159× 1159× 1159× 800× 359× 1159× 1159× 1159× 359× 359× 359× 1159× 23× 1159× 174× 174× 1159× 524× 524× 1159× 206× 1159× 1159× 1159× 1159× 359× 800× 202× 598× 512× 512× 86× 2× 1176× 1176× 1176× 490× 1176× 1176× 1176× 1176× 1176× 1176× 858× 858× 1176× 1176× 1176× 2× 359× 359× 359× 359× 359× 359× 2× 445× 445× 445× 445× 445× 445× 445× 445× 445× 445× 445× 445× 86× 86× 86× 359× 359× 359× 359× 359× 359× 359× 445× 86× 86× 86× 359× 359× 359× 359× 143× 359× 359× 359× 5× 359× 359× 359× 338× 359× 26× 26× 359× 359× 359× 359× 359× 445× 2× 445× 445× 445× 445× 445× 445× 445× 86× 86× 359× 359× 359× 359× 359× 445× 86× 86× 86× 359× 359× 359× 359× 359× 27× 359× 359× 359× 359× 359× 359× 359× 359× 359× 359× 23× 359× 5× 5× 5× 5× 5× 5× 5× 359× 359× 359× 153× 153× 206× 359× 445× 2× 2× 137× 137× 133× 4× 4× 4× 4× 4× 4× 4× 4× 2× 2× 2× 142× 28× 114× 114× 114× 114× 109× 109× 109× 2× 90× 90× 90× 90× 90× 90× 90× 2× 142× 142× 142× 142× 142× 142× 142× 142× 137× 137× 137× 137× 137× 137× 137× 137× 137× 137× 28× 137× 137× 137× 5× 142× 142× 2× 2× 2× 58× 58× 58× 58× 58× 2× 59× 59× 2× 289× 289× 289× 289× 289× 289× 2× 152× 152× 152× 152× 152× 152× 2× 428× 428× 428× 428× 428× 428× 428× 428× 2× 114× 114× 114× 2× 2× 114× 114× 114× 114× 1596× 114× 114× 114× 114× 114× 114× 114× 114× 114× 114× 114× 114× 114× 114× 114× 114× 2× 114× 114× 114× 114× 114× 114× 228× 114× 114× 114× 2× 114× 114× 114× 114× 114× 114× 114× 114× 114× 114× 114× 2× 2× 114× 114× 114× 114× 114× 114× 114× 2× 2× 304× 304× 1216× 1216× 4275× 516× 1216× 428× 304× 128× 2× 304× 304× 304× 304× 304× 304× 304× 304× 2× 2× 2× 1× 2× 182× 182× 182× 182× 182× 2× 1× 1× 2× 2× 2× 2× 2× 2× | 'use strict'; var http = require('http'), _ = require('lodash'), _s = require('underscore.string'), Q = require('q'), tld = require('tldjs'), moment = require('moment-timezone'), UAParser = require('ua-parser-js'), urllib = require('url'), config = require(__dirname + '/../config'), logger = require(__dirname + '/../loggers/logger'), flashLogger = require(__dirname + '/../loggers/flash-logger'), syslog = require(__dirname + '/../../pnr-common/lib/node/logging/syslog-logger').syslog, fluent = require(__dirname + '/../../pnr-common/lib/node/logging/fluent-logger').fluent, Formatter = require(__dirname + '/../loggers/formatter'), policyEvaluator = require(__dirname + '/policy-evaluation'), serverDetails = require(__dirname + '/server-details'), redisHelper = require(__dirname + '/../utils/redis-helper'), safemail = require(__dirname + '/pdp'), child_process = require('child_process'), aesCrypto = require(__dirname + '/../utils/crypto'); const mmdbreader = require('maxmind-db-reader'); const dns = require('dns'); const net = require('net'); const formatter = new Formatter({'version': config.internal.product_version}); const winston = require('winston'); const winstonCommon = require('winston/lib/winston/common'); const logFormatters = require(__dirname + '/../../pnr-common/lib/node/logging/logFormatter'); const RedisSubscriber = require(__dirname + '/../utils/redis-subscriber'); const syslogLogger = syslog(config); const fluentLogger = require('fluent-logger'); const cluster = require('cluster'); let redisSubscriber = null; // Use the keepalive agent to avoid connection leaks // NOTE: this will generate warnings in pnr-enforcement error log // this is a known nodejs issue. upgrading nodejs resolves the issue. // ref: https://github.com/nodejs/node/issues/9268 var keepAliveAgent = new http.Agent({ keepAlive: true }); const addTime = kvps => kvps.map( ks => ks[0] === 'time_started' ? ['time_taken', new Date().getTime() - ks[1]]: ks ); const pdpLogger = config.fluentd.enabled ? fluent(config, { tag: config.pnr_enforcement.fluentd_client_tag, label: 'pdpHandler' }): config.networking.syslog_format === 'CEF' && config.networking.syslog_host ? syslog(config, { level: 'info', formatter: opts => { delete opts.meta.stack; const flattened = logFormatters.flattenFormatter(opts, addTime); return formatter.formatCEF(flattened.meta); } }): new winston.Logger(); // whatever remote logging is configured, log to Console as a backup and as // a more detailed log pdpLogger.add(winston.transports.Console, { level: 'verbose', colorize: false, timestamp: true, formatter: opts => winstonCommon.log( logFormatters.logKVPFormatter(opts, addTime) ) }); // 1. extract stack from error // 2. log as reason=..., not error=... pdpLogger.rewriters.push((level, msg, meta) => { Iif (meta && meta.error) { if (meta.error.stack) { meta.stack = meta.error.stack; } meta.reason = meta.error.message || meta.error.toString(); delete meta.error; } return meta; }); Q.longStackSupport = true; // The default maxSockets is 5 and is too low. http.globalAgent.maxSockets = 100; //export namespace as `peController` var peController = exports; var uaParser = new UAParser(), requestStats = {'allow' : 0, 'safeview' : 0, 'safedoc' : 0, 'safeview_readonly': 0, 'block' : 0, 'bypass' : 0}, responseStats = {'allow' : 0, 'safeview' : 0, 'safedoc' : 0, 'safeview_readonly': 0, 'block' : 0, 'bypass' : 0}, fluentdStats = {'sent' : 0, 'error' : 0}, sslbumpStats = {'sslbump' : 0, 'sslbump_bypass' : 0}, actionPriorityMap = {'allow' : 0, 'safeview': 1, 'safedoc': 2, 'safeview_readonly': 3, 'bypass' : 4, 'block': 5}, analyticsRequestKeys = ['accept', 'referer', 'content-type', 'allow', 'request_type', 'date', 'origin', 'user-agent', 'x-client-ip', 'time', 'unix_time', 'unix_time_secs', 'http_version', 'response_code'], tridentVersionMap = {'10' : 6, '11' : 7}, supportedRequestTypes = ['GET', 'POST'], fileUploadDomains = ['dl-web.dropbox.com', 'upload.app.box.com'], safeviewEventSources = ['safeview', 'surrogate'], // The following safeview readonly* actions are different from // block/safeview/block actions which are policy evaluation results. // The readonly* actions are safemail/anti-phishing related actions // which safeview informs PE and are not used during policy evaluation. safeviewReadonlyActions = { 'entry': { 'block': 'block_entry', 'direct': 'direct_entry', 'read_only': 'readonly_entry', 'read_write': 'readwrite_entry'}, 'exit': { 'direct': 'direct_exit', 'read_write': 'readwrite_exit'}, 'navigate': {'readonly': 'readonly'} }, safeviewActionsToLogInRequestPath = ['entry', 'exit']; var firefoxAcceptHeaders = ['text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8']; var chromeAcceptHeaders = ['text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,' + 'image/apng,*/*;q=0.8']; var edgeAcceptHeaders = ['text/html, application/xhtml+xml, image/jxr, */*']; var ieAcceptHeaders = ['text/html, application/xhtml+xml, */*', 'text/html, application/xhtml+xml, image/jxr, */*']; var ieCompatibilityAcceptHeaders = [ // Windows7 + IE11 'image/jpeg, application/x-ms-application, ' + 'image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap', // Windows10 + IE11 'image/gif, image/jpeg, image/pjpeg, application/x-ms-application, ' + 'application/xaml+xml, application/x-ms-xbap']; var uceTimeoutVal = config.pnr_enforcement.pnr_uce_timeout_ms; var uceTimeoutMsg = 'Query uce timed out after ' + uceTimeoutVal + 'ms during'+ ' request evaluation. Going to use fail-open policy'; var authHostname = 'localhost'; var authPort = 14101; const pnrRedisNamespace = 'pnr-enforcement:'; const CACHE_PREFIX_RESP = 'x-icap-resp-cache:'; //Do not log entries to druid in pnr-proxy if it a safeview related action const donotLogActions = ['safeview', 'safeview_readonly']; function ensureAuthSet() { const safly_home = process.env.SAFELY_HOME || '/opt/safeview'; try { const h = child_process.execSync(safly_home + '/service/bin/get_config_value nodes.helper_host', {timeout: 1000}).toString().trim(); if (h) { authHostname = h; logger.info('Found nodes.helper_host; will assume ' + authHostname); } else { logger.error('Could not get nodes.helper_host; will assume ' + authHostname); } } catch (e) { logger.error('Could not get nodes.helper_host; will assume ' + authHostname, e); } try { const p = child_process.execSync(safly_home + '/service/bin/get_config_value auth-server.port', {timeout: 1000}).toString().trim(); if (p) { authPort = p; logger.info('Found auth-server.port; will assume ' + authPort); } else { logger.error('Could not get auth-server.port; will assume ' + authPort); } } catch (e) { logger.error('Could not get auth-server.port; will assume ' + authPort, e); } } var initFluentd = function () { Iif (!config.fluentd.enabled) { logger.info('msg="Fluentd is disabled"'); return; } fluentLogger.configure(config.pnr_enforcement.fluentd_client_tag, { host: config.fluentd.host, port: parseInt(config.fluentd.port, 10), timeout: parseInt(config.fluentd.socket_timeout_ms, 10), reconnectInterval: parseInt(config.fluentd.reconnect_interval_ms, 10) }); fluentLogger.on('error', function(err){ fluentdStats.error += 1; logger.error('event=fluent_error err=' + err); }); }; var sendResponse = function (req, res, response, stats) { Iif (!req) { req = {}; } Iif (!req.body) { req.body = {}; } if (req.body.responseSent) { return; } res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(response)); req.body.responseSent = true; if (stats) { stats[response.result] += 1; } }; var sendDefaultResponse = function (req, res, stats) { var defaultAction = 'allow'; if (_.contains(safeviewEventSources, req.body.event_source)) { defaultAction = 'safeview'; } var response = { 'result' : defaultAction }; sendResponse(req, res, response, stats); }; var getValue = function (obj, property, defaultValue) { return _.isUndefined(obj[property]) ? defaultValue : obj[property]; }; var isPageRequest = function (req, browser, userAgent, userInfo, modType) { // If the request originated from safeview, trust safeview to tell // whether this was a top level page request if (_.contains(safeviewEventSources, req.body.event_source)) { if (modType === 'request') { //Safeview calls request handler only it is a navigation request return true; } else { // Safeview calls response handler for top level page requests // and for resource loads. return req.body.is_top_frame || req.body.is_frame || false; } } var acceptHeader = getValue(req.body, 'accept'), requestType = getValue(req.body, 'request_type'), browserName = getValue(browser, 'name'), browserMajor = getValue(browser, 'major'), url = req.body.url, result = false; Iif (!_.contains(supportedRequestTypes, requestType) || (_.isEmpty(acceptHeader)) || (_.isEmpty(userAgent))){ return false; } if (_.isUndefined(browserName)) { logger.warn('msg="Undefined browser" userAgent=' + userAgent + ' url=' + url); return false; } switch(browserName) { case 'Chrome': Eif (_.contains(chromeAcceptHeaders, acceptHeader)) { result = true; } break; case 'Firefox': case 'Safari': Eif (_.contains(firefoxAcceptHeaders, acceptHeader)) { result = true; } break; case 'Edge': Eif (_.contains(edgeAcceptHeaders, acceptHeader)) { result = true; } break; case 'IE': // In compatibility mode, IE sends the version string as 7, 8 etc.. // Use the engine version instead of browser version // Trident/7.0 => Internet Explorer 11 // Trident/6.0 => Internet Explorer 10 // Trident/5.0 => Internet Explorer 9 // Trident/4.0 => Internet Explorer 8 var engine = uaParser.setUA(userAgent).getEngine(); var engVersion = parseInt(engine.version, 10); const isIECompatibilityAccept = function(accept) { let matches = ieCompatibilityAcceptHeaders.filter(function(header) { return _.contains(accept, header); }); return (matches.length > 0); }; Eif (engine.name === 'Trident' && engVersion > 5) { Eif (_.contains(ieAcceptHeaders, acceptHeader) || isIECompatibilityAccept(acceptHeader)) { result = true; } Iif (engVersion !== tridentVersionMap[browserMajor]) { logger.info('msg="IE compatibility mode" engine=' + engVersion + ' browser=' + browserMajor + ' userInfo=' + JSON.stringify(userInfo) + ' url=' + url); } } break; default: logger.warn('msg="Unsupported browser" browser=' + browserName + ' url=' + url); break; } return result; }; var updateUserGroups = function (userInfo) { Iif (!userInfo || !userInfo.userId || !userInfo.tenantId) { logger.warn('msg="Unexpected userInfo" user_info="' + JSON.stringify(userInfo) + '"'); return; } Iif (!policyEvaluator.isCapabilityEnabled(userInfo.tenantId, 'groups')) { return userInfo; } let uid = userInfo.userId; let tid = userInfo.tenantId; let cacheKey = pnrRedisNamespace + tid + ':' + uid + ':' + 'groups'; return Q.when(redisHelper.getDataFromRedis(cacheKey)) .then(function (groups) { if (groups) { userInfo.groups = groups; userInfo.cacheHit = true; return; } userInfo.cacheHit = false; logger.info('msg="No data in local redis for user_groups" ' + ' key=' + cacheKey); return Q.when(policyEvaluator.getGroupsFromPolicyServer(userInfo)); }) .then(function (result) { if (userInfo.cacheHit) { return; } userInfo.groups = result || []; let expiry = config.pnr_enforcement.user_groups_expiry || 3600; return Q.when(redisHelper.setDataInRedis(cacheKey, userInfo.groups, expiry)); }) .then(function () { delete userInfo.cacheHit; return userInfo; }) .fail(function (error) { logger.warn('msg="unable to get user groups" stack="' + error.stack + '"'); return userInfo; }); }; var updateTenantIdUsingIp = function(req, userInfo) { Iif (userInfo.tenantId !== -1) { return userInfo; } // Policy enforcement will get a tid if it is directly called by // the surrogate. If it is called by a squid acl helper, it needs to // use the squid cache to determine the tid. if (req.body.tid) { userInfo.tenantId = req.body.tid; return userInfo; } var redisKey = 'squid_whitelist:' + req.body['x-client-ip']; return Q.when(redisHelper.getDataFromSharedRedis(redisKey)) .then(function(tenantInfo) { Iif (tenantInfo) { userInfo.tenantId = tenantInfo.tid; userInfo.clientIp = req.body['x-client-ip']; } else { logger.info('msg="No data in redis for ip address" ' + ' key=' + redisKey); } return userInfo; }) .fail(function (error) { logger.warn('msg="unable to query redis for tenant id" stack="' + error.stack + '"'); return userInfo; }); }; var getUserInfo = function (req) { let userInfo = {}; userInfo.userId = 'Unknown'; userInfo.tenantId = -1; userInfo.groups = []; let icapUserData = getValue(req.body, 'x-icap-userdata', ''); Iif (!icapUserData) { return userInfo; } let sepIndex = icapUserData.indexOf(':'); Iif (sepIndex === -1) { logger.warn('msg="Unexpected userdata" user_info="' + JSON.stringify(icapUserData) + '"'); return userInfo; } let userInfoParts = [icapUserData.slice(0, sepIndex), icapUserData.slice(sepIndex + 1)]; let val = userInfoParts[0].trim(); Eif (val) { userInfo.tenantId = parseInt(val, 10); } val = userInfoParts[1].trim(); Eif (val) { userInfo.userId = val; } return Q.when(updateUserGroups(userInfo)) .then(function () { return userInfo; }) .fail(function (error) { logger.warn('msg="updateUserGroups error" stack="' + error.stack + '"'); return userInfo; }); }; var getUserAgent = function (req) { // Icap server sends the user agent string in the http header - user-agent // Safeview sends the snake cased version of user agent string - user_agent let userAgent = getValue(req.body, 'user_agent', ''); if (!userAgent) { userAgent = getValue(req.body, 'user-agent', ''); } return userAgent; }; var generateBypassToken = function (domain) { var timestamp = Math.floor(Date.now() / 1000); // in secs timestamp var tokenStr = '1:' + timestamp + ':' + domain; return aesCrypto.encrypt(tokenStr); }; var decodeBypassToken = function (token) { token = decodeURIComponent(token); var tokenStr = aesCrypto.decrypt(token); if (!tokenStr) { return null; } var tokenParts = tokenStr.split(':'); if (tokenParts.length !== 3) { logger.info('msg="Unexpected bypass token" token=' + tokenStr); return null; } var result = {}; result.version = parseInt(tokenParts[0], 10); result.timestamp = parseInt(tokenParts[1], 10); result.domain = tokenParts[2]; return result; }; var getResourceCategory = function (analyticsData) { var resourceCategory = []; if (analyticsData.is_page_request === 'true') { resourceCategory.push('page'); } Iif (analyticsData.file_upload === 'true') { resourceCategory.push('upload'); } Iif (analyticsData.flash_request === 'true') { resourceCategory.push('flash'); } Iif (analyticsData.file_download === 'true') { resourceCategory.push('download'); } if (getValue(analyticsData, 'ua_type', 'supported_browser') !== 'supported_browser') { resourceCategory.push('unsupported_agent'); } return resourceCategory; }; var addDefaultRequestAnalyticsData = function (analyticsData) { analyticsData.risks = []; analyticsData.risks_v2 = []; analyticsData.top_level_risks = []; analyticsData.cats = []; analyticsData.cats_ids = []; analyticsData.webroot_cats = []; analyticsData.webroot_cats_ids = []; analyticsData.rep = []; analyticsData.mdbl = 'ok'; analyticsData.code = 'G'; analyticsData.uce_error = 'false'; analyticsData.readonly_action = ''; }; var addDefaultResponseAnalyticsData = function (analyticsData) { analyticsData.server_details = []; analyticsData.server_top_level_details = []; analyticsData.vulnerable_servers = []; analyticsData['content-type'] = ''; analyticsData.response_code = ''; analyticsData.document_type = ''; analyticsData.file_type = ''; }; var isFileUploadRequest = function (req) { var requestType = getValue(req.body, 'request_type'); Eif (!requestType || requestType !== 'POST') { return false; } var contentLengthStr = getValue(req.body, 'content-length'); if (!contentLengthStr) { return false; } var contentLength = parseInt(contentLengthStr, 10); if (contentLength <= 0) { return false; } var contentType = getValue(req.body, 'content-type'); if (contentType && _.contains(contentType, 'multipart/form-data')) { return true; } var urlParts = urllib.parse(req.body.url); var domain = getValue(urlParts, 'hostname', ''); if (_.contains(fileUploadDomains, domain)) { return true; } return false; }; var isFlashRequest = function (req, browser) { var requestType = getValue(req.body, 'request_type'); if (!requestType || requestType !== 'GET') { return false; } //We need to parse the url and look for '.swf' in the pathname //and not the in full url since there may be query params at //the end of the url. var url = req.body.url.toLowerCase().trim(); var urlParts = urllib.parse(url); var xFlashVersion = getValue(req.body, 'x-flash-version', ''); //IE header var xRequestedWith = getValue(req.body, 'x-requested-with', ''); //Chrome xRequestedWith = xRequestedWith.toLowerCase(); var contentType = getValue(req.body, 'content-type', '').toLowerCase(); Iif ((urlParts.pathname && _s.endsWith(urlParts.pathname, '.swf')) || xFlashVersion || _.contains(xRequestedWith, 'shockwaveflash') || _.contains(contentType, 'application/x-shockwave-flash')) { var referer = getValue(req.body, 'referer', ''); var browserName = getValue(browser, 'name', ''); var browserVersion = getValue(browser, 'major', ''); var domain = tld.getDomain(url) || ''; var rDomain = tld.getDomain(referer) || ''; flashLogger.info('domain=' + domain + ' referer_domain=' + rDomain + ' url=' + url + ' referer=' + referer + ' x-flash-version=' + xFlashVersion + ' x-requested-with=' + xRequestedWith + ' content-type=' + contentType + ' browser="' + browserName + ' ' + browserVersion + '"'); return true; } return false; }; var isFileDownloadRequest = function (req) { // If the request json has a field called sha256 with non-empty value, // it is file download request. Also, if the file_download failed, the json // should contain a field file_download_status = 'error' return (!_.isEmpty(req.body.sha256) || !_.isEmpty(req.body.file_download_status)); }; let isIframe = function(req) { if (!_.contains(safeviewEventSources, req.body.event_source)) { return 'NA'; } return (req.body.is_subframe || req.body.is_top_frame === false); }; const getBrowserVersion = function (browser, engine, versionType) { if (browser.name !== 'IE' || !engine.version) { return getValue(browser, versionType); } //If it is IE, use the trident engion's version since IE may be //in compatibility mode where browser version is off by 4.0 //For trident engine map see wikipedia - //https://en.wikipedia.org/wiki/Trident_(layout_engine) const parts = engine.version.split('.'); const dLen = (parts.length > 1) ? parts[1].length : 0; let browserVersion = (parseFloat(engine.version) + 4.0).toFixed(dLen); if (versionType === 'major') { browserVersion = Math.floor(browserVersion); } return browserVersion.toString(); }; let getBrowserInfo = function (analyticsData) { let userAgent = analyticsData['user-agent']; let browser = uaParser.setUA(userAgent).getBrowser(); let device = uaParser.setUA(userAgent).getDevice(); let engine = uaParser.setUA(userAgent).getEngine(); let mVersion = getBrowserVersion(browser, engine, 'major'); let bVersion = getBrowserVersion(browser, engine, 'version'); if (device.type && getValue(browser, 'name')) { // Device is one of: mobile, console, tablet, smarttv, // wearable, or embedded browser.name = 'Unsupported' + '_' + getValue(browser, 'name'); } analyticsData.browser = getValue(browser, 'name'); analyticsData.browser_major_version = mVersion; analyticsData.browser_version = bVersion; analyticsData.browser_and_version = analyticsData.browser + '_' + mVersion; return browser; }; let addAwsInfo = function (analyticsData) { analyticsData.region = config.system_settings.zone || 'NA'; analyticsData.instance_id = config.system_settings.instance_id || 'NA'; }; var addOtherAnalyticsData = function (analyticsData, req, userInfo, modType) { addDefaultRequestAnalyticsData(analyticsData); addDefaultResponseAnalyticsData(analyticsData); addAwsInfo(analyticsData); analyticsData.file_type = getValue(req.body, 'file_type') || ''; // TODO: Update if access modes ever differ from prepend and proxy analyticsData.access_mode = getValue(req.body, 'is_prepend', false) ? 'prepend' : 'proxy'; _.forEach(analyticsRequestKeys, function (key) { analyticsData[key] = req.body[key] || ''; }); var userAgent = getUserAgent(req); analyticsData['user-agent'] = userAgent; let browser = getBrowserInfo(analyticsData); var pageRequest = isPageRequest(req, browser, userAgent, userInfo, modType); analyticsData.is_page_request = pageRequest.toString(); analyticsData.file_upload = isFileUploadRequest(req).toString(); analyticsData.flash_request = isFlashRequest(req, browser).toString(); analyticsData.file_download = isFileDownloadRequest(req).toString(); analyticsData.is_iframe = isIframe(req).toString(); var url = req.body.url; var urlParts = urllib.parse(url); analyticsData.url = url; analyticsData.domain = getValue(urlParts, 'hostname', ''); analyticsData.userid = userInfo.userId; analyticsData.tid = userInfo.tenantId; analyticsData.userGroups = userInfo.groups || []; analyticsData.protocol = 'http'; if (_s.startsWith(url.toLowerCase(), 'https')) { analyticsData.protocol = 'https'; } Eif (policyEvaluator.isCapabilityEnabled(userInfo.tenantId, 'bnb')) { policyEvaluator.populateNonBrowserAndBrowserInfo(analyticsData, userInfo.tenantId); } else { analyticsData.ua_type = 'supported_browser'; } analyticsData.resource_category = getResourceCategory(analyticsData); analyticsData.x_uncategorized = false; const xCat = req.body['x-menlo-category']; Iif (xCat && xCat.status === 'ok' && xCat.category === 'Unknown') { analyticsData.x_uncategorized = true; } else Iif (xCat && xCat.status === 'failed') { // FIXME (PNR-2949): Use policy to determine this once we expose // the UI setting. const tenantCaps = policyEvaluator.getTenantCapabilities( analyticsData.tid); const unknownOnFailure = (tenantCaps.proxy_category || {}).unknownOnFailure; if (unknownOnFailure) { analyticsData.x_uncategorized = true; } } analyticsData.sha256 = ''; analyticsData.sha256_score = -1; analyticsData.av_scan_result = ''; analyticsData.av_vendors = []; analyticsData.virus_details = []; analyticsData.file_download_status = 'ok'; analyticsData.file_download_error_reason = ''; analyticsData.ro_pe_reason = ''; analyticsData.risk_score = 'NA'; analyticsData.risk_tally = -1; analyticsData.readonly_user_experience = 'NA'; Iif (analyticsData.file_download === 'true') { if (req.body.sha256) { analyticsData.sha256 = req.body.sha256.toLowerCase(); } else { analyticsData.file_download_status = req.body.file_download_status; analyticsData.file_download_error_reason = req.body.reason || 'unknown'; } } //If it is a readonly_* type of action, keep it as readonly_action in //druid payload. It will be required to support ui widgets which //use pe_action field in the payload. We cannot set the pe_action here //to readonly_* since pe_action is also used during policy evaluation. var evtSrc = req.body.event_source; var readonlyAction = req.body.readonly_action; if (_.contains(safeviewEventSources, evtSrc) && readonlyAction && (readonlyAction in safeviewReadonlyActions)) { let actionModes = safeviewReadonlyActions[readonlyAction]; let readonlyMode = req.body.readonly_mode || 'readonly'; Eif (readonlyMode in actionModes) { analyticsData.readonly_action = actionModes[readonlyMode]; } analyticsData.ro_pe_reason = req.body.readonly_rule_match || analyticsData.ro_pe_reason; analyticsData.risk_score = req.body.readonly_risk_score || analyticsData.risk_score; analyticsData.risk_tally = req.body.readonly_risk_tally === 0 ? req.body.readonly_risk_tally: req.body.readonly_risk_tally || analyticsData.risk_tally; analyticsData.readonly_user_experience = req.body.readonly_user_experience || analyticsData.readonly_user_experience; } if (req.body.event_source === 'icap') { analyticsData.pe_action = 'allow'; analyticsData.event_source = 'icap'; } else { analyticsData.pe_action = 'safeview'; analyticsData.event_source = 'safeview'; } analyticsData.pe_reason = ''; }; var getEmptyUceResponse = function(params) { var uceResponseBody = { cats : [], webroot_cats : [], malware : 'ok', reputation : 'ok', code : 'G', url : params.url }; var uceResponse = {}; uceResponse[params.url] = uceResponseBody; return uceResponse; }; var http_it = function(params, callback) { const payload = JSON.stringify(params.payload); const options = { hostname: params.host, port: params.port, path: params.path, method: 'POST', headers: { 'Content-Length': payload.length, 'Content-Type':'application/json' } }; logger.debug('will call REST ' + JSON.stringify(options) + ' with payload ' + payload); // Use the keep alive agent options.agent = keepAliveAgent; let req_socket; let on_timeout; const req = http.request(options, res => { let str = ''; res.setEncoding('utf8'); //another chunk of data has been recieved, so append it to `str` res.on('data', chunk => str += chunk); // the whole response has been received, so we just pass it on // to the callback here res.on('end', () => { let jsonResponse, err; logger.debug('REST response: ' + str); try { jsonResponse = JSON.parse(str); } catch (ex) { err = 'JSON parsing error - "' + str + '"'; } req_socket.removeListener('timeout', on_timeout); callback(err, jsonResponse); }); }); req.on('socket', socket => { req_socket = socket; on_timeout = () => { req.abort(); (params.onTimeout || callback)('service ' + (params.host + ':' + params.port + params.path) + ' timed out after ' + params.timeout + ' ms'); }; socket.setTimeout(params.timeout, on_timeout); }); req.on('error', err => { if (req_socket) { req_socket.removeListener('timeout', on_timeout); } req.abort(); (params.onError || callback)(err); }); req.end(payload); }; var queryUce = function (params, callback) { Iif (!config.networking.policy_server_enabled && _s.endsWith(config.networking.policies_folder, 'isolate_all') && !config.networking.isolate_all_uce_enabled) { callback(null, getEmptyUceResponse(params)); return; } Iif (!params || !params.url || !params.timeoutMsg || !params.resourceCategory) { callback('Invalid or missing params to queryUce', null); return; } let inspectCats = ['page', 'sslbump', 'unsupported_agent', 'strictmode']; Iif (_.isEmpty(_.intersection(params.resourceCategory, inspectCats))) { callback(null, getEmptyUceResponse(params)); return; } let httpInput = { host: config.networking.pnr_uce_host, port: config.networking.pnr_uce_port, path: '/api/v1/uce' + (params.riskFactors? '?risk_factors=1': ''), timeout: parseInt(config.pnr_enforcement.pnr_uce_timeout_ms, 10), payload: [params.url], onTimeout: () => callback(params.timeoutMsg, null), onError: err => callback('uce error - ' + err, null) }; if (params.failWithEmptyResponse) { httpInput.onTimeout = () => callback(null, getEmptyUceResponse(params)); httpInput.onError = () => callback(null, getEmptyUceResponse(params)); } http_it(httpInput, callback); }; var authCalled = false; let queryAuth = Q.denodeify(function (userInfo, attributes, callback) { if (!authCalled) { ensureAuthSet(); authCalled = true; } http_it({ host: authHostname, port: authPort, path: '/userattributes', timeout: parseInt(config.pnr_enforcement.pnr_auth_server_timeout_ms || config.pnr_enforcement.pnr_uce_timeout_ms, 10), payload: { username: userInfo.userId, tid: userInfo.tenantId, attributes: attributes } }, (err, searchResult) => { if (!err && !searchResult.success) { err = new Error('auth-server responded with error'); err.searchResult = searchResult.msg; } callback(err, searchResult); }); }); let q_queryUce = Q.denodeify(queryUce); let q_queryAttrs = (userInfo, attributes) => policyEvaluator.maybeSaml(userInfo.tenantId) ? policyEvaluator.getAttributesFromPolicyServer(userInfo, attributes): queryAuth(userInfo, attributes); var setAnalyticsDataInRedis = function (req, analyticsData, alreadySent) { var cacheValue = {}; var cacheKey = 'x-icap-req-cache:' + getValue(req.body, 'x-icap-req-cache'); cacheValue.alreadySent = alreadySent; cacheValue.analyticsData = analyticsData; return Q.when(redisHelper.setDataInRedis(cacheKey, cacheValue)); }; var handleUceError, sendResponseAndHandleUceError = function (req, res, analyticsData) { sendDefaultResponse(req, res, requestStats); handleUceError(req, analyticsData); }; handleUceError = function(req, analyticsData) { analyticsData.uce_error = 'true'; analyticsData.cats = ['Unavailable']; analyticsData.cats_ids = ['-1']; analyticsData.webroot_cats = ['Unavailable']; analyticsData.webroot_cats_ids = ['-1']; analyticsData.dest_ips = ['Unavailable']; return setAnalyticsDataInRedis(req, analyticsData, false); }; const modifyPayloadForDruid = function (analytics) { Iif (!analytics) { return analytics; } const payload = Object.assign({}, analytics); // merged payload could be 'block' if the av_check result // is 'block' therefore set the pe_action to be 'safeview' // in that case. if (_.contains(payload.resource_category, 'safedoc')) { payload.pe_action = 'safeview'; } //If action is safedoc, send the pe_action as 'safeview', //since the ui widget does not distinguish safeview vs. safedoc Iif (payload.pe_action === 'safedoc') { payload.pe_action = 'safeview'; } //If it is a readonly_* type of action, log it as the pe_action //to druid in order to support ui widgets in dashboard. if (payload.readonly_action) { payload.pe_action = payload.readonly_action; payload.pe_reason = payload.ro_pe_reason; } //Delete unnecessary fields from the payload. const fieldsToDelete = ['file_download_status', 'file_download_error_reason', 'readonly_action', 'ro_pe_reason', 'x_uncategorized', 'userGroups']; fieldsToDelete.forEach(param => delete payload[param]); return payload; }; var mergeAnalyticsData = function (analyticsData, responseAnalyticsData) { Iif (!analyticsData || !responseAnalyticsData) { logger.info('Invalid params in mergeAnalyticsData'); return; } var ad = analyticsData; var rad = responseAnalyticsData; var mergeBooleanStringParams = function (param) { return (ad[param] === 'true') ? ad[param] : rad[param]; }; ad.is_page_request = mergeBooleanStringParams('is_page_request'); ad.file_upload = mergeBooleanStringParams('file_upload'); ad.file_download = mergeBooleanStringParams('file_download'); ad.flash_request = mergeBooleanStringParams('flash_request'); ad.resource_category = _.union(ad.resource_category, rad.resource_category); ad.risks = _.union(ad.risks, rad.risks); ad.risks_v2 = _.union(ad.risks_v2, rad.risks_v2); ad.top_level_risks = _.union(ad.top_level_risks, rad.top_level_risks); ad.vulnerable_servers = rad.vulnerable_servers; ad.server_details = rad.server_details; ad.server_top_level_details = rad.server_top_level_details; ad['content-type'] = rad['content-type']; ad.response_code = rad.response_code; ad.cats = _.union(ad.cats, rad.cats); ad.cats_ids = _.union(ad.cats_ids, rad.cats_ids); ad.webroot_cats = _.union(ad.webroot_cats, rad.webroot_cats); ad.webroot_cats_ids = _.union(ad.webroot_cats_ids, rad.webroot_cats_ids); ad.sha256 = rad.sha256; ad.sha256_score = rad.sha256_score; ad.file_size = rad.file_size || '0'; ad.filename = rad.filename || 'NA'; ad.file_id = rad.file_id || 'NA'; ad.av_scan_result = rad.av_scan_result; ad.action_on_malware = rad.action_on_malware || 'NA'; ad.av_vendors = rad.av_vendors; ad.virus_details = rad.virus_details; ad.file_fa = rad.file_fa || ad.file_fa || 'NA'; ad.soph = rad.soph || ad.soph || 'NA'; ad.soph_v = rad.soph_v || ad.soph_v || 'NA'; ad.soph_vers = rad.soph_vers || ad.soph_vers || 'NA'; ad.sbox = rad.sbox || ad.sbox || 'NA'; ad.sbox_mal_act = rad.sbox_mal_act || ad.sbox_mal_act || 'NA'; ad.mail_from = rad.mail_from || ad.mail_from || 'NA'; ad.mail_to = rad.mail_to || ad.mail_to || 'NA'; ad.mail_subject = rad.mail_subject || ad.mail_subject || 'NA'; ad.mail_id = rad.mail_id || ad.mail_id || 'NA'; ad.mail_timestamp = rad.mail_timestamp || ad.mail_timestamp || 'NA'; ad.dropfile_id = rad.dropfile_id || ad.dropfile_id || 'NA'; ad.dropfile_ver = rad.dropfile_ver || ad.dropfile_ver || 'NA'; // sbox_score can be 0, so we can't use the standard falsy assignment Iif (rad.sbox_score === 0) { ad.sbox_score = 0; } else Iif (ad.sbox_score === 0) { ad.sbox_score = 0; } else { ad.sbox_score = rad.sbox_score || ad.sbox_score || 'NA'; } ad.feye = rad.feye || ad.feye || 'NA'; ad.feye_mal_alrt = rad.feye_mal_alrt || ad.feye_mal_alrt || 'NA'; ad.feye_job_url = rad.feye_job_url || ad.feye_job_url || 'NA'; ad.feye_job_id = rad.feye_job_id || ad.feye_job_id || 'NA'; ad.file_type = rad.file_type || ''; ad.document_type = rad.file_type || ''; //deprecated. if (ad.code === 'G') { ad.code = rad.code; } if (ad.event_source === 'safeview' && ad.file_download === 'true') { // Ensure the download policy is logged instead of the isolation policy ad.pe_action = rad.pe_action; ad.pe_reason = rad.pe_reason; } else { var reqPriority = actionPriorityMap[ad.pe_action]; var resPriority = actionPriorityMap[rad.pe_action]; if (resPriority > reqPriority) { ad.pe_action = rad.pe_action; ad.pe_reason = rad.pe_reason; } } if (rad.readonly_action) { ad.readonly_action = rad.readonly_action; } // assuming response analytics contains all readonly data, if risk_score is // provided by the caller Eif (rad.risk_score) { ad.ro_pe_reason = rad.ro_pe_reason; ad.risk_score = rad.risk_score; ad.risk_tally = rad.risk_tally; ad.readonly_user_experience = rad.readonly_user_experience; } return modifyPayloadForDruid(ad); }; let localizeTime = function(payload) { if (!config.system_config.timezone && config.networking.syslog_format !== 'CEF') { return payload.time; } let unixTime = payload.unix_time; let dateTime = moment.unix(unixTime); dateTime.tz('Etc/UTC'); if (config.system_config.timezone) { dateTime.tz(config.system_config.timezone); } if (config.networking.syslog_format === 'CEF') { dateTime = dateTime.format('MMM DD YYYY HH:mm:ss zz').trim(); } else { dateTime = dateTime.format(); } return dateTime; }; var modifyPayloadForSyslog = function(payload) { if (payload.pe_action === 'safeview') { payload.pe_action = 'isolate'; } else if (payload.pe_action === 'sslbump_bypass') { payload.pe_action = 'ssl_exception'; payload.ssl_inspection_exception = 'true'; } else if (payload.pe_action === 'safeview_readonly') { payload.pe_action = 'isolate_readonly'; } if (payload.is_page_request === 'true') { payload.page_request = 'true'; } // FIXME: doesn't this mean that the time will not be localized in druid, // if Syslog is not enabled? payload.event_time = localizeTime(payload); return payload; }; var sendDataToSyslog = function (payload) { Eif (!config.networking.syslog_host) { return; } let syslogPayload = _.cloneDeep(payload); // TODO: this should be a logger formatter // https://github.com/winstonjs/winston#filters-and-rewriters syslogPayload = modifyPayloadForSyslog(syslogPayload); // TODO: Fix double logging of page requests between // pnr-enforcement and event consumer if (config.networking.syslog_format === 'CEF') { // TODO: this should be a logger formatter - winston supports // a formatter per transport syslogPayload = formatter.formatCEF(syslogPayload); } else { syslogPayload = formatter.formatKVP(syslogPayload); } syslogLogger.info(syslogPayload); }; var sendDataToFluentdOrSyslog = function (payload) { Iif (!payload) { fluentdStats.error += 1; logger.error('msg="Payload is empty"'); return; } // Send logs via configured syslog settings sendDataToSyslog(payload); Eif (config.fluentd.enabled) { const tag = policyEvaluator.getDruidLoggingChannel(payload.tid); fluentLogger.emit(tag, payload); fluentdStats.sent += 1; return; } }; var checkIsolationBypass = function (req, url, userInfo, policyResult, checkExpiry) { if (!policyResult || !policyResult.action || (policyResult.action !== 'safeview' && policyResult.action !== 'safeview_readonly')) { //If the action was not safeview, no need to check for bypass. return; } if (!url || !req || !req.body || !req.body.cookie) { return; } Iif (_.contains(safeviewEventSources, req.body.event_source)) { //Bypass is not supported in safeview mode. return; } Eif (!userInfo || !userInfo.tenantId || !policyEvaluator.isBypassAllowed(userInfo.tenantId)) { return; } if (!_.contains(req.body.cookie, '_sc_bypass')) { return; } var cookieValue = _s.strRight(req.body.cookie, '_sc_bypass='); cookieValue = _s.strLeft(cookieValue, ';'); var decodedToken = decodeBypassToken(cookieValue); if (!decodedToken) { logger.info('Invalid bypass cookie. ' + ' userInfo - ' + JSON.stringify(userInfo) + ', url - ' + url + ', cookie - ' + cookieValue); return; } var domain = '.' + tld.getDomain(url); if (domain !== decodedToken.domain) { logger.info('Bypass domain and domain in url do not match.' + ' Domain in token - ' + decodedToken.domain + ', url requested - ' + url + ', userInfo - ' + JSON.stringify(userInfo)); return; } if (!checkExpiry) { policyResult.action = 'bypass'; policyResult.reason = 'bypass'; return; } var now = Math.floor(Date.now() / 1000); // in secs var diff = now - decodedToken.timestamp; if (diff > config.pnr_enforcement.bypass_cookie_expires_after_secs) { logger.info('Bypass domain expired. Diff (secs)- ' + diff + ', domain in token - ' + decodedToken.domain + ', url requested - ' + url + ', userInfo - ' + JSON.stringify(userInfo)); policyResult.action = 'bypass'; policyResult.reason = ''; policyResult.cookieAction = 'remove'; policyResult.domain = domain; return; } if (diff > config.pnr_enforcement.bypass_cookie_update_after_secs) { logger.info('Bypass domain cookie needs update. Diff (secs)- ' + diff + ', domain in token - ' + decodedToken.domain + ', url requested - ' + url + ', userInfo - ' + JSON.stringify(userInfo)); policyResult.action = 'bypass'; policyResult.reason = ''; policyResult.cookieAction = 'update'; policyResult.domain = domain; policyResult.cookie = generateBypassToken(policyResult.domain); return; } policyResult.action = 'bypass'; policyResult.reason = 'bypass'; }; var populateTimeInfo = function (req) { var currentTime = new Date(); req.body.time = currentTime.toISOString(); req.body.unix_time = currentTime.getTime()/1000; req.body.unix_time_secs = req.body.unix_time; }; var populateAdditionalSafeviewData = function (req, handlerType) { req.body.response_code = 200; //TODO: see if safeview can provide this data req.body.request_type = 'GET'; //TODO: see if safeview can provide this data req.body.http_version = 'HTTP/1.1'; // ICAP related header. req.body.allow = '204'; // ICAP related header. var urlParts = urllib.parse(req.body.url); req.body.domain = getValue(urlParts, 'hostname', ''); var xClientIp = ''; if (req.body.client_ip) { xClientIp = req.body.client_ip; } req.body['x-client-ip'] = xClientIp; //Safeview surrogate uses uid and RProxy uses 'user' //Safeview surrogate uses tid and RProxy uses 'tenant_id' var uid = req.body.uid || req.body.user || 'Unknown'; var tid = req.body.tid || req.body.tenant_id || '-1'; req.body['x-icap-userdata'] = tid + ':' + uid; if (req.body.tenant_id) { req.body.tenantId = req.body.tenant_id; } if (req.body.request_headers) { _.transform(req.body.request_headers, function (result, val, key) { req.body[key.toLowerCase()] = val; }); } if (req.body.response_headers) { _.transform(req.body.response_headers, function (result, val, key) { req.body[key.toLowerCase()] = val; }); } var cacheKey = ''; if (req.body.nav_session_id) { if (handlerType === 'request') { cacheKey = req.body.nav_session_id; } else Eif (handlerType === 'response' && (req.body.is_top_frame || req.body.is_frame)){ cacheKey = req.body.nav_session_id; } } req.body['x-icap-req-cache'] = cacheKey; }; var shouldSendDataToFluentdInRequestPath = function(policyResult, req) { if (policyResult.action === 'block') { //In the case of block, we will be sending a 403 forbidden //error message to the client browser. Squid will not //call the resp mod in this case. return true; } var evtSrc = req.body.event_source; var readonlyAction = req.body.readonly_action; Iif (_.contains(safeviewEventSources, evtSrc) && readonlyAction && _.contains(safeviewActionsToLogInRequestPath, readonlyAction)) { //Some safeview action like readonly_entry, readonly_exit are //one time events and response path will not called. So, log //the info to druid in the request path itself. return true; } return false; }; var addCookieDetailsToIcapResponse = function(icapResponse, policyResult) { Iif (!icapResponse || !policyResult) { return; } Iif (policyResult.cookieAction) { icapResponse.cookie_action = policyResult.cookieAction; } Iif (policyResult.cookie) { icapResponse.cookie = policyResult.cookie; } Iif (policyResult.domain) { icapResponse.domain = policyResult.domain; } }; var requireInspection = function (analyticsData) { // We need to inspect request for threats/categories etc.. // and log it to druid only if it is a - // (a) page request. // (b) file upload request. // (c) flash request // (d) file download request and av scan file type. // (e) unsupported browser return !_.isEmpty(analyticsData.resource_category); }; var getLogMessage = function (modType, req, status, userInfo, uceJsonResponse, analyticsData, policyResult, errorMsg) { var url = req.body.url; var currentTime = new Date(); var unixTime = currentTime.getTime(); var resourceCategory = _.union(analyticsData.resource_category).join(', '); var msg = 'pe_type=' + modType + ' user_id=' + userInfo.userId + ' tenant_id=' + userInfo.tenantId + ' browser=' + analyticsData.browser + ' browser_version=' + analyticsData.browser_major_version + ' url=' + url + ' page_request=' + analyticsData.is_page_request + ' resource_category="' + resourceCategory + '"' + ' status=' + status + ' event_source=' + req.body.event_source; Eif (policyResult) { msg += ' pe_action=' + policyResult.action; msg += ' pe_reason="' + policyResult.reason + '"'; } Iif (errorMsg) { msg += ' reason="' + errorMsg + '"'; } if (uceJsonResponse && uceJsonResponse[url]) { msg += ' uceResponse=' + JSON.stringify(uceJsonResponse[url]); } Eif (req.body.unix_time) { msg += ' time_taken=' + (unixTime - req.body.unix_time * 1000); } return msg; }; var updatePolicyIfPostOrUpload = function (req, url, policyResult, analyticsData) { var requestType = getValue(req.body, 'request_type'); if (req.body.event_source === 'icap' && (policyResult.action === 'safeview' || policyResult.action === 'safeview_readonly')) { Iif ((requestType && requestType === 'POST') || analyticsData.file_upload === 'true') { // We cannot send the safeview TC to the browser // if it is a POST or upload request policyResult.action = 'allow'; policyResult.reason = ''; logger.info('Cannot send safeview for POST or upload request - ' + url); } } }; var isBypassCookieUpdateRequest = function (req, policyResult, msg) { var result = false; Iif (req.body.event_source === 'icap' && policyResult.action === 'bypass' && policyResult.cookieAction) { // This will result in redirect to same url by icap. // So, don't log anything to druid. msg += ', cookie_action=' + policyResult.cookieAction; logger.info(msg); result = true; } return result; }; var makeUceRequestParam = function (url, analyticsData, failWithEmptyResponse) { var uceParams = { url: url, timeoutMsg: uceTimeoutMsg, resourceCategory: analyticsData.resource_category }; uceParams.failWithEmptyResponse = failWithEmptyResponse || false; return uceParams; }; let shouldLogFrame = function(req, policyResult) { if (!_.contains(safeviewEventSources, req.body.event_source)) { return true; //from icap so we don't know if it is an iframe or not } if (req.body.is_subframe === false || req.body.is_top_frame) { return true; //not an iframe } // NOTE: we default parentAction to 'allow' so that if no parent action // is sent from SV, we still log let parentAction = req.body.parent_frame_action || 'allow'; return policyEvaluator.applyMostSevereAction({action: parentAction}, policyResult.action); }; var checkUceResponse = function (uceJsonResponse, url) { Iif (!uceJsonResponse[url]) { throw 'Invalid Uce response - "' + JSON.stringify(uceJsonResponse) + '"'; } return uceJsonResponse; }; var handleSendingDataToFluentd = function (req, analyticsData, policyResult) { analyticsData.pe_action = policyResult.action; analyticsData.pe_reason = policyResult.reason; var alreadySent = false; // Non-browser policy will set field log to false if we should // not log, icap will not call on the response path so must log // in the request path. if (_.has(policyResult, 'log')) { Eif (policyResult.log) { analyticsData = modifyPayloadForDruid(analyticsData); sendDataToFluentdOrSyslog(analyticsData); } return setAnalyticsDataInRedis(req, analyticsData, true); } if (shouldSendDataToFluentdInRequestPath(policyResult, req)) { analyticsData = modifyPayloadForDruid(analyticsData); sendDataToFluentdOrSyslog(analyticsData); alreadySent = true; } return setAnalyticsDataInRedis(req, analyticsData, alreadySent); }; const mergeAnalyticsDataAndSendToFluentd = function (eventSource, analyticsData, responseAnalyticsData) { Iif (!eventSource || !analyticsData || !responseAnalyticsData) { return; } if (eventSource === 'icap') { //In PnR context - Log to druid if the action is not safeview //In safeview context, log all actions to druid. const actions = [analyticsData.pe_action, responseAnalyticsData.pe_action]; if (!_.isEmpty(_.intersection(actions, donotLogActions))) { return; } } // See the table in policy enforcement doc in google docs // for more details on when and who logs details to druid const payload = mergeAnalyticsData(analyticsData, responseAnalyticsData); sendDataToFluentdOrSyslog(payload); }; var getDataFromRedisAndSendToFluentd = function (url, cacheKey, responseAnalyticsData, eventSource) { return redisHelper.getDataFromRedisWithRetries(cacheKey, 30, 100) .then(function (cachedData) { Iif (!cachedData) { //No data about request/uce info is found in redis. //But, we need to log the response to druid. //So, make a copy of response analytics data and //set it as request analytics data cachedData = {}; cachedData.alreadySent = false; cachedData.analyticsData = _.cloneDeep(responseAnalyticsData); } Iif (getValue(cachedData, 'alreadySent', false)) { logger.info('Data already sent to druid'); return; } const analyticsData = cachedData.analyticsData || {}; mergeAnalyticsDataAndSendToFluentd(eventSource, analyticsData, responseAnalyticsData); }); }; var sendPendingAVDataToFluentd = function (cacheKey, analyticsData) { Iif (!cacheKey || !analyticsData) { logger.warn('msg="Invalid data"'); return; } Iif (!_s.include(cacheKey, ':')) { logger.warn('msg="Invalid resp cache key" ' + 'key=' + cacheKey); return; } var requestId = _s.strRight(cacheKey, ':'); var reqCacheKey = 'x-icap-req-cache:' + requestId; var url = analyticsData.url; var evtSrc = analyticsData.event_source; return Q.when(getDataFromRedisAndSendToFluentd(url, reqCacheKey, analyticsData, evtSrc)) .then(function () { redisHelper.deleteKeyInRedis(cacheKey); redisHelper.deleteKeyInRedis(reqCacheKey); }); }; var queryUceAndSendToFluentd = function (req, url, responseAnalyticsData, userInfo, evtSrc) { var analyticsData = {}; q_queryUce(makeUceRequestParam(url, responseAnalyticsData)) .timeout(uceTimeoutVal, uceTimeoutMsg) .then(function (uceResponse) { var uceJsonResponse = checkUceResponse(uceResponse, url); addOtherAnalyticsData(analyticsData, req, userInfo, 'response'); var fn = policyEvaluator.getPolicyActionForRequest; return Q.when(fn(url, analyticsData, uceJsonResponse, userInfo, evtSrc)); }) .then(function (policyResult) { checkIsolationBypass(req, url, userInfo, policyResult, false /*checkExpiry*/); mergeAnalyticsDataAndSendToFluentd(evtSrc, analyticsData, responseAnalyticsData); }) .fail(function (error) { var msg = getLogMessage('response', req, 'error', userInfo, null /*uce*/, responseAnalyticsData, null /*policyResult*/, error); logger.warn(msg); }); }; var storeAnalyticsData = function (key, url, responseAnalyticsData, expiresAfter) { Iif (!key) { return; } var respCacheKey = CACHE_PREFIX_RESP + key; return Q.when(redisHelper.setDataInRedis(respCacheKey, responseAnalyticsData, expiresAfter)); }; var modifyIpData = function (req) { var xClientIp = ''; var clientIpParams = ['x-client-ip', 'x-forwarded-for', 'forwarded']; _.forEach(clientIpParams, function(param) { if (req.body[param] && req.body[param] !== '-') { xClientIp = req.body[param]; } }); req.body['x-client-ip'] = xClientIp; }; let applyMostSevereFramePolicy = function(req, policyResult) { if (req.body.entry_mode === 'email') { let email_action = req.body.email_entry_action || 'safeview'; policyEvaluator.applyMostSevereAction(policyResult, email_action, 'email_entry_severity'); } if (req.body.parent_frame_action === 'safeview_readonly') { policyEvaluator.applyMostSevereAction(policyResult, 'safeview_readonly', 'parent_frame_severity'); } }; var peRequestHandler = function (req, res, userInfo) { var url = req.body.url; var evtSrc = req.body.event_source; var analyticsData = {}; Iif (!policyEvaluator.isPolicyDefined(userInfo)) { logger.info('No policy found for userInfo - ' + JSON.stringify(userInfo) + ', url - ' + url); sendDefaultResponse(req, res, requestStats); return; } addOtherAnalyticsData(analyticsData, req, userInfo, 'request'); Iif (!requireInspection(analyticsData)) { if (policyEvaluator.isCapabilityEnabled(userInfo.tenantId, 'strict_resource_mode')) { logger.info('msg="Blocking resource request" url=' + url); let response = {'result': 'block'}; sendResponse(req, res, response, requestStats); return; } logger.info('msg="Skipping resource request" url=' + url); sendDefaultResponse(req, res, requestStats); return; } var uceJsonResponse = null; return Q.when(q_queryUce(makeUceRequestParam(url, analyticsData))) .timeout(uceTimeoutVal, uceTimeoutMsg) .then(function (uceResponse) { uceJsonResponse = checkUceResponse(uceResponse, url); var fn = policyEvaluator.getPolicyActionForRequest; return Q.when(fn(url, analyticsData, uceJsonResponse, userInfo, req.body.event_source)); }) .then(function (policyResult) { checkIsolationBypass(req, url, userInfo, policyResult, true /*checkExpiry*/); updatePolicyIfPostOrUpload(req, url, policyResult, analyticsData); // safeview cannot allow Iif (evtSrc === 'safeview' && policyResult.action === 'allow') { policyResult.action = 'safeview'; } var response = {}; addCookieDetailsToIcapResponse(response, policyResult); Iif (_.contains(analyticsData.resource_category, 'download')) { response.file_download = true; } if (policyResult.action === 'block') { response.categories = analyticsData.cats; // FIXME: Remove when we introduce a 'reason' field // to the custom block page if (policyResult.ua_type === 'unsupported_browser' || policyResult.ua_type === 'blocked_browser') { response.categories = ['Unsupported Browser']; } response.risks = analyticsData.top_level_risks; response.ua_type = policyResult.ua_type; } applyMostSevereFramePolicy(req, policyResult); response.result = policyResult.action; sendResponse(req, res, response, requestStats); var msg = getLogMessage('request', req, 'ok', userInfo, uceJsonResponse, analyticsData, policyResult, null /*errorMsg*/); Iif (isBypassCookieUpdateRequest(req, policyResult, msg)) { return; } logger.info(msg); return handleSendingDataToFluentd(req, analyticsData, policyResult); }) .fail(function (error) { var msg = getLogMessage('request', req, 'error', userInfo, uceJsonResponse, analyticsData, null /*policyResult*/, error); logger.warn(msg); if (error.stack) { logger.warn('msg="requestHandler exception" stack="' + error.stack + '"'); } sendDefaultResponse(req, res, requestStats); sendResponseAndHandleUceError(req, res, analyticsData); }); }; /** * @function requestHandler * @desc Handles ICAP request filter query * @param {object} * req request object * @param {object} * res response object */ peController.requestHandler = function (req, res) { Iif (!req || !req.body || !req.body.url || !req.body.event_source) { logger.warn('Invalid request params'); sendDefaultResponse(req, res, requestStats); return; } populateTimeInfo(req); if (_.contains(safeviewEventSources, req.body.event_source)) { populateAdditionalSafeviewData(req, 'request'); } return Q.when(getUserInfo(req)) .then(function (userInfo) { return updateTenantIdUsingIp(req, userInfo); }) .then(function (userInfo) { modifyIpData(req); return peRequestHandler(req, res, userInfo); }) .fail(function (error) { logger.warn('msg="requestHandler error" stack="' + error.stack + '"'); }) .fin(function () { // Catch all cases where response is still not sent sendDefaultResponse(req, res, requestStats); }); }; var safeviewQueryParams = ['url', 'user', 'tenantId', 'safe_bid']; var isValidRequest = function (req, queryParams) { Iif (!req || !req.body) { logger.info('Not a valid request: Missing param - body'); return false; } Eif (req.body.tenant_id) { req.body.tenantId = req.body.tenant_id; } const missing = (queryParams || safeviewQueryParams) .filter(key => !req.body[key]); Iif (missing.length !== 0) { logger.info('Missing request params: ' + missing.join(', ') + '. Invalid request ' + JSON.stringify(req.body)); return false; } return true; }; const MAXMIND_FILE = __dirname + '/../../config/GeoLite2-Country/GeoLite2-Country.mmdb'; const maxmind = config.pnr_enforcement.use_maxmind && mmdbreader.openSync(config.pnr_enforcement.maxmind_file || MAXMIND_FILE); let maxmind_getGeoData = maxmind && Q.nbind(maxmind.getGeoData, maxmind); const dns_resolve = Q.denodeify(dns.resolve); let domainToIP = domain => { Iif (net.isIP(domain)) { return [domain]; } return Q.when(domain).then(dns_resolve); }; const riskScore = (url, resourceCategory, logContext) => { function query_uce() { let uceJsonResponse = null; return q_queryUce({ url: url, timeoutMsg: uceTimeoutMsg, riskFactors: true, resourceCategory: resourceCategory }) .timeout(uceTimeoutVal, uceTimeoutMsg) .then(uceResponse => { uceJsonResponse = uceResponse; const response = checkUceResponse(uceResponse, url); return safemail.uceToTally(response[url]); }) .fail(error => pdpLogger.verbose({ event: 'uce-failed', error: error, status: 'error', uceResponse: uceJsonResponse, context: logContext }) ); } function query_maxmind(url) { const domain = url.hostname; return !maxmind? Q.when({score: 0}): Q.fcall(domainToIP, domain) .timeout(uceTimeoutVal, 'DNS lookup failed') .then(ips => ips.map(i => maxmind_getGeoData(i))) .all() .timeout(uceTimeoutVal, 'Maxmind lookup timed out') .then(safemail.countryCodeToTally) .fail(error => pdpLogger.verbose({ event: 'maxmind-failed', error: error, status: 'error', context: logContext })); } return safemail.riskScore([query_uce, query_maxmind], url); }; /** * @function riskScoreHandler * @desc Handles Risk Score queries */ peController.riskScoreHandler = (req, res) => { if (!isValidRequest(req, ['url'])) { sendResponse(req, res, {error: 'Invalid request: url missing'}, requestStats); return; } populateTimeInfo(req); let analyticsData = {}; const userInfo = { userId: req.body.user || 'Mobile User', tenantId: req.body.tenant_id || -1 }; addOtherAnalyticsData(analyticsData, req, userInfo, 'request'); const logContext = { user: { user_id: userInfo.userId, tenant_id: userInfo.tenantId }, url: req.body.url }; riskScore(req.body.url, ['page'], logContext) .then(score => { const resp = { url_score: { risk_score: score.riskScore, risk_tally: score.tally && score.tally.score }, explain: score.tally && score.tally.explanations() || [] }; pdpLogger.info({ event: 'risk-score', status: 'ok', context: logContext, score: resp, trace: req.body.verbose && JSON.stringify(score) }); switch(score.riskScore){ case 'high': analyticsData.pe_action = 'mobile_block_high'; break; case 'medium': analyticsData.pe_action = 'mobile_block_medium'; break; case 'low': analyticsData.pe_action = 'mobile_block_low'; break; } if (req.body.verbose) { resp.raw = score; } sendResponse(req, res, resp, requestStats); sendDataToFluentdOrSyslog(analyticsData); }) .fail(error => { pdpLogger.verbose({ event: 'risk-score-uncaught-error', status: 'error', error: error, context: logContext }); sendResponse(req, res, {error: 'Internal error'}, requestStats); }); }; /** * @function pdpHandler * @desc Handles safemail policy decision query * @param {object} * req request object * @param {object} * res response object */ peController.pdpHandler = (req, res) => { function noDecision() { const response = { 'entry_action' : 'block', 'upgrade_action' : 'block', 'nodecision' : true }; sendResponse(req, res, response, requestStats); } Iif (!isValidRequest(req, ['url', 'user'])) { noDecision(); return; } req.body.event_source = req.body.event_source || 'surrogate'; populateTimeInfo(req); Eif (_.contains(safeviewEventSources, req.body.event_source)) { populateAdditionalSafeviewData(req, 'request'); } const url = req.body.url; // FIXME: shouldn't default tenantId be set somewhere in isValidRequest? const userInfo = {userId: req.body.user, tenantId: req.body.tenantId || -1}; const analyticsData = {}; addOtherAnalyticsData(analyticsData, req, userInfo, 'request'); const logContext = { handler: { pe_type: 'pdp' }, user: { user_id: userInfo.userId, tenant_id: userInfo.tenantId }, browser: { browser: analyticsData.browser, browser_version: analyticsData.browser_major_version }, request: { resource_category: analyticsData.resource_category.join(', '), page_request: analyticsData.is_page_request, event_source: req.body.event_source, url: req.body.url }, time_started: req.body.unix_time * 1000 }; Iif (!requireInspection(analyticsData)) { // TODO: do we skip resource requests? pdpLogger.info({ event: 'resource-request', status: 'skipped', context: logContext }); sendResponse(req, res, { 'entry_action' : 'direct' }, requestStats); return; } const safemailPolicy = policyEvaluator.getUserPolicy(userInfo, {safemail_isolation: false}).safemail_isolation; function query_attrs() { return q_queryAttrs(userInfo, safemail.policyUserAttributes(safemailPolicy)) .timeout(uceTimeoutVal, 'user attribute retrieval timed out') .fail(error => pdpLogger.verbose({ event: 'attribute-retrieval-failed', // if searchResult is present, it is expected pnr-policy response // so log only search_result, not the error or its stack error: error.searchResult? undefined: error, search_result: JSON.stringify(error.searchResult), status: 'error', context: logContext }) ); } Q.fcall(() => { Iif (!safemailPolicy) { throw new Error('Request for tenant with no policy: tenantId=' + userInfo.tenantId); } return [riskScore(url, analyticsData.resource_category, logContext), query_attrs()]; }) .spread((urlScore, attributeSearchResult) => { const decision = safemail.pdp(urlScore, attributeSearchResult, safemailPolicy); Iif (decision.error) { pdpLogger.verbose({ event: 'pdp-error', status: 'error', decision: decision, context: logContext }); return; } else { // when the decision is ok, reduce the diagnostic output to // just the Risk Score (H/M/L) and the numeric value it is // produced from decision.decision.explain = decision.url_score && decision.url_score.tally && decision.url_score.tally.explanations(); Eif (!req.body.verbose) { delete decision.role_assignment_policy_trace; Eif (decision.url_score) { decision.decision.url_score = { risk_score: decision.url_score.riskScore, risk_tally: decision.url_score.tally && decision.url_score.tally.score }; decision.score_trace = JSON.stringify( decision.url_score.tally.trace ); delete decision.url_score; } } pdpLogger.info({ event: 'pdp-decision', status: 'ok', decision: decision, context: logContext }); } sendResponse(req, res, req.body.verbose ? decision: decision.decision, requestStats ); return true; }) .fail(error => pdpLogger.verbose({ event: 'pdp-uncaught-error', status: 'error', error: error, context: logContext })) .then(d => { Iif (!d) { pdpLogger.verbose({ event: 'pdp-fall-through', status: 'error', context: logContext }); noDecision(); } }); }; peController.listPolicies = (req, res) => { const list = {policies: policyEvaluator.getCurrentPolicyVersions()}; res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(list)); }; const updateCategoryInfo = function (url, analyticsData, cacheKey) { return Q.when(redisHelper.getDataFromRedis('x-icap-req-cache:' + cacheKey)) .then(function (data) { if (data) { const ad = data.analyticsData || {}; analyticsData.cats = ad.cats || []; // TODO: This probably does not need to be only // done on safeview_readonly requests. Investigate // to make sure that doing it for all pe_actions // does not have any negative effects if (ad.pe_action === 'safeview_readonly') { analyticsData.pe_action = ad.pe_action; analyticsData.pe_reason = ad.pe_reason; } return; } return Q.when(q_queryUce(makeUceRequestParam(url, analyticsData))) .timeout(uceTimeoutVal, uceTimeoutMsg) .then(function (uceResponse) { Iif (!uceResponse || !uceResponse[url]) { logger.warn('msg="No Uce response" url=' + url); return; } policyEvaluator.updateCategoryInfo(uceResponse, analyticsData); }); }); }; // Returns whether the user request should be logged to druid immediately // (meaning no more pnr-enforcement APIs are needing to be called for this user // request) or whether logging should be deferred (meaning that further calls // are required for av scan etc. and that the logging should only happen once // final results are determined. If this is the case, the logging happens // explicitly via a later call to the avLogHandler. const _shouldLogNow = function (responseAnalyticsData, policyResult) { if (!responseAnalyticsData.file_type || policyResult.action === 'block') { return true; } const eSrc = responseAnalyticsData.event_source; const pAction = policyResult.action; const actions = ['allow', 'bypass']; Iif (eSrc === 'icap' && policyResult.skipAV && _.contains(actions, pAction)) { //Only pnr-icap supports skipAV flag. Safeview does not. return true; } return false; }; const checkFileDownloadStatus = function (ad) { Eif (!ad || (ad.file_download !== 'true') || (ad.file_download_status !== 'error')) { return null; } let reason = ad.file_download_error_reason; logger.warn('msg="File download error" reason='+ reason + ' url=' + ad.url); let policyAction = {}; policyAction.action = 'block'; policyAction.download_original = 'block'; policyAction.reason = reason || 'download_error'; return policyAction; }; var peResponseHandler = function (req, res, serverInfos, userInfo) { var url = req.body.url; var contentType = getValue(req.body, 'content-type') || ''; var responseAnalyticsData = {}; addOtherAnalyticsData(responseAnalyticsData, req, userInfo, 'response'); if (getValue(responseAnalyticsData, 'ua_type', 'supported_browser') !== 'supported_browser') { // Unsupported/non-browser have policy only to block or allow // If it comes to the response path, must be an allow // unsupported/non-browser requests are always logged in request path sendResponse(req, res, {'result': 'allow'}, null); return; } var inspect = requireInspection(responseAnalyticsData); Iif (!inspect) { sendDefaultResponse(req, res, responseStats); if (!config.pnr_enforcement.evaluate_risks_for_resources) { return; } } var evtSrc = req.body.event_source; var fn = policyEvaluator.getPolicyActionForResponse; var policyResult = null; var shouldLogNow = true; // If this flag is false, the analysis data will not // be logged straight away but will be either stored // in Redis (safeview) or passed back to the icap // server for forwarding on to the file-server, and // used later when avlog is called with the full // results. (This will only happen for files.) var key = getValue(req.body, 'x-icap-req-cache', ''); if (!key) { key = getValue(req.body, 'x-safeview-fs-cache', ''); } return Q.when(updateCategoryInfo(url, responseAnalyticsData, key)) .then(function () { const res = checkFileDownloadStatus(responseAnalyticsData); Iif (res) { return res; } return Q.when(fn(url, responseAnalyticsData, serverInfos, contentType, userInfo, evtSrc)); }) .then(function (result) { policyResult = result; applyMostSevereFramePolicy(req, policyResult); if (evtSrc === 'safeview') { // Safeview only reacts to the policy result from the response, // so if the request has a more severe safeview action than the // response, we want to respond with that action policyEvaluator.applyMostSevereAction(policyResult, responseAnalyticsData.pe_action, responseAnalyticsData.pe_reason); } // Note: CheckExpiry is false here since we cannot take any // cookie update/removal related action. checkIsolationBypass(req, url, userInfo, policyResult, false/*checkExpiry*/); Iif (!inspect) { return; } responseAnalyticsData.pe_action = policyResult.action; responseAnalyticsData.pe_reason = policyResult.reason; // Log the result now if this completes the action (e.g. block or // straight allow/bypass without AV Scan) shouldLogNow = _shouldLogNow(responseAnalyticsData, policyResult); if (shouldLogNow) { return; } return Q.when(storeAnalyticsData(key, url, responseAnalyticsData)); }) .then(function () { // safeview cannot allow Iif (evtSrc === 'safeview' && policyResult.action === 'allow') { policyResult.action = 'safeview'; } let response = { 'result' : policyResult.action }; if (policyResult.action !== 'block' && policyResult.download_original){ response.download_original = policyResult.download_original; responseAnalyticsData.pe_action = policyResult.download_original; responseAnalyticsData.pe_reason = policyResult.reason; } if (policyResult.action === 'safedoc') { response.download_safe = policyResult.download_safe; } if (policyResult.action === 'block') { response.categories = responseAnalyticsData.cats; response.risks = responseAnalyticsData.top_level_risks; } if (_.contains(responseAnalyticsData.resource_category, 'download')) { response.file_download = true; response.skip_av = policyResult.skipAV; } // Logging later (partial request) so cache the analytics data for // the later call. For icap this will be sent back as part of the // response, otherwise, put it into redis if (!shouldLogNow && evtSrc === 'icap') { response.analyticsData = responseAnalyticsData; } sendResponse(req, res, response, responseStats); let msg = getLogMessage('response', req, 'ok', userInfo, null /*uce*/, responseAnalyticsData, policyResult, null /*errorMsg*/); logger.info(msg); }) .then(function () { if (!shouldLogNow) { // Do not log anything to druid about the request details. // Wait till pnr-icap or safeview-fs calls back with sha256 of // the document/executable. return; } if (!shouldLogFrame(req, policyResult)) { return; } if (getValue(req.body, 'x-icap-req-cache')) { var cacheKey = 'x-icap-req-cache:' + getValue(req.body, 'x-icap-req-cache'); getDataFromRedisAndSendToFluentd(url, cacheKey, responseAnalyticsData, evtSrc); } else { queryUceAndSendToFluentd(req, url, responseAnalyticsData, userInfo, evtSrc); } }); }; /** * @function responseHandler * @desc Handles ICAP request filter query * @param {object} * req request object * @param {object} * res response object */ peController.responseHandler = function (req, res) { Iif (!req || !req.body || !req.body.url || !req.body.event_source) { logger.warn('Invalid request params'); sendDefaultResponse(req, res, responseStats); return; } populateTimeInfo(req); if (_.contains(safeviewEventSources, req.body.event_source)) { populateAdditionalSafeviewData(req, 'response'); } var userInfo = null; return Q.when(getUserInfo(req)) .then(function (result) { userInfo = result; var fingerPrints = []; var htmlContents = getValue(req.body, 'resource_data', ''); if (htmlContents) { var tid = userInfo.tenantId; fingerPrints = policyEvaluator.getEnabledFingerPrints(tid); } return serverDetails.getServerInfo(req.body, fingerPrints); }) .then(function (serverInfos) { return Q.when(peResponseHandler(req, res, serverInfos, userInfo)); }) .fail(function (error) { logger.warn('msg="responseHandler error" stack="' + error.stack + '"'); }) .fin(function () { // Catch all cases where response is still not sent sendDefaultResponse(req, res, responseStats); }); }; // // Add file transfer direction and other file related information to // the analyticsData object used to log to druid var addFileTransferAnalytics = function (req, analyticsData) { Iif (!analyticsData.resource_category) { analyticsData.resource_category = []; } Iif (req.body.direction === 'upload') { analyticsData.file_download = 'false'; analyticsData.file_upload = 'true'; if (!_.contains(analyticsData.resource_category, 'upload')) { analyticsData.resource_category.push('upload'); } } else { analyticsData.file_download = 'true'; analyticsData.file_upload = 'false'; Iif (!_.contains(analyticsData.resource_category, 'download')) { analyticsData.resource_category.push('download'); } } Iif (req.body.file_type) { analyticsData.file_type = req.body.file_type; } }; // // avCheckHandler (POST /api/v1/pe/avcheck) // handles querying download policy, getting virustotal results, // and file scan policy for plugin file scan / export. // peController.avCheckHandler = function (req, res) { var response = {}; response.download_original = 'allow'; Iif (!req || !req.body || !req.body.cache_key) { var msg = 'msg="Invalid request params in avcheck query"'; if (req && req.body) { msg += ' request_body=' + JSON.stringify(req.body); } logger.warn(msg); sendResponse(req, res, response, null /*stats*/); return; } populateTimeInfo(req); Eif (_.contains(safeviewEventSources, req.body.event_source)) { populateAdditionalSafeviewData(req, 'response'); } const key = req.body.cache_key; const cacheKey = CACHE_PREFIX_RESP + key; let analyticsData = null; let userInfo = null; return Q.when(redisHelper.getDataFromRedis(cacheKey)) .then(function (data) { if (!data) { Iif (req.body.analyticsData) { data = req.body.analyticsData; } else { logger.warn('msg="No analytics data in redis during avcheck" ' + 'sha256='+ req.body.sha256 + ' key=' + cacheKey); return; } } analyticsData = data; addFileTransferAnalytics(req, analyticsData); userInfo = { tenantId : analyticsData.tid, userId : analyticsData.userid, groups : analyticsData.userGroups }; Iif (req.body.file_download_status === 'error' || !req.body.sha256) { logger.warn('msg="File download error" reason='+ req.body.reason + ' url=' + analyticsData.url); var policyAction = {}; policyAction.download_original = 'block'; policyAction.reason = req.body.reason || 'unknown'; return Q.when(policyAction); } analyticsData.sha256 = req.body.sha256.toLowerCase(); var fn = policyEvaluator.getPolicyActionForAVScan; return Q.when(fn(userInfo, analyticsData)); }) .then(function (policyAction) { if (!policyAction || !analyticsData) { logger.warn('msg="No policy action during avcheck" ' + 'sha256='+ req.body.sha256 + ' key=' + cacheKey); sendResponse(req, res, response, null /*stats*/); return; } Eif (policyAction.download_original) { response.download_original = policyAction.download_original; analyticsData.pe_action = policyAction.download_original; } if (policyAction.download_safe) { response.download_safe = policyAction.download_safe; } Eif (analyticsData.virus_details) { response.virus_details = analyticsData.virus_details; } if (analyticsData.av_scan_result) { response.av_scan_result = analyticsData.av_scan_result; } Eif (analyticsData.av_vendors) { response.av_vendors = analyticsData.av_vendors; } if (analyticsData.action_on_malware) { response.action_on_malware = analyticsData.action_on_malware; } if (policyAction.download_original === 'block') { response.categories = analyticsData.cats; response.risks = analyticsData.top_level_risks; } // Add the AV File Scan / File Export policy // This is a list of File plugins and their config/credentials // that needs to be executed before allowing the original file // download through to the user. // Even if VT scan has already said that the file is malicious, we // still need to run content inspection as it may include actions // like 'forensic archive' which archives off copies of files being // uploaded or downloaded by users for later analysis. Eif (config.safefile && config.safefile.enabled) { policyEvaluator.getContentInspectionPolicy(response, analyticsData, policyAction, analyticsData.event_source === 'icap'); } Eif (policyAction.reason) { analyticsData.pe_reason = policyAction.reason; } // Store the updated metadata back into redis for logging later // (see /avLogHandler) return Q.when(storeAnalyticsData(key, analyticsData.url, analyticsData, config.safefile.avcheck_cache_duration)); }) .fail(function (error) { logger.warn('msg="avcheck error" stack="' + error.stack + '"'); }) .fin(function () { // Catch all cases where response is still not sent sendResponse(req, res, response, null /*stats*/); }); }; // // avLogHandler (POST /api/v1/pe/avlog) // handles logging to druid when the final virus scan results are known. // peController.avLogHandler = function (req, res) { let response = {}; Iif (!req || !req.body || !req.body.cache_key) { let msg = 'msg="Invalid request params in avlog query"'; if (req && req.body) { msg += ' request_body=' + JSON.stringify(req.body); } logger.warn(msg); sendResponse(req, res, response, null /*stats*/); return; } const cacheKey = CACHE_PREFIX_RESP + req.body.cache_key; let analyticsData = null; let userInfo = null; return Q.when(redisHelper.getDataFromRedis(cacheKey)) .then(function (data) { if (!data) { logger.warn('msg="No analytics data in redis during avlog" ' + 'key=' + cacheKey); return; } req.body.url = data.url; populateTimeInfo(req); Eif (_.contains(safeviewEventSources, req.body.event_source)) { populateAdditionalSafeviewData(req, 'response'); } return data; }) .then(function (data) { if (!data) { logger.warn('msg="No policy action during avlog" ' + 'key=' + cacheKey); sendResponse(req, res, response, null /*stats*/); return; } analyticsData = data; userInfo = { tenantId : analyticsData.tid, userId : analyticsData.userid, groups : analyticsData.userGroups }; // Update the pe_action if download_original has been passed Eif (req.body.download_original) { analyticsData.pe_action = req.body.download_original; } // Override the code if set and not already 'R' (red) if (req.body.code && analyticsData.code !== 'R' ) { analyticsData.code = req.body.code; } // Override various settings with the values discovered during // the embedded scan and other file extraction plugins. analyticsData.pe_reason = req.body.pe_reason || analyticsData.pe_reason; analyticsData.virus_details = _.union(analyticsData.virus_details, req.body.virus_details); analyticsData.av_scan_result = req.body.av_scan_result || analyticsData.av_scan_result; analyticsData.av_vendors = _.union(analyticsData.av_vendors, req.body.av_vendors); analyticsData.risks = _.union(analyticsData.risks, req.body.risks); analyticsData.risks_v2 = _.union(analyticsData.risks_v2, req.body.risks_v2); analyticsData.top_level_risks = _.union(analyticsData.top_level_risks, req.body.top_level_risks); // TODO: pdf report link, additional details UK-1719 // TODO: What do we want to log when a file has been sanitized? UK-1719 // Union the analyticsData with anything custom added by the file // processing plugins Eif (req.body.analyticsData) { analyticsData = _.merge(analyticsData, req.body.analyticsData); } // If a doc_id was passed, the file went to safedocs so add 'safedoc' to // the list of resource categories. if (req.body.docId) { analyticsData.resource_category.push('safedoc'); } // If the content inspection has been skipped completely with the // exceptions to skip and Mark as Infected reflect that in the logs // We could have an 'ExceptionAllow' but don't need that as the log // is already correct for Mark as Clean if (analyticsData.av_scan_result === 'ExceptionBlock') { analyticsData.code = 'R'; analyticsData.av_scan_result = 'Infected'; analyticsData.av_vendors.push('User Exception'); analyticsData.virus_details.push('Exception|User Exception - Block File'); analyticsData.risks.push('Infected'); analyticsData.risks_v2.push('Infected'); analyticsData.top_level_risks.push('Risky File'); } // Filter resource categories to remove any duplicates before logging analyticsData.resource_category = Array.from( new Set(analyticsData.resource_category || [])); // Add additional Resource Categories and special cases for Attachment // Isolation and 'dropfile' support (to make sure we set an appropriate // source url and category for this attachment. In later phases of email // attachment support when we have policy for mail attachment viewing // this can be removed and handled properly (own category and log viewer) Iif (analyticsData.dropfile_id && analyticsData.dropfile_id !== 'NA') { // FIXME: Could check dropfile_ver to determine if browse vs attachment if (analyticsData.resource_category.indexOf('attachment') === -1) { analyticsData.resource_category.push('attachment'); } // Set the url to an empty string, as it's not relevant for email analyticsData.url = ''; // Use domain from from: address if available, otherwise set to empty. analyticsData.domain = ''; try { if (analyticsData.mail_from && analyticsData.mail_from.indexOf('@') > -1) { analyticsData.domain = analyticsData.mail_from.split('@')[1]; } } catch (err) { logger.warn('event="mail_from_error" error="' + err + '"'); } analyticsData.cats = ['']; analyticsData.cats_ids = ['-1']; analyticsData.webroot_cats = ['']; analyticsData.webroot_cats_ids = ['-1']; // Skip UCE and log analyticsData analyticsData = modifyPayloadForDruid(analyticsData); sendDataToFluentdOrSyslog(analyticsData); } else if (analyticsData.event_source === 'safeview') { req.body.url = analyticsData.url; queryUceAndSendToFluentd(req, analyticsData.url, analyticsData, userInfo, analyticsData.event_source); } else { sendPendingAVDataToFluentd(cacheKey, analyticsData); } response.result = 'ok'; }) .fail(function (error) { logger.warn('msg="avlog error" stack="' + error.stack + '"'); }) .fin(function () { // Catch all cases where response is still not sent sendResponse(req, res, response, null /*stats*/); }); }; const safeviewFeatureToPolicyMap = { 'enable_bypass': 'bypass', 'enable_logo': 'displayLogo', 'enable_file_upload': 'fn:isFileUploadAllowed', 'rev_id': 'rev_id', 'config_rev_id': 'config_rev_id', 'tid': 'tid', 'safemail_config': 'safemail_config', 'safemail_whitelist': 'safemail_whitelist', 'safemail_attachments': 'safemail_attachments', 'customization': 'customization_email', 'notification_customization': 'customization_web.notifications' }; // Log blocked uploads to druid, push analytics for allowed uploads // into redis for logging later const handleLoggingToFluentd = function (features, analyticsData, result) { Iif (!features || !analyticsData || !result) { return; } // We currently only log uploads if (!_.contains(features, 'enable_file_upload')) { return; } analyticsData.browser_and_version = 'NA'; analyticsData.file_upload = 'true'; analyticsData.resource_category = ['upload']; analyticsData.pe_action = 'allow'; Iif (result.enable_file_upload) { // Use a generated key as the nav_session_id will change between the upload // check here and the actual upload request. User can only do one upload at // a time as it is modal so just key off of the user. var key = 'file-upload-' + analyticsData.tid + '-' + analyticsData.userid; storeAnalyticsData(key, analyticsData.url, analyticsData); return; } analyticsData.pe_action = 'block'; analyticsData.pe_reason = 'dlp_FileUpload_isolated_site'; sendDataToFluentdOrSyslog(analyticsData); }; /** * @function isBypassAllowed * @desc method used by safeview to check if bypass is allowed * @param {object} * req request object * @param {object} * res response object * * @deprecated. Use getUserPolicy instead */ peController.isBypassAllowed = function (req, res) { var result = {}; result.isAllowed = false; if (isValidRequest(req)) { result.isAllowed = policyEvaluator.isBypassAllowed(req.body.tenantId); } result.is_allowed = result.isAllowed; res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(result)); }; /** * @function getBypassToken * @desc method used by safeview to get bypass token * @param {object} * req request object * @param {object} * res response object */ peController.getBypassToken = function (req, res) { var result = {}; result.token = ''; if (isValidRequest(req) && policyEvaluator.isBypassAllowed(req.body.tenantId)) { result.domain = '.' + tld.getDomain(req.body.url); result.token = generateBypassToken(result.domain); } res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(result)); }; let updateUserInfoAndAnalyticsData = function (req, userInfo, url, analyticsData, uceJsonResponse) { if (!url || !userInfo || !userInfo.userId) { return; } req.body.event_source = 'safeview'; addOtherAnalyticsData(analyticsData, req, userInfo, 'request'); uceJsonResponse[url] = {}; return Q.when(q_queryUce(makeUceRequestParam(url, analyticsData))) .timeout(uceTimeoutVal, uceTimeoutMsg) .then(function (uceResponse) { Eif (uceResponse && uceResponse[url]) { uceJsonResponse[url] = uceResponse[url]; } return Q.when(updateUserGroups(userInfo)); }); }; /** * @function getPolicyKeys * @desc method to get policy for a tenant as json * @param {object} * req request object * @param {object} * res response object */ peController.getPolicyKeys = function(req, res) { const pResult = {}; Iif (!req.body.features) { res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(pResult)); return; } const tenantId = req.body.tenantId || -1; _.forEach(req.body.features, function(feature) { pResult[feature] = policyEvaluator.getPolicyKeys(feature, tenantId); }); res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(pResult)); }; /** * @function getUserPolicy * @desc method used by safeview to get different features * enabled/disabled in the policy for a user/tenant * @param {object} * req request object * @param {object} * res response object */ peController.getUserPolicy = function (req, res) { const result = {}; Iif (!isValidRequest(req, []) || !req.body.features) { res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(result)); return; } populateTimeInfo(req); const userInfo = { userId: req.body.user || req.body.user_id, tenantId: req.body.tenantId || -1 }; const analyticsData = {}; const uceJsonResponse = {}; const url = req.body.url; return Q.when(updateUserInfoAndAnalyticsData(req, userInfo, url, analyticsData, uceJsonResponse)) .then(function () { //First get the safeview feature to policy mapping let pResult = {}; _.forEach(req.body.features, function (feature) { const pFeature = safeviewFeatureToPolicyMap[feature]; Eif (pFeature) { pResult[pFeature] = false; } else { logger.warn('Unknown feature queried - ' + feature); } }); //Query policy for features pResult = policyEvaluator.getUserPolicy(userInfo, pResult, url, analyticsData, uceJsonResponse); //Map back policy features to safeview features _.forEach(req.body.features, function (feature) { result[feature] = false; var pFeature = safeviewFeatureToPolicyMap[feature]; // FIXME: this looks wrong. It will leave result set to false for // any falsy pResult[pFeature] - including 0 and '', which do not // have the same meaning as false. if (pFeature && pResult[pFeature]) { result[feature] = pResult[pFeature]; } }); // special treatment of safemail_config - it is obtained from tenant // config. A sufficient test is to see the key is present Iif (result.safemail_config !== undefined) { const safemailConfig = ( policyEvaluator.safemailConfig(userInfo.tenantId) || {} ); // TODO: for now tenant config just overrides policy, as there is no // UI to set safemail_config in tenant config. // At the same time devops will have a way to effect any changes, if // the tenant is not using UI to set these values. // safemail_config is being migrated to tenant config, so when the // migration is complete, no need to merge result.safemail_config // obtained from policy and no need to shallow-copy // safemailConfig result.safemail_config = Object.assign( Object.assign({}, result.safemail_config), safemailConfig ); } Iif (result.config_rev_id !== undefined) { result.config_rev_id = ( policyEvaluator.configRevId(userInfo.tenantId) || false ); } // Log to druid / add to redis cache for later logging handleLoggingToFluentd(req.body.features, analyticsData, result); }) .fail(function (error) { logger.warn('msg="getUserPolicy error" stack="' + error.stack + '"'); }) .fin(function () { res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(result)); }); }; /** * @function getFlashOnTidList * @desc Returns list of tenants with flashOn flag * @param {object} req request object * @param {object} res response object */ peController.getFlashOnTidList = function(req, res) { var result = policyEvaluator.getFlashOnTidList(); res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(result)); }; /** * @function getFlashSiteListV1 * @desc Returns flash site whitelist * @param {object} req request object * @param {object} res response object */ peController.getFlashSiteListV1 = function(req, res) { var result = []; var tid = req.body.tid; res.setHeader('Content-Type', 'application/json'); result = policyEvaluator.getFlashSiteList(tid); // v1 does not send flash flags result = result.map(function(x) { return x[0]; }); res.send(JSON.stringify(result)); }; /** * @function getFlashSiteListV2 * @desc Returns flash site whitelist * @param {object} req request object * @param {object} res response object */ peController.getFlashSiteListV2 = function(req, res) { var result = []; var tid = req.body.tid; res.setHeader('Content-Type', 'application/json'); result = policyEvaluator.getFlashSiteList(tid); res.send(JSON.stringify(result)); }; /** * @function getSiteFlagsV1 * @desc Returns site_flags used by surrogate to make per site customization. * @param {object} req request object * @param {object} res response object */ peController.getSiteFlagsV1 = function(req, res) { res.setHeader('Content-Type', 'text/plain; charset=UTF-8'); res.send(policyEvaluator.getSiteFlags()); }; /** * @function getTenantCapabilities * @desc Returns tenant capabilities * @param {object} req request object * @param {object} res response object */ peController.getTenantCapabilities = function(req, res) { let result = {}; const tid = req.body.tid; res.setHeader('Content-Type', 'application/json'); Iif (!tid) { logger.warn('msg="No tid in tenant_capabilities api"'); res.send(JSON.stringify(result)); return; } result = policyEvaluator.getTenantCapabilities(tid); res.send(JSON.stringify(result)); }; /** * @function getTenantsPerCapability * @desc Returns all tenants with a capability * @param {object} req request object * @param {object} res response object */ peController.getTenantsPerCapability = function(req, res) { let result = {}; const capabilities = req.body.capabilities; res.setHeader('Content-Type', 'application/json'); Iif (!capabilities || _.isEmpty(capabilities)) { logger.warn('msg="No capability in tenants_per_capability api"'); res.send(JSON.stringify(result)); return; } result = policyEvaluator.getTenantsPerCapability(capabilities); res.send(JSON.stringify(result)); }; /** * @function getTenantCustomization * @desc Returns Customized content for a specific tenant/language * @param {object} req request object * @param {object} res response object */ peController.getTenantCustomization = function(req, res) { const tid = req.body.tid; const lang = req.body.lang; const type = req.body.type; let result = {}; res.setHeader('Content-Type', 'application/json'); Iif (!tid || !type || !lang) { logger.warn('msg="No tid/type/lang in tenant_customization api"'); res.send(JSON.stringify(result)); return; } result = policyEvaluator.getTenantCustomization(tid, type, lang); res.send(JSON.stringify(result)); }; var sendDefaultSslBumpBypassResponse = function(req, res) { var response = {}; response.result = config.pnr_enforcement.default_sslbump_action; sendResponse(req, res, response, sslbumpStats); }; var sendDefaultBounceAllResponse = function(req, res) { var response = {}; response.bounce = config.pnr_enforcement.default_bounce_all_action; sendResponse(req, res, response, null); }; var getAnalyticData = function (req, userInfo, type, defaultUserId) { var analyticsData = {}; addDefaultRequestAnalyticsData(analyticsData); addDefaultResponseAnalyticsData(analyticsData); _.forEach(analyticsRequestKeys, function (key) { analyticsData[key] = req.body[key] || ''; }); analyticsData.url = req.body.destination; analyticsData.domain = req.body.destination; analyticsData.userid = (userInfo.userId === 'Unknown') ? defaultUserId : userInfo.userId; analyticsData.tid = userInfo.tenantId; let userAgent = getUserAgent(req); analyticsData['user-agent'] = userAgent; Eif (!userAgent) { analyticsData.browser = 'Unavailable'; } else { getBrowserInfo(analyticsData); } analyticsData.protocol = 'https'; analyticsData.resource_category = [type]; analyticsData.pe_action = config.pnr_enforcement.default_sslbump_action; analyticsData.pe_reason = ''; analyticsData.event_source = 'squid'; analyticsData.readonly_action = ''; Iif (type !== 'sslbump') { analyticsData.protocol = req.body.protocol; analyticsData.event_source = req.body.event_source || 'unknown'; analyticsData.url = req.body.url; analyticsData.domain = req.body.domain; analyticsData.pe_action = req.body.pe_action; analyticsData.pe_reason = req.body.pe_reason; analyticsData.risk_score = 'NA'; analyticsData.risk_tally = -1; analyticsData.readonly_user_experience = 'NA'; } return analyticsData; }; var populateClientIpAndUserData = function (req) { var userdata = '-1:Unknown'; Iif (req.body.user && req.body.user !== '-') { userdata = req.body.user; } req.body['x-icap-userdata'] = userdata; var xClientIp = ''; // Currently the result of this function is only used to determine TID for // the request. As such, it should only rely on real source IP (on not on // any forwareded for header). var clientIpParams = ['src', 'src_ip']; _.forEach(clientIpParams, function(param) { if (req.body[param] && req.body[param] !== '-') { xClientIp = req.body[param]; } }); req.body['x-client-ip'] = xClientIp; }; const shouldSslBumpLog = analyticsData => analyticsData && analyticsData.pe_action !== 'sslbump'; var peSslBumpHandler = function (req, res, userInfo) { var domain = req.body.destination; // Needed for transparent proxy ssl exceptions Iif (net.isIP(domain) && req.body.sni && req.body.sni !== '-') { domain = req.body.sni; } var analyticsData = getAnalyticData(req, userInfo, 'sslbump', 'SSL_Exception'); return Q.when(q_queryUce(makeUceRequestParam(domain, analyticsData, true))) .timeout(uceTimeoutVal, uceTimeoutMsg) .then(function (uceResponse) { var uceJsonResponse = checkUceResponse(uceResponse, domain); policyEvaluator.populateAnalyticsDataInRequestPath(domain, uceJsonResponse[domain], analyticsData); var fn = policyEvaluator.getPolicyActionForSslBumpBypass; return Q.when(fn(domain, analyticsData, uceJsonResponse, userInfo)); }) .then(function (policyResult) { const response = { result: policyResult && policyResult.action || config.pnr_enforcement.default_sslbump_action }; sendResponse(req, res, response, sslbumpStats); Iif (shouldSslBumpLog(analyticsData)) { sendDataToFluentdOrSyslog(analyticsData); } }); }; var peBounceAllHandler = function (req, res, userInfo) { var response = {}; response.bounce = policyEvaluator.isCapabilityEnabled(userInfo.tenantId, 'bounce'); sendResponse(req, res, response, null); }; peController.sslBumpBypassCheckHandler = function(req, res) { Iif (!req || !req.body || !req.body.destination) { logger.warn('msg="sslbump_error:Invalid ssl_bump_bypass request params'); sendDefaultSslBumpBypassResponse(req, res); return; } populateTimeInfo(req); populateClientIpAndUserData(req); //The tenantId will be -1 mostly. It will change only when we start looking //at the 'source ip'-'tenant id' map. return Q.when(getUserInfo(req)) .then(function(userInfo) { return updateTenantIdUsingIp(req, userInfo); }) .then(function (userInfo) { return peSslBumpHandler(req, res, userInfo); }) .fail(function (error) { logger.warn('msg="sslbump_error" error="' + error.stack + '"'); }) .fin(function () { // Catch all cases where response is still not sent sendDefaultSslBumpBypassResponse(req, res); }); }; peController.bounceAllCheckHandler = function(req, res) { if (!req || !req.body || (!req.body.tid && !req.body.src_ip)) { logger.warn('msg="bounce_all_error:Invalid bounce_all request params'); sendDefaultBounceAllResponse(req, res); return; } populateTimeInfo(req); populateClientIpAndUserData(req); return Q.when(getUserInfo(req)) .then(function(userInfo) { return updateTenantIdUsingIp(req, userInfo); }) .then(function (userInfo) { return peBounceAllHandler(req, res, userInfo); }) .fail(function (error) { logger.warn('msg="bounce_all_error" error="' + error.stack + '"'); }) .fin(function () { // Catch all cases where response is still not sent sendDefaultBounceAllResponse(req, res); }); }; let logStats = function (stats) { let logMsg = []; _.forEach(stats, function(statsObj, name) { let msg = []; _.forEach(statsObj, function(value, key) { if (value) { msg.push(key + '=' + value); } }); if (msg.length) { logMsg.push(name + ':' + msg.join()); } }); if (logMsg.length) { logger.info(logMsg.join(' ')); } }; /** * @function statsHandler * @desc Handles ICAP stats query * @param {object} * req request object * @param {object} * res response object */ var statsHandler = function () { const stats = {'request' : requestStats, 'response' : responseStats, 'fluentd' : fluentdStats, 'sslbump' : sslbumpStats}; logStats(stats); requestStats = {'allow' : 0, 'safeview' : 0, 'safedoc' : 0, 'block' : 0, 'bypass' : 0}; responseStats = {'allow' : 0, 'safeview' : 0, 'safedoc' : 0, 'block' : 0, 'bypass' : 0}; fluentdStats = {'sent' : 0, 'error' : 0}; sslbumpStats = {'sslbump' : 0, 'sslbump_bypass' : 0}; redisHelper.initializeRedis(); serverDetails.checkForUpdate(); }; // Functions to handle redis subscriber channel logging messages // FIXME (PNR-4243): These functions need to go into a separate module let sendLogEvent = function(data) { let req = { body: data, }; populateTimeInfo(req); let analyticsData = {}; let url = req.body.url; return Q.when(getUserInfo(req)) .then(function (userInfo) { return updateTenantIdUsingIp(req, userInfo); }) .then(function (userInfo) { analyticsData = getAnalyticData( req, userInfo, data.resource_category, data.default_user_id); return q_queryUce(makeUceRequestParam(url, analyticsData, true)) .timeout(uceTimeoutVal, uceTimeoutMsg); }) .then(function (uceResponse) { let uceJsonResponse = checkUceResponse(uceResponse, url); policyEvaluator.populateAnalyticsDataInRequestPath( url, uceJsonResponse[url], analyticsData); sendDataToFluentdOrSyslog(analyticsData); }); }; let processLogEvent = function(message) { const events = { strict_resource_mode_block: { pe_action: 'block', pe_reason: 'Strict resource mode request', resource_category: 'strictmode', default_user_id: 'Resource_Request' } }; let data = {}; try { data = JSON.parse(message); } catch (err) { logger.error('Unexpected message format received: "' + err + '"'); return; } if (_.isEmpty(data.event_type) || !(data.event_type in events)) { logger.error('Unexpected event received: "' + data.event_type + '"'); return; } sendLogEvent(Object.assign(data, events[data.event_type])); }; peController.redisSubcriberChannelHandler = function() { redisSubscriber.on('message', function (channel, message) { if (process.env.WORKER_NAME !== 'non_pe_worker') { logger.warning('Dropping log message from an incorrect ' + 'worker process'); return; } processLogEvent(message); }); }; peController.redisChannelStatusHandler = function(req, res) { redisSubscriber.getStatus(function(err, result) { Iif (err) { logger.error('Redis subscriber channel error: "' + err + '"'); return res.status(500).json({'error': 'backend error'}); } Iif (!result || result.length < 1 || result[1] < 1) { logger.error('No subscribers listening on redis subscriber channel'); return res.status(500).json({'error': 'unavailable'}); } Iif (result[1] > 1) { logger.warn('More than one subscriber listening on redis ' + 'subscriber channel'); return res.status(400).json({'warning': 'duplicate logging may occur'}); } return res.json({'ok': true}); }); }; peController.initRedisChannelSubscriber = function() { Iif (redisSubscriber) { logger.warn('Redis subscriber has been already initialized'); return; } redisSubscriber = new RedisSubscriber(); }; Eif (cluster.isWorker) { initFluentd(); //Initialize fluentd client redisHelper.initializeRedis(); //Initialize redis policyEvaluator.init(); //Load all the policies serverDetails.checkForUpdate(); //Load the vulnerable servers map setInterval(statsHandler, 60 * 1000); //every minute } |