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
|
#! /usr/bin/python3
# ------------------------------------------------------------------
#
# Copyright (C) 2011-2015 Canonical Ltd.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License published by the Free Software Foundation.
#
# ------------------------------------------------------------------
import glob
import json
import optparse
import os
import shutil
import sys
import tempfile
import unittest
import apparmor.easyprof as easyprof
from apparmor.common import AppArmorException
topdir = None
debugging = False
def recursive_rm(dirPath, contents_only=False):
"""recursively remove directory"""
names = os.listdir(dirPath)
for name in names:
path = os.path.join(dirPath, name)
if os.path.islink(path) or not os.path.isdir(path):
os.unlink(path)
else:
recursive_rm(path)
if not contents_only:
os.rmdir(dirPath)
# From Lib/test/test_optparse.py from python 2.7.4
class InterceptedError(Exception):
def __init__(self,
error_message=None,
exit_status=None,
exit_message=None):
self.error_message = error_message
self.exit_status = exit_status
self.exit_message = exit_message
def __str__(self):
return self.error_message or self.exit_message or "intercepted error"
class InterceptingOptionParser(optparse.OptionParser):
def exit(self, status=0, msg=None):
raise InterceptedError(exit_status=status, exit_message=msg)
def error(self, msg):
raise InterceptedError(error_message=msg)
class Manifest:
def __init__(self, profile_name):
self.security = dict()
self.security['profiles'] = dict()
self.profile_name = profile_name
self.security['profiles'][self.profile_name] = dict()
def add_policygroups(self, policy_list):
self.security['profiles'][self.profile_name]['policy_groups'] = policy_list.split(",")
def add_author(self, author):
self.security['profiles'][self.profile_name]['author'] = author
def add_copyright(self, copyright):
self.security['profiles'][self.profile_name]['copyright'] = copyright
def add_comment(self, comment):
self.security['profiles'][self.profile_name]['comment'] = comment
def add_binary(self, binary):
self.security['profiles'][self.profile_name]['binary'] = binary
def add_template(self, template):
self.security['profiles'][self.profile_name]['template'] = template
def add_template_variable(self, name, value):
if 'template_variables' not in self.security['profiles'][self.profile_name]:
self.security['profiles'][self.profile_name]['template_variables'] = dict()
self.security['profiles'][self.profile_name]['template_variables'][name] = value
def emit_json(self, use_security_prefix=True):
manifest = dict()
manifest['security'] = self.security
if use_security_prefix:
dumpee = manifest
else:
dumpee = self.security
return json.dumps(dumpee, indent=2)
#
# Our test class
#
class T(unittest.TestCase):
# work around UsrMove
ls = os.path.realpath('/bin/ls')
def setUp(self):
"""Setup for tests"""
global topdir
self.tmpdir = os.path.realpath(tempfile.mkdtemp(prefix='test-aa-easyprof'))
# Copy everything into place
for d in ('easyprof/policygroups', 'easyprof/templates'):
shutil.copytree(os.path.join(topdir, d),
os.path.join(self.tmpdir, os.path.basename(d)))
# Create a test template
self.test_template = "test-template"
contents = '''# vim:syntax=apparmor
# %s
# AppArmor policy for ###NAME###
# ###AUTHOR###
# ###COPYRIGHT###
# ###COMMENT###
#include <tunables/global>
###VAR###
###PROFILEATTACH### {
#include <abstractions/base>
###ABSTRACTIONS###
###POLICYGROUPS###
###READS###
###WRITES###
}
''' % (self.test_template,)
with open(os.path.join(self.tmpdir, 'templates', self.test_template), 'w') as f:
f.write(contents)
# Create a test policygroup
self.test_policygroup = "test-policygroup"
contents = '''
# {}
#include <abstractions/gnome>
#include <abstractions/nameservice>
'''.format(self.test_policygroup)
with open(os.path.join(self.tmpdir, 'policygroups', self.test_policygroup), 'w') as f:
f.write(contents)
# setup our conffile
self.conffile = os.path.join(self.tmpdir, 'easyprof.conf')
contents = '''
POLICYGROUPS_DIR="{}/policygroups"
TEMPLATES_DIR="{}/templates"
'''.format(self.tmpdir, self.tmpdir)
with open(self.conffile, 'w') as f:
f.write(contents)
self.binary = "/opt/bin/foo"
self.full_args = ['-c', self.conffile, self.binary]
# Check __AA_BASEDIR, which may be set by the Makefile, to see if
# we should use a non-default base directory path to find
# abstraction files
#
# NOTE: Individual tests can append another --base path to the
# args list and override a base path set here
base = os.getenv('__AA_BASEDIR')
if base:
self.full_args.append('--base=' + base)
# Check __AA_PARSER, which may be set by the Makefile, to see if
# we should use a non-default apparmor_parser path to verify
# policy
parser = os.getenv('__AA_PARSER')
if parser:
self.full_args.append('--parser=' + parser)
if debugging:
self.full_args.append('-d')
(self.options, self.args) = easyprof.parse_args(self.full_args + [self.binary])
# Now create some differently prefixed files in the include-dir
self.test_include_dir = os.path.join(self.tmpdir, 'include-dir')
os.mkdir(self.test_include_dir)
os.mkdir(os.path.join(self.test_include_dir, "templates"))
os.mkdir(os.path.join(self.test_include_dir, "policygroups"))
for d in ('policygroups', 'templates'):
for f in easyprof.get_directory_contents(os.path.join(
self.tmpdir, d)):
shutil.copy(f, os.path.join(self.test_include_dir, d,
"inc_" + os.path.basename(f)))
def tearDown(self):
"""Teardown for tests"""
if os.path.exists(self.tmpdir):
if debugging:
sys.stdout.write(self.tmpdir + "\n")
else:
recursive_rm(self.tmpdir)
#
# config file tests
#
def test_configuration_file_p_invalid(self):
"""Test config parsing (invalid POLICYGROUPS_DIR)"""
contents = '''
POLICYGROUPS_DIR=
TEMPLATES_DIR="{}/templates"
'''.format(self.tmpdir)
with open(self.conffile, 'w') as f:
f.write(contents)
try:
easyprof.AppArmorEasyProfile(self.binary, self.options)
except AppArmorException:
return
raise Exception("File should have been invalid")
def test_configuration_file_p_empty(self):
"""Test config parsing (empty POLICYGROUPS_DIR)"""
contents = '''
POLICYGROUPS_DIR=""
TEMPLATES_DIR="{}/templates"
'''.format(self.tmpdir)
with open(self.conffile, 'w') as f:
f.write(contents)
try:
easyprof.AppArmorEasyProfile(self.binary, self.options)
except AppArmorException:
return
raise Exception("File should have been invalid")
def test_configuration_file_p_nonexistent(self):
"""Test config parsing (nonexistent POLICYGROUPS_DIR)"""
contents = '''
POLICYGROUPS_DIR="/nonexistent/policygroups"
TEMPLATES_DIR="{}/templates"
'''.format(self.tmpdir)
with open(self.conffile, 'w') as f:
f.write(contents)
try:
easyprof.AppArmorEasyProfile(self.binary, self.options)
except AppArmorException:
return
raise Exception("File should have been invalid")
def test_policygroups_dir_relative(self):
"""Test --policy-groups-dir (relative DIR)"""
os.chdir(self.tmpdir)
rel = os.path.join(self.tmpdir, 'relative')
os.mkdir(rel)
shutil.copy(os.path.join(self.tmpdir, 'policygroups', self.test_policygroup), os.path.join(rel, self.test_policygroup))
args = self.full_args
args += ['--policy-groups-dir', './relative', '--show-policy-group', '--policy-groups=' + self.test_policygroup]
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(self.binary, self.options)
# no fallback
self.assertTrue(easyp.dirs['policygroups'] == rel,
"Not using specified --policy-groups-dir\n"
"Specified dir: {}\nActual dir: {}".format(rel, easyp.dirs['policygroups']))
self.assertFalse(easyp.get_policy_groups() is None, "Could not find policy-groups")
def test_policygroups_dir_nonexistent(self):
"""Test --policy-groups-dir (nonexistent DIR)"""
os.chdir(self.tmpdir)
rel = os.path.join(self.tmpdir, 'nonexistent')
args = self.full_args
args += ['--policy-groups-dir', rel, '--show-policy-group', '--policy-groups=' + self.test_policygroup]
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(self.binary, self.options)
# test if using fallback
self.assertFalse(easyp.dirs['policygroups'] == rel, "Using nonexistent --policy-groups-dir")
# test fallback
self.assertTrue(easyp.get_policy_groups() is not None, "Found policy-groups when shouldn't have")
def test_policygroups_dir_valid(self):
"""Test --policy-groups-dir (valid DIR)"""
os.chdir(self.tmpdir)
valid = os.path.join(self.tmpdir, 'valid')
os.mkdir(valid)
shutil.copy(os.path.join(self.tmpdir, 'policygroups', self.test_policygroup), os.path.join(valid, self.test_policygroup))
args = self.full_args
args += ['--policy-groups-dir', valid, '--show-policy-group', '--policy-groups=' + self.test_policygroup]
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(self.binary, self.options)
# no fallback
self.assertTrue(easyp.dirs['policygroups'] == valid, "Not using specified --policy-groups-dir")
self.assertFalse(easyp.get_policy_groups() is None, "Could not find policy-groups")
def test_policygroups_dir_valid_with_vendor(self):
"""Test --policy-groups-dir (valid DIR with vendor)"""
os.chdir(self.tmpdir)
valid = os.path.join(self.tmpdir, 'valid')
os.mkdir(valid)
shutil.copy(os.path.join(self.tmpdir, 'policygroups', self.test_policygroup),
os.path.join(valid, self.test_policygroup))
vendor = "ubuntu"
version = "1.0"
valid_distro = os.path.join(valid, vendor, version)
os.mkdir(os.path.join(valid, vendor))
os.mkdir(valid_distro)
shutil.copy(os.path.join(self.tmpdir, 'policygroups', self.test_policygroup), valid_distro)
args = self.full_args
args += ['--policy-groups-dir', valid, '--show-policy-group', '--policy-groups=' + self.test_policygroup]
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(self.binary, self.options)
self.assertTrue(easyp.dirs['policygroups'] == valid, "Not using specified --policy-groups-dir")
self.assertFalse(easyp.get_policy_groups() is None, "Could not find policy-groups")
for f in easyp.get_policy_groups():
self.assertFalse(os.path.basename(f) == vendor, "Found '{}' in {}".format(vendor, f))
def test_configuration_file_t_invalid(self):
"""Test config parsing (invalid TEMPLATES_DIR)"""
contents = '''
TEMPLATES_DIR=
POLICYGROUPS_DIR="{}/templates"
'''.format(self.tmpdir)
with open(self.conffile, 'w') as f:
f.write(contents)
try:
easyprof.AppArmorEasyProfile(self.binary, self.options)
except AppArmorException:
return
raise Exception("File should have been invalid")
def test_configuration_file_t_empty(self):
"""Test config parsing (empty TEMPLATES_DIR)"""
contents = '''
TEMPLATES_DIR=""
POLICYGROUPS_DIR="{}/templates"
'''.format(self.tmpdir)
with open(self.conffile, 'w') as f:
f.write(contents)
try:
easyprof.AppArmorEasyProfile(self.binary, self.options)
except AppArmorException:
return
raise Exception("File should have been invalid")
def test_configuration_file_t_nonexistent(self):
"""Test config parsing (nonexistent TEMPLATES_DIR)"""
contents = '''
TEMPLATES_DIR="/nonexistent/policygroups"
POLICYGROUPS_DIR="{}/templates"
'''.format(self.tmpdir)
with open(self.conffile, 'w') as f:
f.write(contents)
try:
easyprof.AppArmorEasyProfile(self.binary, self.options)
except AppArmorException:
return
raise Exception("File should have been invalid")
def test_templates_dir_relative(self):
"""Test --templates-dir (relative DIR)"""
os.chdir(self.tmpdir)
rel = os.path.join(self.tmpdir, 'relative')
os.mkdir(rel)
shutil.copy(os.path.join(self.tmpdir, 'templates', self.test_template), os.path.join(rel, self.test_template))
args = self.full_args
args += ['--templates-dir', './relative', '--show-template', '--template=' + self.test_template]
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(self.binary, self.options)
# no fallback
self.assertTrue(easyp.dirs['templates'] == rel,
"Not using specified --template-dir\n"
"Specified dir: {}\nActual dir: {}".format(rel, easyp.dirs['templates']))
self.assertFalse(easyp.get_templates() is None, "Could not find templates")
def test_templates_dir_nonexistent(self):
"""Test --templates-dir (nonexistent DIR)"""
os.chdir(self.tmpdir)
rel = os.path.join(self.tmpdir, 'nonexistent')
args = self.full_args
args += ['--templates-dir', rel, '--show-template', '--template=' + self.test_template]
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(self.binary, self.options)
# test if using fallback
self.assertFalse(easyp.dirs['templates'] == rel, "Using nonexistent --template-dir")
# test fallback
self.assertTrue(easyp.get_templates() is not None, "Found templates when shouldn't have")
def test_templates_dir_valid(self):
"""Test --templates-dir (valid DIR)"""
os.chdir(self.tmpdir)
valid = os.path.join(self.tmpdir, 'valid')
os.mkdir(valid)
shutil.copy(os.path.join(self.tmpdir, 'templates', self.test_template), os.path.join(valid, self.test_template))
args = self.full_args
args += ['--templates-dir', valid, '--show-template', '--template=' + self.test_template]
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(self.binary, self.options)
# no fallback
self.assertTrue(easyp.dirs['templates'] == valid, "Not using specified --template-dir")
self.assertFalse(easyp.get_templates() is None, "Could not find templates")
def test_templates_dir_valid_with_vendor(self):
"""Test --templates-dir (valid DIR with vendor)"""
os.chdir(self.tmpdir)
valid = os.path.join(self.tmpdir, 'valid')
os.mkdir(valid)
shutil.copy(os.path.join(self.tmpdir, 'templates', self.test_template), os.path.join(valid, self.test_template))
vendor = "ubuntu"
version = "1.0"
valid_distro = os.path.join(valid, vendor, version)
os.mkdir(os.path.join(valid, vendor))
os.mkdir(valid_distro)
shutil.copy(os.path.join(self.tmpdir, 'templates', self.test_template), valid_distro)
args = self.full_args
args += ['--templates-dir', valid, '--show-template', '--template=' + self.test_template]
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(self.binary, self.options)
self.assertTrue(easyp.dirs['templates'] == valid, "Not using specified --template-dir")
self.assertFalse(easyp.get_templates() is None, "Could not find templates")
for f in easyp.get_templates():
self.assertFalse(os.path.basename(f) == vendor, "Found '{}' in {}".format(vendor, f))
#
# Binary file tests
#
def test_binary_without_profile_name(self):
"""Test binary (<binary> { })"""
easyprof.AppArmorEasyProfile(self.ls, self.options)
def test_binary_with_profile_name(self):
"""Test binary (profile <name> <binary> { })"""
args = self.full_args
args += ['--profile-name=some-profile-name']
(self.options, self.args) = easyprof.parse_args(args)
easyprof.AppArmorEasyProfile(self.ls, self.options)
def test_binary_omitted_with_profile_name(self):
"""Test binary (profile <name> { })"""
args = self.full_args
args += ['--profile-name=some-profile-name']
(self.options, self.args) = easyprof.parse_args(args)
easyprof.AppArmorEasyProfile(None, self.options)
def test_binary_nonexistent(self):
"""Test binary (nonexistent)"""
easyprof.AppArmorEasyProfile(os.path.join(self.tmpdir, 'nonexistent'), self.options)
def test_binary_relative(self):
"""Test binary (relative)"""
try:
easyprof.AppArmorEasyProfile('./foo', self.options)
except AppArmorException:
return
raise Exception("Binary should have been invalid")
def test_binary_symlink(self):
"""Test binary (symlink)"""
exe = os.path.join(self.tmpdir, 'exe')
open(exe, 'a').close()
symlink = exe + ".lnk"
os.symlink(exe, symlink)
try:
easyprof.AppArmorEasyProfile(symlink, self.options)
except AppArmorException:
return
raise Exception("Binary should have been invalid")
#
# Templates tests
#
def test_templates_list(self):
"""Test templates (list)"""
args = self.full_args
args.append('--list-templates')
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(None, self.options)
for i in easyp.get_templates():
self.assertTrue(os.path.exists(i), "Could not find '{}'".format(i))
def test_templates_show(self):
"""Test templates (show)"""
files = glob.glob(self.tmpdir + "/templates/*")
for f in files:
args = self.full_args
args += ['--show-template', '--template', f]
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(None, self.options)
path = os.path.join(easyp.dirs['templates'], f)
self.assertTrue(os.path.exists(path), "Could not find '{}'".format(path))
with open(path) as fd:
fd.read()
def test_templates_list_include(self):
"""Test templates (list with --include-templates-dir)"""
args = self.full_args
args.append('--list-templates')
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(None, self.options)
orig_templates = easyp.get_templates()
args = self.full_args
args.append('--list-templates')
args.append('--include-templates-dir='
+ os.path.join(self.test_include_dir, 'templates'))
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(None, self.options)
inc_templates = easyp.get_templates()
self.assertTrue(len(inc_templates) == len(orig_templates) * 2,
"templates missing: {}".format(inc_templates))
for i in inc_templates:
self.assertTrue(os.path.exists(i), "Could not find '{}'".format(i))
def test_templates_show_include(self):
"""Test templates (show with --include-templates-dir)"""
files = glob.glob(self.test_include_dir + "/templates/*")
for f in files:
args = self.full_args
args += ['--show-template',
'--template', f,
'--include-templates-dir='
+ os.path.join(self.test_include_dir, 'templates')]
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(None, self.options)
path = os.path.join(easyp.dirs['templates_include'], f)
self.assertTrue(os.path.exists(path), "Could not find '{}'".format(path))
with open(path) as fd:
fd.read()
bn = os.path.basename(f)
# setup() copies everything in the include prefixed with inc_
self.assertTrue(bn.startswith('inc_'),
"'{}' does not start with 'inc_'".format(bn))
#
# Policygroups tests
#
def test_policygroups_list(self):
"""Test policygroups (list)"""
args = self.full_args
args.append('--list-policy-groups')
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(None, self.options)
for i in easyp.get_policy_groups():
self.assertTrue(os.path.exists(i), "Could not find '{}'".format(i))
def test_policygroups_show(self):
"""Test policygroups (show)"""
files = glob.glob(self.tmpdir + "/policygroups/*")
for f in files:
args = self.full_args
args += ['--show-policy-group',
'--policy-groups', os.path.basename(f)]
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(None, self.options)
path = os.path.join(easyp.dirs['policygroups'], f)
self.assertTrue(os.path.exists(path), "Could not find '{}'".format(path))
with open(path) as fd:
fd.read()
def test_policygroups_list_include(self):
"""Test policygroups (list with --include-policy-groups-dir)"""
args = self.full_args
args.append('--list-policy-groups')
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(None, self.options)
orig_policy_groups = easyp.get_policy_groups()
args = self.full_args
args.append('--list-policy-groups')
args.append('--include-policy-groups-dir='
+ os.path.join(self.test_include_dir, 'policygroups'))
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(None, self.options)
inc_policy_groups = easyp.get_policy_groups()
self.assertTrue(len(inc_policy_groups) == len(orig_policy_groups) * 2,
"policy_groups missing: {}".format(inc_policy_groups))
for i in inc_policy_groups:
self.assertTrue(os.path.exists(i), "Could not find '{}'".format(i))
def test_policygroups_show_include(self):
"""Test policygroups (show with --include-policy-groups-dir)"""
files = glob.glob(self.test_include_dir + "/policygroups/*")
for f in files:
args = self.full_args
args += ['--show-policy-group',
'--policy-groups', os.path.basename(f),
'--include-policy-groups-dir='
+ os.path.join(self.test_include_dir, 'policygroups')]
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(None, self.options)
path = os.path.join(easyp.dirs['policygroups_include'], f)
self.assertTrue(os.path.exists(path), "Could not find '{}'".format(path))
with open(path) as fd:
fd.read()
bn = os.path.basename(f)
# setup() copies everything in the include prefixed with inc_
self.assertTrue(bn.startswith('inc_'),
"'{}' does not start with 'inc_'".format(bn))
#
# Manifest file argument tests
#
def test_manifest_argument(self):
"""Test manifest argument"""
# setup our manifest
self.manifest = os.path.join(self.tmpdir, 'manifest.json')
contents = '''
{"security": {"domain.reverse.appname": {"name": "simple-app"}}}
'''
with open(self.manifest, 'w') as f:
f.write(contents)
args = self.full_args
args.extend(('--manifest', self.manifest))
easyprof.parse_args(args)
def _manifest_conflicts(self, opt, value):
"""Helper for conflicts tests"""
# setup our manifest
self.manifest = os.path.join(self.tmpdir, 'manifest.json')
contents = '''
{"security": {"domain.reverse.appname": {"binary": /nonexistent"}}}
'''
with open(self.manifest, 'w') as f:
f.write(contents)
# opt first
args = self.full_args
args.extend((opt, value, '--manifest', self.manifest))
raised = False
try:
easyprof.parse_args(args, InterceptingOptionParser())
except InterceptedError:
raised = True
self.assertTrue(raised, msg=opt + " and manifest arguments did not "
"raise a parse error")
# manifest first
args = self.full_args
args.extend(('--manifest', self.manifest, opt, value))
raised = False
try:
easyprof.parse_args(args, InterceptingOptionParser())
except InterceptedError:
raised = True
self.assertTrue(raised, msg=opt + " and manifest arguments did not "
"raise a parse error")
def test_manifest_conflicts_profilename(self):
"""Test manifest arg conflicts with profile_name arg"""
self._manifest_conflicts("--profile-name", "simple-app")
def test_manifest_conflicts_copyright(self):
"""Test manifest arg conflicts with copyright arg"""
self._manifest_conflicts("--copyright", "2013-01-01")
def test_manifest_conflicts_author(self):
"""Test manifest arg conflicts with author arg"""
self._manifest_conflicts("--author", "Foo Bar")
def test_manifest_conflicts_comment(self):
"""Test manifest arg conflicts with comment arg"""
self._manifest_conflicts("--comment", "some comment")
def test_manifest_conflicts_abstractions(self):
"""Test manifest arg conflicts with abstractions arg"""
self._manifest_conflicts("--abstractions", "base")
def test_manifest_conflicts_read_path(self):
"""Test manifest arg conflicts with read-path arg"""
self._manifest_conflicts("--read-path", "/etc/passwd")
def test_manifest_conflicts_write_path(self):
"""Test manifest arg conflicts with write-path arg"""
self._manifest_conflicts("--write-path", "/tmp/foo")
def test_manifest_conflicts_policy_groups(self):
"""Test manifest arg conflicts with policy-groups arg"""
self._manifest_conflicts("--policy-groups", "opt-application")
def test_manifest_conflicts_name(self):
"""Test manifest arg conflicts with name arg"""
self._manifest_conflicts("--name", "foo")
def test_manifest_conflicts_template_var(self):
"""Test manifest arg conflicts with template-var arg"""
self._manifest_conflicts("--template-var", "foo")
def test_manifest_conflicts_policy_version(self):
"""Test manifest arg conflicts with policy-version arg"""
self._manifest_conflicts("--policy-version", "1.0")
def test_manifest_conflicts_policy_vendor(self):
"""Test manifest arg conflicts with policy-vendor arg"""
self._manifest_conflicts("--policy-vendor", "somevendor")
#
# Test genpolicy
#
def _gen_policy(self, name=None, template=None, extra_args=None):
"""Generate a policy"""
# Build up our args
args = self.full_args
if template is None:
args.append('--template=' + self.test_template)
else:
args.append('--template=' + template)
if name is not None:
args.append('--name=' + name)
if extra_args:
args += extra_args
args.append(self.binary)
# Now parse our args
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(self.binary, self.options)
params = easyprof.gen_policy_params(self.binary, self.options)
p = easyp.gen_policy(**params)
# We always need to check for these
search_terms = [self.binary]
if name is not None:
search_terms.append(name)
if template is None:
search_terms.append(self.test_template)
for s in search_terms:
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
# ###NAME### should be replaced with self.binary or 'name'. Check for that
inv_s = '###NAME###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
if debugging:
sys.stdout.write(p + "\n")
return p
def _gen_manifest_policy(self, manifest, use_security_prefix=True):
# Build up our args
args = self.full_args
args.append("--manifest=/dev/null")
(self.options, self.args) = easyprof.parse_args(args)
(binary, self.options) = easyprof.parse_manifest(manifest.emit_json(use_security_prefix), self.options)[0]
easyp = easyprof.AppArmorEasyProfile(binary, self.options)
params = easyprof.gen_policy_params(binary, self.options)
p = easyp.gen_policy(**params)
# ###NAME### should be replaced with self.binary or 'name'. Check for that
inv_s = '###NAME###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
if debugging:
sys.stdout.write(p + "\n")
return p
def test__is_safe(self):
"""Test _is_safe()"""
bad = (
"/../../../../etc/passwd",
"abstraction with spaces",
"semicolon;bad",
"bad\x00baz",
"foo/bar",
"foo'bar",
'foo"bar',
)
for s in bad:
self.assertFalse(easyprof._is_safe(s), "'{}' should be bad".format(s))
def test_genpolicy_templates_abspath(self):
"""Test genpolicy (abspath to template)"""
# create a new template
template = os.path.join(self.tmpdir, "test-abspath-template")
shutil.copy(os.path.join(self.tmpdir, 'templates', self.test_template), template)
with open(template) as f:
contents = f.read()
test_string = "#teststring"
with open(template, 'w') as f:
f.write(contents + "\n{}\n".format(test_string))
p = self._gen_policy(template=template)
for s in (self.test_template, test_string):
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
def test_genpolicy_templates_system(self):
"""Test genpolicy (system template)"""
self._gen_policy()
def test_genpolicy_templates_nonexistent(self):
"""Test genpolicy (nonexistent template)"""
try:
self._gen_policy(template=os.path.join(self.tmpdir, "/nonexistent"))
except AppArmorException:
return
raise Exception("template should be invalid")
def test_genpolicy_name(self):
"""Test genpolicy (name)"""
self._gen_policy(name='test-foo')
def test_genpolicy_comment(self):
"""Test genpolicy (comment)"""
s = "test comment"
p = self._gen_policy(extra_args=['--comment=' + s])
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
inv_s = '###COMMENT###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_author(self):
"""Test genpolicy (author)"""
s = "Archibald Poindexter"
p = self._gen_policy(extra_args=['--author=' + s])
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
inv_s = '###AUTHOR###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_copyright(self):
"""Test genpolicy (copyright)"""
s = "2112/01/01"
p = self._gen_policy(extra_args=['--copyright=' + s])
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
inv_s = '###COPYRIGHT###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_abstractions(self):
"""Test genpolicy (single abstraction)"""
s = "nameservice"
p = self._gen_policy(extra_args=['--abstractions=' + s])
search = "#include <abstractions/{}>".format(s)
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###ABSTRACTIONS###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_abstractions_multiple(self):
"""Test genpolicy (multiple abstractions)"""
abstractions = "authentication,X,user-tmp"
p = self._gen_policy(extra_args=['--abstractions=' + abstractions])
for s in abstractions.split(','):
search = "#include <abstractions/{}>".format(s)
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###ABSTRACTIONS###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_abstractions_bad(self):
"""Test genpolicy (abstractions - bad values)"""
bad = (
"nonexistent",
"/../../../../etc/passwd",
"abstraction with spaces",
)
for s in bad:
try:
self._gen_policy(extra_args=['--abstractions=' + s])
except AppArmorException:
continue
raise Exception("abstraction '{}' should be invalid".format(s))
def _create_tmp_base_dir(self, prefix='', abstractions=(), tunables=()):
"""Create a temporary base dir layout"""
base_name = 'apparmor.d'
if prefix:
base_name = '{}-{}'.format(prefix, base_name)
base_dir = os.path.join(self.tmpdir, base_name)
abstractions_dir = os.path.join(base_dir, 'abstractions')
tunables_dir = os.path.join(base_dir, 'tunables')
os.mkdir(base_dir)
os.mkdir(abstractions_dir)
os.mkdir(tunables_dir)
for f in abstractions:
contents = '''
# Abstraction file for testing
/{} r,
'''.format(f)
with open(os.path.join(abstractions_dir, f), 'w') as fd:
fd.write(contents)
for f in tunables:
contents = '''
# Tunable file for testing
@{AA_TEST_%s}=foo
''' % (f,)
with open(os.path.join(tunables_dir, f), 'w') as fd:
fd.write(contents)
return base_dir
def test_genpolicy_abstractions_custom_base(self):
"""Test genpolicy (custom base dir)"""
abstraction = "custom-base-dir-test-abstraction"
# The default template #includes the base abstraction and global
# tunable so we need to create placeholders
base = self._create_tmp_base_dir(abstractions=['base', abstraction], tunables=['global'])
args = ['--abstractions=' + abstraction, '--base=' + base]
p = self._gen_policy(extra_args=args)
search = "#include <abstractions/{}>".format(abstraction)
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###ABSTRACTIONS###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_abstractions_custom_base_bad(self):
"""Test genpolicy (custom base dir - bad base dirs)"""
abstraction = "custom-base-dir-test-abstraction"
bad = [None, '/etc/apparmor.d', '/']
for base in bad:
try:
args = ['--abstractions=' + abstraction]
if base:
args.append('--base={}'.format(base))
self._gen_policy(extra_args=args)
except AppArmorException:
continue
raise Exception("abstraction '{}' should be invalid".format(abstraction))
def test_genpolicy_abstractions_custom_include(self):
"""Test genpolicy (custom include dir)"""
abstraction = "custom-include-dir-test-abstraction"
# No need to create placeholders for the base abstraction or global
# tunable since we're not adjusting the base directory
include = self._create_tmp_base_dir(abstractions=[abstraction])
args = ['--abstractions=' + abstraction, '--Include=' + include]
p = self._gen_policy(extra_args=args)
search = "#include <abstractions/{}>".format(abstraction)
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###ABSTRACTIONS###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_abstractions_custom_include_bad(self):
"""Test genpolicy (custom include dir - bad include dirs)"""
abstraction = "custom-include-dir-test-abstraction"
bad = [None, '/etc/apparmor.d', '/']
for include in bad:
try:
args = ['--abstractions=' + abstraction]
if include:
args.append('--Include={}'.format(include))
self._gen_policy(extra_args=args)
except AppArmorException:
continue
raise Exception("abstraction '{}' should be invalid".format(abstraction))
def test_genpolicy_profile_name_bad(self):
"""Test genpolicy (profile name - bad values)"""
bad = [
"/../../../../etc/passwd",
"../../../../etc/passwd",
"profile name with spaces",
]
for s in bad:
try:
self._gen_policy(extra_args=['--profile-name=' + s])
except AppArmorException:
continue
raise Exception("profile_name '{}' should be invalid".format(s))
def test_genpolicy_policy_group_bad(self):
"""Test genpolicy (policy group - bad values)"""
bad = [
"/../../../../etc/passwd",
"../../../../etc/passwd",
"profile name with spaces",
]
for s in bad:
try:
self._gen_policy(extra_args=['--policy-groups=' + s])
except AppArmorException:
continue
raise Exception("policy group '{}' should be invalid".format(s))
def test_genpolicy_policygroups(self):
"""Test genpolicy (single policygroup)"""
groups = self.test_policygroup
p = self._gen_policy(extra_args=['--policy-groups=' + groups])
for s in ('#include <abstractions/nameservice>', '#include <abstractions/gnome>'):
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
inv_s = '###POLICYGROUPS###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_policygroups_multiple(self):
"""Test genpolicy (multiple policygroups)"""
test_policygroup2 = "test-policygroup2"
contents = '''
# {}
#include <abstractions/kde>
#include <abstractions/openssl>
'''.format(self.test_policygroup)
with open(os.path.join(self.tmpdir, 'policygroups', test_policygroup2), 'w') as f:
f.write(contents)
groups = "{},{}".format(self.test_policygroup, test_policygroup2)
p = self._gen_policy(extra_args=['--policy-groups=' + groups])
for s in ('#include <abstractions/nameservice>',
'#include <abstractions/gnome>',
'#include <abstractions/kde>',
'#include <abstractions/openssl>'):
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
inv_s = '###POLICYGROUPS###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_policygroups_nonexistent(self):
"""Test genpolicy (nonexistent policygroup)"""
try:
self._gen_policy(extra_args=['--policy-groups=nonexistent'])
except AppArmorException:
return
raise Exception("policygroup should be invalid")
def test_genpolicy_readpath_file(self):
"""Test genpolicy (read-path file)"""
s = "/opt/test-foo"
p = self._gen_policy(extra_args=['--read-path=' + s])
search = "{} rk,".format(s)
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###READPATH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_readpath_home_file(self):
"""Test genpolicy (read-path file in /home)"""
s = "/home/*/test-foo"
p = self._gen_policy(extra_args=['--read-path=' + s])
search = "owner {} rk,".format(s)
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###READPATH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_readpath_homevar_file(self):
"""Test genpolicy (read-path file in @{HOME})"""
s = "@{HOME}/test-foo"
p = self._gen_policy(extra_args=['--read-path=' + s])
search = "owner {} rk,".format(s)
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###READPATH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_readpath_homedirs_file(self):
"""Test genpolicy (read-path file in @{HOMEDIRS})"""
s = "@{HOMEDIRS}/test-foo"
p = self._gen_policy(extra_args=['--read-path=' + s])
search = "owner {} rk,".format(s)
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###READPATH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_readpath_dir(self):
"""Test genpolicy (read-path directory/)"""
s = "/opt/test-foo-dir/"
p = self._gen_policy(extra_args=['--read-path=' + s])
search_terms = ["{} rk,".format(s), "{}** rk,".format(s)]
for search in search_terms:
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###READPATH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_readpath_dir_glob(self):
"""Test genpolicy (read-path directory/*)"""
s = "/opt/test-foo-dir/*"
p = self._gen_policy(extra_args=['--read-path=' + s])
search_terms = ["{} rk,".format(os.path.dirname(s)), "{} rk,".format(s)]
for search in search_terms:
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###READPATH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_readpath_dir_glob_all(self):
"""Test genpolicy (read-path directory/**)"""
s = "/opt/test-foo-dir/**"
p = self._gen_policy(extra_args=['--read-path=' + s])
search_terms = ["{} rk,".format(os.path.dirname(s)), "{} rk,".format(s)]
for search in search_terms:
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###READPATH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_readpath_multiple(self):
"""Test genpolicy (read-path multiple)"""
paths = [
"/opt/test-foo",
"/home/*/test-foo",
"@{HOME}/test-foo",
"@{HOMEDIRS}/test-foo",
"/opt/test-foo-dir/",
"/opt/test-foo-dir/*",
"/opt/test-foo-dir/**",
]
args = []
search_terms = []
for s in paths:
args.append('--read-path=' + s)
# This mimics easyprof.gen_path_rule()
owner = ""
if s.startswith('/home/') or s.startswith("@{HOME"):
owner = "owner "
if s.endswith('/'):
search_terms.append("{} rk,".format(s))
search_terms.append("{}{}** rk,".format(owner, s))
elif s.endswith('/**') or s.endswith('/*'):
search_terms.append("{} rk,".format(os.path.dirname(s)))
search_terms.append("{}{} rk,".format(owner, s))
else:
search_terms.append("{}{} rk,".format(owner, s))
p = self._gen_policy(extra_args=args)
for search in search_terms:
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###READPATH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_readpath_bad(self):
"""Test genpolicy (read-path bad)"""
s = "bar"
try:
self._gen_policy(extra_args=['--read-path=' + s])
except AppArmorException:
return
raise Exception("read-path should be invalid")
def test_genpolicy_writepath_file(self):
"""Test genpolicy (write-path file)"""
s = "/opt/test-foo"
p = self._gen_policy(extra_args=['--write-path=' + s])
search = "{} rwk,".format(s)
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###READPATH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_writepath_home_file(self):
"""Test genpolicy (write-path file in /home)"""
s = "/home/*/test-foo"
p = self._gen_policy(extra_args=['--write-path=' + s])
search = "owner {} rwk,".format(s)
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###READPATH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_writepath_homevar_file(self):
"""Test genpolicy (write-path file in @{HOME})"""
s = "@{HOME}/test-foo"
p = self._gen_policy(extra_args=['--write-path=' + s])
search = "owner {} rwk,".format(s)
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###READPATH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_writepath_homedirs_file(self):
"""Test genpolicy (write-path file in @{HOMEDIRS})"""
s = "@{HOMEDIRS}/test-foo"
p = self._gen_policy(extra_args=['--write-path=' + s])
search = "owner {} rwk,".format(s)
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###READPATH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_writepath_dir(self):
"""Test genpolicy (write-path directory/)"""
s = "/opt/test-foo-dir/"
p = self._gen_policy(extra_args=['--write-path=' + s])
search_terms = ["{} rwk,".format(s), "{}** rwk,".format(s)]
for search in search_terms:
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###READPATH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_writepath_dir_glob(self):
"""Test genpolicy (write-path directory/*)"""
s = "/opt/test-foo-dir/*"
p = self._gen_policy(extra_args=['--write-path=' + s])
search_terms = ["{} rwk,".format(os.path.dirname(s)), "{} rwk,".format(s)]
for search in search_terms:
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###READPATH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_writepath_dir_glob_all(self):
"""Test genpolicy (write-path directory/**)"""
s = "/opt/test-foo-dir/**"
p = self._gen_policy(extra_args=['--write-path=' + s])
search_terms = ["{} rwk,".format(os.path.dirname(s)), "{} rwk,".format(s)]
for search in search_terms:
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###READPATH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_writepath_multiple(self):
"""Test genpolicy (write-path multiple)"""
paths = [
"/opt/test-foo",
"/home/*/test-foo",
"@{HOME}/test-foo",
"@{HOMEDIRS}/test-foo",
"/opt/test-foo-dir/",
"/opt/test-foo-dir/*",
"/opt/test-foo-dir/**",
]
args = []
search_terms = []
for s in paths:
args.append('--write-path=' + s)
# This mimics easyprof.gen_path_rule()
owner = ""
if s.startswith('/home/') or s.startswith("@{HOME"):
owner = "owner "
if s.endswith('/'):
search_terms.append("{} rwk,".format(s))
search_terms.append("{}{}** rwk,".format(owner, s))
elif s.endswith('/**') or s.endswith('/*'):
search_terms.append("{} rwk,".format(os.path.dirname(s)))
search_terms.append("{}{} rwk,".format(owner, s))
else:
search_terms.append("{}{} rwk,".format(owner, s))
p = self._gen_policy(extra_args=args)
for search in search_terms:
self.assertTrue(search in p, "Could not find '{}' in:\n{}".format(search, p))
inv_s = '###READPATH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_writepath_bad(self):
"""Test genpolicy (write-path bad)"""
s = "bar"
try:
self._gen_policy(extra_args=['--write-path=' + s])
except AppArmorException:
return
raise Exception("write-path should be invalid")
def test_genpolicy_templatevar(self):
"""Test genpolicy (template-var single)"""
s = "@{FOO}=bar"
p = self._gen_policy(extra_args=['--template-var=' + s])
k, v = s.split('=')
s = '{}="{}"'.format(k, v)
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
inv_s = '###TEMPLATEVAR###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_templatevar_multiple(self):
"""Test genpolicy (template-var multiple)"""
variables = ['@{FOO}=bar', '@{BAR}=baz']
args = []
for s in variables:
args.append('--template-var=' + s)
p = self._gen_policy(extra_args=args)
for s in variables:
k, v = s.split('=')
s = '{}="{}"'.format(k, v)
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
inv_s = '###TEMPLATEVAR###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_templatevar_bad(self):
"""Test genpolicy (template-var - bad values)"""
bad = [
"{FOO}=bar",
"@FOO}=bar",
"@{FOO=bar",
"FOO=bar",
"@FOO=bar",
"@{FOO}=/../../../etc/passwd",
"@{FOO}=bar=foo",
"@{FOO;BAZ}=bar",
'@{FOO}=bar"baz',
]
for s in bad:
try:
self._gen_policy(extra_args=['--template-var=' + s])
except AppArmorException:
continue
raise Exception("template-var should be invalid")
def test_genpolicy_invalid_template_policy(self):
"""Test genpolicy (invalid template policy)"""
# create a new template
template = os.path.join(self.tmpdir, "test-invalid-template")
shutil.copy(os.path.join(self.tmpdir, 'templates', self.test_template), template)
with open(template) as f:
contents = f.read()
bad_pol = ""
bad_string = "bzzzt"
for line in contents.splitlines():
if '}' in line:
bad_pol += bad_string
else:
bad_pol += line
bad_pol += "\n"
with open(template, 'w') as f:
f.write(bad_pol)
try:
self._gen_policy(template=template)
except AppArmorException:
return
raise Exception("policy should be invalid")
def test_genpolicy_no_binary_without_profile_name(self):
"""Test genpolicy (no binary with no profile name)"""
try:
easyprof.gen_policy_params(None, self.options)
except AppArmorException:
return
raise Exception("No binary or profile name should have been invalid")
def test_genpolicy_with_binary_with_profile_name(self):
"""Test genpolicy (binary with profile name)"""
profile_name = "some-profile-name"
p = self._gen_policy(extra_args=['--profile-name=' + profile_name])
s = 'profile "%s" "%s" {' % (profile_name, self.binary)
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
inv_s = '###PROFILEATTACH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_with_binary_without_profile_name(self):
"""Test genpolicy (binary without profile name)"""
p = self._gen_policy()
s = '"%s" {' % (self.binary,)
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
inv_s = '###PROFILEATTACH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_genpolicy_without_binary_with_profile_name(self):
"""Test genpolicy (no binary with profile name)"""
profile_name = "some-profile-name"
args = self.full_args
args.append('--profile-name=' + profile_name)
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(None, self.options)
params = easyprof.gen_policy_params(None, self.options)
p = easyp.gen_policy(**params)
s = 'profile "%s" {' % (profile_name,)
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
inv_s = '###PROFILEATTACH###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
# manifest tests
def test_gen_manifest_policy_with_binary_with_profile_name(self):
"""Test gen_manifest_policy (binary with profile name)"""
m = Manifest("test_gen_manifest_policy")
m.add_binary(self.ls)
self._gen_manifest_policy(m)
def test_gen_manifest_policy_without_binary_with_profile_name(self):
"""Test gen_manifest_policy (no binary with profile name)"""
m = Manifest("test_gen_manifest_policy")
self._gen_manifest_policy(m)
def test_gen_manifest_policy_templates_system(self):
"""Test gen_manifest_policy (system template)"""
m = Manifest("test_gen_manifest_policy")
m.add_template(self.test_template)
self._gen_manifest_policy(m)
def test_gen_manifest_policy_templates_system_noprefix(self):
"""Test gen_manifest_policy (system template, no security prefix)"""
m = Manifest("test_gen_manifest_policy")
m.add_template(self.test_template)
self._gen_manifest_policy(m, use_security_prefix=False)
def test_gen_manifest_abs_path_template(self):
"""Test gen_manifest_policy (abs path template)"""
m = Manifest("test_gen_manifest_policy")
m.add_template("/etc/shadow")
try:
self._gen_manifest_policy(m)
except AppArmorException:
return
raise Exception("abs path template name should be invalid")
def test_gen_manifest_escape_path_templates(self):
"""Test gen_manifest_policy (esc path template)"""
m = Manifest("test_gen_manifest_policy")
m.add_template("../../../../../../../../etc/shadow")
try:
self._gen_manifest_policy(m)
except AppArmorException:
return
raise Exception("../ template name should be invalid")
def test_gen_manifest_policy_templates_nonexistent(self):
"""Test gen manifest policy (nonexistent template)"""
m = Manifest("test_gen_manifest_policy")
m.add_template("nonexistent")
try:
self._gen_manifest_policy(m)
except AppArmorException:
return
raise Exception("template should be invalid")
def test_gen_manifest_policy_comment(self):
"""Test gen manifest policy (comment)"""
s = "test comment"
m = Manifest("test_gen_manifest_policy")
m.add_comment(s)
p = self._gen_manifest_policy(m)
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
inv_s = '###COMMENT###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_gen_manifest_policy_author(self):
"""Test gen manifest policy (author)"""
s = "Archibald Poindexter"
m = Manifest("test_gen_manifest_policy")
m.add_author(s)
p = self._gen_manifest_policy(m)
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
inv_s = '###AUTHOR###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_gen_manifest_policy_copyright(self):
"""Test genpolicy (copyright)"""
s = "2112/01/01"
m = Manifest("test_gen_manifest_policy")
m.add_copyright(s)
p = self._gen_manifest_policy(m)
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
inv_s = '###COPYRIGHT###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_gen_manifest_policy_policygroups(self):
"""Test gen manifest policy (single policygroup)"""
groups = self.test_policygroup
m = Manifest("test_gen_manifest_policy")
m.add_policygroups(groups)
p = self._gen_manifest_policy(m)
for s in ('#include <abstractions/nameservice>', '#include <abstractions/gnome>'):
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
inv_s = '###POLICYGROUPS###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_gen_manifest_policy_policygroups_multiple(self):
"""Test genpolicy (multiple policygroups)"""
test_policygroup2 = "test-policygroup2"
contents = '''
# {}
#include <abstractions/kde>
#include <abstractions/openssl>
'''.format(self.test_policygroup)
with open(os.path.join(self.tmpdir, 'policygroups', test_policygroup2), 'w') as f:
f.write(contents)
groups = "{},{}".format(self.test_policygroup, test_policygroup2)
m = Manifest("test_gen_manifest_policy")
m.add_policygroups(groups)
p = self._gen_manifest_policy(m)
for s in ('#include <abstractions/nameservice>',
'#include <abstractions/gnome>',
'#include <abstractions/kde>',
'#include <abstractions/openssl>'):
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
inv_s = '###POLICYGROUPS###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_gen_manifest_policy_policygroups_nonexistent(self):
"""Test gen manifest policy (nonexistent policygroup)"""
groups = "nonexistent"
m = Manifest("test_gen_manifest_policy")
m.add_policygroups(groups)
try:
self._gen_manifest_policy(m)
except AppArmorException:
return
raise Exception("policygroup should be invalid")
def test_gen_manifest_policy_templatevar(self):
"""Test gen manifest policy (template-var single)"""
m = Manifest("test_gen_manifest_policy")
m.add_template_variable("FOO", "bar")
p = self._gen_manifest_policy(m)
s = '@{FOO}="bar"'
self.assertTrue(s in p, "Could not find '{}' in:\n{}".format(s, p))
inv_s = '###TEMPLATEVAR###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_gen_manifest_policy_templatevar_multiple(self):
"""Test gen manifest policy (template-var multiple)"""
variables = [["FOO", "bar"], ["BAR", "baz"]]
m = Manifest("test_gen_manifest_policy")
for s in variables:
m.add_template_variable(s[0], s[1])
p = self._gen_manifest_policy(m)
for s in variables:
str_s = '@{%s}="%s"' % (s[0], s[1])
self.assertTrue(str_s in p, "Could not find '{}' in:\n{}".format(str_s, p))
inv_s = '###TEMPLATEVAR###'
self.assertFalse(inv_s in p, "Found '{}' in :\n{}".format(inv_s, p))
def test_gen_manifest_policy_invalid_keys(self):
"""Test gen manifest policy (invalid keys)"""
keys = [
'config_file',
'debug',
'help',
'list-templates',
'list_templates',
'show-template',
'show_template',
'list-policy-groups',
'list_policy_groups',
'show-policy-group',
'show_policy_group',
'templates-dir',
'templates_dir',
'policy-groups-dir',
'policy_groups_dir',
'nonexistent',
'no_verify',
]
args = self.full_args
args.append("--manifest=/dev/null")
(self.options, self.args) = easyprof.parse_args(args)
for k in keys:
security = dict()
security["profile_name"] = "test-app"
security[k] = "bad"
j = json.dumps(security, indent=2)
try:
easyprof.parse_manifest(j, self.options)
except AppArmorException:
continue
raise Exception("'{}' should be invalid".format(k))
def test_gen_manifest(self):
"""Test gen_manifest"""
# this should come from manpage
m = '''{
"security": {
"profiles": {
"com.example.foo": {
"abstractions": [
"audio",
"gnome"
],
"author": "Your Name",
"binary": "/opt/foo/**",
"comment": "Unstructured single-line comment",
"copyright": "Unstructured single-line copyright statement",
"name": "My Foo App",
"policy_groups": [
"opt-application",
"user-application"
],
"policy_vendor": "somevendor",
"policy_version": 1.0,
"read_path": [
"/tmp/foo_r",
"/tmp/bar_r/"
],
"template": "user-application",
"template_variables": {
"APPNAME": "foo",
"VAR1": "bar",
"VAR2": "baz"
},
"write_path": [
"/tmp/foo_w",
"/tmp/bar_w/"
]
}
}
}
}'''
for d in ('policygroups', 'templates'):
shutil.copytree(os.path.join(self.tmpdir, d),
os.path.join(self.tmpdir, d, "somevendor/1.0"))
args = self.full_args
args.append("--manifest=/dev/null")
(self.options, self.args) = easyprof.parse_args(args)
(binary, self.options) = easyprof.parse_manifest(m, self.options)[0]
easyp = easyprof.AppArmorEasyProfile(binary, self.options)
params = easyprof.gen_policy_params(binary, self.options)
# verify we get the same manifest back
man_new = easyp.gen_manifest(params)
self.assertEqual(m, man_new)
def test_gen_manifest_ubuntu(self):
"""Test gen_manifest (ubuntu)"""
# this should be based on the manpage (but use existing policy_groups
# and template
m = '''{
"security": {
"profiles": {
"com.ubuntu.developer.myusername.MyCoolApp": {
"name": "MyCoolApp",
"policy_groups": [
"opt-application",
"user-application"
],
"policy_vendor": "ubuntu",
"policy_version": 1.0,
"template": "user-application",
"template_variables": {
"APPNAME": "MyCoolApp",
"APPVERSION": "0.1.2"
}
}
}
}
}'''
for d in ('policygroups', 'templates'):
shutil.copytree(os.path.join(self.tmpdir, d),
os.path.join(self.tmpdir, d, "ubuntu/1.0"))
args = self.full_args
args.append("--manifest=/dev/null")
(self.options, self.args) = easyprof.parse_args(args)
(binary, self.options) = easyprof.parse_manifest(m, self.options)[0]
easyp = easyprof.AppArmorEasyProfile(binary, self.options)
params = easyprof.gen_policy_params(binary, self.options)
# verify we get the same manifest back
man_new = easyp.gen_manifest(params)
self.assertEqual(m, man_new)
def test_parse_manifest_no_version(self):
"""Test parse_manifest (vendor with no version)"""
# this should come from manpage
m = '''{
"security": {
"profiles": {
"com.ubuntu.developer.myusername.MyCoolApp": {
"policy_groups": [
"opt-application",
"user-application"
],
"policy_vendor": "ubuntu",
"template": "user-application",
"template_variables": {
"APPNAME": "MyCoolApp",
"APPVERSION": "0.1.2"
}
}
}
}
}'''
args = self.full_args
args.append("--manifest=/dev/null")
(self.options, self.args) = easyprof.parse_args(args)
(binary, self.options) = easyprof.parse_manifest(m, self.options)[0]
try:
easyprof.AppArmorEasyProfile(binary, self.options)
except AppArmorException:
return
raise Exception("Should have failed on missing version")
def test_parse_manifest_no_vendor(self):
"""Test parse_manifest (version with no vendor)"""
# this should come from manpage
m = '''{
"security": {
"profiles": {
"com.ubuntu.developer.myusername.MyCoolApp": {
"policy_groups": [
"opt-application",
"user-application"
],
"policy_version": 1.0,
"template": "user-application",
"template_variables": {
"APPNAME": "MyCoolApp",
"APPVERSION": "0.1.2"
}
}
}
}
}'''
args = self.full_args
args.append("--manifest=/dev/null")
(self.options, self.args) = easyprof.parse_args(args)
(binary, self.options) = easyprof.parse_manifest(m, self.options)[0]
try:
easyprof.AppArmorEasyProfile(binary, self.options)
except AppArmorException:
return
raise Exception("Should have failed on missing vendor")
def test_parse_manifest_multiple(self):
"""Test parse_manifest_multiple"""
m = '''{
"security": {
"profiles": {
"com.example.foo": {
"abstractions": [
"audio",
"gnome"
],
"author": "Your Name",
"binary": "/opt/foo/**",
"comment": "Unstructured single-line comment",
"copyright": "Unstructured single-line copyright statement",
"name": "My Foo App",
"policy_groups": [
"opt-application",
"user-application"
],
"read_path": [
"/tmp/foo_r",
"/tmp/bar_r/"
],
"template": "user-application",
"template_variables": {
"APPNAME": "foo",
"VAR1": "bar",
"VAR2": "baz"
},
"write_path": [
"/tmp/foo_w",
"/tmp/bar_w/"
]
},
"com.ubuntu.developer.myusername.MyCoolApp": {
"policy_groups": [
"opt-application"
],
"policy_vendor": "ubuntu",
"policy_version": 1.0,
"template": "user-application",
"template_variables": {
"APPNAME": "MyCoolApp",
"APPVERSION": "0.1.2"
}
}
}
}
}'''
for d in ('policygroups', 'templates'):
shutil.copytree(os.path.join(self.tmpdir, d),
os.path.join(self.tmpdir, d, "ubuntu/1.0"))
args = self.full_args
args.append("--manifest=/dev/null")
(self.options, self.args) = easyprof.parse_args(args)
profiles = easyprof.parse_manifest(m, self.options)
for (binary, options) in profiles:
easyp = easyprof.AppArmorEasyProfile(binary, options)
params = easyprof.gen_policy_params(binary, options)
easyp.gen_manifest(params)
easyp.gen_policy(**params)
# verify manifest tests
def _verify_manifest(self, m, expected, invalid=False):
args = self.full_args
args.append("--manifest=/dev/null")
(self.options, self.args) = easyprof.parse_args(args)
try:
(binary, options) = easyprof.parse_manifest(m, self.options)[0]
except AppArmorException:
if invalid:
return
raise
params = easyprof.gen_policy_params(binary, options)
if expected:
self.assertTrue(easyprof.verify_manifest(params, args), "params={}\nmanifest={}".format(params, m))
else:
self.assertFalse(easyprof.verify_manifest(params, args), "params={}\nmanifest={}".format(params, m))
def test_verify_manifest_full(self):
"""Test verify_manifest (full)"""
m = '''{
"security": {
"profiles": {
"com.example.foo": {
"abstractions": [
"base"
],
"author": "Your Name",
"binary": "/opt/com.example/foo/**",
"comment": "some free-form single-line comment",
"copyright": "Unstructured single-line copyright statement",
"name": "foo",
"policy_groups": [
"user-application",
"opt-application"
],
"template": "user-application",
"template_variables": {
"OK1": "foo",
"OK2": "com.example.foo"
}
}
}
}
}'''
self._verify_manifest(m, expected=True)
def test_verify_manifest_full_bad(self):
"""Test verify_manifest (full bad)"""
m = '''{
"security": {
"profiles": {
"/com.example.foo": {
"abstractions": [
"audio",
"gnome"
],
"author": "Your Name",
"binary": "/usr/foo/**",
"comment": "some free-form single-line comment",
"copyright": "Unstructured single-line copyright statement",
"name": "foo",
"policy_groups": [
"user-application",
"opt-application"
],
"read_path": [
"/tmp/foo_r",
"/tmp/bar_r/"
],
"template": "user-application",
"template_variables": {
"VAR1": "f*o",
"VAR2": "*foo",
"VAR3": "fo*",
"VAR4": "b{ar",
"VAR5": "b{a,r}",
"VAR6": "b}ar",
"VAR7": "bar[0-9]",
"VAR8": "b{ar",
"VAR9": "/tmp/../etc/passwd"
},
"write_path": [
"/tmp/foo_w",
"/tmp/bar_w/"
]
}
}
}
}'''
self._verify_manifest(m, expected=False, invalid=True)
def test_verify_manifest_binary(self):
"""Test verify_manifest (binary in /usr)"""
m = '''{
"security": {
"profiles": {
"com.example.foo": {
"binary": "/usr/foo/**",
"template": "user-application"
}
}
}
}'''
self._verify_manifest(m, expected=True)
def test_verify_manifest_profile_profile_name_bad(self):
"""Test verify_manifest (bad profile_name)"""
m = '''{
"security": {
"profiles": {
"/foo": {
"binary": "/opt/com.example/foo/**",
"template": "user-application"
}
}
}
}'''
self._verify_manifest(m, expected=False, invalid=True)
m = '''{
"security": {
"profiles": {
"bin/*": {
"binary": "/opt/com.example/foo/**",
"template": "user-application"
}
}
}
}'''
self._verify_manifest(m, expected=False)
def test_verify_manifest_profile_profile_name(self):
"""Test verify_manifest (profile_name)"""
m = '''{
"security": {
"profiles": {
"com.example.foo": {
"binary": "/opt/com.example/foo/**",
"template": "user-application"
}
}
}
}'''
self._verify_manifest(m, expected=True)
def test_verify_manifest_profile_abstractions(self):
"""Test verify_manifest (abstractions)"""
m = '''{
"security": {
"profiles": {
"com.example.foo": {
"binary": "/opt/com.example/foo/**",
"template": "user-application",
"abstractions": [
"base"
]
}
}
}
}'''
self._verify_manifest(m, expected=True)
def test_verify_manifest_profile_abstractions_bad(self):
"""Test verify_manifest (bad abstractions)"""
m = '''{
"security": {
"profiles": {
"com.example.foo": {
"binary": "/opt/com.example/foo/**",
"template": "user-application",
"abstractions": [
"user-tmp"
]
}
}
}
}'''
self._verify_manifest(m, expected=False)
def test_verify_manifest_profile_template_var(self):
"""Test verify_manifest (good template_var)"""
m = '''{
"security": {
"profiles": {
"com.example.foo": {
"binary": "/opt/com.example/something with spaces/**",
"template": "user-application",
"template_variables": {
"OK1": "foo",
"OK2": "com.example.foo",
"OK3": "something with spaces"
}
}
}
}
}'''
self._verify_manifest(m, expected=True)
def test_verify_manifest_profile_template_var_bad(self):
"""Test verify_manifest (bad template_var)"""
for v in ('"VAR1": "f*o"',
'"VAR2": "*foo"',
'"VAR3": "fo*"',
'"VAR4": "b{ar"',
'"VAR5": "b{a,r}"',
'"VAR6": "b}ar"',
'"VAR7": "bar[0-9]"',
'"VAR8": "b{ar"',
'"VAR9": "foo/bar"' # this is valid, but potentially unsafe
):
m = '''{
"security": {
"profiles": {
"com.example.foo": {
"binary": "/opt/com.example/foo/**",
"template": "user-application",
"template_variables": {
%s
}
}
}
}
}''' % (v,)
self._verify_manifest(m, expected=False)
def test_manifest_invalid(self):
"""Test invalid manifest (parse error)"""
m = '''{
"security": {
"com.example.foo": {
"binary": "/opt/com.example/foo/**",
"template": "user-application",
"abstractions": [
"base"
]
}'''
self._verify_manifest(m, expected=False, invalid=True)
def test_manifest_invalid2(self):
"""Test invalid manifest (profile_name is not key)"""
m = '''{
"security": {
"binary": "/opt/com.example/foo/**",
"template": "user-application",
"abstractions": [
"base"
]
}
}'''
self._verify_manifest(m, expected=False, invalid=True)
def test_manifest_invalid3(self):
"""Test invalid manifest (profile_name in dict)"""
m = '''{
"security": {
"binary": "/opt/com.example/foo/**",
"template": "user-application",
"abstractions": [
"base"
],
"profile_name": "com.example.foo"
}
}'''
self._verify_manifest(m, expected=False, invalid=True)
def test_manifest_invalid4(self):
"""Test invalid manifest (bad path in template var)"""
for v in ('"VAR1": "/tmp/../etc/passwd"',
'"VAR2": "./"',
'"VAR3": "foo\"bar"',
'"VAR4": "foo//bar"',
):
m = '''{
"security": {
"profiles": {
"com.example.foo": {
"binary": "/opt/com.example/foo/**",
"template": "user-application",
"template_variables": {
%s
}
}
}
}
}''' % (v,)
args = self.full_args
args.append("--manifest=/dev/null")
(self.options, self.args) = easyprof.parse_args(args)
(binary, options) = easyprof.parse_manifest(m, self.options)[0]
params = easyprof.gen_policy_params(binary, options)
try:
easyprof.verify_manifest(params)
except AppArmorException:
return
raise Exception("Should have failed with invalid variable declaration")
# policy version tests
def test_policy_vendor_manifest_nonexistent(self):
"""Test policy vendor via manifest (nonexistent)"""
m = '''{
"security": {
"profiles": {
"com.example.foo": {
"policy_vendor": "nonexistent",
"policy_version": 1.0,
"binary": "/opt/com.example/foo/**",
"template": "user-application"
}
}
}
}'''
# Build up our args
args = self.full_args
args.append("--manifest=/dev/null")
(self.options, self.args) = easyprof.parse_args(args)
(binary, self.options) = easyprof.parse_manifest(m, self.options)[0]
try:
easyprof.AppArmorEasyProfile(binary, self.options)
except AppArmorException:
return
raise Exception("Should have failed with non-existent directory")
def test_policy_version_manifest(self):
"""Test policy version via manifest (good)"""
policy_vendor = "somevendor"
policy_version = "1.0"
policy_subdir = "{}/{}".format(policy_vendor, policy_version)
m = '''{
"security": {
"profiles": {
"com.example.foo": {
"policy_vendor": "%s",
"policy_version": %s,
"binary": "/opt/com.example/foo/**",
"template": "user-application"
}
}
}
}''' % (policy_vendor, policy_version)
for d in ('policygroups', 'templates'):
shutil.copytree(os.path.join(self.tmpdir, d),
os.path.join(self.tmpdir, d, policy_subdir))
# Build up our args
args = self.full_args
args.append("--manifest=/dev/null")
(self.options, self.args) = easyprof.parse_args(args)
(binary, self.options) = easyprof.parse_manifest(m, self.options)[0]
easyp = easyprof.AppArmorEasyProfile(binary, self.options)
tdir = os.path.join(self.tmpdir, 'templates', policy_subdir)
for t in easyp.get_templates():
self.assertTrue(t.startswith(tdir))
pdir = os.path.join(self.tmpdir, 'policygroups', policy_subdir)
for p in easyp.get_policy_groups():
self.assertTrue(p.startswith(pdir))
params = easyprof.gen_policy_params(binary, self.options)
easyp.gen_policy(**params)
def test_policy_vendor_version_args(self):
"""Test policy vendor and version via command line args (good)"""
policy_version = "1.0"
policy_vendor = "somevendor"
policy_subdir = "{}/{}".format(policy_vendor, policy_version)
# Create the directories
for d in ('policygroups', 'templates'):
shutil.copytree(os.path.join(self.tmpdir, d),
os.path.join(self.tmpdir, d, policy_subdir))
# Build up our args
args = self.full_args
args.append("--policy-version=" + policy_version)
args.append("--policy-vendor=" + policy_vendor)
(self.options, self.args) = easyprof.parse_args(args)
(self.options, self.args) = easyprof.parse_args(self.full_args + [self.binary])
easyp = easyprof.AppArmorEasyProfile(self.binary, self.options)
tdir = os.path.join(self.tmpdir, 'templates', policy_subdir)
for t in easyp.get_templates():
self.assertTrue(t.startswith(tdir),
"'{}' does not start with '{}'".format(t, tdir))
pdir = os.path.join(self.tmpdir, 'policygroups', policy_subdir)
for p in easyp.get_policy_groups():
self.assertTrue(p.startswith(pdir),
"'{}' does not start with '{}'".format(p, pdir))
params = easyprof.gen_policy_params(self.binary, self.options)
easyp.gen_policy(**params)
def test_policy_vendor_args_nonexistent(self):
"""Test policy vendor via command line args (nonexistent)"""
policy_vendor = "nonexistent"
policy_version = "1.0"
args = self.full_args
args.append("--policy-version=" + policy_version)
args.append("--policy-vendor=" + policy_vendor)
(self.options, self.args) = easyprof.parse_args(args)
(self.options, self.args) = easyprof.parse_args(self.full_args + [self.binary])
try:
easyprof.AppArmorEasyProfile(self.binary, self.options)
except AppArmorException:
return
raise Exception("Should have failed with non-existent directory")
def test_policy_version_args_bad(self):
"""Test policy version via command line args (bad)"""
bad = [
"../../../../../../etc",
"notanumber",
"v1.0a",
"-1",
]
for policy_version in bad:
args = self.full_args
args.append("--policy-version=" + policy_version)
args.append("--policy-vendor=somevendor")
(self.options, self.args) = easyprof.parse_args(args)
(self.options, self.args) = easyprof.parse_args(self.full_args + [self.binary])
try:
easyprof.AppArmorEasyProfile(self.binary, self.options)
except AppArmorException:
continue
raise Exception("Should have failed with bad version")
def test_policy_vendor_args_bad(self):
"""Test policy vendor via command line args (bad)"""
bad = [
"../../../../../../etc",
"vendor with space",
"semicolon;isbad",
]
for policy_vendor in bad:
args = self.full_args
args.append("--policy-vendor=" + policy_vendor)
args.append("--policy-version=1.0")
(self.options, self.args) = easyprof.parse_args(args)
(self.options, self.args) = easyprof.parse_args(self.full_args + [self.binary])
try:
easyprof.AppArmorEasyProfile(self.binary, self.options)
except AppArmorException:
continue
raise Exception("Should have failed with bad vendor")
# output_directory tests
def test_output_directory_multiple(self):
"""Test output_directory (multiple)"""
files = dict()
files["com.example.foo"] = "com.example.foo"
files["com.ubuntu.developer.myusername.MyCoolApp"] = "com.ubuntu.developer.myusername.MyCoolApp"
files["usr.bin.baz"] = "/usr/bin/baz"
m = '''{
"security": {
"profiles": {
"%s": {
"abstractions": [
"audio",
"gnome"
],
"author": "Your Name",
"binary": "/opt/foo/**",
"comment": "Unstructured single-line comment",
"copyright": "Unstructured single-line copyright statement",
"name": "My Foo App",
"policy_groups": [
"opt-application",
"user-application"
],
"read_path": [
"/tmp/foo_r",
"/tmp/bar_r/"
],
"template": "user-application",
"template_variables": {
"APPNAME": "foo",
"VAR1": "bar",
"VAR2": "baz"
},
"write_path": [
"/tmp/foo_w",
"/tmp/bar_w/"
]
},
"%s": {
"policy_groups": [
"opt-application",
"user-application"
],
"template": "user-application",
"template_variables": {
"APPNAME": "MyCoolApp",
"APPVERSION": "0.1.2"
}
},
"%s": {
"abstractions": [
"gnome"
],
"policy_groups": [
"user-application"
],
"template_variables": {
"APPNAME": "baz"
}
}
}
}
}''' % (
files["com.example.foo"],
files["com.ubuntu.developer.myusername.MyCoolApp"],
files["usr.bin.baz"]
)
out_dir = os.path.join(self.tmpdir, "output")
args = self.full_args
args.append("--manifest=/dev/null")
(self.options, self.args) = easyprof.parse_args(args)
profiles = easyprof.parse_manifest(m, self.options)
for (binary, options) in profiles:
easyp = easyprof.AppArmorEasyProfile(binary, options)
params = easyprof.gen_policy_params(binary, options)
easyp.output_policy(params, dir=out_dir)
for fn in files:
f = os.path.join(out_dir, fn)
self.assertTrue(os.path.exists(f), "Could not find '{}'".format(f))
def test_output_directory_single(self):
"""Test output_directory (single)"""
files = dict()
files["com.example.foo"] = "com.example.foo"
m = '''{
"security": {
"profiles": {
"%s": {
"abstractions": [
"audio",
"gnome"
],
"author": "Your Name",
"binary": "/opt/foo/**",
"comment": "Unstructured single-line comment",
"copyright": "Unstructured single-line copyright statement",
"name": "My Foo App",
"policy_groups": [
"opt-application",
"user-application"
],
"read_path": [
"/tmp/foo_r",
"/tmp/bar_r/"
],
"template": "user-application",
"template_variables": {
"APPNAME": "foo",
"VAR1": "bar",
"VAR2": "baz"
},
"write_path": [
"/tmp/foo_w",
"/tmp/bar_w/"
]
}
}
}
}''' % (files["com.example.foo"],)
out_dir = os.path.join(self.tmpdir, "output")
args = self.full_args
args.append("--manifest=/dev/null")
(self.options, self.args) = easyprof.parse_args(args)
profiles = easyprof.parse_manifest(m, self.options)
for (binary, options) in profiles:
easyp = easyprof.AppArmorEasyProfile(binary, options)
params = easyprof.gen_policy_params(binary, options)
easyp.output_policy(params, dir=out_dir)
for fn in files:
f = os.path.join(out_dir, fn)
self.assertTrue(os.path.exists(f), "Could not find '{}'".format(f))
def test_output_directory_invalid(self):
"""Test output_directory (output directory exists as file)"""
files = dict()
files["usr.bin.baz"] = "/usr/bin/baz"
m = '''{
"security": {
"profiles": {
"%s": {
"abstractions": [
"gnome"
],
"policy_groups": [
"user-application"
],
"template_variables": {
"APPNAME": "baz"
}
}
}
}
}''' % (files["usr.bin.baz"],)
out_dir = os.path.join(self.tmpdir, "output")
open(out_dir, 'w').close()
args = self.full_args
args.append("--manifest=/dev/null")
(self.options, self.args) = easyprof.parse_args(args)
(binary, options) = easyprof.parse_manifest(m, self.options)[0]
easyp = easyprof.AppArmorEasyProfile(binary, options)
params = easyprof.gen_policy_params(binary, options)
try:
easyp.output_policy(params, dir=out_dir)
except AppArmorException:
return
raise Exception("Should have failed with 'is not a directory'")
def test_output_directory_invalid_params(self):
"""Test output_directory (no binary or profile_name)"""
files = dict()
files["usr.bin.baz"] = "/usr/bin/baz"
m = '''{
"security": {
"profiles": {
"%s": {
"abstractions": [
"gnome"
],
"policy_groups": [
"user-application"
],
"template_variables": {
"APPNAME": "baz"
}
}
}
}
}''' % (files["usr.bin.baz"],)
out_dir = os.path.join(self.tmpdir, "output")
args = self.full_args
args.append("--manifest=/dev/null")
(self.options, self.args) = easyprof.parse_args(args)
(binary, options) = easyprof.parse_manifest(m, self.options)[0]
easyp = easyprof.AppArmorEasyProfile(binary, options)
params = easyprof.gen_policy_params(binary, options)
del params['binary']
try:
easyp.output_policy(params, dir=out_dir)
except AppArmorException:
return
raise Exception("Should have failed with 'Must specify binary and/or profile name'")
def test_output_directory_invalid2(self):
"""Test output_directory (profile exists)"""
files = dict()
files["usr.bin.baz"] = "/usr/bin/baz"
m = '''{
"security": {
"profiles": {
"%s": {
"abstractions": [
"gnome"
],
"policy_groups": [
"user-application"
],
"template_variables": {
"APPNAME": "baz"
}
}
}
}
}''' % (files["usr.bin.baz"],)
out_dir = os.path.join(self.tmpdir, "output")
os.mkdir(out_dir)
open(os.path.join(out_dir, "usr.bin.baz"), 'w').close()
args = self.full_args
args.append("--manifest=/dev/null")
(self.options, self.args) = easyprof.parse_args(args)
(binary, options) = easyprof.parse_manifest(m, self.options)[0]
easyp = easyprof.AppArmorEasyProfile(binary, options)
params = easyprof.gen_policy_params(binary, options)
try:
easyp.output_policy(params, dir=out_dir)
except AppArmorException:
return
raise Exception("Should have failed with 'already exists'")
def test_output_directory_args(self):
"""Test output_directory (args)"""
files = dict()
files["usr.bin.baz"] = "/usr/bin/baz"
# Build up our args
args = self.full_args
args.append('--template=' + self.test_template)
args.append('--name=foo')
args.append(files["usr.bin.baz"])
out_dir = os.path.join(self.tmpdir, "output")
# Now parse our args
(self.options, self.args) = easyprof.parse_args(args)
easyp = easyprof.AppArmorEasyProfile(files["usr.bin.baz"], self.options)
params = easyprof.gen_policy_params(files["usr.bin.baz"], self.options)
easyp.output_policy(params, dir=out_dir)
for fn in files:
f = os.path.join(out_dir, fn)
self.assertTrue(os.path.exists(f), "Could not find '{}'".format(f))
#
# utility classes
#
def test_valid_profile_name(self):
"""Test valid_profile_name"""
names = [
'foo',
'com.example.foo',
'/usr/bin/foo',
'com.example.app_myapp_1:2.3+ab12~foo',
]
for n in names:
self.assertTrue(easyprof.valid_profile_name(n), "'{}' should be valid".format(n))
def test_valid_profile_name_invalid(self):
"""Test valid_profile_name (invalid)"""
names = [
'fo/o',
'/../../etc/passwd',
'../../etc/passwd',
'./../etc/passwd',
'./etc/passwd',
'/usr/bin//foo',
'/usr/bin/./foo',
'foo`',
'foo!',
'foo@',
'foo$',
'foo#',
'foo%',
'foo^',
'foo&',
'foo*',
'foo(',
'foo)',
'foo=',
'foo{',
'foo}',
'foo[',
'foo]',
'foo|',
'foo/',
'foo\\',
'foo;',
"foo'",
'foo"',
'foo<',
'foo>',
'foo?',
r'foo\/',
'foo,',
'_foo',
]
for n in names:
self.assertFalse(easyprof.valid_profile_name(n), "'{}' should be invalid".format(n))
def test_valid_path(self):
"""Test valid_path"""
names = [
'/bin/bar',
'/etc/apparmor.d/com.example.app_myapp_1:2.3+ab12~foo',
]
names_rel = [
'bin/bar',
'apparmor.d/com.example.app_myapp_1:2.3+ab12~foo',
'com.example.app_myapp_1:2.3+ab12~foo',
]
for n in names:
self.assertTrue(easyprof.valid_path(n), "'{}' should be valid".format(n))
for n in names_rel:
self.assertTrue(easyprof.valid_path(n, relative_ok=True), "'{}' should be valid".format(n))
def test_zz_valid_path_invalid(self):
"""Test valid_path (invalid)"""
names = [
'/bin//bar',
'bin/bar',
'/../etc/passwd',
'./bin/bar',
'./',
]
names_rel = [
'bin/../bar',
'apparmor.d/../passwd',
'com.example.app_"myapp_1:2.3+ab12~foo',
]
for n in names:
self.assertFalse(easyprof.valid_path(n, relative_ok=False), "'{}' should be invalid".format(n))
for n in names_rel:
self.assertFalse(easyprof.valid_path(n, relative_ok=True), "'{}' should be invalid".format(n))
#
# End test class
#
#
# Main
#
if __name__ == '__main__':
absfn = os.path.abspath(sys.argv[0])
topdir = os.path.dirname(os.path.dirname(absfn))
if len(sys.argv) > 1 and (sys.argv[1] == '-d' or sys.argv[1] == '--debug'):
debugging = True
# run the tests
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(T))
rc = unittest.TextTestRunner(verbosity=1).run(suite)
if not rc.wasSuccessful():
sys.exit(1)
|