ssh-agent.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719
  1. /* $OpenBSD: ssh-agent.c,v 1.264 2020/09/18 08:16:38 djm Exp $ */
  2. /*
  3. * Author: Tatu Ylonen <ylo@cs.hut.fi>
  4. * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
  5. * All rights reserved
  6. * The authentication agent program.
  7. *
  8. * As far as I am concerned, the code I have written for this software
  9. * can be used freely for any purpose. Any derived versions of this
  10. * software must be clearly marked as such, and if the derived work is
  11. * incompatible with the protocol description in the RFC file, it must be
  12. * called by a name other than "ssh" or "Secure Shell".
  13. *
  14. * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
  15. *
  16. * Redistribution and use in source and binary forms, with or without
  17. * modification, are permitted provided that the following conditions
  18. * are met:
  19. * 1. Redistributions of source code must retain the above copyright
  20. * notice, this list of conditions and the following disclaimer.
  21. * 2. Redistributions in binary form must reproduce the above copyright
  22. * notice, this list of conditions and the following disclaimer in the
  23. * documentation and/or other materials provided with the distribution.
  24. *
  25. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  26. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  27. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  28. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  29. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  30. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  31. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  32. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  33. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  34. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  35. */
  36. #include "includes.h"
  37. #include <sys/types.h>
  38. #include <sys/param.h>
  39. #include <sys/resource.h>
  40. #include <sys/stat.h>
  41. #include <sys/socket.h>
  42. #include <sys/wait.h>
  43. #ifdef HAVE_SYS_TIME_H
  44. # include <sys/time.h>
  45. #endif
  46. #ifdef HAVE_SYS_UN_H
  47. # include <sys/un.h>
  48. #endif
  49. #include "openbsd-compat/sys-queue.h"
  50. #ifdef WITH_OPENSSL
  51. #include <openssl/evp.h>
  52. #include "openbsd-compat/openssl-compat.h"
  53. #endif
  54. #include <errno.h>
  55. #include <fcntl.h>
  56. #include <limits.h>
  57. #ifdef HAVE_PATHS_H
  58. # include <paths.h>
  59. #endif
  60. #ifdef HAVE_POLL_H
  61. # include <poll.h>
  62. #endif
  63. #include <signal.h>
  64. #include <stdarg.h>
  65. #include <stdio.h>
  66. #include <stdlib.h>
  67. #include <time.h>
  68. #include <string.h>
  69. #include <unistd.h>
  70. #ifdef HAVE_UTIL_H
  71. # include <util.h>
  72. #endif
  73. #include "xmalloc.h"
  74. #include "ssh.h"
  75. #include "ssh2.h"
  76. #include "sshbuf.h"
  77. #include "sshkey.h"
  78. #include "authfd.h"
  79. #include "compat.h"
  80. #include "log.h"
  81. #include "misc.h"
  82. #include "digest.h"
  83. #include "ssherr.h"
  84. #include "match.h"
  85. #include "msg.h"
  86. #include "ssherr.h"
  87. #include "pathnames.h"
  88. #include "ssh-pkcs11.h"
  89. #include "sk-api.h"
  90. #ifndef DEFAULT_ALLOWED_PROVIDERS
  91. # define DEFAULT_ALLOWED_PROVIDERS "/usr/lib*/*,/usr/local/lib*/*"
  92. #endif
  93. /* Maximum accepted message length */
  94. #define AGENT_MAX_LEN (256*1024)
  95. /* Maximum bytes to read from client socket */
  96. #define AGENT_RBUF_LEN (4096)
  97. typedef enum {
  98. AUTH_UNUSED = 0,
  99. AUTH_SOCKET = 1,
  100. AUTH_CONNECTION = 2,
  101. } sock_type;
  102. typedef struct socket_entry {
  103. int fd;
  104. sock_type type;
  105. struct sshbuf *input;
  106. struct sshbuf *output;
  107. struct sshbuf *request;
  108. } SocketEntry;
  109. u_int sockets_alloc = 0;
  110. SocketEntry *sockets = NULL;
  111. typedef struct identity {
  112. TAILQ_ENTRY(identity) next;
  113. struct sshkey *key;
  114. char *comment;
  115. char *provider;
  116. time_t death;
  117. u_int confirm;
  118. char *sk_provider;
  119. } Identity;
  120. struct idtable {
  121. int nentries;
  122. TAILQ_HEAD(idqueue, identity) idlist;
  123. };
  124. /* private key table */
  125. struct idtable *idtab;
  126. int max_fd = 0;
  127. /* pid of shell == parent of agent */
  128. pid_t parent_pid = -1;
  129. time_t parent_alive_interval = 0;
  130. /* pid of process for which cleanup_socket is applicable */
  131. pid_t cleanup_pid = 0;
  132. /* pathname and directory for AUTH_SOCKET */
  133. char socket_name[PATH_MAX];
  134. char socket_dir[PATH_MAX];
  135. /* Pattern-list of allowed PKCS#11/Security key paths */
  136. static char *allowed_providers;
  137. /* locking */
  138. #define LOCK_SIZE 32
  139. #define LOCK_SALT_SIZE 16
  140. #define LOCK_ROUNDS 1
  141. int locked = 0;
  142. u_char lock_pwhash[LOCK_SIZE];
  143. u_char lock_salt[LOCK_SALT_SIZE];
  144. extern char *__progname;
  145. /* Default lifetime in seconds (0 == forever) */
  146. static int lifetime = 0;
  147. static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
  148. /* Refuse signing of non-SSH messages for web-origin FIDO keys */
  149. static int restrict_websafe = 1;
  150. static void
  151. close_socket(SocketEntry *e)
  152. {
  153. close(e->fd);
  154. sshbuf_free(e->input);
  155. sshbuf_free(e->output);
  156. sshbuf_free(e->request);
  157. memset(e, '\0', sizeof(*e));
  158. e->fd = -1;
  159. e->type = AUTH_UNUSED;
  160. }
  161. static void
  162. idtab_init(void)
  163. {
  164. idtab = xcalloc(1, sizeof(*idtab));
  165. TAILQ_INIT(&idtab->idlist);
  166. idtab->nentries = 0;
  167. }
  168. static void
  169. free_identity(Identity *id)
  170. {
  171. sshkey_free(id->key);
  172. free(id->provider);
  173. free(id->comment);
  174. free(id->sk_provider);
  175. free(id);
  176. }
  177. /* return matching private key for given public key */
  178. static Identity *
  179. lookup_identity(struct sshkey *key)
  180. {
  181. Identity *id;
  182. TAILQ_FOREACH(id, &idtab->idlist, next) {
  183. if (sshkey_equal(key, id->key))
  184. return (id);
  185. }
  186. return (NULL);
  187. }
  188. /* Check confirmation of keysign request */
  189. static int
  190. confirm_key(Identity *id, const char *extra)
  191. {
  192. char *p;
  193. int ret = -1;
  194. p = sshkey_fingerprint(id->key, fingerprint_hash, SSH_FP_DEFAULT);
  195. if (p != NULL &&
  196. ask_permission("Allow use of key %s?\nKey fingerprint %s.%s%s",
  197. id->comment, p,
  198. extra == NULL ? "" : "\n", extra == NULL ? "" : extra))
  199. ret = 0;
  200. free(p);
  201. return (ret);
  202. }
  203. static void
  204. send_status(SocketEntry *e, int success)
  205. {
  206. int r;
  207. if ((r = sshbuf_put_u32(e->output, 1)) != 0 ||
  208. (r = sshbuf_put_u8(e->output, success ?
  209. SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
  210. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  211. }
  212. /* send list of supported public keys to 'client' */
  213. static void
  214. process_request_identities(SocketEntry *e)
  215. {
  216. Identity *id;
  217. struct sshbuf *msg;
  218. int r;
  219. debug2("entering");
  220. if ((msg = sshbuf_new()) == NULL)
  221. fatal("%s: sshbuf_new failed", __func__);
  222. if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
  223. (r = sshbuf_put_u32(msg, idtab->nentries)) != 0)
  224. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  225. TAILQ_FOREACH(id, &idtab->idlist, next) {
  226. if ((r = sshkey_puts_opts(id->key, msg, SSHKEY_SERIALIZE_INFO))
  227. != 0 ||
  228. (r = sshbuf_put_cstring(msg, id->comment)) != 0) {
  229. error("%s: put key/comment: %s", __func__,
  230. ssh_err(r));
  231. continue;
  232. }
  233. }
  234. if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
  235. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  236. sshbuf_free(msg);
  237. }
  238. static char *
  239. agent_decode_alg(struct sshkey *key, u_int flags)
  240. {
  241. if (key->type == KEY_RSA) {
  242. if (flags & SSH_AGENT_RSA_SHA2_256)
  243. return "rsa-sha2-256";
  244. else if (flags & SSH_AGENT_RSA_SHA2_512)
  245. return "rsa-sha2-512";
  246. } else if (key->type == KEY_RSA_CERT) {
  247. if (flags & SSH_AGENT_RSA_SHA2_256)
  248. return "rsa-sha2-256-cert-v01@openssh.com";
  249. else if (flags & SSH_AGENT_RSA_SHA2_512)
  250. return "rsa-sha2-512-cert-v01@openssh.com";
  251. }
  252. return NULL;
  253. }
  254. /*
  255. * This function inspects a message to be signed by a FIDO key that has a
  256. * web-like application string (i.e. one that does not begin with "ssh:".
  257. * It checks that the message is one of those expected for SSH operations
  258. * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
  259. * for the web.
  260. */
  261. static int
  262. parse_userauth_request(struct sshbuf *msg, const struct sshkey *expected_key,
  263. char **userp, struct sshbuf **sess_idp)
  264. {
  265. struct sshbuf *b = NULL, *sess_id = NULL;
  266. char *user = NULL, *service = NULL, *method = NULL, *pkalg = NULL;
  267. int r;
  268. u_char t, sig_follows;
  269. struct sshkey *mkey = NULL;
  270. if (userp != NULL)
  271. *userp = NULL;
  272. if (sess_idp != NULL)
  273. *sess_idp = NULL;
  274. if ((b = sshbuf_fromb(msg)) == NULL)
  275. fatal("sshbuf_fromb");
  276. /* SSH userauth request */
  277. if ((r = sshbuf_froms(b, &sess_id)) != 0)
  278. goto out;
  279. if (sshbuf_len(sess_id) == 0) {
  280. r = SSH_ERR_INVALID_FORMAT;
  281. goto out;
  282. }
  283. if ((r = sshbuf_get_u8(b, &t)) != 0 || /* SSH2_MSG_USERAUTH_REQUEST */
  284. (r = sshbuf_get_cstring(b, &user, NULL)) != 0 || /* server user */
  285. (r = sshbuf_get_cstring(b, &service, NULL)) != 0 || /* service */
  286. (r = sshbuf_get_cstring(b, &method, NULL)) != 0 || /* method */
  287. (r = sshbuf_get_u8(b, &sig_follows)) != 0 || /* sig-follows */
  288. (r = sshbuf_get_cstring(b, &pkalg, NULL)) != 0 || /* alg */
  289. (r = sshkey_froms(b, &mkey)) != 0) /* key */
  290. goto out;
  291. if (t != SSH2_MSG_USERAUTH_REQUEST ||
  292. sig_follows != 1 ||
  293. strcmp(service, "ssh-connection") != 0 ||
  294. !sshkey_equal(expected_key, mkey) ||
  295. sshkey_type_from_name(pkalg) != expected_key->type) {
  296. r = SSH_ERR_INVALID_FORMAT;
  297. goto out;
  298. }
  299. if (strcmp(method, "publickey") != 0) {
  300. r = SSH_ERR_INVALID_FORMAT;
  301. goto out;
  302. }
  303. if (sshbuf_len(b) != 0) {
  304. r = SSH_ERR_INVALID_FORMAT;
  305. goto out;
  306. }
  307. /* success */
  308. r = 0;
  309. debug3("well formed userauth");
  310. if (userp != NULL) {
  311. *userp = user;
  312. user = NULL;
  313. }
  314. if (sess_idp != NULL) {
  315. *sess_idp = sess_id;
  316. sess_id = NULL;
  317. }
  318. out:
  319. sshbuf_free(b);
  320. sshbuf_free(sess_id);
  321. free(user);
  322. free(service);
  323. free(method);
  324. free(pkalg);
  325. sshkey_free(mkey);
  326. return r;
  327. }
  328. /*
  329. * Attempt to parse the contents of a buffer as a SSHSIG signature request.
  330. * Note: does not modify buffer.
  331. */
  332. static int
  333. parse_sshsig_request(struct sshbuf *msg)
  334. {
  335. int r;
  336. struct sshbuf *b;
  337. if ((b = sshbuf_fromb(msg)) == NULL)
  338. fatal("sshbuf_fromb");
  339. if ((r = sshbuf_cmp(b, 0, "SSHSIG", 6)) != 0 ||
  340. (r = sshbuf_consume(b, 6)) != 0 ||
  341. (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* namespace */
  342. (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0 || /* reserved */
  343. (r = sshbuf_get_cstring(b, NULL, NULL)) != 0 || /* hashalg */
  344. (r = sshbuf_get_string_direct(b, NULL, NULL)) != 0) /* H(msg) */
  345. goto out;
  346. if (sshbuf_len(b) != 0) {
  347. r = SSH_ERR_INVALID_FORMAT;
  348. goto out;
  349. }
  350. /* success */
  351. r = 0;
  352. out:
  353. sshbuf_free(b);
  354. return r;
  355. }
  356. /*
  357. * This function inspects a message to be signed by a FIDO key that has a
  358. * web-like application string (i.e. one that does not begin with "ssh:".
  359. * It checks that the message is one of those expected for SSH operations
  360. * (pubkey userauth, sshsig, CA key signing) to exclude signing challenges
  361. * for the web.
  362. */
  363. static int
  364. check_websafe_message_contents(struct sshkey *key, struct sshbuf *data)
  365. {
  366. if (parse_userauth_request(data, key, NULL, NULL) == 0) {
  367. debug("signed data matches public key userauth request");
  368. return 1;
  369. }
  370. if (parse_sshsig_request(data) == 0) {
  371. debug("signed data matches SSHSIG signature request");
  372. return 1;
  373. }
  374. /* XXX check CA signature operation */
  375. error("web-origin key attempting to sign non-SSH message");
  376. return 0;
  377. }
  378. /* ssh2 only */
  379. static void
  380. process_sign_request2(SocketEntry *e)
  381. {
  382. u_char *signature = NULL;
  383. size_t slen = 0;
  384. u_int compat = 0, flags;
  385. int r, ok = -1;
  386. char *fp = NULL;
  387. struct sshbuf *msg = NULL, *data = NULL;
  388. struct sshkey *key = NULL;
  389. struct identity *id;
  390. struct notifier_ctx *notifier = NULL;
  391. debug("entering");
  392. if ((msg = sshbuf_new()) == NULL || (data = sshbuf_new()) == NULL)
  393. fatal("%s: sshbuf_new failed", __func__);
  394. if ((r = sshkey_froms(e->request, &key)) != 0 ||
  395. (r = sshbuf_get_stringb(e->request, data)) != 0 ||
  396. (r = sshbuf_get_u32(e->request, &flags)) != 0) {
  397. error("%s: couldn't parse request: %s", __func__, ssh_err(r));
  398. goto send;
  399. }
  400. if ((id = lookup_identity(key)) == NULL) {
  401. verbose("%s: %s key not found", __func__, sshkey_type(key));
  402. goto send;
  403. }
  404. if (id->confirm && confirm_key(id, NULL) != 0) {
  405. verbose("%s: user refused key", __func__);
  406. goto send;
  407. }
  408. if (sshkey_is_sk(id->key)) {
  409. if (strncmp(id->key->sk_application, "ssh:", 4) != 0 &&
  410. !check_websafe_message_contents(key, data)) {
  411. /* error already logged */
  412. goto send;
  413. }
  414. if ((id->key->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
  415. if ((fp = sshkey_fingerprint(key, SSH_FP_HASH_DEFAULT,
  416. SSH_FP_DEFAULT)) == NULL)
  417. fatal("%s: fingerprint failed", __func__);
  418. notifier = notify_start(0,
  419. "Confirm user presence for key %s %s",
  420. sshkey_type(id->key), fp);
  421. }
  422. }
  423. /* XXX support PIN required FIDO keys */
  424. if ((r = sshkey_sign(id->key, &signature, &slen,
  425. sshbuf_ptr(data), sshbuf_len(data), agent_decode_alg(key, flags),
  426. id->sk_provider, NULL, compat)) != 0) {
  427. error("%s: sshkey_sign: %s", __func__, ssh_err(r));
  428. goto send;
  429. }
  430. /* Success */
  431. ok = 0;
  432. send:
  433. //notify_complete(notifier, "User presence confirmed");
  434. if (ok == 0) {
  435. if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
  436. (r = sshbuf_put_string(msg, signature, slen)) != 0)
  437. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  438. } else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
  439. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  440. if ((r = sshbuf_put_stringb(e->output, msg)) != 0)
  441. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  442. sshbuf_free(data);
  443. sshbuf_free(msg);
  444. sshkey_free(key);
  445. free(fp);
  446. free(signature);
  447. }
  448. /* shared */
  449. static void
  450. process_remove_identity(SocketEntry *e)
  451. {
  452. int r, success = 0;
  453. struct sshkey *key = NULL;
  454. Identity *id;
  455. debug2("entering");
  456. if ((r = sshkey_froms(e->request, &key)) != 0) {
  457. error("%s: get key: %s", __func__, ssh_err(r));
  458. goto done;
  459. }
  460. if ((id = lookup_identity(key)) == NULL) {
  461. debug("%s: key not found", __func__);
  462. goto done;
  463. }
  464. /* We have this key, free it. */
  465. if (idtab->nentries < 1)
  466. fatal("%s: internal error: nentries %d",
  467. __func__, idtab->nentries);
  468. TAILQ_REMOVE(&idtab->idlist, id, next);
  469. free_identity(id);
  470. idtab->nentries--;
  471. success = 1;
  472. done:
  473. sshkey_free(key);
  474. send_status(e, success);
  475. }
  476. static void
  477. process_remove_all_identities(SocketEntry *e)
  478. {
  479. Identity *id;
  480. debug2("entering");
  481. /* Loop over all identities and clear the keys. */
  482. for (id = TAILQ_FIRST(&idtab->idlist); id;
  483. id = TAILQ_FIRST(&idtab->idlist)) {
  484. TAILQ_REMOVE(&idtab->idlist, id, next);
  485. free_identity(id);
  486. }
  487. /* Mark that there are no identities. */
  488. idtab->nentries = 0;
  489. /* Send success. */
  490. send_status(e, 1);
  491. }
  492. /* removes expired keys and returns number of seconds until the next expiry */
  493. static time_t
  494. reaper(void)
  495. {
  496. time_t deadline = 0, now = monotime();
  497. Identity *id, *nxt;
  498. for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
  499. nxt = TAILQ_NEXT(id, next);
  500. if (id->death == 0)
  501. continue;
  502. if (now >= id->death) {
  503. debug("expiring key '%s'", id->comment);
  504. TAILQ_REMOVE(&idtab->idlist, id, next);
  505. free_identity(id);
  506. idtab->nentries--;
  507. } else
  508. deadline = (deadline == 0) ? id->death :
  509. MINIMUM(deadline, id->death);
  510. }
  511. if (deadline == 0 || deadline <= now)
  512. return 0;
  513. else
  514. return (deadline - now);
  515. }
  516. static int
  517. parse_key_constraint_extension(struct sshbuf *m, char **sk_providerp)
  518. {
  519. char *ext_name = NULL;
  520. int r;
  521. if ((r = sshbuf_get_cstring(m, &ext_name, NULL)) != 0) {
  522. error(r, "parse constraint extension");
  523. goto out;
  524. }
  525. debug("constraint ext %s", ext_name);
  526. if (strcmp(ext_name, "sk-provider@openssh.com") == 0) {
  527. if (sk_providerp == NULL) {
  528. error("%s not valid here", ext_name);
  529. r = SSH_ERR_INVALID_FORMAT;
  530. goto out;
  531. }
  532. if (*sk_providerp != NULL) {
  533. error("%s already set", ext_name);
  534. r = SSH_ERR_INVALID_FORMAT;
  535. goto out;
  536. }
  537. if ((r = sshbuf_get_cstring(m, sk_providerp, NULL)) != 0) {
  538. error(r, "parse %s", ext_name);
  539. goto out;
  540. }
  541. } else {
  542. error("unsupported constraint \"%s\"", ext_name);
  543. r = SSH_ERR_FEATURE_UNSUPPORTED;
  544. goto out;
  545. }
  546. /* success */
  547. r = 0;
  548. out:
  549. free(ext_name);
  550. return r;
  551. }
  552. static int
  553. parse_key_constraints(struct sshbuf *m, struct sshkey *k, time_t *deathp,
  554. u_int *secondsp, int *confirmp, char **sk_providerp)
  555. {
  556. u_char ctype;
  557. int r;
  558. u_int seconds, maxsign = 0;
  559. while (sshbuf_len(m)) {
  560. if ((r = sshbuf_get_u8(m, &ctype)) != 0) {
  561. error("%s: buffer error: %s", __func__, ssh_err(r));
  562. goto out;
  563. }
  564. switch (ctype) {
  565. case SSH_AGENT_CONSTRAIN_LIFETIME:
  566. if (*deathp != 0) {
  567. error("lifetime already set");
  568. r = SSH_ERR_INVALID_FORMAT;
  569. goto out;
  570. }
  571. if ((r = sshbuf_get_u32(m, &seconds)) != 0) {
  572. error(r, "parse lifetime constraint");
  573. goto out;
  574. }
  575. *deathp = monotime() + seconds;
  576. *secondsp = seconds;
  577. break;
  578. case SSH_AGENT_CONSTRAIN_CONFIRM:
  579. if (*confirmp != 0) {
  580. error("confirm already set");
  581. r = SSH_ERR_INVALID_FORMAT;
  582. goto out;
  583. }
  584. *confirmp = 1;
  585. break;
  586. case SSH_AGENT_CONSTRAIN_MAXSIGN:
  587. if (k == NULL) {
  588. error("maxsign not valid here");
  589. r = SSH_ERR_INVALID_FORMAT;
  590. goto out;
  591. }
  592. if (maxsign != 0) {
  593. error("maxsign already set");
  594. r = SSH_ERR_INVALID_FORMAT;
  595. goto out;
  596. }
  597. if ((r = sshbuf_get_u32(m, &maxsign)) != 0) {
  598. error("%s: bad maxsign constraint: %s",
  599. __func__, ssh_err(r));
  600. goto out;
  601. }
  602. if ((r = sshkey_enable_maxsign(k, maxsign)) != 0) {
  603. error("%s: cannot enable maxsign: %s",
  604. __func__, ssh_err(r));
  605. goto out;
  606. }
  607. break;
  608. if ((r = parse_key_constraint_extension(m,
  609. sk_providerp)) != 0)
  610. goto out; /* error already logged */
  611. break;
  612. default:
  613. error("%s: Unknown constraint %d", __func__, ctype);
  614. r = SSH_ERR_FEATURE_UNSUPPORTED;
  615. goto out;
  616. }
  617. }
  618. /* success */
  619. r = 0;
  620. out:
  621. return r;
  622. }
  623. static void
  624. process_add_identity(SocketEntry *e)
  625. {
  626. Identity *id;
  627. int success = 0, confirm = 0;
  628. char *fp, *comment = NULL, *sk_provider = NULL;
  629. char canonical_provider[PATH_MAX];
  630. time_t death = 0;
  631. u_int seconds = 0;
  632. struct sshkey *k = NULL;
  633. int r = SSH_ERR_INTERNAL_ERROR;
  634. debug2("entering");
  635. if ((r = sshkey_private_deserialize(e->request, &k)) != 0 ||
  636. k == NULL ||
  637. (r = sshbuf_get_cstring(e->request, &comment, NULL)) != 0) {
  638. error(r, "parse");
  639. goto out;
  640. }
  641. if (parse_key_constraints(e->request, k, &death, &seconds, &confirm,
  642. &sk_provider) != 0) {
  643. error("failed to parse constraints");
  644. sshbuf_reset(e->request);
  645. goto out;
  646. }
  647. if (sk_provider != NULL) {
  648. if (!sshkey_is_sk(k)) {
  649. error("Cannot add provider: %s is not an "
  650. "authenticator-hosted key", sshkey_type(k));
  651. goto out;
  652. }
  653. if (strcasecmp(sk_provider, "internal") == 0) {
  654. debug("%s: internal provider", __func__);
  655. } else {
  656. if (realpath(sk_provider, canonical_provider) == NULL) {
  657. verbose("failed provider \"%.100s\": "
  658. "realpath: %s", sk_provider,
  659. strerror(errno));
  660. goto out;
  661. }
  662. free(sk_provider);
  663. sk_provider = xstrdup(canonical_provider);
  664. if (match_pattern_list(sk_provider,
  665. allowed_providers, 0) != 1) {
  666. error("Refusing add key: "
  667. "provider %s not allowed", sk_provider);
  668. goto out;
  669. }
  670. }
  671. }
  672. if ((r = sshkey_shield_private(k)) != 0) {
  673. error("%s: shield private key: %s", __func__, ssh_err(r));
  674. goto out;
  675. }
  676. if (lifetime && !death)
  677. death = monotime() + lifetime;
  678. if ((id = lookup_identity(k)) == NULL) {
  679. id = xcalloc(1, sizeof(Identity));
  680. TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
  681. /* Increment the number of identities. */
  682. idtab->nentries++;
  683. } else {
  684. /* key state might have been updated */
  685. sshkey_free(id->key);
  686. free(id->comment);
  687. free(id->sk_provider);
  688. }
  689. /* success */
  690. id->key = k;
  691. id->comment = comment;
  692. id->death = death;
  693. id->confirm = confirm;
  694. id->sk_provider = sk_provider;
  695. if ((fp = sshkey_fingerprint(k, SSH_FP_HASH_DEFAULT,
  696. SSH_FP_DEFAULT)) == NULL)
  697. fatal("%s: sshkey_fingerprint failed", __func__);
  698. debug("%s: add %s %s \"%.100s\" (life: %u) (confirm: %u) "
  699. "(provider: %s)", sshkey_ssh_name(k), fp, comment, seconds,
  700. confirm, sk_provider == NULL ? "none" : sk_provider);
  701. free(fp);
  702. /* transferred */
  703. k = NULL;
  704. comment = NULL;
  705. sk_provider = NULL;
  706. success = 1;
  707. out:
  708. free(sk_provider);
  709. free(comment);
  710. sshkey_free(k);
  711. send_status(e, success);
  712. }
  713. /* XXX todo: encrypt sensitive data with passphrase */
  714. static void
  715. process_lock_agent(SocketEntry *e, int lock)
  716. {
  717. int r, success = 0, delay;
  718. char *passwd;
  719. u_char passwdhash[LOCK_SIZE];
  720. static u_int fail_count = 0;
  721. size_t pwlen;
  722. debug2("entering");
  723. /*
  724. * This is deliberately fatal: the user has requested that we lock,
  725. * but we can't parse their request properly. The only safe thing to
  726. * do is abort.
  727. */
  728. if ((r = sshbuf_get_cstring(e->request, &passwd, &pwlen)) != 0)
  729. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  730. if (pwlen == 0) {
  731. debug("empty password not supported");
  732. } else if (locked && !lock) {
  733. if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
  734. passwdhash, sizeof(passwdhash), LOCK_ROUNDS) < 0)
  735. fatal("bcrypt_pbkdf");
  736. if (timingsafe_bcmp(passwdhash, lock_pwhash, LOCK_SIZE) == 0) {
  737. debug("agent unlocked");
  738. locked = 0;
  739. fail_count = 0;
  740. explicit_bzero(lock_pwhash, sizeof(lock_pwhash));
  741. success = 1;
  742. } else {
  743. /* delay in 0.1s increments up to 10s */
  744. if (fail_count < 100)
  745. fail_count++;
  746. delay = 100000 * fail_count;
  747. debug("unlock failed, delaying %0.1lf seconds",
  748. (double)delay/1000000);
  749. usleep(delay);
  750. }
  751. explicit_bzero(passwdhash, sizeof(passwdhash));
  752. } else if (!locked && lock) {
  753. debug("agent locked");
  754. locked = 1;
  755. arc4random_buf(lock_salt, sizeof(lock_salt));
  756. if (bcrypt_pbkdf(passwd, pwlen, lock_salt, sizeof(lock_salt),
  757. lock_pwhash, sizeof(lock_pwhash), LOCK_ROUNDS) < 0)
  758. fatal("bcrypt_pbkdf");
  759. success = 1;
  760. }
  761. freezero(passwd, pwlen);
  762. send_status(e, success);
  763. }
  764. static void
  765. no_identities(SocketEntry *e)
  766. {
  767. struct sshbuf *msg;
  768. int r;
  769. if ((msg = sshbuf_new()) == NULL)
  770. fatal("%s: sshbuf_new failed", __func__);
  771. if ((r = sshbuf_put_u8(msg, SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
  772. (r = sshbuf_put_u32(msg, 0)) != 0 ||
  773. (r = sshbuf_put_stringb(e->output, msg)) != 0)
  774. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  775. sshbuf_free(msg);
  776. }
  777. #ifdef ENABLE_PKCS11
  778. static char *
  779. sanitize_pkcs11_provider(const char *provider)
  780. {
  781. struct pkcs11_uri *uri = NULL;
  782. char *sane_uri, *module_path = NULL; /* default path */
  783. char canonical_provider[PATH_MAX];
  784. if (provider == NULL)
  785. return NULL;
  786. if (strlen(provider) >= strlen(PKCS11_URI_SCHEME) &&
  787. strncmp(provider, PKCS11_URI_SCHEME,
  788. strlen(PKCS11_URI_SCHEME)) == 0) {
  789. /* PKCS#11 URI */
  790. uri = pkcs11_uri_init();
  791. if (uri == NULL) {
  792. error("Failed to init PKCS#11 URI");
  793. return NULL;
  794. }
  795. if (pkcs11_uri_parse(provider, uri) != 0) {
  796. error("Failed to parse PKCS#11 URI");
  797. return NULL;
  798. }
  799. /* validate also provider from URI */
  800. if (uri->module_path)
  801. module_path = strdup(uri->module_path);
  802. } else
  803. module_path = strdup(provider); /* simple path */
  804. if (module_path != NULL) { /* do not validate default NULL path in URI */
  805. if (realpath(module_path, canonical_provider) == NULL) {
  806. verbose("failed PKCS#11 provider \"%.100s\": realpath: %s",
  807. module_path, strerror(errno));
  808. free(module_path);
  809. pkcs11_uri_cleanup(uri);
  810. return NULL;
  811. }
  812. free(module_path);
  813. if (match_pattern_list(canonical_provider, allowed_providers, 0) != 1) {
  814. verbose("refusing PKCS#11 provider \"%.100s\": "
  815. "not allowed", canonical_provider);
  816. pkcs11_uri_cleanup(uri);
  817. return NULL;
  818. }
  819. /* copy verified and sanitized provider path back to the uri */
  820. if (uri) {
  821. free(uri->module_path);
  822. uri->module_path = xstrdup(canonical_provider);
  823. }
  824. }
  825. if (uri) {
  826. sane_uri = pkcs11_uri_get(uri);
  827. pkcs11_uri_cleanup(uri);
  828. return sane_uri;
  829. } else {
  830. return xstrdup(canonical_provider); /* simple path */
  831. }
  832. }
  833. static void
  834. process_add_smartcard_key(SocketEntry *e)
  835. {
  836. char *provider = NULL, *pin = NULL, *sane_uri = NULL;
  837. char **comments = NULL;
  838. int r, i, count = 0, success = 0, confirm = 0;
  839. u_int seconds = 0;
  840. time_t death = 0;
  841. struct sshkey **keys = NULL, *k;
  842. Identity *id;
  843. debug2("entering");
  844. if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
  845. (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
  846. error("%s: buffer error: %s", __func__, ssh_err(r));
  847. goto send;
  848. }
  849. if (parse_key_constraints(e->request, NULL, &death, &seconds, &confirm,
  850. NULL) != 0) {
  851. error("failed to parse constraints");
  852. goto send;
  853. }
  854. sane_uri = sanitize_pkcs11_provider(provider);
  855. if (sane_uri == NULL)
  856. goto send;
  857. if (lifetime && !death)
  858. death = monotime() + lifetime;
  859. debug("%s: add %.100s", __func__, sane_uri);
  860. count = pkcs11_add_provider(sane_uri, pin, &keys, &comments);
  861. for (i = 0; i < count; i++) {
  862. k = keys[i];
  863. if (lookup_identity(k) == NULL) {
  864. id = xcalloc(1, sizeof(Identity));
  865. id->key = k;
  866. keys[i] = NULL; /* transferred */
  867. id->provider = xstrdup(sane_uri);
  868. if (*comments[i] != '\0') {
  869. id->comment = comments[i];
  870. comments[i] = NULL; /* transferred */
  871. } else {
  872. id->comment = xstrdup(sane_uri);
  873. }
  874. id->death = death;
  875. id->confirm = confirm;
  876. TAILQ_INSERT_TAIL(&idtab->idlist, id, next);
  877. idtab->nentries++;
  878. success = 1;
  879. }
  880. /* XXX update constraints for existing keys */
  881. sshkey_free(keys[i]);
  882. free(comments[i]);
  883. }
  884. send:
  885. free(pin);
  886. free(provider);
  887. free(sane_uri);
  888. free(keys);
  889. free(comments);
  890. send_status(e, success);
  891. }
  892. static void
  893. process_remove_smartcard_key(SocketEntry *e)
  894. {
  895. char *provider = NULL, *pin = NULL, *sane_uri = NULL;
  896. int r, success = 0;
  897. Identity *id, *nxt;
  898. debug2("entering");
  899. if ((r = sshbuf_get_cstring(e->request, &provider, NULL)) != 0 ||
  900. (r = sshbuf_get_cstring(e->request, &pin, NULL)) != 0) {
  901. error("%s: buffer error: %s", __func__, ssh_err(r));
  902. goto send;
  903. }
  904. free(pin);
  905. sane_uri = sanitize_pkcs11_provider(provider);
  906. if (sane_uri == NULL)
  907. goto send;
  908. debug("%s: remove %.100s", __func__, sane_uri);
  909. for (id = TAILQ_FIRST(&idtab->idlist); id; id = nxt) {
  910. nxt = TAILQ_NEXT(id, next);
  911. /* Skip file--based keys */
  912. if (id->provider == NULL)
  913. continue;
  914. if (!strcmp(sane_uri, id->provider)) {
  915. TAILQ_REMOVE(&idtab->idlist, id, next);
  916. free_identity(id);
  917. idtab->nentries--;
  918. }
  919. }
  920. if (pkcs11_del_provider(sane_uri) == 0)
  921. success = 1;
  922. else
  923. error("%s: pkcs11_del_provider failed", __func__);
  924. send:
  925. free(provider);
  926. free(sane_uri);
  927. send_status(e, success);
  928. }
  929. #endif /* ENABLE_PKCS11 */
  930. /*
  931. * dispatch incoming message.
  932. * returns 1 on success, 0 for incomplete messages or -1 on error.
  933. */
  934. static int
  935. process_message(u_int socknum)
  936. {
  937. u_int msg_len;
  938. u_char type;
  939. const u_char *cp;
  940. int r;
  941. SocketEntry *e;
  942. if (socknum >= sockets_alloc) {
  943. fatal("%s: socket number %u >= allocated %u",
  944. __func__, socknum, sockets_alloc);
  945. }
  946. e = &sockets[socknum];
  947. if (sshbuf_len(e->input) < 5)
  948. return 0; /* Incomplete message header. */
  949. cp = sshbuf_ptr(e->input);
  950. msg_len = PEEK_U32(cp);
  951. if (msg_len > AGENT_MAX_LEN) {
  952. debug("%s: socket %u (fd=%d) message too long %u > %u",
  953. __func__, socknum, e->fd, msg_len, AGENT_MAX_LEN);
  954. return -1;
  955. }
  956. if (sshbuf_len(e->input) < msg_len + 4)
  957. return 0; /* Incomplete message body. */
  958. /* move the current input to e->request */
  959. sshbuf_reset(e->request);
  960. if ((r = sshbuf_get_stringb(e->input, e->request)) != 0 ||
  961. (r = sshbuf_get_u8(e->request, &type)) != 0) {
  962. if (r == SSH_ERR_MESSAGE_INCOMPLETE ||
  963. r == SSH_ERR_STRING_TOO_LARGE) {
  964. debug("%s: buffer error: %s", __func__, ssh_err(r));
  965. return -1;
  966. }
  967. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  968. }
  969. debug("%s: socket %u (fd=%d) type %d", __func__, socknum, e->fd, type);
  970. /* check whether agent is locked */
  971. if (locked && type != SSH_AGENTC_UNLOCK) {
  972. sshbuf_reset(e->request);
  973. switch (type) {
  974. case SSH2_AGENTC_REQUEST_IDENTITIES:
  975. /* send empty lists */
  976. no_identities(e);
  977. break;
  978. default:
  979. /* send a fail message for all other request types */
  980. send_status(e, 0);
  981. }
  982. return 1;
  983. }
  984. switch (type) {
  985. case SSH_AGENTC_LOCK:
  986. case SSH_AGENTC_UNLOCK:
  987. process_lock_agent(e, type == SSH_AGENTC_LOCK);
  988. break;
  989. case SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
  990. process_remove_all_identities(e); /* safe for !WITH_SSH1 */
  991. break;
  992. /* ssh2 */
  993. case SSH2_AGENTC_SIGN_REQUEST:
  994. process_sign_request2(e);
  995. break;
  996. case SSH2_AGENTC_REQUEST_IDENTITIES:
  997. process_request_identities(e);
  998. break;
  999. case SSH2_AGENTC_ADD_IDENTITY:
  1000. case SSH2_AGENTC_ADD_ID_CONSTRAINED:
  1001. process_add_identity(e);
  1002. break;
  1003. case SSH2_AGENTC_REMOVE_IDENTITY:
  1004. process_remove_identity(e);
  1005. break;
  1006. case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
  1007. process_remove_all_identities(e);
  1008. break;
  1009. #ifdef ENABLE_PKCS11
  1010. case SSH_AGENTC_ADD_SMARTCARD_KEY:
  1011. case SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED:
  1012. process_add_smartcard_key(e);
  1013. break;
  1014. case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
  1015. process_remove_smartcard_key(e);
  1016. break;
  1017. #endif /* ENABLE_PKCS11 */
  1018. default:
  1019. /* Unknown message. Respond with failure. */
  1020. error("Unknown message %d", type);
  1021. sshbuf_reset(e->request);
  1022. send_status(e, 0);
  1023. break;
  1024. }
  1025. return 1;
  1026. }
  1027. static void
  1028. new_socket(sock_type type, int fd)
  1029. {
  1030. u_int i, old_alloc, new_alloc;
  1031. debug("type = %s", type == AUTH_CONNECTION ? "CONNECTION" :
  1032. (type == AUTH_SOCKET ? "SOCKET" : "UNKNOWN"));
  1033. set_nonblock(fd);
  1034. if (fd > max_fd)
  1035. max_fd = fd;
  1036. for (i = 0; i < sockets_alloc; i++)
  1037. if (sockets[i].type == AUTH_UNUSED) {
  1038. sockets[i].fd = fd;
  1039. if ((sockets[i].input = sshbuf_new()) == NULL)
  1040. fatal("%s: sshbuf_new failed", __func__);
  1041. if ((sockets[i].output = sshbuf_new()) == NULL)
  1042. fatal("%s: sshbuf_new failed", __func__);
  1043. if ((sockets[i].request = sshbuf_new()) == NULL)
  1044. fatal("%s: sshbuf_new failed", __func__);
  1045. sockets[i].type = type;
  1046. return;
  1047. }
  1048. old_alloc = sockets_alloc;
  1049. new_alloc = sockets_alloc + 10;
  1050. sockets = xrecallocarray(sockets, old_alloc, new_alloc,
  1051. sizeof(sockets[0]));
  1052. for (i = old_alloc; i < new_alloc; i++)
  1053. sockets[i].type = AUTH_UNUSED;
  1054. sockets_alloc = new_alloc;
  1055. sockets[old_alloc].fd = fd;
  1056. if ((sockets[old_alloc].input = sshbuf_new()) == NULL)
  1057. fatal("%s: sshbuf_new failed", __func__);
  1058. if ((sockets[old_alloc].output = sshbuf_new()) == NULL)
  1059. fatal("%s: sshbuf_new failed", __func__);
  1060. if ((sockets[old_alloc].request = sshbuf_new()) == NULL)
  1061. fatal("%s: sshbuf_new failed", __func__);
  1062. sockets[old_alloc].type = type;
  1063. }
  1064. static int
  1065. handle_socket_read(u_int socknum)
  1066. {
  1067. struct sockaddr_un sunaddr;
  1068. socklen_t slen;
  1069. uid_t euid;
  1070. gid_t egid;
  1071. int fd;
  1072. slen = sizeof(sunaddr);
  1073. fd = accept(sockets[socknum].fd, (struct sockaddr *)&sunaddr, &slen);
  1074. if (fd == -1) {
  1075. error("accept from AUTH_SOCKET: %s", strerror(errno));
  1076. return -1;
  1077. }
  1078. if (getpeereid(fd, &euid, &egid) == -1) {
  1079. error("getpeereid %d failed: %s", fd, strerror(errno));
  1080. close(fd);
  1081. return -1;
  1082. }
  1083. if ((euid != 0) && (getuid() != euid)) {
  1084. error("uid mismatch: peer euid %u != uid %u",
  1085. (u_int) euid, (u_int) getuid());
  1086. close(fd);
  1087. return -1;
  1088. }
  1089. new_socket(AUTH_CONNECTION, fd);
  1090. return 0;
  1091. }
  1092. static int
  1093. handle_conn_read(u_int socknum)
  1094. {
  1095. char buf[AGENT_RBUF_LEN];
  1096. ssize_t len;
  1097. int r;
  1098. if ((len = read(sockets[socknum].fd, buf, sizeof(buf))) <= 0) {
  1099. if (len == -1) {
  1100. if (errno == EAGAIN || errno == EINTR)
  1101. return 0;
  1102. error("%s: read error on socket %u (fd %d): %s",
  1103. __func__, socknum, sockets[socknum].fd,
  1104. strerror(errno));
  1105. }
  1106. return -1;
  1107. }
  1108. if ((r = sshbuf_put(sockets[socknum].input, buf, len)) != 0)
  1109. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  1110. explicit_bzero(buf, sizeof(buf));
  1111. for (;;) {
  1112. if ((r = process_message(socknum)) == -1)
  1113. return -1;
  1114. else if (r == 0)
  1115. break;
  1116. }
  1117. return 0;
  1118. }
  1119. static int
  1120. handle_conn_write(u_int socknum)
  1121. {
  1122. ssize_t len;
  1123. int r;
  1124. if (sshbuf_len(sockets[socknum].output) == 0)
  1125. return 0; /* shouldn't happen */
  1126. if ((len = write(sockets[socknum].fd,
  1127. sshbuf_ptr(sockets[socknum].output),
  1128. sshbuf_len(sockets[socknum].output))) <= 0) {
  1129. if (len == -1) {
  1130. if (errno == EAGAIN || errno == EINTR)
  1131. return 0;
  1132. error("%s: read error on socket %u (fd %d): %s",
  1133. __func__, socknum, sockets[socknum].fd,
  1134. strerror(errno));
  1135. }
  1136. return -1;
  1137. }
  1138. if ((r = sshbuf_consume(sockets[socknum].output, len)) != 0)
  1139. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  1140. return 0;
  1141. }
  1142. static void
  1143. after_poll(struct pollfd *pfd, size_t npfd, u_int maxfds)
  1144. {
  1145. size_t i;
  1146. u_int socknum, activefds = npfd;
  1147. for (i = 0; i < npfd; i++) {
  1148. if (pfd[i].revents == 0)
  1149. continue;
  1150. /* Find sockets entry */
  1151. for (socknum = 0; socknum < sockets_alloc; socknum++) {
  1152. if (sockets[socknum].type != AUTH_SOCKET &&
  1153. sockets[socknum].type != AUTH_CONNECTION)
  1154. continue;
  1155. if (pfd[i].fd == sockets[socknum].fd)
  1156. break;
  1157. }
  1158. if (socknum >= sockets_alloc) {
  1159. error("%s: no socket for fd %d", __func__, pfd[i].fd);
  1160. continue;
  1161. }
  1162. /* Process events */
  1163. switch (sockets[socknum].type) {
  1164. case AUTH_SOCKET:
  1165. if ((pfd[i].revents & (POLLIN|POLLERR)) == 0)
  1166. break;
  1167. if (npfd > maxfds) {
  1168. debug3("out of fds (active %u >= limit %u); "
  1169. "skipping accept", activefds, maxfds);
  1170. break;
  1171. }
  1172. if (handle_socket_read(socknum) == 0)
  1173. activefds++;
  1174. break;
  1175. case AUTH_CONNECTION:
  1176. if ((pfd[i].revents & (POLLIN|POLLERR)) != 0 &&
  1177. handle_conn_read(socknum) != 0) {
  1178. goto close_sock;
  1179. }
  1180. if ((pfd[i].revents & (POLLOUT|POLLHUP)) != 0 &&
  1181. handle_conn_write(socknum) != 0) {
  1182. close_sock:
  1183. if (activefds == 0)
  1184. fatal("activefds == 0 at close_sock");
  1185. close_socket(&sockets[socknum]);
  1186. activefds--;
  1187. break;
  1188. }
  1189. break;
  1190. default:
  1191. break;
  1192. }
  1193. }
  1194. }
  1195. static int
  1196. prepare_poll(struct pollfd **pfdp, size_t *npfdp, int *timeoutp, u_int maxfds)
  1197. {
  1198. struct pollfd *pfd = *pfdp;
  1199. size_t i, j, npfd = 0;
  1200. time_t deadline;
  1201. int r;
  1202. /* Count active sockets */
  1203. for (i = 0; i < sockets_alloc; i++) {
  1204. switch (sockets[i].type) {
  1205. case AUTH_SOCKET:
  1206. case AUTH_CONNECTION:
  1207. npfd++;
  1208. break;
  1209. case AUTH_UNUSED:
  1210. break;
  1211. default:
  1212. fatal("Unknown socket type %d", sockets[i].type);
  1213. break;
  1214. }
  1215. }
  1216. if (npfd != *npfdp &&
  1217. (pfd = recallocarray(pfd, *npfdp, npfd, sizeof(*pfd))) == NULL)
  1218. fatal("%s: recallocarray failed", __func__);
  1219. *pfdp = pfd;
  1220. *npfdp = npfd;
  1221. for (i = j = 0; i < sockets_alloc; i++) {
  1222. switch (sockets[i].type) {
  1223. case AUTH_SOCKET:
  1224. if (npfd > maxfds) {
  1225. debug3("out of fds (active %zu >= limit %u); "
  1226. "skipping arming listener", npfd, maxfds);
  1227. break;
  1228. }
  1229. pfd[j].fd = sockets[i].fd;
  1230. pfd[j].revents = 0;
  1231. pfd[j].events = POLLIN;
  1232. j++;
  1233. break;
  1234. case AUTH_CONNECTION:
  1235. pfd[j].fd = sockets[i].fd;
  1236. pfd[j].revents = 0;
  1237. /*
  1238. * Only prepare to read if we can handle a full-size
  1239. * input read buffer and enqueue a max size reply..
  1240. */
  1241. if ((r = sshbuf_check_reserve(sockets[i].input,
  1242. AGENT_RBUF_LEN)) == 0 &&
  1243. (r = sshbuf_check_reserve(sockets[i].output,
  1244. AGENT_MAX_LEN)) == 0)
  1245. pfd[j].events = POLLIN;
  1246. else if (r != SSH_ERR_NO_BUFFER_SPACE) {
  1247. fatal("%s: buffer error: %s",
  1248. __func__, ssh_err(r));
  1249. }
  1250. if (sshbuf_len(sockets[i].output) > 0)
  1251. pfd[j].events |= POLLOUT;
  1252. j++;
  1253. break;
  1254. default:
  1255. break;
  1256. }
  1257. }
  1258. deadline = reaper();
  1259. if (parent_alive_interval != 0)
  1260. deadline = (deadline == 0) ? parent_alive_interval :
  1261. MINIMUM(deadline, parent_alive_interval);
  1262. if (deadline == 0) {
  1263. *timeoutp = -1; /* INFTIM */
  1264. } else {
  1265. if (deadline > INT_MAX / 1000)
  1266. *timeoutp = INT_MAX / 1000;
  1267. else
  1268. *timeoutp = deadline * 1000;
  1269. }
  1270. return (1);
  1271. }
  1272. static void
  1273. cleanup_socket(void)
  1274. {
  1275. if (cleanup_pid != 0 && getpid() != cleanup_pid)
  1276. return;
  1277. debug("%s: cleanup", __func__);
  1278. if (socket_name[0])
  1279. unlink(socket_name);
  1280. if (socket_dir[0])
  1281. rmdir(socket_dir);
  1282. }
  1283. void
  1284. cleanup_exit(int i)
  1285. {
  1286. cleanup_socket();
  1287. _exit(i);
  1288. }
  1289. /*ARGSUSED*/
  1290. static void
  1291. cleanup_handler(int sig)
  1292. {
  1293. cleanup_socket();
  1294. #ifdef ENABLE_PKCS11
  1295. pkcs11_terminate();
  1296. #endif
  1297. _exit(2);
  1298. }
  1299. static void
  1300. check_parent_exists(void)
  1301. {
  1302. /*
  1303. * If our parent has exited then getppid() will return (pid_t)1,
  1304. * so testing for that should be safe.
  1305. */
  1306. if (parent_pid != -1 && getppid() != parent_pid) {
  1307. /* printf("Parent has died - Authentication agent exiting.\n"); */
  1308. cleanup_socket();
  1309. _exit(2);
  1310. }
  1311. }
  1312. static void
  1313. usage(void)
  1314. {
  1315. fprintf(stderr,
  1316. "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n"
  1317. " [-P allowed_providers] [-t life]\n"
  1318. " ssh-agent [-a bind_address] [-E fingerprint_hash] [-P allowed_providers]\n"
  1319. " [-t life] command [arg ...]\n"
  1320. " ssh-agent [-c | -s] -k\n");
  1321. exit(1);
  1322. }
  1323. int
  1324. main(int ac, char **av)
  1325. {
  1326. int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
  1327. int sock, fd, ch, result, saved_errno;
  1328. char *shell, *format, *pidstr, *agentsocket = NULL;
  1329. #ifdef HAVE_SETRLIMIT
  1330. struct rlimit rlim;
  1331. #endif
  1332. extern int optind;
  1333. extern char *optarg;
  1334. pid_t pid;
  1335. char pidstrbuf[1 + 3 * sizeof pid];
  1336. size_t len;
  1337. mode_t prev_mask;
  1338. int timeout = -1; /* INFTIM */
  1339. struct pollfd *pfd = NULL;
  1340. size_t npfd = 0;
  1341. u_int maxfds;
  1342. /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
  1343. sanitise_stdfd();
  1344. /* drop */
  1345. (void) setegid(getgid());
  1346. (void) setgid(getgid());
  1347. platform_disable_tracing(0); /* strict=no */
  1348. #ifdef RLIMIT_NOFILE
  1349. if (getrlimit(RLIMIT_NOFILE, &rlim) == -1)
  1350. fatal("%s: getrlimit: %s", __progname, strerror(errno));
  1351. #endif
  1352. __progname = ssh_get_progname(av[0]);
  1353. seed_rng();
  1354. while ((ch = getopt(ac, av, "cDdksE:a:O:P:t:")) != -1) {
  1355. switch (ch) {
  1356. case 'E':
  1357. fingerprint_hash = ssh_digest_alg_by_name(optarg);
  1358. if (fingerprint_hash == -1)
  1359. fatal("Invalid hash algorithm \"%s\"", optarg);
  1360. break;
  1361. case 'c':
  1362. if (s_flag)
  1363. usage();
  1364. c_flag++;
  1365. break;
  1366. case 'k':
  1367. k_flag++;
  1368. break;
  1369. case 'O':
  1370. if (strcmp(optarg, "no-restrict-websafe") == 0)
  1371. restrict_websafe = 0;
  1372. else
  1373. fatal("Unknown -O option");
  1374. break;
  1375. case 'P':
  1376. if (allowed_providers != NULL)
  1377. fatal("-P option already specified");
  1378. allowed_providers = xstrdup(optarg);
  1379. break;
  1380. case 's':
  1381. if (c_flag)
  1382. usage();
  1383. s_flag++;
  1384. break;
  1385. case 'd':
  1386. if (d_flag || D_flag)
  1387. usage();
  1388. d_flag++;
  1389. break;
  1390. case 'D':
  1391. if (d_flag || D_flag)
  1392. usage();
  1393. D_flag++;
  1394. break;
  1395. case 'a':
  1396. agentsocket = optarg;
  1397. break;
  1398. case 't':
  1399. if ((lifetime = convtime(optarg)) == -1) {
  1400. fprintf(stderr, "Invalid lifetime\n");
  1401. usage();
  1402. }
  1403. break;
  1404. default:
  1405. usage();
  1406. }
  1407. }
  1408. ac -= optind;
  1409. av += optind;
  1410. if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
  1411. usage();
  1412. if (allowed_providers == NULL)
  1413. allowed_providers = xstrdup(DEFAULT_ALLOWED_PROVIDERS);
  1414. if (ac == 0 && !c_flag && !s_flag) {
  1415. shell = getenv("SHELL");
  1416. if (shell != NULL && (len = strlen(shell)) > 2 &&
  1417. strncmp(shell + len - 3, "csh", 3) == 0)
  1418. c_flag = 1;
  1419. }
  1420. if (k_flag) {
  1421. const char *errstr = NULL;
  1422. pidstr = getenv(SSH_AGENTPID_ENV_NAME);
  1423. if (pidstr == NULL) {
  1424. fprintf(stderr, "%s not set, cannot kill agent\n",
  1425. SSH_AGENTPID_ENV_NAME);
  1426. exit(1);
  1427. }
  1428. pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
  1429. if (errstr) {
  1430. fprintf(stderr,
  1431. "%s=\"%s\", which is not a good PID: %s\n",
  1432. SSH_AGENTPID_ENV_NAME, pidstr, errstr);
  1433. exit(1);
  1434. }
  1435. if (kill(pid, SIGTERM) == -1) {
  1436. perror("kill");
  1437. exit(1);
  1438. }
  1439. format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
  1440. printf(format, SSH_AUTHSOCKET_ENV_NAME);
  1441. printf(format, SSH_AGENTPID_ENV_NAME);
  1442. printf("echo Agent pid %ld killed;\n", (long)pid);
  1443. exit(0);
  1444. }
  1445. /*
  1446. * Minimum file descriptors:
  1447. * stdio (3) + listener (1) + syslog (1 maybe) + connection (1) +
  1448. * a few spare for libc / stack protectors / sanitisers, etc.
  1449. */
  1450. #define SSH_AGENT_MIN_FDS (3+1+1+1+4)
  1451. if (rlim.rlim_cur < SSH_AGENT_MIN_FDS)
  1452. fatal("%s: file descriptor rlimit %lld too low (minimum %u)",
  1453. __progname, (long long)rlim.rlim_cur, SSH_AGENT_MIN_FDS);
  1454. maxfds = rlim.rlim_cur - SSH_AGENT_MIN_FDS;
  1455. parent_pid = getpid();
  1456. if (agentsocket == NULL) {
  1457. /* Create private directory for agent socket */
  1458. mktemp_proto(socket_dir, sizeof(socket_dir));
  1459. if (mkdtemp(socket_dir) == NULL) {
  1460. perror("mkdtemp: private socket dir");
  1461. exit(1);
  1462. }
  1463. snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
  1464. (long)parent_pid);
  1465. } else {
  1466. /* Try to use specified agent socket */
  1467. socket_dir[0] = '\0';
  1468. strlcpy(socket_name, agentsocket, sizeof socket_name);
  1469. }
  1470. /*
  1471. * Create socket early so it will exist before command gets run from
  1472. * the parent.
  1473. */
  1474. prev_mask = umask(0177);
  1475. sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
  1476. if (sock < 0) {
  1477. /* XXX - unix_listener() calls error() not perror() */
  1478. *socket_name = '\0'; /* Don't unlink any existing file */
  1479. cleanup_exit(1);
  1480. }
  1481. umask(prev_mask);
  1482. /*
  1483. * Fork, and have the parent execute the command, if any, or present
  1484. * the socket data. The child continues as the authentication agent.
  1485. */
  1486. if (D_flag || d_flag) {
  1487. log_init(__progname,
  1488. d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
  1489. SYSLOG_FACILITY_AUTH, 1);
  1490. format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
  1491. printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
  1492. SSH_AUTHSOCKET_ENV_NAME);
  1493. printf("echo Agent pid %ld;\n", (long)parent_pid);
  1494. fflush(stdout);
  1495. goto skip;
  1496. }
  1497. pid = fork();
  1498. if (pid == -1) {
  1499. perror("fork");
  1500. cleanup_exit(1);
  1501. }
  1502. if (pid != 0) { /* Parent - execute the given command. */
  1503. close(sock);
  1504. snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
  1505. if (ac == 0) {
  1506. format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
  1507. printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
  1508. SSH_AUTHSOCKET_ENV_NAME);
  1509. printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
  1510. SSH_AGENTPID_ENV_NAME);
  1511. printf("echo Agent pid %ld;\n", (long)pid);
  1512. exit(0);
  1513. }
  1514. if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
  1515. setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
  1516. perror("setenv");
  1517. exit(1);
  1518. }
  1519. execvp(av[0], av);
  1520. perror(av[0]);
  1521. exit(1);
  1522. }
  1523. /* child */
  1524. log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
  1525. if (setsid() == -1) {
  1526. error("setsid: %s", strerror(errno));
  1527. cleanup_exit(1);
  1528. }
  1529. (void)chdir("/");
  1530. if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
  1531. /* XXX might close listen socket */
  1532. (void)dup2(fd, STDIN_FILENO);
  1533. (void)dup2(fd, STDOUT_FILENO);
  1534. (void)dup2(fd, STDERR_FILENO);
  1535. if (fd > 2)
  1536. close(fd);
  1537. }
  1538. #ifdef HAVE_SETRLIMIT
  1539. /* deny core dumps, since memory contains unencrypted private keys */
  1540. rlim.rlim_cur = rlim.rlim_max = 0;
  1541. if (setrlimit(RLIMIT_CORE, &rlim) == -1) {
  1542. error("setrlimit RLIMIT_CORE: %s", strerror(errno));
  1543. cleanup_exit(1);
  1544. }
  1545. #endif
  1546. skip:
  1547. cleanup_pid = getpid();
  1548. #ifdef ENABLE_PKCS11
  1549. pkcs11_init(0);
  1550. #endif
  1551. new_socket(AUTH_SOCKET, sock);
  1552. if (ac > 0)
  1553. parent_alive_interval = 10;
  1554. idtab_init();
  1555. ssh_signal(SIGPIPE, SIG_IGN);
  1556. ssh_signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
  1557. ssh_signal(SIGHUP, cleanup_handler);
  1558. ssh_signal(SIGTERM, cleanup_handler);
  1559. if (pledge("stdio rpath cpath unix id proc exec", NULL) == -1)
  1560. fatal("%s: pledge: %s", __progname, strerror(errno));
  1561. platform_pledge_agent();
  1562. while (1) {
  1563. prepare_poll(&pfd, &npfd, &timeout, maxfds);
  1564. result = poll(pfd, npfd, timeout);
  1565. saved_errno = errno;
  1566. if (parent_alive_interval != 0)
  1567. check_parent_exists();
  1568. (void) reaper(); /* remove expired keys */
  1569. if (result == -1) {
  1570. if (saved_errno == EINTR)
  1571. continue;
  1572. fatal("poll: %s", strerror(saved_errno));
  1573. } else if (result > 0)
  1574. after_poll(pfd, npfd, maxfds);
  1575. }
  1576. /* NOTREACHED */
  1577. }