/usr/share/perl5/EBox/CA.pm is in zentyal-ca 2.3.6+quantal1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | # Copyright (C) 2008-2012 eBox Technologies S.L.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package EBox::CA;
use strict;
use warnings;
use base qw(EBox::Module::Service);
use File::Slurp;
use Perl6::Junction qw(any);
use Date::Calc::Object qw(:all);
use File::Copy::Recursive qw(dircopy fcopy);
use File::Temp;
use EBox::CA::DN;
use EBox::Gettext;
use EBox::Config;
use EBox::Menu::Item;
use EBox::Dashboard::ModuleStatus;
use EBox::Exceptions::External;
use EBox::Exceptions::Internal;
use EBox::Exceptions::DataMissing;
use EBox::Exceptions::DataInUse;
use EBox;
use EBox::CA::Certificates;
use EBox::Validate;
use EBox::Sudo;
use EBox::AuditLogging;
use constant OPENSSLPATH => "/usr/bin/openssl";
my $output_shell = EBox::Config->tmp() . 'openssl-shell.out';
my $error_shell = EBox::Config->tmp() . 'openssl-shell.err';
use constant CATOPDIR => EBox::Config->home() . "CA/";
use constant SSLCONFFILE => EBox::Config->conf() . "openssl.cnf";
# CATOPDIR . "../openssl.cnf";
# All paths related to CATOPDIR
use constant REQDIR => CATOPDIR . "reqs/";
use constant PRIVDIR => CATOPDIR . "private/";
use constant CRLDIR => CATOPDIR . "crl/";
use constant NEWCERTSDIR => CATOPDIR . "newcerts/";
use constant CERTSDIR => CATOPDIR . "certs/";
# Place to put the public keys
use constant KEYSDIR => CATOPDIR . "keys/";
# Place to put the P12 keystore
use constant P12DIR => CATOPDIR . "p12/";
use constant CAREQ => REQDIR . "careq.pem";
use constant CACERT => CATOPDIR . "cacert.pem";
use constant INDEXFILE => CATOPDIR . "index.txt";
use constant CRLNOFILE => CATOPDIR . "crlnumber";
use constant SERIALNOFILE => CATOPDIR . "serial";
use constant LASTESTCRL => CRLDIR . "latest.pem";
# Keys from CA
use constant CAPRIVKEY => PRIVDIR . "cakey.pem";
use constant CAPUBKEY => KEYSDIR . "capubkey.pem";
# Directory mode to allow only owner and readable from others
# Others means openvpn user (nobody)
use constant DIRMODE => 00751;
use constant PRIVATEDIRMODE => 00700;
use constant CHMOD_DIRMODE => '751';
use constant CHMOD_PRIVATEDIRMODE => '700';
# Use Certification Version 3
use constant EXTENSIONS_V3 => "1";
# Default values for some fields
use constant CA_CN_DEF => "Certification Authority Certificate";
# Index for every field (split with tabs) within the index.txt file
use constant STATE_IDX => 0;
use constant EXPIRE_DATE_IDX => 1;
use constant REV_DATE_REASON_IDX => 2;
use constant SERIAL_IDX => 3;
use constant FILE_IDX => 4;
use constant SUBJECT_IDX => 5;
# Catch the openssl executable
my $openssl;
if ( defined $ENV{OPENSSL} ) {
$openssl = $ENV{OPENSSL};
} else {
$openssl = OPENSSLPATH;
$ENV{OPENSSL} = $openssl;
}
# Group: Public methods
# Constructor: _create
#
# Create a new EBox::CA object
#
# Returns:
#
# A recent EBox::CA object
sub _create
{
my $class = shift;
my $self = $class->SUPER::_create(name => 'ca',
printableName => __n('Certification Authority'),
@_);
bless($self, $class);
# Reasons to revoke
$self->{reasons} = ["unspecified",
"keyCompromise",
"CACompromise",
"affiliationChanged",
"superseded",
"cessationOfOperation",
"certificateHold",
"removeFromCRL"];
# Set a maximum to establish the certificate expiration
# Related to Year 2038 bug
$self->{maxDays} = $self->_maxDays();
$self->{audit} = EBox::Global->modInstance('audit');
return $self;
}
# Method: isCreated
#
# Check whether the Certification Infrastructure has been
# created or not
#
# Returns:
#
# boolean - True, if the Certification Infrastructure has been
# created. Undef, otherwise.
#
sub isCreated
{
my ($self, $name) = @_;
my $retValue = ((-d CATOPDIR) and (-f CACERT) and (-f CAPRIVKEY)
and (-f CAPUBKEY));
return $retValue;
}
# Method: isAvailable
#
# Check whether the Certification Infrastructure is available or not
#
# Returns:
#
# boolean - True, if the Certification Infrastructure is available.
# Undef, otherwise.
#
sub isAvailable
{
my ($self) = @_;
return 0 unless $self->isCreated();
my $currentState = $self->currentCACertificateState();
if ( $currentState =~ m/[RE]/) {
return 0;
} else {
return 1;
}
}
# Method: createCA
#
# Create a Certification Authority with a self-signed certificate
# and if it not setup, create the directory hierarchy for the CA
#
# Parameters:
#
# countryName - country name {2 letter code} (eg, ES) *(Optional)*
# stateName - state or province name (eg, Aragon) *(Optional)*
# localityName - locality name (eg, Zaragoza) *(Optional)*
# orgName - organization name (eg, company name)
# orgNameUnit - organizational unit name (eg, section name) *(Optional)*
# commonName - common name from the CA *(Optional)*
# caKeyPassword - passphrase for generating keys *(Optional)*
# days - expire day of self signed certificate *(Optional)*
#
# - Named parameters
#
# Returns:
#
# 1 - if everything is newly created
# 2 - if the CA certificate already exists
#
# Exceptions:
#
# <EBox::Exceptions::DataMissing> - if any required parameter is
# missing
sub createCA
{
my ($self, %args) = @_;
throw EBox::Exceptions::DataMissing(data => __('Organization Name'))
unless defined($args{orgName});
$self->_checkCertificateFieldsCharacters(%args);
if (! -d CATOPDIR) {
# Create the directory hierchary
mkdir (CATOPDIR, DIRMODE);
# Let's assume the subdirectories have the same name
mkdir (CERTSDIR, DIRMODE);
mkdir (CRLDIR, DIRMODE);
mkdir (NEWCERTSDIR, DIRMODE);
mkdir (KEYSDIR, DIRMODE);
mkdir (PRIVDIR, PRIVATEDIRMODE);
mkdir (REQDIR, DIRMODE);
mkdir (P12DIR, PRIVATEDIRMODE);
# Create index and crl number
open ( my $OUT, ">" . INDEXFILE);
close ($OUT);
open ( $OUT, ">" . CRLNOFILE);
print $OUT "01\n";
close ($OUT);
}
# Save the current CA password for private key (It can be undef)
$self->{caKeyPassword} = $args{caKeyPassword};
return 2 if (-f CACERT);
# Define the distinguished name -> default values in configuration file
$args{commonName} = CA_CN_DEF unless ( $args{commonName} );
$self->{dn} = EBox::CA::DN->new ( countryName => $args{countryName},
stateName => $args{stateName},
localityName => $args{localityName},
organizationName => $args{orgName},
organizationNameUnit => $args{orgNameUnit},
commonName => $args{commonName});
# Make the CA certificate
$args{days} = 3650 unless ( defined ($args{days}) );
if ( $args{days} > $self->{maxDays} ) {
$args{days} = $self->{maxDays};
# Warning -> Year 2038 Bug
# http://www.mail-archive.com/openssl-users@openssl.org/msg45886.html
EBox::warn(__x("Days set to the maximum allowed {days}: Year 2038 Bug",
days => $self->{maxDays}));
}
# To create the request the distinguished name is needed
my $output = $self->_createRequest(reqFile => CAREQ,
genKey => 1,
privKey => CAPRIVKEY,
keyPassword => $self->{caKeyPassword},
dn => $self->{dn},
needPass => defined($self->{caKeyPassword})
);
if ($output) {
throw EBox::Exceptions::External($self->_filterErrorFromOpenSSL($output));
}
# Sign the selfsign certificate
# $self->_signRequest(userReqFile => CAREQ,
# days => $args{days},
# userCertFile => CACERT,
# selfsigned => "1");
# OpenSSL v. 0.9.7
# We should create the serial
my $serialNumber = $self->_createSerial();
$self->_signSelfSignRequest(userReqFile => CAREQ,
days => $args{days},
userCertFile => CACERT,
serialNumber => $serialNumber,
keyFile => CAPRIVKEY);
# OpenSSL v. 0.9.7 Bugs -> Resolved in openssl ca utility later on
# OpenSSL v. 0.9.7 -> Write down in index.txt
$self->_putInIndex(dn => $self->{dn},
certFile => CACERT,
serialNumber => $serialNumber);
# Create the serial file
if ( ! -f SERIALNOFILE ) {
$self->_writeDownNextSerial(CACERT);
}
# Create the serial attribute file
if ( ! (-f INDEXFILE . ".attr") ) {
$self->_writeDownIndexAttr(INDEXFILE . ".attr");
}
# Generate the public key file
$self->_getPubKey(CAPRIVKEY,
CAPUBKEY,
$self->{caKeyPassword});
# Set the CA certificate expiration date
$self->{caExpirationDate} = $self->_obtain(CACERT, 'endDate');
# Generate CRL
$self->generateCRL();
$self->_audit('createCA', $self->{dn}->attribute('orgName'));
#unlink (CAREQ);
$self->_setPasswordRequired(defined($self->{caKeyPassword}));
return 1;
}
# Method: destroyCA
#
# Destroys CA structure (the opposite operation to <createCA> method)
#
# Returns:
#
# 1 - if everything is completely destroys
# 2 - nothing to destroy
#
# Exceptions:
#
# EBox::Exceptions::External - if the remove operation cannot complete
#
sub destroyCA
{
my ($self, $caKeyPassword) = @_;
if (not $self->isCreated()) {
return 2;
}
my $orgName = $self->caDN()->attribute('orgName');
# Delete CA directory
if (system('rm -rf ' . CATOPDIR) != 0) {
throw EBox::Exceptions::External(__("The remove operation cannot be finished. Reason: ") . $!);
}
$self->_audit('destroyCA', $orgName);
# Set internal attribute to undefined
$self->{dn} = undef;
$self->{caExpirationDate} = undef;
$self->{caKeyPassword} = undef;
return 1;
}
# Method: initialSetup
#
# Overrides:
# EBox::Module::Base::initialSetup
#
sub initialSetup
{
my @cmds;
my @dirs = (CATOPDIR, CERTSDIR, CRLDIR, NEWCERTSDIR, KEYSDIR, REQDIR);
foreach my $dir (@dirs) {
if (-d $dir) {
push (@cmds, 'chmod ' . CHMOD_DIRMODE . " $dir ");
}
}
if (-d PRIVDIR) {
push (@cmds, 'chmod ' . CHMOD_PRIVATEDIRMODE . ' ' . PRIVDIR);
}
EBox::Sudo::root(@cmds);
unless (-d P12DIR) {
mkdir (P12DIR, PRIVATEDIRMODE)
}
}
# Method: passwordRequired
#
# Check if the password is required to sign the certificates
# within this Certification Authority
#
# Returns:
#
# boolean - true if pass is required, false otherwise
#
sub passwordRequired
{
my ($self) = @_;
my $caState = $self->currentCACertificateState();
# Password could be required only if a CA has been created
return undef unless ($caState eq 'V');
return $self->get_bool('pass_required');
}
# Method: revokeCACertificate
#
# Revoke the self-signed CA certificate and subsequently all the
# issued certificates
#
# Parameters:
#
# reason - the reason to revoke the certificate. It can be:
# unspecified, keyCompromise, CACompromise,
# affiliationChanged, superseeded, cessationOfOperation
# or certificationHold (Optional)
# caKeyPassword - the CA passpharse (Optional)
# force - Force the revokation (Optional)
#
# Returns:
#
# undef if OK
#
# Exceptions:
#
# EBox::Exceptions::DataInUse - if the CA certificate is being
# used by other modules
sub revokeCACertificate
{
my ($self, %args) = @_;
# Check certificates is not in used
if ($args{force}) {
$self->_freeCert(undef, 1);
}
elsif( $self->_certsInUse(undef, 1) ){
throw EBox::Exceptions::DataInUse();
}
# Revoked all issued and valid certificates
# Revoked only valid ones
# We ensure not to revoke the CA cert before the others
my $listCerts = $self->listCertificates( state => 'V',
excludeCA => 1);
foreach my $element (@{$listCerts}) {
$self->revokeCertificate(commonName => $element->{dn}->attribute('commonName'),
reason => "cessationOfOperation",
caKeyPassword => $args{caKeyPassword},
force => $args{force},
);
}
my $retVal = $self->revokeCertificate(commonName => "",
reason => $args{reason},
caKeyPassword => $args{caKeyPassword},
certFile => CACERT,
force => $args{force});
$self->{caExpirationDate} = undef;
$self->_audit('revokeCACertificate', "reason: $args{reason}");
return $retVal;
}
# Method: issueCACertificate
#
# Issue a self-signed CA certificate
#
# Parameters:
#
# commonName - the CA common name (Optional)
# countryName - country name {2 letter code} (eg, ES) (Optional)
# stateName - state or province name (eg, Zaragoza) (Optional)
# localityName - locality name (eg, Zaragoza) (Optional)
#
# orgName - organization name (eg, company)
#
# orgNameUnit - organizational unit name (eg, section)
# (Optional)
# days - days to hold the same certificate (Optional)
# caKeyPassword - key passpharse for CA (Optional)
# genPair - if you want to generate a new key pair (Optional)
#
# Returns:
#
# the new certificate file path
#
# Exceptions:
#
# DataMissing - if any required parameter is missing
# External - if a CA certificate is already valid
sub issueCACertificate
{
my ($self, %args) = @_;
throw EBox::Exceptions::DataMissing(data => __('Organization Name'))
unless defined( $args{orgName} );
$self->_checkCertificateFieldsCharacters(%args);
# Define the distinguished name -> default values in configuration file
$args{commonName} = CA_CN_DEF unless ( $args{commonName} );
$self->{dn} = EBox::CA::DN->new ( countryName => $args{countryName},
stateName => $args{stateName},
localityName => $args{localityName},
organizationName => $args{orgName},
organizationNameUnit => $args{orgNameUnit},
commonName => $args{commonName});
if ( $self->currentCACertificateState() eq 'V') {
throw EBox::Exceptions::External(
__('The CA certificates should be revoked or has expired before issuing a new certificate'));
}
# Erase the previous cert request to generate a new key pair
if ( $args{genPair} ) {
unlink (CAREQ);
unlink (CAPRIVKEY);
}
my $ret = $self->issueCertificate(commonName => $self->{dn}->attribute('commonName'),
countryName => $self->{dn}->attribute('countryName'),
localityName => $self->{dn}->attribute('localityName'),
orgName => $self->{dn}->attribute('orgName'),
orgNameUnit => $self->{dn}->attribute('orgNameUnit'),
keyPassword => $args{caKeyPassword},
days => $args{days},
caKeyPassword => $args{caKeyPassword},
privateKeyFile => CAPRIVKEY,
requestFile => CAREQ,
certFile => CACERT);
# Expiration CA certificate
$self->{caExpirationDate} = $self->_obtain(CACERT, 'endDate');
$self->_audit('issueCACertificate', $self->{dn}->attribute('orgName'));
$self->_setPasswordRequired( defined( $args{caKeyPassword} ));
return $ret;
}
# Method: renewCACertificate
#
# Renew the self-signed CA certificate. Re-signs all the issued
# certificates with the same expiration date or the CA
# expiration date if the issued certificate is later.
#
#
# Parameters:
#
# commonName - the CA common name *(Optional)*
# countryName - country name {2 letter code} (eg, ES) *(Optional)*
# stateName - state or province name (eg, Zaragoza) *(Optional)*
# localityName - locality name (eg, Zaragoza) *(Optional)*
#
# orgName - organization name (eg, company) *(Optional)*
#
# orgNameUnit - organizational unit name (eg, section)
# *(Optional)*
# days - days to hold the same certificate *(Optional)*
# caKeyPassword - key passpharse for CA *(Optional)*
# force - forcing the renewal of all the certificates *(Optional)*
#
# Returns:
#
# the new certificate file path or undef if any error happened
#
# Exceptions:
#
# DataMissing - if no caKeyPassword is given
#
sub renewCACertificate
{
my ($self, %args) = @_;
$self->{caKeyPassword} = $args{caKeyPassword};
my $listCerts = $self->listCertificates();
my $renewedCert = $self->renewCertificate( countryName => $args{countryName},
stateName => $args{stateName},
localityName => $args{localityName},
orgName => $args{orgName},
orgNameUnit => $args{orgNameUnit},
days => $args{days},
caKeyPassword => $args{caKeyPassword},
certFile => CACERT,
reqFile => CAREQ,
privateKeyFile => CAPRIVKEY,
keyPassword => $args{caKeyPassword},
overwrite => "1",
force => $args{force},
);
# Expiration CA certificate
$self->{caExpirationDate} = $self->_obtain(CACERT, 'endDate');
# Re-signs all the issued certificates with the same expiry date
foreach my $element (@{$listCerts}) {
# Renew the previous ones that remains valid
if ($element->{state} eq 'V' and
-f ( KEYSDIR . $element->{dn}->attribute('commonName') . ".pem") ) {
my $userExpiryDate = $element->{expiryDate};
$userExpiryDate = $self->{caExpirationDate}
if ( $element->{expiryDate} gt $self->{caExpirationDate} );
$self->renewCertificate( commonName => $element->{dn}->attribute('commonName'),
endDate => $userExpiryDate,
caKeyPassword => $args{caKeyPassword},
force => $args{force},
);
}
}
$self->_audit('renewCACertificate', $self->caDN()->attribute('orgName'));
return $renewedCert;
}
# Method: CAPublicKey
#
# Return the public key and certificate file from the
# Certificate Authority
#
# Parameters:
#
# caKeyPassword - the passphrase to access to private key
# (Optional)
#
# Returns:
#
# Path to the file which contains the CA Public Key in PEM
# format or undef if it was not possible to retrieve
#
sub CAPublicKey
{
my ($self, $caKeyPassword) = @_;
if (-f CAPUBKEY) {
return CAPUBKEY;
}
# If does NOT exist, we have to generate it
$caKeyPassword = $self->{caKeyPassword}
unless ( defined ($caKeyPassword) );
return $self->_getPubKey(CAPRIVKEY, CAPUBKEY, $caKeyPassword);
}
# Method: issueCertificate
#
# Create a new certificate for an requester
#
# Parameters:
#
# countryName - country name {2 letter code} (eg, ES) (Optional)
# stateName - state or province name (eg, Zaragoza) (Optional)
# localityName - locality name (eg, Zaragoza) (Optional)
#
# orgName - organization name (eg, company) (Optional)
#
# orgNameUnit - organizational unit name (eg, section)
# (Optional)
#
# commonName - common name from the organization
# keyPassword - passphrase for the private key (Optional)
# days - expiration days of certificate (Optional)
# Only valid if endDate is not present
# endDate - explicity expiration date (Optional)
# A Date::Calc::Object
# caKeyPassword - passphrase for CA to sign (Optional)
# privateKeyFile - path to the private key file if there is already
# a private key file in the CA (Optional)
#
# requestFile - path to save the new certificate request
# (Optional)
# certFile - path to store the new certificate file (Optional)
#
# subjAltNames - Array ref containing the subject alternative
# names in a hash ref with the following keys:
#
# type - String the type must be one of these: DNS, IP or email
#
# value - String the value following these
# constraints:
# DNS - Domain name
# IP - IPv4 address
# email - email address
#
# Returns:
#
# undef if no problem has happened
#
# Exceptions:
#
# External - if the CA passpharse CANNOT be located
# if the expiration date from certificate to issue is later than CA
# certificate expiration date
# if any error happens in signing request process
#
# DataMissing - if any required parameter is missing
#
sub issueCertificate
{
my ($self, %args) = @_;
# Treat arguments
throw EBox::Exceptions::DataMissing(data => __('Common Name'))
unless defined( $args{commonName} );
$self->_checkCertificateFieldsCharacters(%args);
EBox::warn("Two ways to declare expiration date through days and endDate. "
. "Using endDate...")
if ( defined( $args{days} ) and defined( $args{endDate} ) );
my $days = undef;
if (not defined($args{endDate}) ) {
$days = $args{days};
$days = 365 unless $days;
if ( $days > $self->{maxDays} ) {
$days = $self->{maxDays};
# It should be $self->{maxDays} but OpenSSL 0.9.7 lacks in other point
# Another workaround should be, put the enddate explicity
# Warning -> Year 2038 Bug
# http://www.mail-archive.com/openssl-users@openssl.org/msg45886.html
EBox::warn(__x("Days set to the maximum allowed {days}: Year 2038 Bug",
days => $self->{maxDays}));
}
}
# Check the expiration date unless issuing the CA
my $userExpDay = undef;
if (not defined($args{certFile}) or
$args{certFile} ne CACERT) {
if ( defined($days) ) {
$userExpDay = Date::Calc::Object->now();
$userExpDay += [0, 0, $days, 0, 0, 0];
} elsif (defined $args{endDate}) {
$userExpDay = $args{endDate};
}
$userExpDay = $self->_isLaterThanCA($userExpDay);
# Set to undef since we are using userExpDay as endDate
$days = undef;
}
if ( defined($args{caKeyPassword}) ) {
$self->{caKeyPassword} = $args{caKeyPassword};
}
# Name the private key and the user requests by common name
my $privKey = PRIVDIR . "$args{commonName}.pem";
$privKey = $args{privateKeyFile} if ($args{privateKeyFile});
my $pubKey = KEYSDIR . "$args{commonName}.pem";
my $userReq = REQDIR . "$args{commonName}.pem";
$userReq = $args{requestFile} if ($args{requestFile});
my $certFile = $args{certFile};
# Define the distinguished name
# We take the default values from CA dn
my $dn = $self->caDN()->copy();
$dn->attribute("countryName", $args{countryName})
if (defined($args{countryName}));
$dn->attribute("stateName", $args{stateName})
if (defined($args{stateName}));
$dn->attribute("localityName", $args{localityName})
if (defined($args{localityName}));
$dn->attribute("orgName", $args{orgName})
if (defined($args{orgName}));
$dn->attribute("orgNameUnit", $args{orgNameUnit})
if (defined($args{orgNameUnit}));
$dn->attribute("commonName", $args{commonName})
if (defined($args{commonName}));
if (defined($args{subjAltNames})) {
$self->_checkSubjAltNames($args{subjAltNames});
}
# Create the certificate request
my $genKey = 1;
if ( defined($args{privateKeyFile} )) {
if (-f $args{privateKeyFile} ) {
$genKey = 0;
}
}
my $output = $self->_createRequest(reqFile => $userReq,
genKey => $genKey,
privKey => $privKey,
keyPassword => $args{keyPassword},
dn => $dn,
needPass => defined($args{keyPassword})
);
if ( defined($output) ) {
throw EBox::Exceptions::External($self->_filterErrorFromOpenSSL($output));
}
# Signs the request
my $selfSigned = "0";
if ( defined ($certFile) ) {
$selfSigned = $certFile eq CACERT;
}
$output = $self->_signRequest( userReqFile => $userReq,
days => $days,
userCertFile => $certFile,
selfsigned => $selfSigned,
endDate => $userExpDay,
subjAltNames => $args{subjAltNames},
);
# Check if something goes wrong
if ( defined($output) ) {
throw EBox::Exceptions::External($output);
}
# Generate the public key file (if it is a newly created private
# key)
if (not defined($args{privateKeyFile}) ) {
my $result = $self->_getPubKey($privKey,
$pubKey,
$args{keyPassword});
}
# Generate the P12 key store
unless ( $selfSigned ) {
$self->_generateP12Store($privKey, $self->getCertificateMetadata(cn => $args{commonName}), $args{keyPassword});
}
$self->_audit('issueCertificate', $args{commonName});
return $self->_findCertFile($args{"commonName"});
}
# Method: revokeCertificate
#
# Revoke a certificate given the common name
#
# Parameters:
#
# commonName - the common name with the certificate to revoke
# reason - the reason to revoke the certificate. It can be:
# unspecified, keyCompromise, CACompromise,
# affiliationChanged, superseeded, cessationOfOperation
# or certificationHold (Optional)
# caKeyPassword - the CA passpharse (Optional)
# certFile - the Certificate to revoke (Optional)
# force - Force the revokation (Optional)
# renew - This revoke is due to a renew (Optional)
#
# Returns:
#
# undef if OK
#
# Exceptions:
#
# <EBox::Exceptions::External> - if the certificate does NOT exist
# if the reason is NOT a standard one
# if any error occurred when revokation is done
# if any error occurred when creating the CRL is done
# <EBox::Exceptions::DataMissing> - if any required
# parameter is missing
# <EBox::Exceptions::DataInUse> - if the
# certificate to revoke is being used by other modules
#
sub revokeCertificate
{
my ($self, %args) = @_;
my $commonName = $args{commonName};
my $reason = $args{reason};
my $caKeyPassword = $args{caKeyPassword};
my $certFile = $args{certFile};
throw EBox::Exceptions::DataMissing(data => __('Common Name') )
unless defined($commonName);
if ( defined($caKeyPassword) ) {
$self->{caKeyPassword} = $caKeyPassword;
}
# RFC 3280 suggests not to use an unspecified reason when the reason
# is unknown.
$reason = "unspecified" unless defined($reason);
$certFile = $self->_findCertFile($commonName) unless defined ($certFile);
throw EBox::Exceptions::External(__x('Certificate with common name {cn} does NOT exist',
cn => $commonName))
unless (defined($certFile) and -f $certFile);
throw EBox::Exceptions::External(__x("Reason {reason} is NOT an applicable reason.\n"
. "Options:" . $self->{reasons}, reason => $reason))
unless $reason eq any(@{$self->{reasons}});
# Tell observers the following certificate will be revoked
my $dn = $self->caDN();
my $isCACert = $dn->attribute('commonName') eq $commonName;
if ( $args{force} ) {
$self->_freeCert($commonName, $isCACert);
}
elsif ( not $args{renew} and $self->_certsInUse($commonName, $isCACert) ) {
throw EBox::Exceptions::DataInUse("Certificate $commonName in use");
}
# TODO: Different kinds of revokations (CACompromise,
# keyCompromise...)
# We can set different arguments regard to revocation reason
my $cmd = "ca";
$self->_commonArgs("ca", \$cmd);
$cmd .= "-revoke \'$certFile\' ";
if ( defined($self->{caKeyPassword}) ) {
$cmd .= "-passin env:PASS ";
}
$cmd .= "-crl_reason $reason " if (defined($reason));
# Tell openssl to revoke
$ENV{'PASS'} = $self->{caKeyPassword}
if (defined($self->{caKeyPassword}));
my ($retValue, $output) = $self->_executeCommand(command => $cmd);
delete ($ENV{'PASS'});
# If any error is shown from revocation, the result is got back
throw EBox::Exceptions::External($self->_filterErrorFromOpenSSL($output))
if ($retValue eq "ERROR");
# Generate a new Certification Revocation List
$self->generateCRL();
# Mark this module as changed
$self->setAsChanged();
# TODO: audit logging
# action: revokeCertificate
# cn: $args{commonName}
# reason: $args{reason}
# force: $force
return undef;
}
# Method: generateCRL
#
# Generate a new Certification Revocation List. It will create a
# new one with today date and link to the latest.
#
sub generateCRL
{
my ($self) = @_;
# Localtime
(my $year, my $month, my $day) = Date::Calc::Today();
my $date = sprintf("%04d-%02d-%02d", $year, $month, $day);
my $cmd= "ca";
$self->_commonArgs("ca", \$cmd);
$cmd .= "-gencrl ";
if ( defined($self->{caKeyPassword}) ) {
$cmd .= "-passin env:PASS ";
}
$cmd .= "-out " . CRLDIR . $date . "-crl.pem";
$ENV{'PASS'} = $self->{caKeyPassword}
if (defined($self->{caKeyPassword}));
my ($retValue, $output) = $self->_executeCommand(command => $cmd);
delete ($ENV{'PASS'});
throw EBox::Exceptions::External($self->_filterErrorFromOpenSSL($output))
if ($retValue eq "ERROR");
# Set the link to the last
unlink (LASTESTCRL) if ( -l LASTESTCRL );
symlink ( CRLDIR . $date . "-crl.pem", LASTESTCRL );
}
# Method: listCertificates
#
# List the certificates that are ready on the system sorted
# putting the CA certificate first and then valid certificates.
# This list can be filtered according to an state, including or
# not the CA certificate.
#
# Parameters:
#
# state - 'R', 'V' or 'E' in order to show only revoked, valid
# or expired certificates. All are included if not set this
# attribute (Optional)
#
# excludeCA - boolean indicating whether the valid CA certificate
# should be excluded in the response (Optional)
#
# - Named parameters
#
# Returns:
#
# A reference to an array containing hashes which have the following
# elements
#
# - dn - an <EBox::CA::DN> object
# - state - 'V' from Valid, 'R' from Revoked or 'E' from Expired
# - expiryDate - the expiry date in a <Calc::Date::Object> if state valid
#
# - revokeDate - the revocation date in a Date hash if state is
# revoked
# - reason - reason to revoke if state is revoked
# - isCACert - boolean indicating that it is the valid CA certificate
# - path - certificate path
# - serialNumber - serial number within CA
# - subjAltNames - array ref the subject alternative names containing hash ref
# with the following valid types:
# type => 'DNS', 'IP' and 'email'
# value => the subject alternative name
#
# Exceptions:
#
# <EBox::Exceptions::External> - thrown if the CA is not created
#
sub listCertificates
{
my ($self, %args) = @_;
# Getting the arguments
my $state = $args{'state'};
my $excludeCA = $args{'excludeCA'};
# Check parameter state is correct (R, V or E)
if (defined($state) and $state !~ m/[RVE]/ ) {
throw EBox::Exceptions::Internal("State should be R, V or E");
}
unless (-f INDEXFILE) {
throw EBox::Exceptions::External(
__('The Certification Authority Infrastructure is not available, create it first')
);
}
my @lines = read_file( INDEXFILE );
my @out = ();
foreach ( @lines ) {
# Parse line with a tab
my @line = split(/\t/);
my %element;
# Get current state
$element{'state'} = $line[STATE_IDX];
$element{'dn'} = EBox::CA::DN->parseDN($line[SUBJECT_IDX]);
$element{'serialNumber'} = $line[SERIAL_IDX];
# Set paramaters regarding to certificate validity
if (($element{'state'} eq 'V') or ($element{'state'} eq 'E')) {
$element{'expiryDate'} = $self->_parseDate($line[EXPIRE_DATE_IDX]);
$element{'isCACert'} = $self->_isCACert($element{'dn'});
} elsif ( $element{'state'} eq 'R' ) {
my $field = $line[REV_DATE_REASON_IDX];
my ($revDate, $reason) = split(',', $field);
$element{'revokeDate'} = $self->_parseDate($revDate);
$element{'reason'} = $reason;
}
# Setting certificate path
if ($element{'isCACert'}) {
$element{'path'} = CACERT;
} else {
$element{'path'} = CERTSDIR . $line[SERIAL_IDX] . ".pem";
}
# Setting the subject alternative names
$element{'subjAltNames'} = $self->_obtain( $element{'path'}, 'subjAltNames' );
push (@out, \%element);
}
# Setting the filters
if ( defined($state) ) {
# Filter according to state
@out = grep { $_->{state} eq $state } @out;
}
if ( $excludeCA ) {
# Filter the valid CA certificate
@out = grep { not $_->{isCACert} } @out;
}
# Sort the array to have CA certs first (put latest first)
my @sortedOut = sort { $b->{state} cmp $a->{state} } @out;
return \@sortedOut;
}
# Method: getCertificateMetadata
#
# Given an attribute to filter, returns an unique certificate metadata.
# JUST ONE parameter can be passed. To return the CA
# certificate, it is recommended to use <getCACertificateMetadata>.
#
# Parameters:
#
# cn - Common Name (Optional)
# dn - EBox::CA::DN Distinguished Name (Optional)
# serialNumber - A serial number within CA (Optional)
#
# Returns:
#
# A reference to a hash with the following elements
#
# - dn - an <EBox::CA::DN> object
# - state - 'V' from Valid, 'R' from Revoked or 'E' from Expired
# - expiryDate - the expiry date in a <Calc::Date::Object> if state valid
#
# - revokeDate - the revocation date in a Date hash if state is
# revoked
# - reason - reason to revoke if state is revoked
# - path - certificate path
# - serialNumber - serial number within CA
# - subjAltNames - array ref the subject alternative names containing hash ref
# with the following valid types:
# type => 'DNS', 'IP' and 'email'
# value => the subject alternative name
#
# Exceptions:
#
# <EBox::Exceptions::DataMissing> - if any required parameter is missing
sub getCertificateMetadata
{
my ($self, %args) = @_;
if (scalar(keys %args) == 0) {
throw EBox::Exceptions::DataMissing(data =>
__("Either common name, distinguished name or serial number has been passed")
);
} elsif ( scalar(keys %args) > 1 ) {
throw EBox::Exceptions::Internal("Only one parameter is necessary");
} elsif ( defined($args{'dn'})
and not $args{'dn'}->isa('EBox::CA::DN') ) {
throw EBox::Exceptions::Internal("dn parameter should be an instance of EBox::CA::DN");
}
my $cn = $args{'cn'};
my $dn = $args{'dn'};
my $serialNumber = $args{'serialNumber'};
my $listCertsRef = $self->listCertificates();
my $retCert = undef;
if (defined($cn)) {
# Looking for a particular cn
($retCert) = grep { $_->{'dn'}->attribute('commonName') eq $cn } @{$listCertsRef};
} elsif(defined($dn)) {
# Looking for a particular dn
($retCert) = grep { $_->{'dn'}->equals($dn) } @{$listCertsRef};
} elsif( defined($serialNumber) ) {
($retCert) = grep { $_->{'serialNumber'} eq $serialNumber } @{$listCertsRef};
}
return $retCert;
}
# Method: getCACertificateMetadata
#
# Return the current metadata related to the valid Certification
# Authority.
#
#
# Returns:
#
# - A reference to a hash which the following elements
#
# - dn - an <EBox::CA::DN> object
# - expiryDate - the expiry date in a <Calc::Date::Object> if state valid
# - path - certificate path
#
# - Undef if the CA is expired or inexistent -> Check state
# calling to <EBox::CA::currentCACertificateState>
#
sub getCACertificateMetadata
{
my ($self) = @_;
my $certsRef = $self->listCertificates();
# Find the CA certificate in the list
my ($CACert) = grep { $_->{'isCACert'} } @{$certsRef} ;
return $CACert;
}
# Method: getKeys
#
# Get the keys (public and private) from CA given an specific common name.
#
# Parameters:
#
# commonName - the common name to identify the key
#
# Returns:
#
# a reference to a hash containing the public and private key file
# paths (*privateKey* and *publicKey*) stored in _PEM_ format
#
# Exceptions:
#
# External - if the keys do NOT exist
# DataMissing - if any required parameter is missing
#
sub getKeys
{
my ($self, $commonName) = @_;
throw EBox::Exceptions::DataMissing(data => __("Common Name"))
unless defined ($commonName);
my %keys;
if (-f PRIVDIR . "$commonName.pem" ) {
$keys{privateKey} = PRIVDIR . "$commonName.pem";
}
$keys{publicKey} = KEYSDIR . "$commonName.pem";
throw EBox::Exceptions::External(__x('Certificate with common name {cn} does NOT exist',
cn => $commonName))
unless (-f $keys{publicKey});
# Remove private key when the CGI has sent the private key
# DONE in removePrivateKey method
return \%keys;
}
# Method: getP12KeyStore
#
# Given the common name, it returns the PKCS12 keystore file path.
#
# The PKCS12 is a common format used by web browser to store
# certificates and private keys.
#
# Parameters:
#
# commonName - String the common name
#
# Returns:
#
# String - the PKCS 12 key store path
#
sub getP12KeyStore
{
my ($self, $commonName) = @_;
my $target = P12DIR . "${commonName}.p12";
if (-f $target) {
return $target;
} else {
my $privKey = $self->getKeys($commonName)->{privateKey};
my $certMetadata = $self->getCertificateMetadata(cn => $commonName);
return $self->_generateP12Store($privKey, $certMetadata);
}
}
# Method: removePrivateKey
#
# Remove the private key from an user
#
# Parameters:
#
# commonName - the common name to identify the private key
#
# Returns:
#
# 1 - If everything OK
#
# Exceptions:
#
# Internal - if the private key does NOT exist
# DataMissing - if common name is not provided
#
sub removePrivateKey
{
my ($self, $commonName) = @_;
throw EBox::Exceptions::DataMissing(data => __('Common Name'))
unless defined ($commonName);
if (-f PRIVDIR . "$commonName.pem" ) {
unlink (PRIVDIR . "$commonName.pem");
return 1;
} else {
throw EBox::Exceptions::Internal("Private key does NOT exist");
}
}
# Method: renewCertificate
#
# Renew a certificate from a user.
# If any Distinguished Name is needed to change, it is done.
#
# Parameters:
#
# commonName - the common name from the user. Not needed
# if a certificate file is given *(Optional)*
#
# countryName - country name {2 letter code} (eg, ES) *(Optional)*
# stateName - state or province name (eg, Zaragoza) *(Optional)*
# localityName - locality name (eg, Zaragoza) *(Optional)*
#
# orgName - organization name (eg, company) *(Optional)*
#
# orgNameUnit - organizational unit name (eg, section)
# *(Optional)*
# days - days to hold the same certificate *(Optional)*
# Only if enddate not appeared
# endDate - the exact date when the cert expired *(Optional)*
# Only if days not appeared
# It is a Date::Calc::Object
# caKeyPassword - key passpharse for CA *(Optional)*
# certFile - the certificate file to renew *(Optional)*
# reqFile - the request certificate file which to renew *(Optional)*
#
# privateKeyFile - the private key file *(Optional)*
# keyPassword - the private key passpharse. It is used when
# a new request is issued, not compulsory anyway. *(Optional)*
#
# overwrite - overwrite the current certificate file. Only if
# the certFile is passed *(Optional)*
#
# force - this forces the revokation pass to do the renewal *(Optional)*
# subjAltNames - Array ref containing hash ref with key type of certificate
# and value the value for the subject alt name *(Optional)*
#
# Returns:
#
# the new certificate file path
#
# Exceptions:
#
# <EBox::Exceptions::External> - if the user does NOT exist,
# if the expiration date for the certificate to renew is later than CA certificate expiration date
# if the certificate to renew does NOT exist
# if any error occurred when certificate renewal is done
# <EBox::Exceptions::Internal> - if any parameter is an unexcepted type
# <EBox::Exceptions::DataMissing> - if no CA passphrase is given to renew the certificate
# <EBox::Exceptions::DataInUse> - if the certificate to renew is in use and no forcing is done
#
sub renewCertificate
{
my ($self, %args) = @_;
if (not defined($args{endDate}) ) {
$args{days} = 365 unless defined ($args{days});
if ( $args{days} > $self->{maxDays} ) {
$args{days} = $self->{maxDays};
# Warning -> Year 2038 Bug
# http://www.mail-archive.com/openssl-users@openssl.org/msg45886.html
EBox::warn(__x("Days set to the maximum allowed {days}: Year 2038 Bug",
days => $self->{maxDays}));
}
}
throw EBox::Exceptions::Internal("End date parameter (" . ref($args{endDate}) . " is not a Date::Calc object")
if (defined($args{endDate}) and not UNIVERSAL::isa($args{endDate}, "Date::Calc"));
# Check the expiration date unless issuing the CA cert
my $userExpDay = undef;
unless (defined($args{certFile}) and $args{certFile} eq CACERT) {
if ( defined($args{days}) ) {
$userExpDay = Date::Calc::Object->now() + [0, 0, +$args{days}, 0, 0, 0];
} elsif ( defined($args{endDate}) ) {
$userExpDay = $args{endDate};
}
$userExpDay = $self->_isLaterThanCA($userExpDay);
# Set to undef since we are using userExpDay as endDate
$args{days} = undef;
}
throw EBox::Exceptions::DataMissing(data => __('Common Name')
. " " . __("or") . " " .
__('Certificate file'))
unless defined ($args{commonName}) or defined ($args{certFile});
if ( defined($args{caKeyPassword}) ) {
$self->{caKeyPassword} = $args{caKeyPassword};
}
my $overwrite = $args{overwrite} if ($args{certFile});
my $userCertFile;
if ( defined($args{certFile})) {
$userCertFile = $args{certFile};
} else {
$userCertFile = $self->_findCertFile($args{commonName});
}
my $selfsigned = "0";
$selfsigned = "1" if ($userCertFile eq CACERT);
my $userDN = $self->_obtain($userCertFile, 'DN');
if ( not defined($userDN) ) {
throw EBox::Exceptions::External(__("The certificate to renew does NOT exist"));
}
my $dnFieldHasChanged = '0';
if ( defined($args{countryName})
and $args{countryName} ne $userDN->attribute('countryName')) {
$dnFieldHasChanged = "1";
$userDN->attribute('countryName', $args{countryName});
}
if (defined($args{stateName})
and $args{stateName} ne $userDN->attribute('stateName')) {
$dnFieldHasChanged = "1";
$userDN->attribute('stateName', $args{stateName});
}
if (defined($args{localityName})
and $args{localityName} ne $userDN->attribute('localityName')) {
$dnFieldHasChanged = "1";
$userDN->attribute('localityName', $args{localityName});
}
if (defined($args{orgName})
and $args{orgName} ne $userDN->attribute('orgName')) {
$dnFieldHasChanged = "1";
$userDN->attribute('orgName', $args{orgName});
}
if (defined($args{orgNameUnit})
and $args{orgNameUnit} ne $userDN->attribute('orgNameUnit')) {
$dnFieldHasChanged = "1";
$userDN->attribute('orgNameUnit', $args{orgNameUnit});
}
# Revoke old certificate
my $retVal = $self->revokeCertificate(commonName => $userDN->attribute('commonName'),
reason => "superseded",
certFile => $userCertFile,
caKeyPassword => $args{caKeyPassword},
force => $args{force},
renew => "yes",
);
if (defined($retVal) ) {
throw EBox::Exceptions::External(__x("Certificate with this common name {cn} does NOT exist in this CA"
, cn => $userDN->attribute('commonName')));
}
# Sign a new one
my $userReq;
if ( defined($args{reqFile}) ) {
$userReq = $args{reqFile};
} else {
$userReq = REQDIR . $userDN->attribute('commonName') . ".pem";
}
# Overwrite the current certificate? Useful?
my $newCertFile = undef;
if ($overwrite) {
$newCertFile = $userCertFile;
}
my $subjAltNames;
if (defined($args{subjAltNames})) {
$subjAltNames = $args{subjAltNames};
$dnFieldHasChanged = "1";
} else {
$subjAltNames = $self->_obtain($userCertFile, 'subjAltNames');
}
if (-f $userReq) {
# If the request exists, we can renew the certificate without
# having the private key
# New subject
my $newSubject = undef;
if ( $dnFieldHasChanged ) {
$newSubject = $userDN;
# For OpenSSL 0.9.7, we need to create the request
my $privKeyFile = PRIVDIR . $userDN->attribute('commonName') . ".pem";
$privKeyFile = $args{privateKeyFile} if ($args{privateKeyFile});
#throw EBox::Exceptions::External(__("The private key passpharse needed to create a new request. No renewal was made. Issue a new certificate with new keys"))
# if ( not defined($args{keyPassword}) );
my $output = $self->_createRequest(reqFile => $userReq,
genKey => 0,
privKey => $privKeyFile,
keyPassword => $args{keyPassword},
dn => $newSubject,
needPass => defined($args{keyPassword})
);
if ($output) {
throw EBox::Exceptions::External($self->_filterErrorFromOpenSSL($output));
}
if (defined $newCertFile and ($newCertFile eq CACERT)) {
$self->{dn} = $newSubject;
}
}
my $output = $self->_signRequest( userReqFile => $userReq,
days => $args{days},
userCertFile => $newCertFile,
selfsigned => $selfsigned,
createSerial => 0,
# Not in OpenSSL 0.9.7 newSubject => $newSubject,
endDate => $userExpDay,
subjAltNames => $subjAltNames,
);
if (defined($output) ) {
throw EBox::Exceptions::External($output);
}
} else {
# If we don't keep the request, we should create a new one with
# the private key if exists. If not, we need to recreate all...
# by using issuing a new certificate with a new request
my $privKeyFile = PRIVDIR . $userDN->attribute('commonName') . ".pem";
$privKeyFile = $args{privateKeyFile} if ($args{privateKeyFile});
$self->issueCertificate( countryName => $userDN->attribute('countryName'),
stateName => $userDN->attribute('stateName'),
localityName => $userDN->attribute('localityName'),
orgName => $userDN->attribute('orgName'),
orgNameUnit => $userDN->attribute('orgNameUnit'),
commonName => $userDN->attribute('commonName'),
keyPassword => $args{keyPassword},
days => $args{days},
privateKeyFile => $privKeyFile,
requestFile => $userReq,
certFile => $newCertFile,
endDate => $userExpDay,
subjAltNames => $subjAltNames,
);
}
if (not defined($newCertFile) ) {
$newCertFile = $self->_findCertFile($userDN->attribute('commonName'));
}
$self->_audit('renewCertificate', $args{commonName});
# Tells other modules the following certs have been renewed
my $isCACert = 0;
$isCACert = 1 if (defined($args{certFile}) and $args{certFile} eq CACERT);
my $global = EBox::Global->getInstance();
my @mods = @{$global->modInstancesOfType('EBox::CA::Observer')};
foreach my $mod (@mods) {
$mod->certificateRenewed($userDN->attribute('commonName'), $isCACert);
}
EBox::CA::Certificates->certificateRenewed($userDN->attribute('commonName'), $isCACert);
return $newCertFile;
}
# Method: updateDB
#
# Update the index.txt file to mark the expired certificates
# Called by the controller.
#
# Parameters:
#
# caKeyPassword - key passpharse for CA (Optional)
#
# Returns:
#
# undef if everything OK
#
# Exceptions:
#
# EBox::Exceptions::External - if the CA passpharse is incorrect
sub updateDB
{
my ($self, %args) = @_;
# Manage the parameters
my $caKeyPassword = $args{caKeyPassword};
if ( defined($caKeyPassword) ) {
$self->{caKeyPassword} = $caKeyPassword;
}
my @expiredCertsBefore = @{$self->listCertificates(state => 'E')};
my $cmd = "ca";
$self->_commonArgs("ca", \$cmd);
$cmd .= "-updatedb ";
if ( defined($self->{caKeyPassword}) ){
$cmd .= "-passin env:PASS ";
}
$ENV{'PASS'} = $self->{caKeyPassword} if defined($self->{caKeyPassword});
my ($retVal, $output) = $self->_executeCommand( command => $cmd );
delete( $ENV{'PASS'} );
my @expiredCertsAfter = @{$self->listCertificates(state => 'E')};
my %seen;
my @diff;
foreach my $item (@expiredCertsBefore) {
$seen{$item->{serialNumber}} = 1;
}
foreach my $item (@expiredCertsAfter) {
next if ( $seen{$item->{serialNumber}} );
push(@diff, $item);
}
# Tells other modules the following certs have expired
my $global = EBox::Global->getInstance();
my @mods = @{$global->modInstancesOfType('EBox::CA::Observer')};
foreach my $cert (@diff) {
foreach my $mod (@mods) {
$mod->certificateExpired($cert->{dn}->attribute('commonName'),
$cert->{isCACert});
}
EBox::CA::Certificates->certificateExpired($cert->{dn}->attribute('commonName'), $cert->{isCACert});
}
if ($retVal eq "ERROR") {
throw EBox::Exceptions::External($self->_filterErrorFromOpenSSL($output));
}
return undef;
}
# Method: currentCACertificateState
#
# Return the current state for the CA Certificate
#
# Returns:
#
# The current CA Certificate state
# - R - Revoked
# - E - Expired
# - V - Valid
# - ! - Inexistent
#
sub currentCACertificateState
{
my ($self) = @_;
my $serialCert = $self->_obtain(CACERT, 'serial');
return '!' unless (defined($serialCert));
my $certRef = $self->getCertificateMetadata(serialNumber => $serialCert);
if ( not defined($certRef) ) {
return "!";
} else {
return $certRef->{'state'};
}
}
# Method: revokeReasons
#
# Return the current list of possible revoke reasons
#
# Returns:
#
# A reference to the array containing the current list of possible revoke reasons
#
sub revokeReasons
{
my ($self) = @_;
return $self->{reasons};
}
# Method: getCurrentCRL
#
# Return the current Certification Revokation List (CRL)
#
# Returns:
#
# Path to the current CRL or undef if there is no CRL
#
sub getCurrentCRL
{
my ($self) = @_;
if ( -e LASTESTCRL ) {
return LASTESTCRL;
}
else {
return undef;
}
}
# Method: caExpirationDays
#
# Return the CA expiration date in days since the current date
#
# Returns:
#
# Number of days until CA expiration
#
sub caExpirationDays
{
my ($self) = @_;
my ($curY, $curM, $curD) = Date::Calc::Today();
my ($exY, $exM, $exD) = $self->caExpirationDate()->date();
return Date::Calc::Delta_Days($curY, $curM, $curD, $exY, $exM, $exD);
}
# Method: menu
#
# Add CA module to Zentyal menu
#
# Parameters:
#
# root - the <EBox::Menu::Root> where to leave our items
#
sub menu
{
my ($self, $root) = @_;
my $folder = new EBox::Menu::Folder('name' => 'CA',
'text' => $self->printableName(),
'separator' => 'Infrastructure',
'order' => 422);
$folder->add(new EBox::Menu::Item('url' => 'CA/Index',
'text' => __('General')));
$folder->add(new EBox::Menu::Item('url' => 'CA/View/Certificates',
'text' => __('Services Certificates')));
$root->add($folder);
}
# Method: dumpConfig
#
# Dump CA configuration and certificates
#
# Parameters:
#
# dir - Directory where the modules backup files are dumped
#
sub dumpConfig
{
my ($self, $dir) = @_;
# Call super
$self->SUPER::dumpConfig($dir);
if ( -d CATOPDIR ) {
# Storing all OpenSSL directory tree where Certs/keys and DB are stored
dircopy(CATOPDIR, $dir . "/CA");
}
if ( -f SSLCONFFILE ) {
# Storing OpenSSL config file
fcopy(SSLCONFFILE, $dir . "/openssl.cnf");
}
# Dump services certificates
my @srvCerts = @{EBox::CA::Certificates->srvsCerts()};
my @paths;
foreach my $certificate (@srvCerts) {
if (-f $certificate->{'path'}) {
push(@paths, $certificate->{'path'});
}
}
if (@paths) {
my $pathsStr = join(' ', @paths);
EBox::Sudo::root("tar cf $dir/srvCerts.tar $pathsStr");
}
}
# Method: restoreConfig
#
# Restore its configuration from the backup file. Those files are
# the same were created with dumpConfig
#
# Parameters:
# dir - Directory where are located the backup files
#
sub restoreConfig
{
my ($self, $dir) = @_;
# Call super
$self->SUPER::restoreConfig($dir);
# Destroy previous CA
$self->destroyCA();
# Restoring all OpenSSL directory tree where Certs/keys and DB are stored
my $dataDir = $dir . '/CA';
if (-d $dataDir) {
dircopy($dataDir, CATOPDIR);
}
# Restoring OpenSSL config file
fcopy($dir . "/openssl.cnf", SSLCONFFILE);
# Restore services certificates
if (-f "$dir/srvCerts.tar") {
my @commands;
push(@commands, "tar xfp $dir/srvCerts.tar -C /");
my @srvCerts = @{EBox::CA::Certificates->srvsCerts()};
foreach my $certificate (@srvCerts) {
my $certPath = $certificate->{'path'};
if (-f $certPath) {
my $certUser = $certificate->{'user'};
my $certGroup = $certificate->{'group'};
push(@commands, "chown $certUser:$certGroup $certPath");
}
}
EBox::Sudo::root(@commands);
}
}
# Method: showModuleStatus
#
# Indicate to ServiceManager if the module must be shown in Module
# status configuration.
#
# Overrides:
# EBox::Module::Service::showModuleStatus
#
sub showModuleStatus
{
# we don't want it to appear in module status
return undef;
}
# Method: addModuleStatus
#
# Overrides to show a custom status for CA module
#
# Overrides:
#
# <EBox::Module::Service::addModuleStatus>
#
sub addModuleStatus
{
my ($self, $section) = @_;
my $caStatus = __('Not created');
if ( $self->isAvailable() ) {
$caStatus = __('Available');
} elsif ( $self->isCreated() ) {
$caStatus = __('Created but not available');
}
$section->add(new EBox::Dashboard::ModuleStatus(
module => $self->name(),
printableName => $self->printableName(),
nobutton => 1,
statusStr => $caStatus));
}
# Method: report
#
# Returns:
# ref hash with the following fields:
# CAState: state of the CA certificate. It will be ono of this states:
# - R - Revoked
# - E - Expired
# - V - Valid
# - ! - Inexistent
#
# nValidCertificates: number of valid active certificates
# nRevokedCertificates: number of revoked certificates
# nExpiredCertificates: number of expired certifcates
#
# Overrides:
#
# <EBox::Module::Base::report>
#
sub report
{
my ($self) = @_;
my $currentCA = $self->currentCACertificateState();
my ($nValid, $nRevoked, $nExpired) = (0, 0, 0);
if ($currentCA ne '!') {
$nValid = @{ $self->listCertificates(state => 'V', excludeCA => 1) };
$nRevoked = @{ $self->listCertificates(state => 'R', excludeCA => 1) };
$nExpired = @{ $self->listCertificates(state => 'E', excludeCA => 1) };
}
return {
CAState => $currentCA,
nValidCertifcates => $nValid,
nRevokedCertificates => $nRevoked,
nExpiredCertificates => $nExpired,
};
}
# Group: Protected methods
sub _checkCertificateFieldsCharacters
{
my ($self, %args) = @_;
my @fieldsToCheck = qw(orgName commonName
countryName stateName localityName
organizationName organizationNameUnit);
foreach my $field (@fieldsToCheck) {
if (exists $args{$field}) {
$self->_checkValidCharacters($args{$field}, $field);
}
}
if (exists $args{subjAltNames} and (defined $args{subjAltNames})) {
foreach my $alt (@{ $args{subjAltNames} }) {
my $name = 'Subject alternative name of type ' . $alt->{type};
my $value = $alt->{value};
$self->_checkValidCharacters($value, $name);
}
}
}
# openssl does not support UTF-8 a
my $validRe = qr/^[A-Za-z0-9 .?&+:\-\@\*]*$/;
sub _checkValidCharacters
{
my ($self, $string, $stringName) = @_;
$stringName or
$stringName = __('String');
if (not $string =~ $validRe) {
throw EBox::Exceptions::InvalidData(
data => $stringName,
value => $string,
advice => __('The field contains invalid ' .
'characters. All ASCII alphanumeric characters, ' .
'plus these non alphanumeric chars: .?&+:-@* ' .
'and spaces are allowed.'
)
);
}
}
# Method: _supportActions
#
# Overrides <EBox::Module::ServiceBase>
#
# This method determines if the service will have a button to start/restart
# it in the module status widget. By default services will have the button
# unless this method is overriden to return undef
sub _supportActions
{
return undef;
}
# Method: _setConf # # Overrides: # # <EBox::Module::Service::_setConf> #
sub _setConf
{
my ($self) = @_;
EBox::CA::Certificates->genCerts();
}
# Group: Private methods
# Obtain the public key given the private key
#
# Return public key path if it is correct or undef if password is
# incorrect
sub _getPubKey # (privKeyFile, pubKeyFile, password?)
{
my ($self, $privKeyFile, $pubKeyFile, $password) = @_;
$pubKeyFile = EBox::Config->tmp() . "pubKey.pem" unless (defined ($pubKeyFile));
my $cmd = "rsa ";
$cmd .= "-in \'$privKeyFile\' ";
$cmd .= "-out \'$pubKeyFile\' ";
$cmd .= "-outform PEM ";
$cmd .= "-pubout ";
if ( defined($password) ) {
$cmd .= "-passin env:PASS ";
}
$ENV{'PASS'} = $password
if (defined($password));
my ($retVal) = $self->_executeCommand(command => $cmd);
delete( $ENV{'PASS'} );
return undef if ($retVal eq "ERROR");
return $pubKeyFile;
}
# Generate the pkcs12 key store with password if required
sub _generateP12Store
{
my ($self, $privKeyFile, $certMetadata, $password) = @_;
my $certFile = $certMetadata->{path};
my $cn = $certMetadata->{dn}->attribute('commonName');
my $target = P12DIR . "${cn}.p12";
my $cmd = 'pkcs12 -export ';
$cmd .= "-in '$certFile' ";
$cmd .= "-inkey '$privKeyFile' ";
$cmd .= "-name '$cn' ";
$cmd .= "-out '$target' ";
$password = '' unless (defined($password));
$cmd .= "-passout pass:$password ";
$ENV{'PASS'} = $password
if (defined($password));
my ($retVal) = $self->_executeCommand(command => $cmd);
delete( $ENV{'PASS'} );
return undef if ($retVal eq "ERROR");
return $target;
}
# Given a serial number, it returns the file path
sub _certFile
{
my ($self, $serial) = @_;
my $file = CATOPDIR . "newcerts/${serial}.pem";
return $file;
}
# Given a common name, it returns the file path to the valid certificate
# file which has as a subject a dn with this common name
# Undef if the certificate does NOT exist
# Path to the certificate if the certificate exists
sub _findCertFile # (commonName)
{
my ($self, $commonName) = @_;
open (my $fh, '<', INDEXFILE);
my $found = '0';
my $certFile = undef;
while(defined(my $line = <$fh>) and not $found) {
my @fields = split ('\t', $line);
if ( $fields[STATE_IDX] eq 'V') {
# Extract cn from subject
my $subject = EBox::CA::DN->parseDN($fields[SUBJECT_IDX]);
$found = $subject->attribute("commonName") eq $commonName;
if ($found) {
$certFile = CERTSDIR . $fields[SERIAL_IDX] . ".pem";
return $certFile;
}
}
}
return $certFile;
}
# Create a request certificate
# return undef if any error occurs
sub _createRequest # (reqFile, genKey, privKey, keyPassword, dn, needPass?)
{
my ($self, %args) = @_;
# To create the request the distinguished name is needed
my $cmd = 'req';
$self->_commonArgs('req', \$cmd);
$cmd .= '-new ';
if ($args{genKey}) {
$cmd .= qq{-keyout '$args{privKey}' };
if (defined($args{keyPassword})) {
$cmd .= '-passout env:PASS ';
} else {
# If the password is undefined, the keys are created and left
# unencrypted
$cmd .= '-nodes ';
}
} else {
$cmd .= qq{-key '$args{privKey}' };
if ($args{needPass}) {
$cmd .= '-passin env:PASS ';
}
}
$cmd .= qq{-out '$args{reqFile}' };
$cmd .= "-subj '" . $args{dn}->stringOpenSSLStyle() . "' ";
# Not implemented till 0.9.8
# $cmd .= '-multivalue-rdn ' if ( $args{dn}->stringOpenSSLStyle()
# =~ /[^\\](\\\\)*\+/);
# We have to define the environment variable PASS to pass the
# password
$ENV{'PASS'} = $args{keyPassword} if ( defined($args{keyPassword}));
# Execute the command
my ($retVal, $output) = $self->_executeCommand(command => $cmd);
delete( $ENV{'PASS'} );
return $output if ($retVal eq 'ERROR');
return;
}
# Sign a request
# return the output error if any error occurr, nothing otherwise
# ? Optional Parameter
sub _signRequest # (userReqFile, days, userCertFile?, policy?, selfsigned?,
# newSubject?, endDate?, subjAltNames?)
{
my ($self, %args) = @_;
# For OpenSSL 0.9.7
if ($args{selfsigned}) {
my $output = $self->_signSelfSignRequest( userReqFile => $args{userReqFile},
days => $args{days},
userCertFile => $args{userCertFile},
policy => $args{policy},
newSubject => $args{newSubject},
endDate => $args{endDate},
keyFile => CAPRIVKEY);
if (defined $args{newSubject}) {
$self->{dn} = $args{newSubject};
}
# If any error has occurred return inmediately
if ( $output) {
return $output;
}
# Put in the index.txt file (update database...)
$self->_putInIndex(dn => $self->caDN(),
certFile => CACERT,
serialNumber => $self->_obtain(CACERT,'serial'));
return $output;
}
my $policy = "policy_anything" unless (defined($args{policy}));
my $endDate = $self->_flatDate($args{endDate}) if defined($args{endDate});
# Sign the request
my $cmd = "ca";
$self->_commonArgs("ca", \$cmd);
# Only available since OpenSSL 0.9.8
# $cmd .= "-create_serial "if ($args{createSerial});
if (defined($self->{caKeyPassword})) {
# it can be no pass for CA key
$cmd .= "-passin env:PASS ";
}
$cmd .= "-outdir " . CERTSDIR . " ";
$cmd .= "-out \'$args{userCertFile}\' " if defined($args{userCertFile});
$cmd .= '-extensions v3_ca ' if ( EXTENSIONS_V3 and $args{selfsigned});
my $tmpFileName;
if ( defined($args{subjAltNames}) ) {
$tmpFileName = $self->_generateExtFile($args{subjAltNames});
$cmd .= "-extfile '$tmpFileName' ";
} else {
$cmd .= '-extensions usr_cert ' if ( EXTENSIONS_V3 and not $args{selfsigned});
}
# Only available in OpenSSL 0.9.8
$cmd .= "-selfsign " if ($args{selfsigned});
$cmd .= "-policy $policy ";
$cmd .= "-keyfile " . CAPRIVKEY . " ";
$cmd .= "-days $args{days} " if defined($args{days});
$cmd .= "-enddate " . $self->_flatDate($args{endDate}) . " " if defined($args{endDate});
if ( defined($args{newSubject}) ) {
$cmd .= "-subj \"". $args{newSubject}->stringOpenSSLStyle() . "\" ";
$cmd .= "-multivalue-rdn " if ( $args{newSubject}->stringOpenSSLStyle() =~ /[^\\](\\\\)*\+/);
}
$cmd .= "-in \'$args{userReqFile}\'";
$ENV{'PASS'} = $self->{caKeyPassword}
if(defined($self->{caKeyPassword}));
my ($retVal, $output) = $self->_executeCommand(command => $cmd);
delete ( $ENV{'PASS'} );
# Remove ext file if exists
# unlink( $tmpFileName ) if ( -e $tmpFileName );
return $self->_filterErrorFromOpenSSL($output) if ($retVal eq "ERROR");
return undef;
}
# Sign a self-signed request (compatible with OpenSSL 0.9.7 series)
sub _signSelfSignRequest # (userReqFile, days?, userCertFile,
# serialNumber?, newSubject?, endDate?,
# keyFile)
{
my ($self, %args) = @_;
my $endDate = $self->_flatDate($args{endDate}) if defined($args{endDate});
# Sign the request
my $cmd = "req";
$self->_commonArgs("req", \$cmd);
# Only available since OpenSSL 0.9.8
# Maybe the password is not necessary
if ( defined($self->{caKeyPassword}) ){
$cmd .= "-passin env:PASS ";
}
$cmd .= "-out \'$args{userCertFile}\' " if defined($args{userCertFile});
$cmd .= "-extensions v3_ca " if ( EXTENSIONS_V3);
$cmd .= "-x509 ";
$cmd .= "-set_serial \"0x$args{serialNumber}\" " if defined($args{serialNumber});
$cmd .= "-days $args{days} " if defined($args{days});
$cmd .= "-enddate " . $self->_flatDate($args{endDate}) . " " if defined($args{endDate});
if ( defined($args{newSubject}) ) {
$cmd .= "-subj \"". $args{newSubject}->stringOpenSSLStyle() . "\" ";
$cmd .= "-multivalue-rdn " if ( $args{newSubject}->stringOpenSSLStyle() =~ /[^\\](\\\\)*\+/);
}
$cmd .= "-key $args{keyFile} ";
$cmd .= "-in \'$args{userReqFile}\' ";
$ENV{'PASS'} = $self->{caKeyPassword}
if (defined($self->{caKeyPassword}));
my ($retVal, $output) = $self->_executeCommand(command => $cmd);
delete ( $ENV{'PASS'} );
return $output if ($retVal eq "ERROR");
return undef;
}
# Taken the OpenSSL command (req, x509, rsa...)
# and add to the args the common arguments to all openssl commands
# For now, to req and ca commands, it adds config file and batch mode
#
sub _commonArgs # (cmd, args)
{
my ($self, $cmd, $args ) = @_;
if ( $cmd eq "ca" or $cmd eq "req" ) {
${$args} .= " -config " . SSLCONFFILE . " -batch ";
}
}
# Given a certification file Obtain an attribute from the file
# attribute => 'DN' return => EBox::CA::DN object
# attribute => 'serial' return => String containing the serial number
# attribute =>'endDate' return => Date::Calc::Object with the date
# attribute => 'days' return => number of days from today to expire
# attribute => 'subjAltNames' return => Array ref containing hash ref with key type of certificate
# and value the value for the subject alt name
# undef => if certification file does NOT exist
sub _obtain # (certFile, attribute)
{
my ($self, $certFile ,$attribute) = @_;
if (not -f $certFile) {
return undef;
}
my $arg = "";
if ($attribute eq 'DN') {
$arg = "-subject";
} elsif ($attribute eq 'serial') {
$arg = "-serial";
} elsif ($attribute eq 'endDate'
or $attribute eq 'days') {
$arg = "-enddate";
} elsif ($attribute eq 'subjAltNames' ) {
$arg = '-text -certopt -no_header,no_version,no_serial,no_signame,no_validity,no_subject';
}
my $cmd = "x509 " . $arg . " -in \'$certFile\' -noout";
my ($retVal, $output) = $self->_executeCommand(command => $cmd);
return undef if ($retVal ne "OK");
# Remove the attribute name part
$arg =~ s/-//g;
if ($arg eq "enddate") {
$arg = "notAfter";
}
$output =~ s/^$arg=( )*//g;
chomp($output);
if ($attribute eq 'DN') {
return EBox::CA::DN->parseDN($output);
} elsif ($attribute eq 'serial' ) {
return $output;
} elsif ($attribute eq 'endDate' ) {
my ($monthStr, $day, $hour, $min, $sec, $yyyy) =
($output =~ /(.+) (\d+) (\d+):(\d+):(\d+) (\d+) (.+)/);
$monthStr =~ s/ +//g;
my $dateObj = Date::Calc->new($yyyy,
Decode_Month($monthStr),
$day, $hour, $min, $sec);
return $dateObj;
} elsif ($attribute eq 'days') {
my $certDate = $self->_parseDate($output);
my $diffDate = $certDate - Date::Calc->Today();
return $diffDate->day();
} elsif ($attribute eq 'subjAltNames') {
my ($altNameStr) = $output =~ m/X509v3 Subject Alternative Name:\s+(.*)\s+X509v3 Au/s;
return [] if not defined($altNameStr);
$altNameStr =~ s/\s+//g;
my @retValue = ();
my @subjAltNames = split(/,/, $altNameStr);
foreach my $subAlt (@subjAltNames) {
my ($type, $value) = split(/:/, $subAlt);
if ( $type eq 'IPAddress' ) {
push(@retValue, { type => 'IP', value => $value });
} else {
push(@retValue, { type => $type, value => $value });
}
}
return \@retValue;
}
}
# Given the string date from index.txt file
# obtain the date as a Date::Calc::Object
sub _parseDate
{
my ($self, $str) = @_;
my ($y,$mon,$mday,$h,$m,$s) = $str =~ /([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})Z$/;
$y += 2000;
# my $wday = Day_of_Week($y+1999,$mon,$mday);
my $date = Date::Calc->new($y, $mon, $mday, $h, $m, $s);
return $date;
}
# A private method to flat a Date::Calc::Object to a OpenSSL form like
# YYMMDDHHMMSSZ
sub _flatDate # (date)
{
my ($self, $date) = @_;
return "" unless ( UNIVERSAL::isa($date, "Date::Calc"));
my $dateStr =sprintf("%02d%02d%02d%02d%02d%02dZ",
$date->year() - 2000,
$date->month(),
$date->day(),
$date->hours(),
$date->minutes(),
$date->seconds());
return $dateStr;
}
# Create a serial number with 16 digits (a hex number)
# Return the 16-digit string
sub _createSerial
{
my $self = shift;
srand();
my $serial = sprintf("%08X", int(rand(hex('0xFFFFFFFF'))));
$serial .= sprintf("%08X", int(rand(hex('0xFFFFFFFF'))));
return $serial;
}
# Get the maximum number of days to apply to a certificate expiration.
# This is the Year 2038 Bug, explained here ->
# http://www.mail-archive.com/openssl-users@openssl.org/msg45886.html
sub _maxDays
{
my ($self) = @_;
my $now = Date::Calc::Object->now();
# The final day is 2038 19th 04:14:07 :-O
my $year2038 = Date::Calc::Object->new(2038, 1, 19, 4, 14, 7);
my $diff = $year2038 - $now;
return $diff->day();
}
# Print the row for CA cert in index.txt file (to fuck them up)
sub _putInIndex # (EBox::CA::DN dn, String certFile, String
# serialNumber)
{
my ($self, %args) = @_;
my $date = $self->_obtain($args{certFile}, 'endDate');
my $row = "V\t";
$row .= $self->_flatDate($date) . "\t\t";
$row .= $args{serialNumber} . "\t";
$row .= "unknown\t";
# I found that every subject has no final slash
my $subject = $args{dn}->stringOpenSSLStyle();
$subject =~ s/\/$//g;
$row .= $subject . "\n";
open (my $index, ">>" . INDEXFILE);
print $index $row;
close($index);
}
# Return if the given DN is the CA certificate file
sub _isCACert # (EBox::CA::DN dn)
{
my ($self, $dn) = @_;
my $caDN = $self->_obtain(CACERT, 'DN');
return $caDN->equals($dn);
}
# Write down the next serial to serial file, given a certificate file
# Only useful under OpenSSL 0.9.7, later on fixed
sub _writeDownNextSerial # (certFile)
{
my ($self, $certFile) = @_;
my $cmd = "x509 ";
$self->_commonArgs("x509", \$cmd);
$cmd .= "-in \'$certFile\' ";
$cmd .= "-noout ";
$cmd .= "-next_serial ";
$cmd .= "-out " . SERIALNOFILE;
$self->_executeCommand(command => $cmd);
}
# Write down the serial attribute file
# Only useful under OpenSSL 0.9.7, later on fixed
sub _writeDownIndexAttr # (attrFile)
{
my ($self, $attrFile) = @_;
open(my $fh, ">" . $attrFile);
print $fh "unique_subject = yes" . $/;
close($fh);
}
# Filter the given OpenSSL output from error to show normal messages
# Return a normal error message
# Welcome to the hell
sub _filterErrorFromOpenSSL # (input)
{
my ($self, $input) = @_;
if( $input eq "1") {
$input = "1";
} elsif ( $input =~ m/unable to load CA private key/i ) {
$input = __("Unable to sign. Wrong CA passphrase or has CA private key dissappeared?");
} elsif ( $input =~ m/invalid expiry date/i ) {
$input = __("Database corruption");
} elsif ( $input =~ m/TXT_DB error number 2/i ) {
$input = __("Identifier duplicated in Database");
} elsif ( $input =~ m/Already revoked/i ) {
$input = __("Certificate already revoked");
} elsif ( $input =~ m/string too long/i ) {
my ($maxSize) = ($input =~ /maxsize=(\d+)/ );
$input = __("ASN1 field length too long. Maximum Size:") . $maxSize;
} else {
$input = __("Unknown error. Given the OpenSSL output:") . $/ . $input;
}
return $input;
}
# Check none of other Zentyal modules uses the certificate
# Return true if there's any module using it
sub _certsInUse # (cn?, isCACert?)
{
my ($self, $cn, $isCACert) = @_;
if ( not (defined($cn) and defined($isCACert)) ) {
return undef;
}
$cn = $self->caDN()->attribute('commonName')
if ($isCACert);
my $global = EBox::Global->getInstance();
my @observers = @{$global->modInstancesOfType('EBox::CA::Observer')};
foreach my $obs (@observers) {
if( $obs->certificateRevoked($cn, $isCACert) ){
return 1;
}
}
return 1 if EBox::CA::Certificates->certificateRevoked($cn, $isCACert);
return undef;
}
# Force observers to free this certificate
sub _freeCert # (cn?, isCACert?)
{
my ($self, $cn, $isCACert) = @_;
if ($isCACert) {
$cn = $self->caDN()->attribute('commonName');
}
my $global = EBox::Global->getInstance();
my @observers = @{$global->modInstancesOfType('EBox::CA::Observer')};
foreach my $obs (@observers) {
$obs->freeCertificate($cn);
}
EBox::CA::Certificates->freeCertificate($cn);
}
# Set the CA as passwordful or passwordless
sub _setPasswordRequired # (required)
{
my ($self, $required) = @_;
$self->set_bool('pass_required', $required);
}
# Check if a date is later than CA certificate date
# Returns the value to set the expiration date
sub _isLaterThanCA # (date)
{
my ($self, $date) = @_;
my $caExpirationDate = $self->caExpirationDate();
# gt compares date and time
if ( $date gt $caExpirationDate ) {
# != compares date
if ( $date > $caExpirationDate ) {
throw EBox::Exceptions::External(
__('Expiration date later than CA certificate expiration date')
);
} else {
EBox::warn('Defining CA expiration date for a new certificate');
return $caExpirationDate;
}
}
return $date;
}
# Check the given subject alternative names are correct
sub _checkSubjAltNames
{
my ($self, $subjAltNames) = @_;
foreach my $subjAlt (@{$subjAltNames}) {
if ( $subjAlt->{type} eq 'DNS' ) {
EBox::Validate::checkDomainName($subjAlt->{value}, 'DNS value');
} elsif ( $subjAlt->{type} eq 'IP' ) {
EBox::Validate::checkIP($subjAlt->{value}, 'IP value');
} elsif ( $subjAlt->{type} eq 'email' ) {
# copy is an special value to get the email value from CN subject
if ( $subjAlt->{value} ne 'copy' ) {
EBox::Validate::checkEmailAddress($subjAlt->{value}, 'email value');
}
} else {
throw EBox::Exceptions::InvalidData(
data => 'type',
value => $subjAlt->{type},
advice => __x('Only {dns}, {ip} and {email} are valid subject alternative '
. 'name types', dns => 'DNS', ip => 'IP', email => 'email'),
);
}
}
}
# Generate the v3 extension conf file to write the subj alt names
# the results is the temporary file path to write onto
sub _generateExtFile
{
my ($self, $subjAltNames) = @_;
my $tmpFile = new File::Temp(DIR => EBox::Config::tmp());
$tmpFile->unlink_on_destroy(0);
EBox::Module::Base::writeConfFileNoCheck($tmpFile->filename(),
'ca/v3_ext.mas',
[ 'subjAltNames' => $subjAltNames ],
);
return $tmpFile->filename();
}
sub _audit
{
my ($self, $action, $arg) = @_;
$self->{audit}->logAction('ca', 'Certification Authority', $action, $arg);
}
#####
# OpenSSL shell management
#####
sub _startShell
{
my ($self) = @_;
return if ( $self->{shell} );
my $open = '| ' . OPENSSLPATH
. " 1>$output_shell"
. " 2>$error_shell";
if ( not open($self->{shell}, $open) ) {
throw EBox::Exceptions::Internal(__x("Cannot start OpenSSL shell. ({errval})", errval => $!));
}
}
sub _stopShell
{
my ($self) = @_;
return if (not $self->{shell} );
print {$self->{shell}} "exit\n";
close($self->{shell});
undef($self->{shell});
}
# Return two values into an array
# (OK or ERROR, output)
sub _executeCommand # (command, input, hide_output)
{
my ($self, %params) = @_;
# Initialise the shell, launch exception if it is not possible
$self->_startShell();
my $command = $params{command};
# EBox::debug("OpenSSL command: $command");
$command =~ s/\n*$//;
$command .= "\n";
# Send the command
if (not print {$self->{shell}} $command) {
my $errVal = $!;
throw EBox::Exceptions::Internal("Cannot write to the OpenSSL shell: $errVal");
}
my $input;
$input = $params{input} if (exists $params{input});
# Send the input
if ($input and not print {$self->{shell}} $input . "\x00") {
my $errVal = $!;
throw EBox::Exceptions::Internal("Cannot write to the OpenSSL shell: $errVal");
}
# Close the shell
$self->_stopShell();
# check for errors
if (-e $error_shell) {
# There was an error
my $ret = File::Slurp::read_file($error_shell);
unlink($error_shell);
if ( $ret =~ /error/i ) {
unlink($output_shell);
EBox::error("Error: $ret");
return ('ERROR', $ret);
}
}
# Load the output
my $ret = 1;
if ( -e $output_shell ) {
$ret = File::Slurp::read_file($output_shell);
# $ret =~ s/^(OpenSSL>\s)*//s;
$ret =~ s/^OpenSSL>\s*//gm;
$ret = 1 if ($ret eq "");
}
unlink($output_shell);
my $msg = $ret;
$msg = "<NOT LOGGED>" if ($params{hide_output});
return ('OK', $ret);
}
sub caDN
{
my ($self) = @_;
if (not defined $self->{dn}) {
$self->{dn} = $self->_obtain(CACERT, 'DN');
}
return $self->{dn};
}
sub caExpirationDate
{
my ($self) =@_;
if (not defined $self->{caExpirationDate}) {
$self->{caExpirationDate} = $self->_obtain(CACERT, 'endDate');
}
return $self->{caExpirationDate};
}
1;
|