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
|
/* $OpenBSD: ssh-agent.c,v 1.310 2025/02/18 08:02:48 djm Exp $ */
/*
* Author: Tatu Ylonen <ylo@cs.hut.fi>
* Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
* All rights reserved
* The authentication agent program.
*
* As far as I am concerned, the code I have written for this software
* can be used freely for any purpose. Any derived versions of this
* software must be clearly marked as such, and if the derived work is
* incompatible with the protocol description in the RFC file, it must be
* called by a name other than "ssh" or "Secure Shell".
*
* Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "includes.h"
#include <sys/types.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/wait.h>
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
#ifdef HAVE_SYS_UN_H
# include <sys/un.h>
#endif
#include "openbsd-compat/sys-queue.h"
#ifdef WITH_OPENSSL
#include <openssl/evp.h>
#include "openbsd-compat/openssl-compat.h"
#endif
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#ifdef HAVE_PATHS_H
# include <paths.h>
#endif
#ifdef HAVE_POLL_H
# include <poll.h>
#endif
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#ifdef HAVE_UTIL_H
# include <util.h>
#endif
#include "xmalloc.h"
#include "ssh.h"
#include "ssh2.h"
#include "sshbuf.h"
#include "sshkey.h"
#include "authfd.h"
#include "log.h"
#include "misc.h"
#include "digest.h"
#include "ssherr.h"
#include "match.h"
#include "msg.h"
#include "pathnames.h"
#include "ssh-pkcs11.h"
#include "sk-api.h"
#include "myproposal.h"
#ifndef DEFAULT_ALLOWED_PROVIDERS
# define DEFAULT_ALLOWED_PROVIDERS "/usr/lib*/*,/usr/local/lib*/*"
#endif
#ifndef DEFAULT_WEBSAFE_ALLOWLIST
# define DEFAULT_WEBSAFE_ALLOWLIST "ssh:*"
#endif
/* Maximum accepted message length */
#define AGENT_MAX_LEN (256*1024)
/* Maximum bytes to read from client socket */
#define AGENT_RBUF_LEN (4096)
/* Maximum number of recorded session IDs/hostkeys per connection */
#define AGENT_MAX_SESSION_IDS 16
/* Maximum size of session ID */
#define AGENT_MAX_SID_LEN 128
/* Maximum number of destination constraints to accept on a key */
#define AGENT_MAX_DEST_CONSTRAINTS 1024
/* Maximum number of associated certificate constraints to accept on a key */
#define AGENT_MAX_EXT_CERTS 1024
/* XXX store hostkey_sid in a refcounted tree */
typedef enum {
AUTH_UNUSED = 0,
AUTH_SOCKET = 1,
AUTH_CONNECTION = 2,
} sock_type;
struct hostkey_sid {
struct sshkey *key;
struct sshbuf *sid;
int forwarded;
};
typedef struct socket_entry {
int fd;
sock_type type;
struct sshbuf *input;
struct sshbuf *output;
struct sshbuf *request;
size_t nsession_ids;
struct hostkey_sid *session_ids;
int session_bind_attempted;
} SocketEntry;
u_int sockets_alloc = 0;
SocketEntry *sockets = NULL;
typedef struct identity {
TAILQ_ENTRY(identity) next;
struct sshkey *key;
char *comment;
char *provider;
time_t death;
u_int confirm;
char *sk_provider;
struct dest_constraint *dest_constraints;
size_t ndest_constraints;
} Identity;
struct idtable {
int nentries;
TAILQ_HEAD(idqueue, identity) idlist;
};
/* private key table */
struct idtable *idtab;
int max_fd = 0;
/* pid of shell == parent of agent */
pid_t parent_pid = -1;
time_t parent_alive_interval = 0;
static sig_atomic_t signalled_exit;
static sig_atomic_t signalled_keydrop;
/* pid of process for which cleanup_socket is applicable */
pid_t cleanup_pid = 0;
/* pathname and directory for AUTH_SOCKET */
char socket_name[PATH_MAX];
char socket_dir[PATH_MAX];
/* Pattern-list of allowed PKCS#11/Security key paths */
static char *allowed_providers;
/*
* Allows PKCS11 providers or SK keys that use non-internal providers to
* be added over a remote connection (identified by session-bind@openssh.com).
*/
static int remote_add_provider;
/* locking */
#define LOCK_SIZE 32
#define LOCK_SALT_SIZE 16
#define LOCK_ROUNDS 1
int locked = 0;
u_char lock_pwhash[LOCK_SIZE];
u_char lock_salt[LOCK_SALT_SIZE];
extern char *__progname;
/* Default lifetime in seconds (0 == forever) */
static int lifetime = 0;
static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
/* Refuse signing of non-SSH messages for web-origin FIDO keys */
static int restrict_websafe = 1;
static char *websafe_allowlist;
static void
close_socket(SocketEntry *e)
{
size_t i;
close(e->fd);
sshbuf_free(e->input);
sshbuf_free(e->output);
sshbuf_free(e->request);
for (i = 0; i < e->nsession_ids; i++) {
sshkey_free(e->session_ids[i].key);
sshbuf_free(e->session_ids[i].sid);
}
free(e->session_ids);
memset(e, '\0', sizeof(*e));
e->fd = -1;
e->type = AUTH_UNUSED;
}
static void
idtab_init(void)
{
idtab = xcalloc(1, sizeof(*idtab));
TAILQ_INIT(&idtab->idlist);
idtab->nentries = 0;
}
static void
free_dest_constraint_hop(struct dest_constraint_hop *dch)
{
u_int i;
if (dch == NULL)
return;
free(dch->user);
free(dch->hostname);
for (i = 0; i < dch->nkeys; i++)
sshkey_free(dch->keys[i]);
free(dch->keys);
free(dch->key_is_ca);
}
static void
free_dest_constraints(struct dest_constraint *dcs, size_t ndcs)
{
size_t i;
for (i = 0; i < ndcs; i++) {
free_dest_constraint_hop(&dcs[i].from);
free_dest_constraint_hop(&dcs[i].to);
}
free(dcs);
}
#ifdef ENABLE_PKCS11
static void
dup_dest_constraint_hop(const struct dest_constraint_hop *dch,
struct dest_constraint_hop *out)
{
u_int i;
int r;
out->user = dch->user == NULL ? NULL : xstrdup(dch->user);
out->hostname = dch->hostname == NULL ? NULL : xstrdup(dch->hostname);
out->is_ca = dch->is_ca;
out->nkeys = dch->nkeys;
out->keys = out->nkeys == 0 ? NULL :
xcalloc(out->nkeys, sizeof(*out->keys));
out->key_is_ca = out->nkeys == 0 ? NULL :
xcalloc(out->nkeys, sizeof(*out->key_is_ca));
for (i = 0; i < dch->nkeys; i++) {
if (dch->keys[i] != NULL &&
(r = sshkey_from_private(dch->keys[i],
&(out->keys[i]))) != 0)
fatal_fr(r, "copy key");
out->key_is_ca[i] = dch->key_is_ca[i];
}
}
static struct dest_constraint *
dup_dest_constraints(const struct dest_constraint *dcs, size_t ndcs)
{
size_t i;
struct dest_constraint *ret;
if (ndcs == 0)
return NULL;
ret = xcalloc(ndcs, sizeof(*ret));
for (i = 0; i < ndcs; i++) {
dup_dest_constraint_hop(&dcs[i].from, &ret[i].from);
dup_dest_constraint_hop(&dcs[i].to, &ret[i].to);
}
return ret;
}
#endif /* ENABLE_PKCS11 */
#ifdef DEBUG_CONSTRAINTS
static void
dump_dest_constraint_hop(const struct dest_constraint_hop *dch)
{
u_int i;
char *fp;
debug_f("user %s hostname %s is_ca %d nkeys %u",
dch->user == NULL ? "(null)" : dch->user,
dch->hostname == NULL ? "(null)" : dch->hostname,
dch->is_ca, dch->nkeys);
for (i = 0; i < dch->nkeys; i++) {
fp = NULL;
if (dch->keys[i] != NULL &&
(fp = sshkey_fingerprint(dch->keys[i],
SSH_FP_HASH_DEFAULT, SSH_FP_DEFAULT)) == NULL)
fatal_f("fingerprint failed");
debug_f("key %u/%u: %s%s%s key_is_ca %d", i, dch->nkeys,
dch->keys[i] == NULL ? "" : sshkey_ssh_name(dch->keys[i]),
dch->keys[i] == NULL ? "" : " ",
dch->keys[i] == NULL ? "none" : fp,
dch->key_is_ca[i]);
free(fp);
}
}
#endif /* DEBUG_CONSTRAINTS */
static void
dump_dest_constraints(const char *context,
const struct dest_constraint *dcs, size_t ndcs)
{
#ifdef DEBUG_CONSTRAINTS
size_t i;
debug_f("%s: %zu constraints", context, ndcs);
for (i = 0; i < ndcs; i++) {
debug_f("constraint %zu / %zu: from: ", i, ndcs);
dump_dest_constraint_hop(&dcs[i].from);
debug_f("constraint %zu / %zu: to: ", i, ndcs);
dump_dest_constraint_hop(&dcs[i].to);
}
debug_f("done for %s", context);
#endif /* DEBUG_CONSTRAINTS */
}
static void
free_identity(Identity *id)
{
sshkey_free(id->key);
free(id->provider);
free(id->comment);
free(id->sk_provider);
free_dest_constraints(id->dest_constraints, id->ndest_constraints);
free(id);
}
/*
* Match 'key' against the key/CA list in a destination constraint hop
* Returns 0 on success or -1 otherwise.
*/
static int
match_key_hop(const char *tag, const struct sshkey *key,
const struct dest_constraint_hop *dch)
{
const char *reason = NULL;
const char *hostname = dch->hostname ? dch->hostname : "(ORIGIN)";
u_int i;
char *fp;
if (key == NULL)
return -1;
/* XXX logspam */
if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
SSH_FP_DEFAULT)) == NULL)
fatal_f("fingerprint failed");
debug3_f("%s: entering hostname %s, requested key %s %s, %u keys avail",
tag, hostname, sshkey_type(key), fp, dch->nkeys);
free(fp);
for (i = 0; i < dch->nkeys; i++) {
if (dch->keys[i] == NULL)
return -1;
/* XXX logspam */
if ((fp = sshkey_fingerprint(dch->keys[i], SSH_FP_HASH_DEFAULT,
SSH_FP_DEFAULT)) == NULL)
fatal_f("fingerprint failed");
debug3_f("%s: key %u: %s%s %s", tag, i,
dch->key_is_ca[i] ? "CA " : "",
sshkey_type(dch->keys[i]), fp);
free(fp);
if (!sshkey_is_cert(key)) {
/* plain key */
if (dch->key_is_ca[i] ||
!sshkey_equal(key, dch->keys[i]))
continue;
return 0;
}
/* certificate */
if (!dch->key_is_ca[i])
continue;
if (key->cert == NULL || key->cert->signature_key == NULL)
return -1; /* shouldn't happen */
if (!sshkey_equal(key->cert->signature_key, dch->keys[i]))
continue;
if (sshkey_cert_check_host(key, hostname, 1,
SSH_ALLOWED_CA_SIGALGS, &reason) != 0) {
debug_f("cert %s / hostname %s rejected: %s",
key->cert->key_id, hostname, reason);
continue;
}
return 0;
}
return -1;
}
/* Check destination constraints on an identity against the hostkey/user */
static int
permitted_by_dest_constraints(const struct sshkey *fromkey,
const struct sshkey *tokey, Identity *id, const char *user,
const char **hostnamep)
{
size_t i;
struct dest_constraint *d;
if (hostnamep != NULL)
*hostnamep = NULL;
for (i = 0; i < id->ndest_constraints; i++) {
d = id->dest_constraints + i;
/* XXX remove logspam */
debug2_f("constraint %zu %s%s%s (%u keys) > %s%s%s (%u keys)",
i, d->from.user ? d->from.user : "",
d->from.user ? "@" : "",
d->from.hostname ? d->from.hostname : "(ORIGIN)",
d->from.nkeys,
d->to.user ? d->to.user : "", d->to.user ? "@" : "",
d->to.hostname ? d->to.hostname : "(ANY)", d->to.nkeys);
/* Match 'from' key */
if (fromkey == NULL) {
/* We are matching the first hop */
if (d->from.hostname != NULL || d->from.nkeys != 0)
continue;
} else if (match_key_hop("from", fromkey, &d->from) != 0)
continue;
/* Match 'to' key */
if (tokey != NULL && match_key_hop("to", tokey, &d->to) != 0)
continue;
/* Match user if specified */
if (d->to.user != NULL && user != NULL &&
!match_pattern(user, d->to.user))
continue;
/* successfully matched this constraint */
if (hostnamep != NULL)
*hostnamep = d->to.hostname;
debug2_f("allowed for hostname %s",
d->to.hostname == NULL ? "*" : d->to.hostname);
return 0;
}
/* no match */
debug2_f("%s identity \"%s\" not permitted for this destination",
sshkey_type(id->key), id->comment);
return -1;
}
/*
* Check whether hostkeys on a SocketEntry and the optionally specified user
* are permitted by the destination constraints on the Identity.
* Returns 0 on success or -1 otherwise.
*/
static int
identity_permitted(Identity *id, SocketEntry *e, char *user,
const char **forward_hostnamep, const char **last_hostnamep)
{
size_t i;
const char **hp;
struct hostkey_sid *hks;
const struct sshkey *fromkey = NULL;
const char *test_user;
char *fp1, *fp2;
/* XXX remove logspam */
debug3_f("entering: key %s comment \"%s\", %zu socket bindings, "
"%zu constraints", sshkey_type(id->key), id->comment,
e->nsession_ids, id->ndest_constraints);
if (id->ndest_constraints == 0)
return 0; /* unconstrained */
if (e->session_bind_attempted && e->nsession_ids == 0) {
error_f("previous session bind failed on socket");
return -1;
}
if (e->nsession_ids == 0)
return 0; /* local use */
/*
* Walk through the hops recorded by session_id and try to find a
* constraint that satisfies each.
*/
for (i = 0; i < e->nsession_ids; i++) {
hks = e->session_ids + i;
if (hks->key == NULL)
fatal_f("internal error: no bound key");
/* XXX remove logspam */
fp1 = fp2 = NULL;
if (fromkey != NULL &&
(fp1 = sshkey_fingerprint(fromkey, SSH_FP_HASH_DEFAULT,
SSH_FP_DEFAULT)) == NULL)
fatal_f("fingerprint failed");
if ((fp2 = sshkey_fingerprint(hks->key, SSH_FP_HASH_DEFAULT,
SSH_FP_DEFAULT)) == NULL)
fatal_f("fingerprint failed");
debug3_f("socketentry fd=%d, entry %zu %s, "
"from hostkey %s %s to user %s hostkey %s %s",
e->fd, i, hks->forwarded ? "FORWARD" : "AUTH",
fromkey ? sshkey_type(fromkey) : "(ORIGIN)",
fromkey ? fp1 : "", user ? user : "(ANY)",
sshkey_type(hks->key), fp2);
free(fp1);
free(fp2);
/*
* Record the hostnames for the initial forwarding and
* the final destination.
*/
hp = NULL;
if (i == e->nsession_ids - 1)
hp = last_hostnamep;
else if (i == 0)
hp = forward_hostnamep;
/* Special handling for final recorded binding */
test_user = NULL;
if (i == e->nsession_ids - 1) {
/* Can only check user at final hop */
test_user = user;
/*
* user is only presented for signature requests.
* If this is the case, make sure last binding is not
* for a forwarding.
*/
if (hks->forwarded && user != NULL) {
error_f("tried to sign on forwarding hop");
return -1;
}
} else if (!hks->forwarded) {
error_f("tried to forward though signing bind");
return -1;
}
if (permitted_by_dest_constraints(fromkey, hks->key, id,
test_user, hp) != 0)
return -1;
fromkey = hks->key;
}
/*
* Another special case: if the last bound session ID was for a
* forwarding, and this function is not being called to check a sign
* request (i.e. no 'user' supplied), then only permit the key if
* there is a permission that would allow it to be used at another
* destination. This hides keys that are allowed to be used to
* authenticate *to* a host but not permitted for *use* beyond it.
*/
hks = &e->session_ids[e->nsession_ids - 1];
if (hks->forwarded && user == NULL &&
permitted_by_dest_constraints(hks->key, NULL, id,
NULL, NULL) != 0) {
debug3_f("key permitted at host but not after");
return -1;
}
/* success */
return 0;
}
static int
socket_is_remote(SocketEntry *e)
{
return e->session_bind_attempted || (e->nsession_ids != 0);
}
/* return matching private key for given public key */
static Identity *
lookup_identity(struct sshkey *key)
{
Identity *id;
TAILQ_FOREACH(id, &idtab->idlist, next) {
if (sshkey_equal(key, id->key))
return (id);
}
return (NULL);
}
/* Check confirmation of keysign request */
static int
confirm_key(Identity *id, const char *extra)
{
char *p;
int ret = -1;
p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
if (p != NULL &&
ask_permission("Allow use of key %s?\nKey fingerprint %s.%s%s",
id->comment, p,
extra == NULL ? "" : "\n", extra == NULL ? "" : extra))
ret = 0;
free(p);
return (ret);
}
static void
send_status(SocketEntry *e, int success)
{
int r;
if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
(r = sshbuf_put_u8(e->output, success ?
SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
fatal_fr(r, "compose");
}
/* send list of supported public keys to 'client' */
static void
process_request_identities(SocketEntry *e)
{
Identity *id;
struct sshbuf *msg, *keys;
int r;
u_int i = 0, nentries = 0;
char *fp;
debug2_f("entering");
if ((msg = sshbuf_new()) == NULL || (keys = sshbuf_new()) == NULL)
fatal_f("sshbuf_new failed");
TAILQ_FOREACH(id, &idtab->idlist, next) {
if ((fp = sshkey_fingerprint(id->key, SSH_FP_HASH_DEFAULT,
SSH_FP_DEFAULT)) == NULL)
fatal_f("fingerprint failed");
debug_f("key %u / %u: %s %s", i++, idtab->nentries,
sshkey_ssh_name(id->key), fp);
dump_dest_constraints(__func__,
id->dest_constraints, id->ndest_constraints);
free(fp);
/* identity not visible, don't include in response */
if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
continue;
if ((r = sshkey_puts_opts(id->key, keys,
SSHKEY_SERIALIZE_INFO)) != 0 ||
(r = sshbuf_put_cstring(keys, id->comment)) != 0) {
error_fr(r, "compose key/comment");
continue;
}
nentries++;
}
debug2_f("replying with %u allowed of %u available keys",
nentries, idtab->nentries);
if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
(r = sshbuf_put_u32(msg, nentries)) != 0 ||
(r = sshbuf_putb(msg, keys)) != 0)
fatal_fr(r, "compose");
if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
fatal_fr(r, "enqueue");
sshbuf_free(msg);
sshbuf_free(keys);
}
static char *
agent_decode_alg(struct sshkey *key, u_int flags)
{
if (key->type == KEY_RSA) {
if (flags & SSH_AGENT_RSA_SHA2_256)
return "rsa-sha2-256";
else if (flags & SSH_AGENT_RSA_SHA2_512)
return "rsa-sha2-512";
} else if (key->type == KEY_RSA_CERT) {
if (flags & SSH_AGENT_RSA_SHA2_256)
return "rsa-sha2-256-cert-v01@openssh.com";
else if (flags & SSH_AGENT_RSA_SHA2_512)
return "rsa-sha2-512-cert-v01@openssh.com";
}
return NULL;
}
/*
* Attempt to parse the contents of a buffer as a SSH publickey userauth
* request, checking its contents for consistency and matching the embedded
* key against the one that is being used for signing.
* Note: does not modify msg buffer.
* Optionally extract the username, session ID and/or hostkey from the request.
*/
static int
parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key,
char **userp, struct sshbuf **sess_idp, struct sshkey **hostkeyp)
{
struct sshbuf *b = NULL, *sess_id = NULL;
char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL;
int r;
u_char t, sig_follows;
struct sshkey *mkey = NULL, *hostkey = NULL;
if (userp != NULL)
*userp = NULL;
if (sess_idp != NULL)
*sess_idp = NULL;
if (hostkeyp != NULL)
*hostkeyp = NULL;
if ((b = sshbuf_fromb(msg)) == NULL)
fatal_f("sshbuf_fromb");
/* SSH userauth request */
if ((r = sshbuf_froms(b, &sess_id)) != 0)
goto out;
if (sshbuf_len(sess_id) == 0) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */
(r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */
(r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */
(r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */
(r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */
(r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */
(r = sshkey_froms(b, &mkey)) != 0) /* key */
goto out;
if (t != SSH2_MSG_USERAUTH_REQUEST ||
sig_follows != 1 ||
strcmp(service, "ssh-connection") != 0 ||
!sshkey_equal(expected_key, mkey) ||
sshkey_type_from_name(pkalg) != expected_key->type) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if (strcmp(method, "publickey-hostbound-v00@openssh.com") == 0) {
if ((r = sshkey_froms(b, &hostkey)) != 0)
goto out;
} else if (strcmp(method, "publickey") != 0) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if (sshbuf_len(b) != 0) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
/* success */
r = 0;
debug3_f("well formed userauth");
if (userp != NULL) {
*userp = user;
user = NULL;
}
if (sess_idp != NULL) {
*sess_idp = sess_id;
sess_id = NULL;
}
if (hostkeyp != NULL) {
*hostkeyp = hostkey;
hostkey = NULL;
}
out:
sshbuf_free(b);
sshbuf_free(sess_id);
free(user);
free(service);
free(method);
free(pkalg);
sshkey_free(mkey);
sshkey_free(hostkey);
return r;
}
/*
* Attempt to parse the contents of a buffer as a SSHSIG signature request.
* Note: does not modify buffer.
*/
static int
parse_sshsig_request(struct sshbuf *msg)
{
int r;
struct sshbuf *b;
if ((b = sshbuf_fromb(msg)) == NULL)
fatal_f("sshbuf_fromb");
if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 ||
(r = sshbuf_consume(b, 6)) != 0 ||
(r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */
(r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */
(r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */
(r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */
goto out;
if (sshbuf_len(b) != 0) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
/* success */
r = 0;
out:
sshbuf_free(b);
return r;
}
/*
* This function inspects a message to be signed by a FIDO key that has a
* web-like application string (i.e. one that does not begin with "ssh:".
* It checks that the message is one of those expected for SSH operations
* (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
* for the web.
*/
static int
check_websafe_message_contents(struct sshkey *key, struct sshbuf *data)
{
if (parse_userauth_request(data, key, NULL, NULL, NULL) == 0) {
debug_f("signed data matches public key userauth request");
return 1;
}
if (parse_sshsig_request(data) == 0) {
debug_f("signed data matches SSHSIG signature request");
return 1;
}
/* XXX check CA signature operation */
error("web-origin key attempting to sign non-SSH message");
return 0;
}
static int
buf_equal(const struct sshbuf *a, const struct sshbuf *b)
{
if (sshbuf_ptr(a) == NULL || sshbuf_ptr(b) == NULL)
return SSH_ERR_INVALID_ARGUMENT;
if (sshbuf_len(a) != sshbuf_len(b))
return SSH_ERR_INVALID_FORMAT;
if (timingsafe_bcmp(sshbuf_ptr(a), sshbuf_ptr(b), sshbuf_len(a)) != 0)
return SSH_ERR_INVALID_FORMAT;
return 0;
}
/* ssh2 only */
static void
process_sign_request2(SocketEntry *e)
{
u_char *signature = NULL;
size_t slen = 0;
u_int compat = 0, flags;
int r, ok = -1, retried = 0;
char *fp = NULL, *pin = NULL, *prompt = NULL;
char *user = NULL, *sig_dest = NULL;
const char *fwd_host = NULL, *dest_host = NULL;
struct sshbuf *msg = NULL, *data = NULL, *sid = NULL;
struct sshkey *key = NULL, *hostkey = NULL;
struct identity *id;
struct notifier_ctx *notifier = NULL;
debug_f("entering");
if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL)
fatal_f("sshbuf_new failed");
if ((r = sshkey_froms(e->request, &key)) != 0 ||
(r = sshbuf_get_stringb(e->request, data)) != 0 ||
(r = sshbuf_get_u32(e->request, &flags)) != 0) {
error_fr(r, "parse");
goto send;
}
if ((id = lookup_identity(key)) == NULL) {
verbose_f("%s key not found", sshkey_type(key));
goto send;
}
if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
SSH_FP_DEFAULT)) == NULL)
fatal_f("fingerprint failed");
if (id->ndest_constraints != 0) {
if (e->nsession_ids == 0) {
logit_f("refusing use of destination-constrained key "
"to sign on unbound connection");
goto send;
}
if (parse_userauth_request(data, key, &user, &sid,
&hostkey) != 0) {
logit_f("refusing use of destination-constrained key "
"to sign an unidentified signature");
goto send;
}
/* XXX logspam */
debug_f("user=%s", user);
if (identity_permitted(id, e, user, &fwd_host, &dest_host) != 0)
goto send;
/* XXX display fwd_host/dest_host in askpass UI */
/*
* Ensure that the session ID is the most recent one
* registered on the socket - it should have been bound by
* ssh immediately before userauth.
*/
if (buf_equal(sid,
e->session_ids[e->nsession_ids - 1].sid) != 0) {
error_f("unexpected session ID (%zu listed) on "
"signature request for target user %s with "
"key %s %s", e->nsession_ids, user,
sshkey_type(id->key), fp);
goto send;
}
/*
* Ensure that the hostkey embedded in the signature matches
* the one most recently bound to the socket. An exception is
* made for the initial forwarding hop.
*/
if (e->nsession_ids > 1 && hostkey == NULL) {
error_f("refusing use of destination-constrained key: "
"no hostkey recorded in signature for forwarded "
"connection");
goto send;
}
if (hostkey != NULL && !sshkey_equal(hostkey,
e->session_ids[e->nsession_ids - 1].key)) {
error_f("refusing use of destination-constrained key: "
"mismatch between hostkey in request and most "
"recently bound session");
goto send;
}
xasprintf(&sig_dest, "public key authentication request for "
"user \"%s\" to listed host", user);
}
if (id->confirm && confirm_key(id, sig_dest) != 0) {
verbose_f("user refused key");
goto send;
}
if (sshkey_is_sk(id->key)) {
if (restrict_websafe &&
match_pattern_list(id->key->sk_application,
websafe_allowlist, 0) != 1 &&
!check_websafe_message_contents(key, data)) {
/* error already logged */
goto send;
}
if (id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
notifier = notify_start(0,
"Confirm user presence for key %s %s%s%s",
sshkey_type(id->key), fp,
sig_dest == NULL ? "" : "\n",
sig_dest == NULL ? "" : sig_dest);
}
}
retry_pin:
if ((r = sshkey_sign(id->key, &signature, &slen,
sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags),
id->sk_provider, pin, compat)) != 0) {
debug_fr(r, "sshkey_sign");
if (pin == NULL && !retried && sshkey_is_sk(id->key) &&
r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
notify_complete(notifier, NULL);
notifier = NULL;
/* XXX include sig_dest */
xasprintf(&prompt, "Enter PIN%sfor %s key %s: ",
(id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD) ?
" and confirm user presence " : " ",
sshkey_type(id->key), fp);
pin = read_passphrase(prompt, RP_USE_ASKPASS);
retried = 1;
goto retry_pin;
}
error_fr(r, "sshkey_sign");
goto send;
}
/* Success */
ok = 0;
debug_f("good signature");
send:
notify_complete(notifier, "User presence confirmed");
if (ok == 0) {
if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
(r = sshbuf_put_string(msg, signature, slen)) != 0)
fatal_fr(r, "compose");
} else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
fatal_fr(r, "compose failure");
if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
fatal_fr(r, "enqueue");
sshbuf_free(sid);
sshbuf_free(data);
sshbuf_free(msg);
sshkey_free(key);
sshkey_free(hostkey);
free(fp);
free(signature);
free(sig_dest);
free(user);
free(prompt);
if (pin != NULL)
freezero(pin, strlen(pin));
}
/* shared */
static void
process_remove_identity(SocketEntry *e)
{
int r, success = 0;
struct sshkey *key = NULL;
Identity *id;
debug2_f("entering");
if ((r = sshkey_froms(e->request, &key)) != 0) {
error_fr(r, "parse key");
goto done;
}
if ((id = lookup_identity(key)) == NULL) {
debug_f("key not found");
goto done;
}
/* identity not visible, cannot be removed */
if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
goto done; /* error already logged */
/* We have this key, free it. */
if (idtab->nentries < 1)
fatal_f("internal error: nentries %d", idtab->nentries);
TAILQ_REMOVE(&idtab->idlist, id, next);
free_identity(id);
idtab->nentries--;
success = 1;
done:
sshkey_free(key);
send_status(e, success);
}
static void
remove_all_identities(void)
{
Identity *id;
debug2_f("entering");
/* Loop over all identities and clear the keys. */
for (id = TAILQ_FIRST(&idtab->idlist); id;
id = TAILQ_FIRST(&idtab->idlist)) {
TAILQ_REMOVE(&idtab->idlist, id, next);
free_identity(id);
}
/* Mark that there are no identities. */
idtab->nentries = 0;
}
static void
process_remove_all_identities(SocketEntry *e)
{
remove_all_identities();
/* Send success. */
send_status(e, 1);
}
/* removes expired keys and returns number of seconds until the next expiry */
static time_t
reaper(void)
{
time_t deadline = 0, now = monotime();
Identity *id, *nxt;
for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
nxt = TAILQ_NEXT(id, next);
if (id->death == 0)
continue;
if (now >= id->death) {
debug("expiring key '%s'", id->comment);
TAILQ_REMOVE(&idtab->idlist, id, next);
free_identity(id);
idtab->nentries--;
} else
deadline = (deadline == 0) ? id->death :
MINIMUM(deadline, id->death);
}
if (deadline == 0 || deadline <= now)
return 0;
else
return (deadline - now);
}
static int
parse_dest_constraint_hop(struct sshbuf *b, struct dest_constraint_hop *dch)
{
u_char key_is_ca;
size_t elen = 0;
int r;
struct sshkey *k = NULL;
char *fp;
memset(dch, '\0', sizeof(*dch));
if ((r = sshbuf_get_cstring(b, &dch->user, NULL)) != 0 ||
(r = sshbuf_get_cstring(b, &dch->hostname, NULL)) != 0 ||
(r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
error_fr(r, "parse");
goto out;
}
if (elen != 0) {
error_f("unsupported extensions (len %zu)", elen);
r = SSH_ERR_FEATURE_UNSUPPORTED;
goto out;
}
if (*dch->hostname == '\0') {
free(dch->hostname);
dch->hostname = NULL;
}
if (*dch->user == '\0') {
free(dch->user);
dch->user = NULL;
}
while (sshbuf_len(b) != 0) {
dch->keys = xrecallocarray(dch->keys, dch->nkeys,
dch->nkeys + 1, sizeof(*dch->keys));
dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys,
dch->nkeys + 1, sizeof(*dch->key_is_ca));
if ((r = sshkey_froms(b, &k)) != 0 ||
(r = sshbuf_get_u8(b, &key_is_ca)) != 0)
goto out;
if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
SSH_FP_DEFAULT)) == NULL)
fatal_f("fingerprint failed");
debug3_f("%s%s%s: adding %skey %s %s",
dch->user == NULL ? "" : dch->user,
dch->user == NULL ? "" : "@",
dch->hostname, key_is_ca ? "CA " : "", sshkey_type(k), fp);
free(fp);
dch->keys[dch->nkeys] = k;
dch->key_is_ca[dch->nkeys] = key_is_ca != 0;
dch->nkeys++;
k = NULL; /* transferred */
}
/* success */
r = 0;
out:
sshkey_free(k);
return r;
}
static int
parse_dest_constraint(struct sshbuf *m, struct dest_constraint *dc)
{
struct sshbuf *b = NULL, *frombuf = NULL, *tobuf = NULL;
int r;
size_t elen = 0;
debug3_f("entering");
memset(dc, '\0', sizeof(*dc));
if ((r = sshbuf_froms(m, &b)) != 0 ||
(r = sshbuf_froms(b, &frombuf)) != 0 ||
(r = sshbuf_froms(b, &tobuf)) != 0 ||
(r = sshbuf_get_string_direct(b, NULL, &elen)) != 0) {
error_fr(r, "parse");
goto out;
}
if ((r = parse_dest_constraint_hop(frombuf, &dc->from)) != 0 ||
(r = parse_dest_constraint_hop(tobuf, &dc->to)) != 0)
goto out; /* already logged */
if (elen != 0) {
error_f("unsupported extensions (len %zu)", elen);
r = SSH_ERR_FEATURE_UNSUPPORTED;
goto out;
}
debug2_f("parsed %s (%u keys) > %s%s%s (%u keys)",
dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys,
dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "",
dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys);
/* check consistency */
if ((dc->from.hostname == NULL) != (dc->from.nkeys == 0) ||
dc->from.user != NULL) {
error_f("inconsistent \"from\" specification");
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if (dc->to.hostname == NULL || dc->to.nkeys == 0) {
error_f("incomplete \"to\" specification");
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
/* success */
r = 0;
out:
sshbuf_free(b);
sshbuf_free(frombuf);
sshbuf_free(tobuf);
return r;
}
static int
parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp,
struct dest_constraint **dcsp, size_t *ndcsp, int *cert_onlyp,
struct sshkey ***certs, size_t *ncerts)
{
char *ext_name = NULL;
int r;
struct sshbuf *b = NULL;
u_char v;
struct sshkey *k;
if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {
error_fr(r, "parse constraint extension");
goto out;
}
debug_f("constraint ext %s", ext_name);
if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
if (sk_providerp == NULL) {
error_f("%s not valid here", ext_name);
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if (*sk_providerp != NULL) {
error_f("%s already set", ext_name);
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) {
error_fr(r, "parse %s", ext_name);
goto out;
}
} else if (strcmp(ext_name,
"restrict-destination-v00@openssh.com") == 0) {
if (*dcsp != NULL) {
error_f("%s already set", ext_name);
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if ((r = sshbuf_froms(m, &b)) != 0) {
error_fr(r, "parse %s outer", ext_name);
goto out;
}
while (sshbuf_len(b) != 0) {
if (*ndcsp >= AGENT_MAX_DEST_CONSTRAINTS) {
error_f("too many %s constraints", ext_name);
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
*dcsp = xrecallocarray(*dcsp, *ndcsp, *ndcsp + 1,
sizeof(**dcsp));
if ((r = parse_dest_constraint(b,
*dcsp + (*ndcsp)++)) != 0)
goto out; /* error already logged */
}
} else if (strcmp(ext_name,
"associated-certs-v00@openssh.com") == 0) {
if (certs == NULL || ncerts == NULL || cert_onlyp == NULL) {
error_f("%s not valid here", ext_name);
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if (*certs != NULL) {
error_f("%s already set", ext_name);
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if ((r = sshbuf_get_u8(m, &v)) != 0 ||
(r = sshbuf_froms(m, &b)) != 0) {
error_fr(r, "parse %s", ext_name);
goto out;
}
*cert_onlyp = v != 0;
while (sshbuf_len(b) != 0) {
if (*ncerts >= AGENT_MAX_EXT_CERTS) {
error_f("too many %s constraints", ext_name);
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
*certs = xrecallocarray(*certs, *ncerts, *ncerts + 1,
sizeof(**certs));
if ((r = sshkey_froms(b, &k)) != 0) {
error_fr(r, "parse key");
goto out;
}
(*certs)[(*ncerts)++] = k;
}
} else {
error_f("unsupported constraint \"%s\"", ext_name);
r = SSH_ERR_FEATURE_UNSUPPORTED;
goto out;
}
/* success */
r = 0;
out:
free(ext_name);
sshbuf_free(b);
return r;
}
static int
parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,
u_int *secondsp, int *confirmp, char **sk_providerp,
struct dest_constraint **dcsp, size_t *ndcsp,
int *cert_onlyp, size_t *ncerts, struct sshkey ***certs)
{
u_char ctype;
int r;
u_int seconds, maxsign = 0;
while (sshbuf_len(m)) {
if ((r = sshbuf_get_u8(m, &ctype)) != 0) {
error_fr(r, "parse constraint type");
goto out;
}
switch (ctype) {
case SSH_AGENT_CONSTRAIN_LIFETIME:
if (*deathp != 0) {
error_f("lifetime already set");
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if ((r = sshbuf_get_u32(m, &seconds)) != 0) {
error_fr(r, "parse lifetime constraint");
goto out;
}
*deathp = monotime() + seconds;
*secondsp = seconds;
break;
case SSH_AGENT_CONSTRAIN_CONFIRM:
if (*confirmp != 0) {
error_f("confirm already set");
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
*confirmp = 1;
break;
case SSH_AGENT_CONSTRAIN_MAXSIGN:
if (k == NULL) {
error_f("maxsign not valid here");
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if (maxsign != 0) {
error_f("maxsign already set");
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if ((r = sshbuf_get_u32(m, &maxsign)) != 0) {
error_fr(r, "parse maxsign constraint");
goto out;
}
if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
error_fr(r, "enable maxsign");
goto out;
}
break;
case SSH_AGENT_CONSTRAIN_EXTENSION:
if ((r = parse_key_constraint_extension(m,
sk_providerp, dcsp, ndcsp,
cert_onlyp, certs, ncerts)) != 0)
goto out; /* error already logged */
break;
default:
error_f("Unknown constraint %d", ctype);
r = SSH_ERR_FEATURE_UNSUPPORTED;
goto out;
}
}
/* success */
r = 0;
out:
return r;
}
static void
process_add_identity(SocketEntry *e)
{
Identity *id;
int success = 0, confirm = 0;
char *fp, *comment = NULL, *sk_provider = NULL;
char canonical_provider[PATH_MAX];
time_t death = 0;
u_int seconds = 0;
struct dest_constraint *dest_constraints = NULL;
size_t ndest_constraints = 0;
struct sshkey *k = NULL;
int r = SSH_ERR_INTERNAL_ERROR;
debug2_f("entering");
if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
k == NULL ||
(r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
error_fr(r, "parse");
goto out;
}
if (parse_key_constraints(e->request, k, &death, &seconds, &confirm,
&sk_provider, &dest_constraints, &ndest_constraints,
NULL, NULL, NULL) != 0) {
error_f("failed to parse constraints");
sshbuf_reset(e->request);
goto out;
}
dump_dest_constraints(__func__, dest_constraints, ndest_constraints);
if (sk_provider != NULL) {
if (!sshkey_is_sk(k)) {
error("Cannot add provider: %s is not an "
"authenticator-hosted key", sshkey_type(k));
goto out;
}
if (strcasecmp(sk_provider, "internal") == 0) {
debug_f("internal provider");
} else {
if (socket_is_remote(e) && !remote_add_provider) {
verbose("failed add of SK provider \"%.100s\": "
"remote addition of providers is disabled",
sk_provider);
goto out;
}
if (realpath(sk_provider, canonical_provider) == NULL) {
verbose("failed provider \"%.100s\": "
"realpath: %s", sk_provider,
strerror(errno));
goto out;
}
free(sk_provider);
sk_provider = xstrdup(canonical_provider);
if (match_pattern_list(sk_provider,
allowed_providers, 0) != 1) {
error("Refusing add key: "
"provider %s not allowed", sk_provider);
goto out;
}
}
}
if ((r = sshkey_shield_private(k)) != 0) {
error_fr(r, "shield private");
goto out;
}
if (lifetime && !death)
death = monotime() + lifetime;
if ((id = lookup_identity(k)) == NULL) {
id = xcalloc(1, sizeof(Identity));
TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
/* Increment the number of identities. */
idtab->nentries++;
} else {
/* identity not visible, do not update */
if (identity_permitted(id, e, NULL, NULL, NULL) != 0)
goto out; /* error already logged */
/* key state might have been updated */
sshkey_free(id->key);
free(id->comment);
free(id->sk_provider);
free_dest_constraints(id->dest_constraints,
id->ndest_constraints);
}
/* success */
id->key = k;
id->comment = comment;
id->death = death;
id->confirm = confirm;
id->sk_provider = sk_provider;
id->dest_constraints = dest_constraints;
id->ndest_constraints = ndest_constraints;
if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
SSH_FP_DEFAULT)) == NULL)
fatal_f("sshkey_fingerprint failed");
debug_f("add %s %s \"%.100s\" (life: %u) (confirm: %u) "
"(provider: %s) (destination constraints: %zu)",
sshkey_ssh_name(k), fp, comment, seconds, confirm,
sk_provider == NULL ? "none" : sk_provider, ndest_constraints);
free(fp);
/* transferred */
k = NULL;
comment = NULL;
sk_provider = NULL;
dest_constraints = NULL;
ndest_constraints = 0;
success = 1;
out:
free(sk_provider);
free(comment);
sshkey_free(k);
free_dest_constraints(dest_constraints, ndest_constraints);
send_status(e, success);
}
/* XXX todo: encrypt sensitive data with passphrase */
static void
process_lock_agent(SocketEntry *e, int lock)
{
int r, success = 0, delay;
char *passwd;
u_char passwdhash[LOCK_SIZE];
static u_int fail_count = 0;
size_t pwlen;
debug2_f("entering");
/*
* This is deliberately fatal: the user has requested that we lock,
* but we can't parse their request properly. The only safe thing to
* do is abort.
*/
if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
fatal_fr(r, "parse");
if (pwlen == 0) {
debug("empty password not supported");
} else if (locked && !lock) {
if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
fatal("bcrypt_pbkdf");
if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
debug("agent unlocked");
locked = 0;
fail_count = 0;
explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
success = 1;
} else {
/* delay in 0.1s increments up to 10s */
if (fail_count < 100)
fail_count++;
delay = 100000 * fail_count;
debug("unlock failed, delaying %0.1lf seconds",
(double)delay/1000000);
usleep(delay);
}
explicit_bzero(passwdhash, sizeof(passwdhash));
} else if (!locked && lock) {
debug("agent locked");
locked = 1;
arc4random_buf(lock_salt, sizeof(lock_salt));
if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
fatal("bcrypt_pbkdf");
success = 1;
}
freezero(passwd, pwlen);
send_status(e, success);
}
static void
no_identities(SocketEntry *e)
{
struct sshbuf *msg;
int r;
if ((msg = sshbuf_new()) == NULL)
fatal_f("sshbuf_new failed");
if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
(r = sshbuf_put_u32(msg, 0)) != 0 ||
(r = sshbuf_put_stringb(e->output, msg)) != 0)
fatal_fr(r, "compose");
sshbuf_free(msg);
}
#ifdef ENABLE_PKCS11
/* Add an identity to idlist; takes ownership of 'key' and 'comment' */
static void
add_p11_identity(struct sshkey *key, char *comment, const char *provider,
time_t death, u_int confirm, struct dest_constraint *dest_constraints,
size_t ndest_constraints)
{
Identity *id;
if (lookup_identity(key) != NULL) {
sshkey_free(key);
free(comment);
return;
}
id = xcalloc(1, sizeof(Identity));
id->key = key;
id->comment = comment;
id->provider = xstrdup(provider);
id->death = death;
id->confirm = confirm;
id->dest_constraints = dup_dest_constraints(dest_constraints,
ndest_constraints);
id->ndest_constraints = ndest_constraints;
TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
idtab->nentries++;
}
static void
process_add_smartcard_key(SocketEntry *e)
{
char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
char **comments = NULL;
int r, i, count = 0, success = 0, confirm = 0;
u_int seconds = 0;
time_t death = 0;
struct sshkey **keys = NULL, *k;
struct dest_constraint *dest_constraints = NULL;
size_t j, ndest_constraints = 0, ncerts = 0;
struct sshkey **certs = NULL;
int cert_only = 0;
debug2_f("entering");
if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
(r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
error_fr(r, "parse");
goto send;
}
if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm,
NULL, &dest_constraints, &ndest_constraints, &cert_only,
&ncerts, &certs) != 0) {
error_f("failed to parse constraints");
goto send;
}
dump_dest_constraints(__func__, dest_constraints, ndest_constraints);
if (socket_is_remote(e) && !remote_add_provider) {
verbose("failed PKCS#11 add of \"%.100s\": remote addition of "
"providers is disabled", provider);
goto send;
}
if (realpath(provider, canonical_provider) == NULL) {
verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
provider, strerror(errno));
goto send;
}
if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
verbose("refusing PKCS#11 add of \"%.100s\": "
"provider not allowed", canonical_provider);
goto send;
}
debug_f("add %.100s", canonical_provider);
if (lifetime && !death)
death = monotime() + lifetime;
count = pkcs11_add_provider(canonical_provider, pin, &keys, &comments);
for (i = 0; i < count; i++) {
if (comments[i] == NULL || comments[i][0] == '\0') {
free(comments[i]);
comments[i] = xstrdup(canonical_provider);
}
for (j = 0; j < ncerts; j++) {
if (!sshkey_is_cert(certs[j]))
continue;
if (!sshkey_equal_public(keys[i], certs[j]))
continue;
if (pkcs11_make_cert(keys[i], certs[j], &k) != 0)
continue;
add_p11_identity(k, xstrdup(comments[i]),
canonical_provider, death, confirm,
dest_constraints, ndest_constraints);
success = 1;
}
if (!cert_only && lookup_identity(keys[i]) == NULL) {
add_p11_identity(keys[i], comments[i],
canonical_provider, death, confirm,
dest_constraints, ndest_constraints);
keys[i] = NULL; /* transferred */
comments[i] = NULL; /* transferred */
success = 1;
}
/* XXX update constraints for existing keys */
sshkey_free(keys[i]);
free(comments[i]);
}
send:
free(pin);
free(provider);
free(keys);
free(comments);
free_dest_constraints(dest_constraints, ndest_constraints);
for (j = 0; j < ncerts; j++)
sshkey_free(certs[j]);
free(certs);
send_status(e, success);
}
static void
process_remove_smartcard_key(SocketEntry *e)
{
char *provider = NULL, *pin = NULL, canonical_provider[PATH_MAX];
int r, success = 0;
Identity *id, *nxt;
debug2_f("entering");
if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
(r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
error_fr(r, "parse");
goto send;
}
free(pin);
if (realpath(provider, canonical_provider) == NULL) {
verbose("failed PKCS#11 add of \"%.100s\": realpath: %s",
provider, strerror(errno));
goto send;
}
debug_f("remove %.100s", canonical_provider);
for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
nxt = TAILQ_NEXT(id, next);
/* Skip file--based keys */
if (id->provider == NULL)
continue;
if (!strcmp(canonical_provider, id->provider)) {
TAILQ_REMOVE(&idtab->idlist, id, next);
free_identity(id);
idtab->nentries--;
}
}
if (pkcs11_del_provider(canonical_provider) == 0)
success = 1;
else
error_f("pkcs11_del_provider failed");
send:
free(provider);
send_status(e, success);
}
#endif /* ENABLE_PKCS11 */
static int
process_ext_session_bind(SocketEntry *e)
{
int r, sid_match, key_match;
struct sshkey *key = NULL;
struct sshbuf *sid = NULL, *sig = NULL;
char *fp = NULL;
size_t i;
u_char fwd = 0;
debug2_f("entering");
e->session_bind_attempted = 1;
if ((r = sshkey_froms(e->request, &key)) != 0 ||
(r = sshbuf_froms(e->request, &sid)) != 0 ||
(r = sshbuf_froms(e->request, &sig)) != 0 ||
(r = sshbuf_get_u8(e->request, &fwd)) != 0) {
error_fr(r, "parse");
goto out;
}
if (sshbuf_len(sid) > AGENT_MAX_SID_LEN) {
error_f("session ID too long");
goto out;
}
if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
SSH_FP_DEFAULT)) == NULL)
fatal_f("fingerprint failed");
/* check signature with hostkey on session ID */
if ((r = sshkey_verify(key, sshbuf_ptr(sig), sshbuf_len(sig),
sshbuf_ptr(sid), sshbuf_len(sid), NULL, 0, NULL)) != 0) {
error_fr(r, "sshkey_verify for %s %s", sshkey_type(key), fp);
goto out;
}
/* check whether sid/key already recorded */
for (i = 0; i < e->nsession_ids; i++) {
if (!e->session_ids[i].forwarded) {
error_f("attempt to bind session ID to socket "
"previously bound for authentication attempt");
r = -1;
goto out;
}
sid_match = buf_equal(sid, e->session_ids[i].sid) == 0;
key_match = sshkey_equal(key, e->session_ids[i].key);
if (sid_match && key_match) {
debug_f("session ID already recorded for %s %s",
sshkey_type(key), fp);
r = 0;
goto out;
} else if (sid_match) {
error_f("session ID recorded against different key "
"for %s %s", sshkey_type(key), fp);
r = -1;
goto out;
}
/*
* new sid with previously-seen key can happen, e.g. multiple
* connections to the same host.
*/
}
/* record new key/sid */
if (e->nsession_ids >= AGENT_MAX_SESSION_IDS) {
error_f("too many session IDs recorded");
r = -1;
goto out;
}
e->session_ids = xrecallocarray(e->session_ids, e->nsession_ids,
e->nsession_ids + 1, sizeof(*e->session_ids));
i = e->nsession_ids++;
debug_f("recorded %s %s (slot %zu of %d)", sshkey_type(key), fp, i,
AGENT_MAX_SESSION_IDS);
e->session_ids[i].key = key;
e->session_ids[i].forwarded = fwd != 0;
key = NULL; /* transferred */
/* can't transfer sid; it's refcounted and scoped to request's life */
if ((e->session_ids[i].sid = sshbuf_new()) == NULL)
fatal_f("sshbuf_new");
if ((r = sshbuf_putb(e->session_ids[i].sid, sid)) != 0)
fatal_fr(r, "sshbuf_putb session ID");
/* success */
r = 0;
out:
free(fp);
sshkey_free(key);
sshbuf_free(sid);
sshbuf_free(sig);
return r == 0 ? 1 : 0;
}
static void
process_extension(SocketEntry *e)
{
int r, success = 0;
char *name;
debug2_f("entering");
if ((r = sshbuf_get_cstring(e->request, &name, NULL)) != 0) {
error_fr(r, "parse");
goto send;
}
if (strcmp(name, "session-bind@openssh.com") == 0)
success = process_ext_session_bind(e);
else
debug_f("unsupported extension \"%s\"", name);
free(name);
send:
send_status(e, success);
}
/*
* dispatch incoming message.
* returns 1 on success, 0 for incomplete messages or -1 on error.
*/
static int
process_message(u_int socknum)
{
u_int msg_len;
u_char type;
const u_char *cp;
int r;
SocketEntry *e;
if (socknum >= sockets_alloc)
fatal_f("sock %u >= allocated %u", socknum, sockets_alloc);
e = &sockets[socknum];
if (sshbuf_len(e->input) < 5)
return 0; /* Incomplete message header. */
cp = sshbuf_ptr(e->input);
msg_len = PEEK_U32(cp);
if (msg_len > AGENT_MAX_LEN) {
debug_f("socket %u (fd=%d) message too long %u > %u",
socknum, e->fd, msg_len, AGENT_MAX_LEN);
return -1;
}
if (sshbuf_len(e->input) < msg_len + 4)
return 0; /* Incomplete message body. */
/* move the current input to e->request */
sshbuf_reset(e->request);
if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
(r = sshbuf_get_u8(e->request, &type)) != 0) {
if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
r == SSH_ERR_STRING_TOO_LARGE) {
error_fr(r, "parse");
return -1;
}
fatal_fr(r, "parse");
}
debug_f("socket %u (fd=%d) type %d", socknum, e->fd, type);
/* check whether agent is locked */
if (locked && type != SSH_AGENTC_UNLOCK) {
sshbuf_reset(e->request);
switch (type) {
case SSH2_AGENTC_REQUEST_IDENTITIES:
/* send empty lists */
no_identities(e);
break;
default:
/* send a fail message for all other request types */
send_status(e, 0);
}
return 1;
}
switch (type) {
case SSH_AGENTC_LOCK:
case SSH_AGENTC_UNLOCK:
process_lock_agent(e, type == SSH_AGENTC_LOCK);
break;
case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
process_remove_all_identities(e); /* safe for !WITH_SSH1 */
break;
/* ssh2 */
case SSH2_AGENTC_SIGN_REQUEST:
process_sign_request2(e);
break;
case SSH2_AGENTC_REQUEST_IDENTITIES:
process_request_identities(e);
break;
case SSH2_AGENTC_ADD_IDENTITY:
case SSH2_AGENTC_ADD_ID_CONSTRAINED:
process_add_identity(e);
break;
case SSH2_AGENTC_REMOVE_IDENTITY:
process_remove_identity(e);
break;
case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
process_remove_all_identities(e);
break;
#ifdef ENABLE_PKCS11
case SSH_AGENTC_ADD_SMARTCARD_KEY:
case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
process_add_smartcard_key(e);
break;
case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
process_remove_smartcard_key(e);
break;
#endif /* ENABLE_PKCS11 */
case SSH_AGENTC_EXTENSION:
process_extension(e);
break;
default:
/* Unknown message. Respond with failure. */
error("Unknown message %d", type);
sshbuf_reset(e->request);
send_status(e, 0);
break;
}
return 1;
}
static void
new_socket(sock_type type, int fd)
{
u_int i, old_alloc, new_alloc;
debug_f("type = %s", type == AUTH_CONNECTION ? "CONNECTION" :
(type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN"));
set_nonblock(fd);
if (fd > max_fd)
max_fd = fd;
for (i = 0; i < sockets_alloc; i++)
if (sockets[i].type == AUTH_UNUSED) {
sockets[i].fd = fd;
if ((sockets[i].input = sshbuf_new()) == NULL ||
(sockets[i].output = sshbuf_new()) == NULL ||
(sockets[i].request = sshbuf_new()) == NULL)
fatal_f("sshbuf_new failed");
sockets[i].type = type;
return;
}
old_alloc = sockets_alloc;
new_alloc = sockets_alloc + 10;
sockets = xrecallocarray(sockets, old_alloc, new_alloc,
sizeof(sockets[0]));
for (i = old_alloc; i < new_alloc; i++)
sockets[i].type = AUTH_UNUSED;
sockets_alloc = new_alloc;
sockets[old_alloc].fd = fd;
if ((sockets[old_alloc].input = sshbuf_new()) == NULL ||
(sockets[old_alloc].output = sshbuf_new()) == NULL ||
(sockets[old_alloc].request = sshbuf_new()) == NULL)
fatal_f("sshbuf_new failed");
sockets[old_alloc].type = type;
}
static int
handle_socket_read(u_int socknum)
{
struct sockaddr_un sunaddr;
socklen_t slen;
uid_t euid;
gid_t egid;
int fd;
slen = sizeof(sunaddr);
fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
if (fd == -1) {
error("accept from AUTH_SOCKET: %s", strerror(errno));
return -1;
}
if (getpeereid(fd, &euid, &egid) == -1) {
error("getpeereid %d failed: %s", fd, strerror(errno));
close(fd);
return -1;
}
if ((euid != 0) && (getuid() != euid)) {
error("uid mismatch: peer euid %u != uid %u",
(u_int) euid, (u_int) getuid());
close(fd);
return -1;
}
new_socket(AUTH_CONNECTION, fd);
return 0;
}
static int
handle_conn_read(u_int socknum)
{
char buf[AGENT_RBUF_LEN];
ssize_t len;
int r;
if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
if (len == -1) {
if (errno == EAGAIN || errno == EINTR)
return 0;
error_f("read error on socket %u (fd %d): %s",
socknum, sockets[socknum].fd, strerror(errno));
}
return -1;
}
if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
fatal_fr(r, "compose");
explicit_bzero(buf, sizeof(buf));
for (;;) {
if ((r = process_message(socknum)) == -1)
return -1;
else if (r == 0)
break;
}
return 0;
}
static int
handle_conn_write(u_int socknum)
{
ssize_t len;
int r;
if (sshbuf_len(sockets[socknum].output) == 0)
return 0; /* shouldn't happen */
if ((len = write(sockets[socknum].fd,
sshbuf_ptr(sockets[socknum].output),
sshbuf_len(sockets[socknum].output))) <= 0) {
if (len == -1) {
if (errno == EAGAIN || errno == EINTR)
return 0;
error_f("read error on socket %u (fd %d): %s",
socknum, sockets[socknum].fd, strerror(errno));
}
return -1;
}
if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
fatal_fr(r, "consume");
return 0;
}
static void
after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
{
size_t i;
u_int socknum, activefds = npfd;
for (i = 0; i < npfd; i++) {
if (pfd[i].revents == 0)
continue;
/* Find sockets entry */
for (socknum = 0; socknum < sockets_alloc; socknum++) {
if (sockets[socknum].type != AUTH_SOCKET &&
sockets[socknum].type != AUTH_CONNECTION)
continue;
if (pfd[i].fd == sockets[socknum].fd)
break;
}
if (socknum >= sockets_alloc) {
error_f("no socket for fd %d", pfd[i].fd);
continue;
}
/* Process events */
switch (sockets[socknum].type) {
case AUTH_SOCKET:
if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
break;
if (npfd > maxfds) {
debug3("out of fds (active %u >= limit %u); "
"skipping accept", activefds, maxfds);
break;
}
if (handle_socket_read(socknum) == 0)
activefds++;
break;
case AUTH_CONNECTION:
if ((pfd[i].revents & (POLLIN|POLLHUP|POLLERR)) != 0 &&
handle_conn_read(socknum) != 0)
goto close_sock;
if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
handle_conn_write(socknum) != 0) {
close_sock:
if (activefds == 0)
fatal("activefds == 0 at close_sock");
close_socket(&sockets[socknum]);
activefds--;
break;
}
break;
default:
break;
}
}
}
static int
prepare_poll(struct pollfd **pfdp, size_t *npfdp, struct timespec *timeoutp, u_int maxfds)
{
struct pollfd *pfd = *pfdp;
size_t i, j, npfd = 0;
time_t deadline;
int r;
/* Count active sockets */
for (i = 0; i < sockets_alloc; i++) {
switch (sockets[i].type) {
case AUTH_SOCKET:
case AUTH_CONNECTION:
npfd++;
break;
case AUTH_UNUSED:
break;
default:
fatal("Unknown socket type %d", sockets[i].type);
break;
}
}
if (npfd != *npfdp &&
(pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
fatal_f("recallocarray failed");
*pfdp = pfd;
*npfdp = npfd;
for (i = j = 0; i < sockets_alloc; i++) {
switch (sockets[i].type) {
case AUTH_SOCKET:
if (npfd > maxfds) {
debug3("out of fds (active %zu >= limit %u); "
"skipping arming listener", npfd, maxfds);
break;
}
pfd[j].fd = sockets[i].fd;
pfd[j].revents = 0;
pfd[j].events = POLLIN;
j++;
break;
case AUTH_CONNECTION:
pfd[j].fd = sockets[i].fd;
pfd[j].revents = 0;
/*
* Only prepare to read if we can handle a full-size
* input read buffer and enqueue a max size reply..
*/
if ((r = sshbuf_check_reserve(sockets[i].input,
AGENT_RBUF_LEN)) == 0 &&
(r = sshbuf_check_reserve(sockets[i].output,
AGENT_MAX_LEN)) == 0)
pfd[j].events = POLLIN;
else if (r != SSH_ERR_NO_BUFFER_SPACE)
fatal_fr(r, "reserve");
if (sshbuf_len(sockets[i].output) > 0)
pfd[j].events |= POLLOUT;
j++;
break;
default:
break;
}
}
deadline = reaper();
if (parent_alive_interval != 0)
deadline = (deadline == 0) ? parent_alive_interval :
MINIMUM(deadline, parent_alive_interval);
if (deadline != 0)
ptimeout_deadline_sec(timeoutp, deadline);
return (1);
}
static void
cleanup_socket(void)
{
if (cleanup_pid != 0 && getpid() != cleanup_pid)
return;
debug_f("cleanup");
if (socket_name[0])
unlink(socket_name);
if (socket_dir[0])
rmdir(socket_dir);
}
void
cleanup_exit(int i)
{
cleanup_socket();
#ifdef ENABLE_PKCS11
pkcs11_terminate();
#endif
_exit(i);
}
static void
cleanup_handler(int sig)
{
signalled_exit = sig;
}
static void
keydrop_handler(int sig)
{
signalled_keydrop = sig;
}
static void
check_parent_exists(void)
{
/*
* If our parent has exited then getppid() will return (pid_t)1,
* so testing for that should be safe.
*/
if (parent_pid != -1 && getppid() != parent_pid) {
/* printf("Parent has died - Authentication agent exiting.\n"); */
cleanup_socket();
_exit(2);
}
}
static void
usage(void)
{
fprintf(stderr,
"usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
" [-O option] [-P allowed_providers] [-t life]\n"
" ssh-agent [-a bind_address] [-E fingerprint_hash] [-O option]\n"
" [-P allowed_providers] [-t life] command [arg ...]\n"
" ssh-agent [-c | -s] -k\n");
exit(1);
}
int
main(int ac, char **av)
{
int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
int sock = -1, ch, result, saved_errno;
char *shell, *format, *fdstr, *pidstr, *agentsocket = NULL;
const char *errstr = NULL;
const char *ccp;
#ifdef HAVE_SETRLIMIT
struct rlimit rlim;
#endif
extern int optind;
extern char *optarg;
pid_t pid;
char pidstrbuf[1 + 3 * sizeof pid];
size_t len;
mode_t prev_mask;
struct timespec timeout;
struct pollfd *pfd = NULL;
size_t npfd = 0;
u_int maxfds;
sigset_t nsigset, osigset;
/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
sanitise_stdfd();
/* drop */
(void)setegid(getgid());
(void)setgid(getgid());
platform_disable_tracing(0); /* strict=no */
#ifdef RLIMIT_NOFILE
if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
fatal("%s: getrlimit: %s", __progname, strerror(errno));
#endif
__progname = ssh_get_progname(av[0]);
seed_rng();
while ((ch = getopt(ac, av, "cDdksE:a:O:P:t:")) != -1) {
switch (ch) {
case 'E':
fingerprint_hash = ssh_digest_alg_by_name(optarg);
if (fingerprint_hash == -1)
fatal("Invalid hash algorithm \"%s\"", optarg);
break;
case 'c':
if (s_flag)
usage();
c_flag++;
break;
case 'k':
k_flag++;
break;
case 'O':
if (strcmp(optarg, "no-restrict-websafe") == 0)
restrict_websafe = 0;
else if (strcmp(optarg, "allow-remote-pkcs11") == 0)
remote_add_provider = 1;
else if ((ccp = strprefix(optarg,
"websafe-allow=", 0)) != NULL) {
if (websafe_allowlist != NULL)
fatal("websafe-allow already set");
websafe_allowlist = xstrdup(ccp);
} else
fatal("Unknown -O option");
break;
case 'P':
if (allowed_providers != NULL)
fatal("-P option already specified");
allowed_providers = xstrdup(optarg);
break;
case 's':
if (c_flag)
usage();
s_flag++;
break;
case 'd':
if (d_flag || D_flag)
usage();
d_flag++;
break;
case 'D':
if (d_flag || D_flag)
usage();
D_flag++;
break;
case 'a':
agentsocket = optarg;
break;
case 't':
if ((lifetime = convtime(optarg)) == -1) {
fprintf(stderr, "Invalid lifetime\n");
usage();
}
break;
default:
usage();
}
}
ac -= optind;
av += optind;
if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
usage();
if (allowed_providers == NULL)
allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS);
if (websafe_allowlist == NULL)
websafe_allowlist = xstrdup(DEFAULT_WEBSAFE_ALLOWLIST);
if (ac == 0 && !c_flag && !s_flag) {
shell = getenv("SHELL");
if (shell != NULL && (len = strlen(shell)) > 2 &&
strncmp(shell + len - 3, "csh", 3) == 0)
c_flag = 1;
}
if (k_flag) {
pidstr = getenv(SSH_AGENTPID_ENV_NAME);
if (pidstr == NULL) {
fprintf(stderr, "%s not set, cannot kill agent\n",
SSH_AGENTPID_ENV_NAME);
exit(1);
}
pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
if (errstr) {
fprintf(stderr,
"%s=\"%s\", which is not a good PID: %s\n",
SSH_AGENTPID_ENV_NAME, pidstr, errstr);
exit(1);
}
if (kill(pid, SIGTERM) == -1) {
perror("kill");
exit(1);
}
format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
printf(format, SSH_AUTHSOCKET_ENV_NAME);
printf(format, SSH_AGENTPID_ENV_NAME);
printf("echo Agent pid %ld killed;\n", (long)pid);
exit(0);
}
/*
* Minimum file descriptors:
* stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
* a few spare for libc / stack protectors / sanitisers, etc.
*/
#define SSH_AGENT_MIN_FDS (3+1+1+1+4)
if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
__progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
parent_pid = getpid();
/* Has the socket been provided via socket activation? */
if (agentsocket == NULL && ac == 0 && (d_flag || D_flag) &&
(pidstr = getenv("LISTEN_PID")) != NULL &&
(fdstr = getenv("LISTEN_FDS")) != NULL) {
if (strcmp(fdstr, "1") != 0) {
fatal("unexpected LISTEN_FDS contents "
"(want: \"1\" got\"%s\"", fdstr);
}
if (fcntl(3, F_GETFL) == -1)
fatal("LISTEN_FDS set but fd 3 unavailable");
pid = (int)strtonum(pidstr, 1, INT_MAX, &errstr);
if (errstr != NULL)
fatal("invalid LISTEN_PID: %s", errstr);
if (pid != getpid())
fatal("bad LISTEN_PID: %d vs pid %d", pid, getpid());
debug("using socket activation on fd=3");
sock = 3;
}
/* Otherwise, create private directory for agent socket */
if (sock == -1) {
if (agentsocket == NULL) {
mktemp_proto(socket_dir, sizeof(socket_dir));
if (mkdtemp(socket_dir) == NULL) {
perror("mkdtemp: private socket dir");
exit(1);
}
snprintf(socket_name, sizeof socket_name,
"%s/agent.%ld", socket_dir,
(long)parent_pid);
} else {
/* Try to use specified agent socket */
socket_dir[0] = '\0';
strlcpy(socket_name, agentsocket, sizeof socket_name);
}
}
closefrom(sock == -1 ? STDERR_FILENO + 1 : sock + 1);
/*
* Create socket early so it will exist before command gets run from
* the parent.
*/
if (sock == -1) {
prev_mask = umask(0177);
sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
if (sock < 0) {
/* XXX - unix_listener() calls error() not perror() */
*socket_name = '\0'; /* Don't unlink existing file */
cleanup_exit(1);
}
umask(prev_mask);
}
/*
* Fork, and have the parent execute the command, if any, or present
* the socket data. The child continues as the authentication agent.
*/
if (D_flag || d_flag) {
log_init(__progname,
d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
SYSLOG_FACILITY_AUTH, 1);
if (socket_name[0] != '\0') {
format = c_flag ?
"setenv %s %s;\n" : "%s=%s; export %s;\n";
printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
SSH_AUTHSOCKET_ENV_NAME);
printf("echo Agent pid %ld;\n", (long)parent_pid);
fflush(stdout);
}
goto skip;
}
pid = fork();
if (pid == -1) {
perror("fork");
cleanup_exit(1);
}
if (pid != 0) { /* Parent - execute the given command. */
close(sock);
snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
if (ac == 0) {
format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
SSH_AUTHSOCKET_ENV_NAME);
printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
SSH_AGENTPID_ENV_NAME);
printf("echo Agent pid %ld;\n", (long)pid);
exit(0);
}
if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
perror("setenv");
exit(1);
}
execvp(av[0], av);
perror(av[0]);
exit(1);
}
/* child */
log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
if (setsid() == -1) {
error("setsid: %s", strerror(errno));
cleanup_exit(1);
}
(void)chdir("/");
if (stdfd_devnull(1, 1, 1) == -1)
error_f("stdfd_devnull failed");
#ifdef HAVE_SETRLIMIT
/* deny core dumps, since memory contains unencrypted private keys */
rlim.rlim_cur = rlim.rlim_max = 0;
if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
error("setrlimit RLIMIT_CORE: %s", strerror(errno));
cleanup_exit(1);
}
#endif
skip:
cleanup_pid = getpid();
#ifdef ENABLE_PKCS11
pkcs11_init(0);
#endif
new_socket(AUTH_SOCKET, sock);
if (ac > 0)
parent_alive_interval = 10;
idtab_init();
ssh_signal(SIGPIPE, SIG_IGN);
ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
ssh_signal(SIGHUP, cleanup_handler);
ssh_signal(SIGTERM, cleanup_handler);
ssh_signal(SIGUSR1, keydrop_handler);
sigemptyset(&nsigset);
sigaddset(&nsigset, SIGINT);
sigaddset(&nsigset, SIGHUP);
sigaddset(&nsigset, SIGTERM);
sigaddset(&nsigset, SIGUSR1);
if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
fatal("%s: pledge: %s", __progname, strerror(errno));
platform_pledge_agent();
while (1) {
sigprocmask(SIG_BLOCK, &nsigset, &osigset);
if (signalled_exit != 0) {
logit("exiting on signal %d", (int)signalled_exit);
cleanup_exit(2);
}
if (signalled_keydrop) {
logit("signal %d received; removing all keys",
signalled_keydrop);
remove_all_identities();
signalled_keydrop = 0;
}
ptimeout_init(&timeout);
prepare_poll(&pfd, &npfd, &timeout, maxfds);
result = ppoll(pfd, npfd, ptimeout_get_tsp(&timeout), &osigset);
sigprocmask(SIG_SETMASK, &osigset, NULL);
saved_errno = errno;
if (parent_alive_interval != 0)
check_parent_exists();
(void) reaper(); /* remove expired keys */
if (result == -1) {
if (saved_errno == EINTR)
continue;
fatal("poll: %s", strerror(saved_errno));
} else if (result > 0)
after_poll(pfd, npfd, maxfds);
}
/* NOTREACHED */
}
|