auth2-pubkey.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  1. /* $OpenBSD: auth2-pubkey.c,v 1.100 2020/08/27 01:07:09 djm Exp $ */
  2. /*
  3. * Copyright (c) 2000 Markus Friedl. All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. *
  14. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  15. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  16. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  17. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  18. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  19. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  20. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  21. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  22. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  23. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. #include "includes.h"
  26. #include <sys/types.h>
  27. #include <sys/stat.h>
  28. #include <stdlib.h>
  29. #include <errno.h>
  30. #include <fcntl.h>
  31. #ifdef HAVE_PATHS_H
  32. # include <paths.h>
  33. #endif
  34. #include <pwd.h>
  35. #include <signal.h>
  36. #include <stdio.h>
  37. #include <stdarg.h>
  38. #include <string.h>
  39. #include <time.h>
  40. #include <unistd.h>
  41. #include <limits.h>
  42. #include "xmalloc.h"
  43. #include "ssh.h"
  44. #include "ssh2.h"
  45. #include "packet.h"
  46. #include "kex.h"
  47. #include "sshbuf.h"
  48. #include "log.h"
  49. #include "misc.h"
  50. #include "servconf.h"
  51. #include "compat.h"
  52. #include "sshkey.h"
  53. #include "hostfile.h"
  54. #include "auth.h"
  55. #include "pathnames.h"
  56. #include "uidswap.h"
  57. #include "auth-options.h"
  58. #include "canohost.h"
  59. #ifdef GSSAPI
  60. #include "ssh-gss.h"
  61. #endif
  62. #include "monitor_wrap.h"
  63. #include "authfile.h"
  64. #include "match.h"
  65. #include "ssherr.h"
  66. #include "channels.h" /* XXX for session.h */
  67. #include "session.h" /* XXX for child_set_env(); refactor? */
  68. #include "sk-api.h"
  69. /* import */
  70. extern ServerOptions options;
  71. static char *
  72. format_key(const struct sshkey *key)
  73. {
  74. char *ret, *fp = sshkey_fingerprint(key,
  75. options.fingerprint_hash, SSH_FP_DEFAULT);
  76. xasprintf(&ret, "%s %s", sshkey_type(key), fp);
  77. free(fp);
  78. return ret;
  79. }
  80. static int
  81. userauth_pubkey(struct ssh *ssh)
  82. {
  83. Authctxt *authctxt = ssh->authctxt;
  84. struct passwd *pw = authctxt->pw;
  85. struct sshbuf *b = NULL;
  86. struct sshkey *key = NULL;
  87. char *pkalg = NULL, *userstyle = NULL, *key_s = NULL, *ca_s = NULL;
  88. u_char *pkblob = NULL, *sig = NULL, have_sig;
  89. size_t blen, slen;
  90. int r, pktype;
  91. int req_presence = 0, req_verify = 0, authenticated = 0;
  92. struct sshauthopt *authopts = NULL;
  93. struct sshkey_sig_details *sig_details = NULL;
  94. if ((r = sshpkt_get_u8(ssh, &have_sig)) != 0 ||
  95. (r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 ||
  96. (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0)
  97. fatal("%s: parse request failed: %s", __func__, ssh_err(r));
  98. if (log_level_get() >= SYSLOG_LEVEL_DEBUG2) {
  99. char *keystring;
  100. struct sshbuf *pkbuf;
  101. if ((pkbuf = sshbuf_from(pkblob, blen)) == NULL)
  102. fatal("%s: sshbuf_from failed", __func__);
  103. if ((keystring = sshbuf_dtob64_string(pkbuf, 0)) == NULL)
  104. fatal("%s: sshbuf_dtob64 failed", __func__);
  105. debug2("%s: %s user %s %s public key %s %s", __func__,
  106. authctxt->valid ? "valid" : "invalid", authctxt->user,
  107. have_sig ? "attempting" : "querying", pkalg, keystring);
  108. sshbuf_free(pkbuf);
  109. free(keystring);
  110. }
  111. pktype = sshkey_type_from_name(pkalg);
  112. if (pktype == KEY_UNSPEC) {
  113. /* this is perfectly legal */
  114. verbose("%s: unsupported public key algorithm: %s",
  115. __func__, pkalg);
  116. goto done;
  117. }
  118. if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
  119. error("%s: could not parse key: %s", __func__, ssh_err(r));
  120. goto done;
  121. }
  122. if (key == NULL) {
  123. error("%s: cannot decode key: %s", __func__, pkalg);
  124. goto done;
  125. }
  126. if (key->type != pktype) {
  127. error("%s: type mismatch for decoded key "
  128. "(received %d, expected %d)", __func__, key->type, pktype);
  129. goto done;
  130. }
  131. if (sshkey_type_plain(key->type) == KEY_RSA &&
  132. (ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
  133. logit("Refusing RSA key because client uses unsafe "
  134. "signature scheme");
  135. goto done;
  136. }
  137. if (auth2_key_already_used(authctxt, key)) {
  138. logit("refusing previously-used %s key", sshkey_type(key));
  139. goto done;
  140. }
  141. if (match_pattern_list(pkalg, options.pubkey_accepted_algos, 0) != 1) {
  142. logit("%s: key type %s not in PubkeyAcceptedKeyAlgorithms",
  143. __func__, sshkey_ssh_name(key));
  144. goto done;
  145. }
  146. if ((r = sshkey_check_cert_sigtype(key,
  147. options.ca_sign_algorithms)) != 0) {
  148. logit("%s: certificate signature algorithm %s: %s", __func__,
  149. (key->cert == NULL || key->cert->signature_type == NULL) ?
  150. "(null)" : key->cert->signature_type, ssh_err(r));
  151. goto done;
  152. }
  153. key_s = format_key(key);
  154. if (sshkey_is_cert(key))
  155. ca_s = format_key(key->cert->signature_key);
  156. if (have_sig) {
  157. debug3("%s: have %s signature for %s%s%s",
  158. __func__, pkalg, key_s,
  159. ca_s == NULL ? "" : " CA ",
  160. ca_s == NULL ? "" : ca_s);
  161. if ((r = sshpkt_get_string(ssh, &sig, &slen)) != 0 ||
  162. (r = sshpkt_get_end(ssh)) != 0)
  163. fatal("%s: %s", __func__, ssh_err(r));
  164. if ((b = sshbuf_new()) == NULL)
  165. fatal("%s: sshbuf_new failed", __func__);
  166. if (ssh->compat & SSH_OLD_SESSIONID) {
  167. if ((r = sshbuf_putb(b, ssh->kex->session_id)) != 0)
  168. fatal("%s: sshbuf_put session id: %s",
  169. __func__, ssh_err(r));
  170. } else {
  171. if ((r = sshbuf_put_stringb(b,
  172. ssh->kex->session_id)) != 0)
  173. fatal("%s: sshbuf_put_string session id: %s",
  174. __func__, ssh_err(r));
  175. }
  176. if (!authctxt->valid || authctxt->user == NULL) {
  177. debug2("%s: disabled because of invalid user",
  178. __func__);
  179. goto done;
  180. }
  181. /* reconstruct packet */
  182. xasprintf(&userstyle, "%s%s%s%s%s", authctxt->user,
  183. authctxt->style ? ":" : "",
  184. authctxt->style ? authctxt->style : "",
  185. #ifdef WITH_SELINUX
  186. authctxt->role ? "/" : "",
  187. authctxt->role ? authctxt->role : ""
  188. #else
  189. "", ""
  190. #endif
  191. );
  192. if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
  193. (r = sshbuf_put_cstring(b, userstyle)) != 0 ||
  194. (r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
  195. (r = sshbuf_put_cstring(b, "publickey")) != 0 ||
  196. (r = sshbuf_put_u8(b, have_sig)) != 0 ||
  197. (r = sshbuf_put_cstring(b, pkalg)) != 0 ||
  198. (r = sshbuf_put_string(b, pkblob, blen)) != 0)
  199. fatal("%s: build packet failed: %s",
  200. __func__, ssh_err(r));
  201. #ifdef DEBUG_PK
  202. sshbuf_dump(b, stderr);
  203. #endif
  204. /* test for correct signature */
  205. authenticated = 0;
  206. if (PRIVSEP(user_key_allowed(ssh, pw, key, 1, &authopts)) &&
  207. PRIVSEP(user_key_verify(ssh, key, sig, slen,
  208. sshbuf_ptr(b), sshbuf_len(b),
  209. (ssh->compat & SSH_BUG_SIGTYPE) == 0 ? pkalg : NULL,
  210. ssh->compat, &sig_details)) == 0) {
  211. authenticated = 1;
  212. }
  213. if (authenticated == 1 && sig_details != NULL) {
  214. auth2_record_info(authctxt, "signature count = %u",
  215. sig_details->sk_counter);
  216. debug("%s: sk_counter = %u, sk_flags = 0x%02x",
  217. __func__, sig_details->sk_counter,
  218. sig_details->sk_flags);
  219. req_presence = (options.pubkey_auth_options &
  220. PUBKEYAUTH_TOUCH_REQUIRED) ||
  221. !authopts->no_require_user_presence;
  222. if (req_presence && (sig_details->sk_flags &
  223. SSH_SK_USER_PRESENCE_REQD) == 0) {
  224. error("public key %s signature for %s%s from "
  225. "%.128s port %d rejected: user presence "
  226. "(authenticator touch) requirement "
  227. "not met ", key_s,
  228. authctxt->valid ? "" : "invalid user ",
  229. authctxt->user, ssh_remote_ipaddr(ssh),
  230. ssh_remote_port(ssh));
  231. authenticated = 0;
  232. goto done;
  233. }
  234. req_verify = (options.pubkey_auth_options &
  235. PUBKEYAUTH_VERIFY_REQUIRED) ||
  236. authopts->require_verify;
  237. if (req_verify && (sig_details->sk_flags &
  238. SSH_SK_USER_VERIFICATION_REQD) == 0) {
  239. error("public key %s signature for %s%s from "
  240. "%.128s port %d rejected: user "
  241. "verification requirement not met ", key_s,
  242. authctxt->valid ? "" : "invalid user ",
  243. authctxt->user, ssh_remote_ipaddr(ssh),
  244. ssh_remote_port(ssh));
  245. authenticated = 0;
  246. goto done;
  247. }
  248. }
  249. auth2_record_key(authctxt, authenticated, key);
  250. } else {
  251. debug("%s: test pkalg %s pkblob %s%s%s",
  252. __func__, pkalg, key_s,
  253. ca_s == NULL ? "" : " CA ",
  254. ca_s == NULL ? "" : ca_s);
  255. if ((r = sshpkt_get_end(ssh)) != 0)
  256. fatal("%s: %s", __func__, ssh_err(r));
  257. if (!authctxt->valid || authctxt->user == NULL) {
  258. debug2("%s: disabled because of invalid user",
  259. __func__);
  260. goto done;
  261. }
  262. /* XXX fake reply and always send PK_OK ? */
  263. /*
  264. * XXX this allows testing whether a user is allowed
  265. * to login: if you happen to have a valid pubkey this
  266. * message is sent. the message is NEVER sent at all
  267. * if a user is not allowed to login. is this an
  268. * issue? -markus
  269. */
  270. if (PRIVSEP(user_key_allowed(ssh, pw, key, 0, NULL))) {
  271. if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_PK_OK))
  272. != 0 ||
  273. (r = sshpkt_put_cstring(ssh, pkalg)) != 0 ||
  274. (r = sshpkt_put_string(ssh, pkblob, blen)) != 0 ||
  275. (r = sshpkt_send(ssh)) != 0 ||
  276. (r = ssh_packet_write_wait(ssh)) != 0)
  277. fatal("%s: %s", __func__, ssh_err(r));
  278. authctxt->postponed = 1;
  279. }
  280. }
  281. done:
  282. if (authenticated == 1 && auth_activate_options(ssh, authopts) != 0) {
  283. debug("%s: key options inconsistent with existing", __func__);
  284. authenticated = 0;
  285. }
  286. debug2("%s: authenticated %d pkalg %s", __func__, authenticated, pkalg);
  287. sshbuf_free(b);
  288. sshauthopt_free(authopts);
  289. sshkey_free(key);
  290. free(userstyle);
  291. free(pkalg);
  292. free(pkblob);
  293. free(key_s);
  294. free(ca_s);
  295. free(sig);
  296. sshkey_sig_details_free(sig_details);
  297. return authenticated;
  298. }
  299. int
  300. user_key_verify(struct ssh *ssh, const struct sshkey *key, const u_char *sig,
  301. size_t slen, const u_char *data, size_t datalen, const char *pkalg, u_int compat,
  302. struct sshkey_sig_details **detailsp)
  303. {
  304. int rv;
  305. rv = sshkey_verify(key, sig, slen, data, datalen, pkalg, compat, detailsp);
  306. #ifdef SSH_AUDIT_EVENTS
  307. audit_key(ssh, 1, &rv, key);
  308. #endif
  309. return rv;
  310. }
  311. static int
  312. match_principals_option(const char *principal_list, struct sshkey_cert *cert)
  313. {
  314. char *result;
  315. u_int i;
  316. /* XXX percent_expand() sequences for authorized_principals? */
  317. for (i = 0; i < cert->nprincipals; i++) {
  318. if ((result = match_list(cert->principals[i],
  319. principal_list, NULL)) != NULL) {
  320. debug3("matched principal from key options \"%.100s\"",
  321. result);
  322. free(result);
  323. return 1;
  324. }
  325. }
  326. return 0;
  327. }
  328. /*
  329. * Process a single authorized_principals format line. Returns 0 and sets
  330. * authoptsp is principal is authorised, -1 otherwise. "loc" is used as a
  331. * log preamble for file/line information.
  332. */
  333. static int
  334. check_principals_line(struct ssh *ssh, char *cp, const struct sshkey_cert *cert,
  335. const char *loc, struct sshauthopt **authoptsp)
  336. {
  337. u_int i, found = 0;
  338. char *ep, *line_opts;
  339. const char *reason = NULL;
  340. struct sshauthopt *opts = NULL;
  341. if (authoptsp != NULL)
  342. *authoptsp = NULL;
  343. /* Trim trailing whitespace. */
  344. ep = cp + strlen(cp) - 1;
  345. while (ep > cp && (*ep == '\n' || *ep == ' ' || *ep == '\t'))
  346. *ep-- = '\0';
  347. /*
  348. * If the line has internal whitespace then assume it has
  349. * key options.
  350. */
  351. line_opts = NULL;
  352. if ((ep = strrchr(cp, ' ')) != NULL ||
  353. (ep = strrchr(cp, '\t')) != NULL) {
  354. for (; *ep == ' ' || *ep == '\t'; ep++)
  355. ;
  356. line_opts = cp;
  357. cp = ep;
  358. }
  359. if ((opts = sshauthopt_parse(line_opts, &reason)) == NULL) {
  360. debug("%s: bad principals options: %s", loc, reason);
  361. auth_debug_add("%s: bad principals options: %s", loc, reason);
  362. return -1;
  363. }
  364. /* Check principals in cert against those on line */
  365. for (i = 0; i < cert->nprincipals; i++) {
  366. if (strcmp(cp, cert->principals[i]) != 0)
  367. continue;
  368. debug3("%s: matched principal \"%.100s\"",
  369. loc, cert->principals[i]);
  370. found = 1;
  371. }
  372. if (found && authoptsp != NULL) {
  373. *authoptsp = opts;
  374. opts = NULL;
  375. }
  376. sshauthopt_free(opts);
  377. return found ? 0 : -1;
  378. }
  379. static int
  380. process_principals(struct ssh *ssh, FILE *f, const char *file,
  381. const struct sshkey_cert *cert, struct sshauthopt **authoptsp)
  382. {
  383. char loc[256], *line = NULL, *cp, *ep;
  384. size_t linesize = 0;
  385. u_long linenum = 0;
  386. u_int found_principal = 0;
  387. if (authoptsp != NULL)
  388. *authoptsp = NULL;
  389. while (getline(&line, &linesize, f) != -1) {
  390. linenum++;
  391. /* Always consume entire input */
  392. if (found_principal)
  393. continue;
  394. /* Skip leading whitespace. */
  395. for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
  396. ;
  397. /* Skip blank and comment lines. */
  398. if ((ep = strchr(cp, '#')) != NULL)
  399. *ep = '\0';
  400. if (!*cp || *cp == '\n')
  401. continue;
  402. snprintf(loc, sizeof(loc), "%.200s:%lu", file, linenum);
  403. if (check_principals_line(ssh, cp, cert, loc, authoptsp) == 0)
  404. found_principal = 1;
  405. }
  406. free(line);
  407. return found_principal;
  408. }
  409. /* XXX remove pw args here and elsewhere once ssh->authctxt is guaranteed */
  410. static int
  411. match_principals_file(struct ssh *ssh, struct passwd *pw, char *file,
  412. struct sshkey_cert *cert, struct sshauthopt **authoptsp)
  413. {
  414. FILE *f;
  415. int success;
  416. if (authoptsp != NULL)
  417. *authoptsp = NULL;
  418. temporarily_use_uid(pw);
  419. debug("trying authorized principals file %s", file);
  420. if ((f = auth_openprincipals(file, pw, options.strict_modes)) == NULL) {
  421. restore_uid();
  422. return 0;
  423. }
  424. success = process_principals(ssh, f, file, cert, authoptsp);
  425. fclose(f);
  426. restore_uid();
  427. return success;
  428. }
  429. /*
  430. * Checks whether principal is allowed in output of command.
  431. * returns 1 if the principal is allowed or 0 otherwise.
  432. */
  433. static int
  434. match_principals_command(struct ssh *ssh, struct passwd *user_pw,
  435. const struct sshkey *key, struct sshauthopt **authoptsp)
  436. {
  437. struct passwd *runas_pw = NULL;
  438. const struct sshkey_cert *cert = key->cert;
  439. FILE *f = NULL;
  440. int r, ok, found_principal = 0;
  441. int i, ac = 0, uid_swapped = 0;
  442. pid_t pid;
  443. char *tmp, *username = NULL, *command = NULL, **av = NULL;
  444. char *ca_fp = NULL, *key_fp = NULL, *catext = NULL, *keytext = NULL;
  445. char serial_s[32], uidstr[32];
  446. void (*osigchld)(int);
  447. if (authoptsp != NULL)
  448. *authoptsp = NULL;
  449. if (options.authorized_principals_command == NULL)
  450. return 0;
  451. if (options.authorized_principals_command_user == NULL) {
  452. error("No user for AuthorizedPrincipalsCommand specified, "
  453. "skipping");
  454. return 0;
  455. }
  456. /*
  457. * NB. all returns later this function should go via "out" to
  458. * ensure the original SIGCHLD handler is restored properly.
  459. */
  460. osigchld = ssh_signal(SIGCHLD, SIG_DFL);
  461. /* Prepare and verify the user for the command */
  462. username = percent_expand(options.authorized_principals_command_user,
  463. "u", user_pw->pw_name, (char *)NULL);
  464. runas_pw = getpwnam(username);
  465. if (runas_pw == NULL) {
  466. error("AuthorizedPrincipalsCommandUser \"%s\" not found: %s",
  467. username, strerror(errno));
  468. goto out;
  469. }
  470. /* Turn the command into an argument vector */
  471. if (argv_split(options.authorized_principals_command, &ac, &av) != 0) {
  472. error("AuthorizedPrincipalsCommand \"%s\" contains "
  473. "invalid quotes", options.authorized_principals_command);
  474. goto out;
  475. }
  476. if (ac == 0) {
  477. error("AuthorizedPrincipalsCommand \"%s\" yielded no arguments",
  478. options.authorized_principals_command);
  479. goto out;
  480. }
  481. if ((ca_fp = sshkey_fingerprint(cert->signature_key,
  482. options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
  483. error("%s: sshkey_fingerprint failed", __func__);
  484. goto out;
  485. }
  486. if ((key_fp = sshkey_fingerprint(key,
  487. options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
  488. error("%s: sshkey_fingerprint failed", __func__);
  489. goto out;
  490. }
  491. if ((r = sshkey_to_base64(cert->signature_key, &catext)) != 0) {
  492. error("%s: sshkey_to_base64 failed: %s", __func__, ssh_err(r));
  493. goto out;
  494. }
  495. if ((r = sshkey_to_base64(key, &keytext)) != 0) {
  496. error("%s: sshkey_to_base64 failed: %s", __func__, ssh_err(r));
  497. goto out;
  498. }
  499. snprintf(serial_s, sizeof(serial_s), "%llu",
  500. (unsigned long long)cert->serial);
  501. snprintf(uidstr, sizeof(uidstr), "%llu",
  502. (unsigned long long)user_pw->pw_uid);
  503. for (i = 1; i < ac; i++) {
  504. tmp = percent_expand(av[i],
  505. "U", uidstr,
  506. "u", user_pw->pw_name,
  507. "h", user_pw->pw_dir,
  508. "t", sshkey_ssh_name(key),
  509. "T", sshkey_ssh_name(cert->signature_key),
  510. "f", key_fp,
  511. "F", ca_fp,
  512. "k", keytext,
  513. "K", catext,
  514. "i", cert->key_id,
  515. "s", serial_s,
  516. (char *)NULL);
  517. if (tmp == NULL)
  518. fatal("%s: percent_expand failed", __func__);
  519. free(av[i]);
  520. av[i] = tmp;
  521. }
  522. /* Prepare a printable command for logs, etc. */
  523. command = argv_assemble(ac, av);
  524. if ((pid = subprocess("AuthorizedPrincipalsCommand", command,
  525. ac, av, &f,
  526. SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD,
  527. runas_pw, temporarily_use_uid, restore_uid)) == 0)
  528. goto out;
  529. uid_swapped = 1;
  530. temporarily_use_uid(runas_pw);
  531. ok = process_principals(ssh, f, "(command)", cert, authoptsp);
  532. fclose(f);
  533. f = NULL;
  534. if (exited_cleanly(pid, "AuthorizedPrincipalsCommand", command, 0) != 0)
  535. goto out;
  536. /* Read completed successfully */
  537. found_principal = ok;
  538. out:
  539. if (f != NULL)
  540. fclose(f);
  541. ssh_signal(SIGCHLD, osigchld);
  542. for (i = 0; i < ac; i++)
  543. free(av[i]);
  544. free(av);
  545. if (uid_swapped)
  546. restore_uid();
  547. free(command);
  548. free(username);
  549. free(ca_fp);
  550. free(key_fp);
  551. free(catext);
  552. free(keytext);
  553. return found_principal;
  554. }
  555. /*
  556. * Check a single line of an authorized_keys-format file. Returns 0 if key
  557. * matches, -1 otherwise. Will return key/cert options via *authoptsp
  558. * on success. "loc" is used as file/line location in log messages.
  559. */
  560. static int
  561. check_authkey_line(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
  562. char *cp, const char *loc, struct sshauthopt **authoptsp)
  563. {
  564. int want_keytype = sshkey_is_cert(key) ? KEY_UNSPEC : key->type;
  565. struct sshkey *found = NULL;
  566. struct sshauthopt *keyopts = NULL, *certopts = NULL, *finalopts = NULL;
  567. char *key_options = NULL, *fp = NULL;
  568. const char *reason = NULL;
  569. int ret = -1;
  570. if (authoptsp != NULL)
  571. *authoptsp = NULL;
  572. if ((found = sshkey_new(want_keytype)) == NULL) {
  573. debug3("%s: keytype %d failed", __func__, want_keytype);
  574. goto out;
  575. }
  576. /* XXX djm: peek at key type in line and skip if unwanted */
  577. if (sshkey_read(found, &cp) != 0) {
  578. /* no key? check for options */
  579. debug2("%s: check options: '%s'", loc, cp);
  580. key_options = cp;
  581. if (sshkey_advance_past_options(&cp) != 0) {
  582. reason = "invalid key option string";
  583. goto fail_reason;
  584. }
  585. skip_space(&cp);
  586. if (sshkey_read(found, &cp) != 0) {
  587. /* still no key? advance to next line*/
  588. debug2("%s: advance: '%s'", loc, cp);
  589. goto out;
  590. }
  591. }
  592. /* Parse key options now; we need to know if this is a CA key */
  593. if ((keyopts = sshauthopt_parse(key_options, &reason)) == NULL) {
  594. debug("%s: bad key options: %s", loc, reason);
  595. auth_debug_add("%s: bad key options: %s", loc, reason);
  596. goto out;
  597. }
  598. /* Ignore keys that don't match or incorrectly marked as CAs */
  599. if (sshkey_is_cert(key)) {
  600. /* Certificate; check signature key against CA */
  601. if (!sshkey_equal(found, key->cert->signature_key) ||
  602. !keyopts->cert_authority)
  603. goto out;
  604. } else {
  605. /* Plain key: check it against key found in file */
  606. if (!sshkey_equal(found, key) || keyopts->cert_authority)
  607. goto out;
  608. }
  609. /* We have a candidate key, perform authorisation checks */
  610. if ((fp = sshkey_fingerprint(found,
  611. options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
  612. fatal("%s: fingerprint failed", __func__);
  613. debug("%s: matching %s found: %s %s", loc,
  614. sshkey_is_cert(key) ? "CA" : "key", sshkey_type(found), fp);
  615. if (auth_authorise_keyopts(ssh, pw, keyopts,
  616. sshkey_is_cert(key), loc) != 0) {
  617. reason = "Refused by key options";
  618. goto fail_reason;
  619. }
  620. /* That's all we need for plain keys. */
  621. if (!sshkey_is_cert(key)) {
  622. verbose("Accepted key %s %s found at %s",
  623. sshkey_type(found), fp, loc);
  624. finalopts = keyopts;
  625. keyopts = NULL;
  626. goto success;
  627. }
  628. /*
  629. * Additional authorisation for certificates.
  630. */
  631. /* Parse and check options present in certificate */
  632. if ((certopts = sshauthopt_from_cert(key)) == NULL) {
  633. reason = "Invalid certificate options";
  634. goto fail_reason;
  635. }
  636. if (auth_authorise_keyopts(ssh, pw, certopts, 0, loc) != 0) {
  637. reason = "Refused by certificate options";
  638. goto fail_reason;
  639. }
  640. if ((finalopts = sshauthopt_merge(keyopts, certopts, &reason)) == NULL)
  641. goto fail_reason;
  642. /*
  643. * If the user has specified a list of principals as
  644. * a key option, then prefer that list to matching
  645. * their username in the certificate principals list.
  646. */
  647. if (keyopts->cert_principals != NULL &&
  648. !match_principals_option(keyopts->cert_principals, key->cert)) {
  649. reason = "Certificate does not contain an authorized principal";
  650. goto fail_reason;
  651. }
  652. if (sshkey_cert_check_authority(key, 0, 0, 0,
  653. keyopts->cert_principals == NULL ? pw->pw_name : NULL, &reason) != 0)
  654. goto fail_reason;
  655. verbose("Accepted certificate ID \"%s\" (serial %llu) "
  656. "signed by CA %s %s found at %s",
  657. key->cert->key_id,
  658. (unsigned long long)key->cert->serial,
  659. sshkey_type(found), fp, loc);
  660. success:
  661. if (finalopts == NULL)
  662. fatal("%s: internal error: missing options", __func__);
  663. if (authoptsp != NULL) {
  664. *authoptsp = finalopts;
  665. finalopts = NULL;
  666. }
  667. /* success */
  668. ret = 0;
  669. goto out;
  670. fail_reason:
  671. error("%s", reason);
  672. auth_debug_add("%s", reason);
  673. out:
  674. free(fp);
  675. sshauthopt_free(keyopts);
  676. sshauthopt_free(certopts);
  677. sshauthopt_free(finalopts);
  678. sshkey_free(found);
  679. return ret;
  680. }
  681. /*
  682. * Checks whether key is allowed in authorized_keys-format file,
  683. * returns 1 if the key is allowed or 0 otherwise.
  684. */
  685. static int
  686. check_authkeys_file(struct ssh *ssh, struct passwd *pw, FILE *f,
  687. char *file, struct sshkey *key, struct sshauthopt **authoptsp)
  688. {
  689. char *cp, *line = NULL, loc[256];
  690. size_t linesize = 0;
  691. int found_key = 0;
  692. u_long linenum = 0;
  693. if (authoptsp != NULL)
  694. *authoptsp = NULL;
  695. while (getline(&line, &linesize, f) != -1) {
  696. linenum++;
  697. /* Always consume entire file */
  698. if (found_key)
  699. continue;
  700. /* Skip leading whitespace, empty and comment lines. */
  701. cp = line;
  702. skip_space(&cp);
  703. if (!*cp || *cp == '\n' || *cp == '#')
  704. continue;
  705. snprintf(loc, sizeof(loc), "%.200s:%lu", file, linenum);
  706. if (check_authkey_line(ssh, pw, key, cp, loc, authoptsp) == 0)
  707. found_key = 1;
  708. }
  709. free(line);
  710. return found_key;
  711. }
  712. /* Authenticate a certificate key against TrustedUserCAKeys */
  713. static int
  714. user_cert_trusted_ca(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
  715. struct sshauthopt **authoptsp)
  716. {
  717. char *ca_fp, *principals_file = NULL;
  718. const char *reason;
  719. struct sshauthopt *principals_opts = NULL, *cert_opts = NULL;
  720. struct sshauthopt *final_opts = NULL;
  721. int r, ret = 0, found_principal = 0, use_authorized_principals;
  722. if (authoptsp != NULL)
  723. *authoptsp = NULL;
  724. if (!sshkey_is_cert(key) || options.trusted_user_ca_keys == NULL)
  725. return 0;
  726. if ((ca_fp = sshkey_fingerprint(key->cert->signature_key,
  727. options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
  728. return 0;
  729. if ((r = sshkey_in_file(key->cert->signature_key,
  730. options.trusted_user_ca_keys, 1, 0)) != 0) {
  731. debug2("%s: CA %s %s is not listed in %s: %s", __func__,
  732. sshkey_type(key->cert->signature_key), ca_fp,
  733. options.trusted_user_ca_keys, ssh_err(r));
  734. goto out;
  735. }
  736. /*
  737. * If AuthorizedPrincipals is in use, then compare the certificate
  738. * principals against the names in that file rather than matching
  739. * against the username.
  740. */
  741. if ((principals_file = authorized_principals_file(pw)) != NULL) {
  742. if (match_principals_file(ssh, pw, principals_file,
  743. key->cert, &principals_opts))
  744. found_principal = 1;
  745. }
  746. /* Try querying command if specified */
  747. if (!found_principal && match_principals_command(ssh, pw, key,
  748. &principals_opts))
  749. found_principal = 1;
  750. /* If principals file or command is specified, then require a match */
  751. use_authorized_principals = principals_file != NULL ||
  752. options.authorized_principals_command != NULL;
  753. if (!found_principal && use_authorized_principals) {
  754. reason = "Certificate does not contain an authorized principal";
  755. goto fail_reason;
  756. }
  757. if (use_authorized_principals && principals_opts == NULL)
  758. fatal("%s: internal error: missing principals_opts", __func__);
  759. if (sshkey_cert_check_authority(key, 0, 1, 0,
  760. use_authorized_principals ? NULL : pw->pw_name, &reason) != 0)
  761. goto fail_reason;
  762. /* Check authority from options in key and from principals file/cmd */
  763. if ((cert_opts = sshauthopt_from_cert(key)) == NULL) {
  764. reason = "Invalid certificate options";
  765. goto fail_reason;
  766. }
  767. if (auth_authorise_keyopts(ssh, pw, cert_opts, 0, "cert") != 0) {
  768. reason = "Refused by certificate options";
  769. goto fail_reason;
  770. }
  771. if (principals_opts == NULL) {
  772. final_opts = cert_opts;
  773. cert_opts = NULL;
  774. } else {
  775. if (auth_authorise_keyopts(ssh, pw, principals_opts, 0,
  776. "principals") != 0) {
  777. reason = "Refused by certificate principals options";
  778. goto fail_reason;
  779. }
  780. if ((final_opts = sshauthopt_merge(principals_opts,
  781. cert_opts, &reason)) == NULL) {
  782. fail_reason:
  783. error("%s", reason);
  784. auth_debug_add("%s", reason);
  785. goto out;
  786. }
  787. }
  788. /* Success */
  789. verbose("Accepted certificate ID \"%s\" (serial %llu) signed by "
  790. "%s CA %s via %s", key->cert->key_id,
  791. (unsigned long long)key->cert->serial,
  792. sshkey_type(key->cert->signature_key), ca_fp,
  793. options.trusted_user_ca_keys);
  794. if (authoptsp != NULL) {
  795. *authoptsp = final_opts;
  796. final_opts = NULL;
  797. }
  798. ret = 1;
  799. out:
  800. sshauthopt_free(principals_opts);
  801. sshauthopt_free(cert_opts);
  802. sshauthopt_free(final_opts);
  803. free(principals_file);
  804. free(ca_fp);
  805. return ret;
  806. }
  807. /*
  808. * Checks whether key is allowed in file.
  809. * returns 1 if the key is allowed or 0 otherwise.
  810. */
  811. static int
  812. user_key_allowed2(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
  813. char *file, struct sshauthopt **authoptsp)
  814. {
  815. FILE *f;
  816. int found_key = 0;
  817. if (authoptsp != NULL)
  818. *authoptsp = NULL;
  819. /* Temporarily use the user's uid. */
  820. temporarily_use_uid(pw);
  821. debug("trying public key file %s", file);
  822. if ((f = auth_openkeyfile(file, pw, options.strict_modes)) != NULL) {
  823. found_key = check_authkeys_file(ssh, pw, f, file,
  824. key, authoptsp);
  825. fclose(f);
  826. }
  827. restore_uid();
  828. return found_key;
  829. }
  830. /*
  831. * Checks whether key is allowed in output of command.
  832. * returns 1 if the key is allowed or 0 otherwise.
  833. */
  834. static int
  835. user_key_command_allowed2(struct ssh *ssh, struct passwd *user_pw,
  836. struct sshkey *key, struct sshauthopt **authoptsp)
  837. {
  838. struct passwd *runas_pw = NULL;
  839. FILE *f = NULL;
  840. int r, ok, found_key = 0;
  841. int i, uid_swapped = 0, ac = 0;
  842. pid_t pid;
  843. char *username = NULL, *key_fp = NULL, *keytext = NULL;
  844. char uidstr[32], *tmp, *command = NULL, **av = NULL;
  845. void (*osigchld)(int);
  846. if (authoptsp != NULL)
  847. *authoptsp = NULL;
  848. if (options.authorized_keys_command == NULL)
  849. return 0;
  850. if (options.authorized_keys_command_user == NULL) {
  851. error("No user for AuthorizedKeysCommand specified, skipping");
  852. return 0;
  853. }
  854. /*
  855. * NB. all returns later this function should go via "out" to
  856. * ensure the original SIGCHLD handler is restored properly.
  857. */
  858. osigchld = ssh_signal(SIGCHLD, SIG_DFL);
  859. /* Prepare and verify the user for the command */
  860. username = percent_expand(options.authorized_keys_command_user,
  861. "u", user_pw->pw_name, (char *)NULL);
  862. runas_pw = getpwnam(username);
  863. if (runas_pw == NULL) {
  864. error("AuthorizedKeysCommandUser \"%s\" not found: %s",
  865. username, strerror(errno));
  866. goto out;
  867. }
  868. /* Prepare AuthorizedKeysCommand */
  869. if ((key_fp = sshkey_fingerprint(key, options.fingerprint_hash,
  870. SSH_FP_DEFAULT)) == NULL) {
  871. error("%s: sshkey_fingerprint failed", __func__);
  872. goto out;
  873. }
  874. if ((r = sshkey_to_base64(key, &keytext)) != 0) {
  875. error("%s: sshkey_to_base64 failed: %s", __func__, ssh_err(r));
  876. goto out;
  877. }
  878. /* Turn the command into an argument vector */
  879. if (argv_split(options.authorized_keys_command, &ac, &av) != 0) {
  880. error("AuthorizedKeysCommand \"%s\" contains invalid quotes",
  881. options.authorized_keys_command);
  882. goto out;
  883. }
  884. if (ac == 0) {
  885. error("AuthorizedKeysCommand \"%s\" yielded no arguments",
  886. options.authorized_keys_command);
  887. goto out;
  888. }
  889. snprintf(uidstr, sizeof(uidstr), "%llu",
  890. (unsigned long long)user_pw->pw_uid);
  891. for (i = 1; i < ac; i++) {
  892. tmp = percent_expand(av[i],
  893. "U", uidstr,
  894. "u", user_pw->pw_name,
  895. "h", user_pw->pw_dir,
  896. "t", sshkey_ssh_name(key),
  897. "f", key_fp,
  898. "k", keytext,
  899. (char *)NULL);
  900. if (tmp == NULL)
  901. fatal("%s: percent_expand failed", __func__);
  902. free(av[i]);
  903. av[i] = tmp;
  904. }
  905. /* Prepare a printable command for logs, etc. */
  906. command = argv_assemble(ac, av);
  907. /*
  908. * If AuthorizedKeysCommand was run without arguments
  909. * then fall back to the old behaviour of passing the
  910. * target username as a single argument.
  911. */
  912. if (ac == 1) {
  913. av = xreallocarray(av, ac + 2, sizeof(*av));
  914. av[1] = xstrdup(user_pw->pw_name);
  915. av[2] = NULL;
  916. /* Fix up command too, since it is used in log messages */
  917. free(command);
  918. xasprintf(&command, "%s %s", av[0], av[1]);
  919. }
  920. if ((pid = subprocess("AuthorizedKeysCommand", command,
  921. ac, av, &f,
  922. SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_STDERR_DISCARD,
  923. runas_pw, temporarily_use_uid, restore_uid)) == 0)
  924. goto out;
  925. uid_swapped = 1;
  926. temporarily_use_uid(runas_pw);
  927. ok = check_authkeys_file(ssh, user_pw, f,
  928. options.authorized_keys_command, key, authoptsp);
  929. fclose(f);
  930. f = NULL;
  931. if (exited_cleanly(pid, "AuthorizedKeysCommand", command, 0) != 0)
  932. goto out;
  933. /* Read completed successfully */
  934. found_key = ok;
  935. out:
  936. if (f != NULL)
  937. fclose(f);
  938. ssh_signal(SIGCHLD, osigchld);
  939. for (i = 0; i < ac; i++)
  940. free(av[i]);
  941. free(av);
  942. if (uid_swapped)
  943. restore_uid();
  944. free(command);
  945. free(username);
  946. free(key_fp);
  947. free(keytext);
  948. return found_key;
  949. }
  950. /*
  951. * Check whether key authenticates and authorises the user.
  952. */
  953. int
  954. user_key_allowed(struct ssh *ssh, struct passwd *pw, struct sshkey *key,
  955. int auth_attempt, struct sshauthopt **authoptsp)
  956. {
  957. u_int success = 0, i;
  958. char *file;
  959. struct sshauthopt *opts = NULL;
  960. if (authoptsp != NULL)
  961. *authoptsp = NULL;
  962. if (auth_key_is_revoked(key))
  963. return 0;
  964. if (sshkey_is_cert(key) &&
  965. auth_key_is_revoked(key->cert->signature_key))
  966. return 0;
  967. for (i = 0; !success && i < options.num_authkeys_files; i++) {
  968. if (strcasecmp(options.authorized_keys_files[i], "none") == 0)
  969. continue;
  970. file = expand_authorized_keys(
  971. options.authorized_keys_files[i], pw);
  972. success = user_key_allowed2(ssh, pw, key, file, &opts);
  973. free(file);
  974. if (!success) {
  975. sshauthopt_free(opts);
  976. opts = NULL;
  977. }
  978. }
  979. if (success)
  980. goto out;
  981. if ((success = user_cert_trusted_ca(ssh, pw, key, &opts)) != 0)
  982. goto out;
  983. sshauthopt_free(opts);
  984. opts = NULL;
  985. if ((success = user_key_command_allowed2(ssh, pw, key, &opts)) != 0)
  986. goto out;
  987. sshauthopt_free(opts);
  988. opts = NULL;
  989. out:
  990. if (success && authoptsp != NULL) {
  991. *authoptsp = opts;
  992. opts = NULL;
  993. }
  994. sshauthopt_free(opts);
  995. return success;
  996. }
  997. Authmethod method_pubkey = {
  998. "publickey",
  999. userauth_pubkey,
  1000. &options.pubkey_authentication
  1001. };