auth.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  1. /* $OpenBSD: auth.c,v 1.147 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 <sys/socket.h>
  29. #include <sys/wait.h>
  30. #include <netinet/in.h>
  31. #include <stdlib.h>
  32. #include <errno.h>
  33. #include <fcntl.h>
  34. #ifdef HAVE_PATHS_H
  35. # include <paths.h>
  36. #endif
  37. #include <pwd.h>
  38. #ifdef HAVE_LOGIN_H
  39. #include <login.h>
  40. #endif
  41. #ifdef USE_SHADOW
  42. #include <shadow.h>
  43. #endif
  44. #include <stdarg.h>
  45. #include <stdio.h>
  46. #include <string.h>
  47. #include <unistd.h>
  48. #include <limits.h>
  49. #include <netdb.h>
  50. #include <time.h>
  51. #include "xmalloc.h"
  52. #include "match.h"
  53. #include "groupaccess.h"
  54. #include "log.h"
  55. #include "sshbuf.h"
  56. #include "misc.h"
  57. #include "servconf.h"
  58. #include "sshkey.h"
  59. #include "hostfile.h"
  60. #include "auth.h"
  61. #include "auth-options.h"
  62. #include "canohost.h"
  63. #include "uidswap.h"
  64. #include "packet.h"
  65. #include "loginrec.h"
  66. #ifdef GSSAPI
  67. #include "ssh-gss.h"
  68. #endif
  69. #include "authfile.h"
  70. #include "monitor_wrap.h"
  71. #include "ssherr.h"
  72. #include "compat.h"
  73. #include "channels.h"
  74. /* import */
  75. extern ServerOptions options;
  76. extern struct include_list includes;
  77. extern int use_privsep;
  78. extern struct sshbuf *loginmsg;
  79. extern struct passwd *privsep_pw;
  80. extern struct sshauthopt *auth_opts;
  81. /* Debugging messages */
  82. static struct sshbuf *auth_debug;
  83. /*
  84. * Check if the user is allowed to log in via ssh. If user is listed
  85. * in DenyUsers or one of user's groups is listed in DenyGroups, false
  86. * will be returned. If AllowUsers isn't empty and user isn't listed
  87. * there, or if AllowGroups isn't empty and one of user's groups isn't
  88. * listed there, false will be returned.
  89. * If the user's shell is not executable, false will be returned.
  90. * Otherwise true is returned.
  91. */
  92. int
  93. allowed_user(struct ssh *ssh, struct passwd * pw)
  94. {
  95. struct stat st;
  96. const char *hostname = NULL, *ipaddr = NULL, *passwd = NULL;
  97. u_int i;
  98. int r;
  99. #ifdef USE_SHADOW
  100. struct spwd *spw = NULL;
  101. #endif
  102. /* Shouldn't be called if pw is NULL, but better safe than sorry... */
  103. if (!pw || !pw->pw_name)
  104. return 0;
  105. #ifdef USE_SHADOW
  106. if (!options.use_pam)
  107. spw = getspnam(pw->pw_name);
  108. #ifdef HAS_SHADOW_EXPIRE
  109. if (!options.use_pam && spw != NULL && auth_shadow_acctexpired(spw))
  110. return 0;
  111. #endif /* HAS_SHADOW_EXPIRE */
  112. #endif /* USE_SHADOW */
  113. /* grab passwd field for locked account check */
  114. passwd = pw->pw_passwd;
  115. #ifdef USE_SHADOW
  116. if (spw != NULL)
  117. #ifdef USE_LIBIAF
  118. passwd = get_iaf_password(pw);
  119. #else
  120. passwd = spw->sp_pwdp;
  121. #endif /* USE_LIBIAF */
  122. #endif
  123. /* check for locked account */
  124. if (!options.use_pam && passwd && *passwd) {
  125. int locked = 0;
  126. #ifdef LOCKED_PASSWD_STRING
  127. if (strcmp(passwd, LOCKED_PASSWD_STRING) == 0)
  128. locked = 1;
  129. #endif
  130. #ifdef LOCKED_PASSWD_PREFIX
  131. if (strncmp(passwd, LOCKED_PASSWD_PREFIX,
  132. strlen(LOCKED_PASSWD_PREFIX)) == 0)
  133. locked = 1;
  134. #endif
  135. #ifdef LOCKED_PASSWD_SUBSTR
  136. if (strstr(passwd, LOCKED_PASSWD_SUBSTR))
  137. locked = 1;
  138. #endif
  139. #ifdef USE_LIBIAF
  140. free((void *) passwd);
  141. #endif /* USE_LIBIAF */
  142. if (locked) {
  143. logit("User %.100s not allowed because account is locked",
  144. pw->pw_name);
  145. return 0;
  146. }
  147. }
  148. /*
  149. * Deny if shell does not exist or is not executable unless we
  150. * are chrooting.
  151. */
  152. if (options.chroot_directory == NULL ||
  153. strcasecmp(options.chroot_directory, "none") == 0) {
  154. char *shell = xstrdup((pw->pw_shell[0] == '\0') ?
  155. _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */
  156. if (stat(shell, &st) == -1) {
  157. logit("User %.100s not allowed because shell %.100s "
  158. "does not exist", pw->pw_name, shell);
  159. free(shell);
  160. return 0;
  161. }
  162. if (S_ISREG(st.st_mode) == 0 ||
  163. (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
  164. logit("User %.100s not allowed because shell %.100s "
  165. "is not executable", pw->pw_name, shell);
  166. free(shell);
  167. return 0;
  168. }
  169. free(shell);
  170. }
  171. if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
  172. options.num_deny_groups > 0 || options.num_allow_groups > 0) {
  173. hostname = auth_get_canonical_hostname(ssh, options.use_dns);
  174. ipaddr = ssh_remote_ipaddr(ssh);
  175. }
  176. /* Return false if user is listed in DenyUsers */
  177. if (options.num_deny_users > 0) {
  178. for (i = 0; i < options.num_deny_users; i++) {
  179. r = match_user(pw->pw_name, hostname, ipaddr,
  180. options.deny_users[i]);
  181. if (r < 0) {
  182. fatal("Invalid DenyUsers pattern \"%.100s\"",
  183. options.deny_users[i]);
  184. } else if (r != 0) {
  185. logit("User %.100s from %.100s not allowed "
  186. "because listed in DenyUsers",
  187. pw->pw_name, hostname);
  188. return 0;
  189. }
  190. }
  191. }
  192. /* Return false if AllowUsers isn't empty and user isn't listed there */
  193. if (options.num_allow_users > 0) {
  194. for (i = 0; i < options.num_allow_users; i++) {
  195. r = match_user(pw->pw_name, hostname, ipaddr,
  196. options.allow_users[i]);
  197. if (r < 0) {
  198. fatal("Invalid AllowUsers pattern \"%.100s\"",
  199. options.allow_users[i]);
  200. } else if (r == 1)
  201. break;
  202. }
  203. /* i < options.num_allow_users iff we break for loop */
  204. if (i >= options.num_allow_users) {
  205. logit("User %.100s from %.100s not allowed because "
  206. "not listed in AllowUsers", pw->pw_name, hostname);
  207. return 0;
  208. }
  209. }
  210. if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
  211. /* Get the user's group access list (primary and supplementary) */
  212. if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
  213. logit("User %.100s from %.100s not allowed because "
  214. "not in any group", pw->pw_name, hostname);
  215. return 0;
  216. }
  217. /* Return false if one of user's groups is listed in DenyGroups */
  218. if (options.num_deny_groups > 0)
  219. if (ga_match(options.deny_groups,
  220. options.num_deny_groups)) {
  221. ga_free();
  222. logit("User %.100s from %.100s not allowed "
  223. "because a group is listed in DenyGroups",
  224. pw->pw_name, hostname);
  225. return 0;
  226. }
  227. /*
  228. * Return false if AllowGroups isn't empty and one of user's groups
  229. * isn't listed there
  230. */
  231. if (options.num_allow_groups > 0)
  232. if (!ga_match(options.allow_groups,
  233. options.num_allow_groups)) {
  234. ga_free();
  235. logit("User %.100s from %.100s not allowed "
  236. "because none of user's groups are listed "
  237. "in AllowGroups", pw->pw_name, hostname);
  238. return 0;
  239. }
  240. ga_free();
  241. }
  242. #ifdef CUSTOM_SYS_AUTH_ALLOWED_USER
  243. if (!sys_auth_allowed_user(pw, loginmsg))
  244. return 0;
  245. #endif
  246. /* We found no reason not to let this user try to log on... */
  247. return 1;
  248. }
  249. /*
  250. * Formats any key left in authctxt->auth_method_key for inclusion in
  251. * auth_log()'s message. Also includes authxtct->auth_method_info if present.
  252. */
  253. static char *
  254. format_method_key(Authctxt *authctxt)
  255. {
  256. const struct sshkey *key = authctxt->auth_method_key;
  257. const char *methinfo = authctxt->auth_method_info;
  258. char *fp, *cafp, *ret = NULL;
  259. if (key == NULL)
  260. return NULL;
  261. if (sshkey_is_cert(key)) {
  262. fp = sshkey_fingerprint(key,
  263. options.fingerprint_hash, SSH_FP_DEFAULT);
  264. cafp = sshkey_fingerprint(key->cert->signature_key,
  265. options.fingerprint_hash, SSH_FP_DEFAULT);
  266. xasprintf(&ret, "%s %s ID %s (serial %llu) CA %s %s%s%s",
  267. sshkey_type(key), fp == NULL ? "(null)" : fp,
  268. key->cert->key_id,
  269. (unsigned long long)key->cert->serial,
  270. sshkey_type(key->cert->signature_key),
  271. cafp == NULL ? "(null)" : cafp,
  272. methinfo == NULL ? "" : ", ",
  273. methinfo == NULL ? "" : methinfo);
  274. free(fp);
  275. free(cafp);
  276. } else {
  277. fp = sshkey_fingerprint(key, options.fingerprint_hash,
  278. SSH_FP_DEFAULT);
  279. xasprintf(&ret, "%s %s%s%s", sshkey_type(key),
  280. fp == NULL ? "(null)" : fp,
  281. methinfo == NULL ? "" : ", ",
  282. methinfo == NULL ? "" : methinfo);
  283. free(fp);
  284. }
  285. return ret;
  286. }
  287. void
  288. auth_log(struct ssh *ssh, int authenticated, int partial,
  289. const char *method, const char *submethod)
  290. {
  291. Authctxt *authctxt = (Authctxt *)ssh->authctxt;
  292. int level = SYSLOG_LEVEL_VERBOSE;
  293. const char *authmsg;
  294. char *extra = NULL;
  295. if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
  296. return;
  297. /* Raise logging level */
  298. if (authenticated == 1 ||
  299. !authctxt->valid ||
  300. authctxt->failures >= options.max_authtries / 2 ||
  301. strcmp(method, "password") == 0)
  302. level = SYSLOG_LEVEL_INFO;
  303. if (authctxt->postponed)
  304. authmsg = "Postponed";
  305. else if (partial)
  306. authmsg = "Partial";
  307. else
  308. authmsg = authenticated ? "Accepted" : "Failed";
  309. if ((extra = format_method_key(authctxt)) == NULL) {
  310. if (authctxt->auth_method_info != NULL)
  311. extra = xstrdup(authctxt->auth_method_info);
  312. }
  313. do_log2(level, "%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s",
  314. authmsg,
  315. method,
  316. submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
  317. authctxt->valid ? "" : "invalid user ",
  318. authctxt->user,
  319. ssh_remote_ipaddr(ssh),
  320. ssh_remote_port(ssh),
  321. extra != NULL ? ": " : "",
  322. extra != NULL ? extra : "");
  323. free(extra);
  324. #ifdef CUSTOM_FAILED_LOGIN
  325. if (authenticated == 0 && !authctxt->postponed &&
  326. (strcmp(method, "password") == 0 ||
  327. strncmp(method, "keyboard-interactive", 20) == 0 ||
  328. strcmp(method, "challenge-response") == 0))
  329. record_failed_login(ssh, authctxt->user,
  330. auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
  331. # ifdef WITH_AIXAUTHENTICATE
  332. if (authenticated)
  333. sys_auth_record_login(authctxt->user,
  334. auth_get_canonical_hostname(ssh, options.use_dns), "ssh",
  335. loginmsg);
  336. # endif
  337. #endif
  338. #ifdef SSH_AUDIT_EVENTS
  339. if (authenticated == 0 && !authctxt->postponed && !partial)
  340. audit_event(ssh, audit_classify_auth(method));
  341. #endif
  342. }
  343. void
  344. auth_maxtries_exceeded(struct ssh *ssh)
  345. {
  346. Authctxt *authctxt = (Authctxt *)ssh->authctxt;
  347. error("maximum authentication attempts exceeded for "
  348. "%s%.100s from %.200s port %d ssh2",
  349. authctxt->valid ? "" : "invalid user ",
  350. authctxt->user,
  351. ssh_remote_ipaddr(ssh),
  352. ssh_remote_port(ssh));
  353. ssh_packet_disconnect(ssh, "Too many authentication failures");
  354. /* NOTREACHED */
  355. }
  356. /*
  357. * Check whether root logins are disallowed.
  358. */
  359. int
  360. auth_root_allowed(struct ssh *ssh, const char *method)
  361. {
  362. switch (options.permit_root_login) {
  363. case PERMIT_YES:
  364. return 1;
  365. case PERMIT_NO_PASSWD:
  366. if (strcmp(method, "publickey") == 0 ||
  367. strcmp(method, "hostbased") == 0 ||
  368. strcmp(method, "gssapi-with-mic") == 0)
  369. return 1;
  370. break;
  371. case PERMIT_FORCED_ONLY:
  372. if (auth_opts->force_command != NULL) {
  373. logit("Root login accepted for forced command.");
  374. return 1;
  375. }
  376. break;
  377. }
  378. logit("ROOT LOGIN REFUSED FROM %.200s port %d",
  379. ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
  380. return 0;
  381. }
  382. /*
  383. * Given a template and a passwd structure, build a filename
  384. * by substituting % tokenised options. Currently, %% becomes '%',
  385. * %h becomes the home directory and %u the username.
  386. *
  387. * This returns a buffer allocated by xmalloc.
  388. */
  389. char *
  390. expand_authorized_keys(const char *filename, struct passwd *pw)
  391. {
  392. char *file, uidstr[32], ret[PATH_MAX];
  393. int i;
  394. snprintf(uidstr, sizeof(uidstr), "%llu",
  395. (unsigned long long)pw->pw_uid);
  396. file = percent_expand(filename, "h", pw->pw_dir,
  397. "u", pw->pw_name, "U", uidstr, (char *)NULL);
  398. /*
  399. * Ensure that filename starts anchored. If not, be backward
  400. * compatible and prepend the '%h/'
  401. */
  402. if (path_absolute(file))
  403. return (file);
  404. i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
  405. if (i < 0 || (size_t)i >= sizeof(ret))
  406. fatal("expand_authorized_keys: path too long");
  407. free(file);
  408. return (xstrdup(ret));
  409. }
  410. char *
  411. authorized_principals_file(struct passwd *pw)
  412. {
  413. if (options.authorized_principals_file == NULL)
  414. return NULL;
  415. return expand_authorized_keys(options.authorized_principals_file, pw);
  416. }
  417. /* return ok if key exists in sysfile or userfile */
  418. HostStatus
  419. check_key_in_hostfiles(struct passwd *pw, struct sshkey *key, const char *host,
  420. const char *sysfile, const char *userfile)
  421. {
  422. char *user_hostfile;
  423. struct stat st;
  424. HostStatus host_status;
  425. struct hostkeys *hostkeys;
  426. const struct hostkey_entry *found;
  427. hostkeys = init_hostkeys();
  428. load_hostkeys(hostkeys, host, sysfile);
  429. if (userfile != NULL) {
  430. user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
  431. if (options.strict_modes &&
  432. (stat(user_hostfile, &st) == 0) &&
  433. ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
  434. (st.st_mode & 022) != 0)) {
  435. logit("Authentication refused for %.100s: "
  436. "bad owner or modes for %.200s",
  437. pw->pw_name, user_hostfile);
  438. auth_debug_add("Ignored %.200s: bad ownership or modes",
  439. user_hostfile);
  440. } else {
  441. temporarily_use_uid(pw);
  442. load_hostkeys(hostkeys, host, user_hostfile);
  443. restore_uid();
  444. }
  445. free(user_hostfile);
  446. }
  447. host_status = check_key_in_hostkeys(hostkeys, key, &found);
  448. if (host_status == HOST_REVOKED)
  449. error("WARNING: revoked key for %s attempted authentication",
  450. host);
  451. else if (host_status == HOST_OK)
  452. debug("%s: key for %s found at %s:%ld", __func__,
  453. found->host, found->file, found->line);
  454. else
  455. debug("%s: key for host %s not found", __func__, host);
  456. free_hostkeys(hostkeys);
  457. return host_status;
  458. }
  459. static FILE *
  460. auth_openfile(const char *file, struct passwd *pw, int strict_modes,
  461. int log_missing, char *file_type)
  462. {
  463. char line[1024];
  464. struct stat st;
  465. int fd;
  466. FILE *f;
  467. if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) {
  468. if (log_missing || errno != ENOENT)
  469. debug("Could not open %s '%s': %s", file_type, file,
  470. strerror(errno));
  471. return NULL;
  472. }
  473. if (fstat(fd, &st) == -1) {
  474. close(fd);
  475. return NULL;
  476. }
  477. if (!S_ISREG(st.st_mode)) {
  478. logit("User %s %s %s is not a regular file",
  479. pw->pw_name, file_type, file);
  480. close(fd);
  481. return NULL;
  482. }
  483. unset_nonblock(fd);
  484. if ((f = fdopen(fd, "r")) == NULL) {
  485. close(fd);
  486. return NULL;
  487. }
  488. if (strict_modes &&
  489. safe_path_fd(fileno(f), file, pw, line, sizeof(line)) != 0) {
  490. fclose(f);
  491. logit("Authentication refused: %s", line);
  492. auth_debug_add("Ignored %s: %s", file_type, line);
  493. return NULL;
  494. }
  495. return f;
  496. }
  497. FILE *
  498. auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
  499. {
  500. return auth_openfile(file, pw, strict_modes, 1, "authorized keys");
  501. }
  502. FILE *
  503. auth_openprincipals(const char *file, struct passwd *pw, int strict_modes)
  504. {
  505. return auth_openfile(file, pw, strict_modes, 0,
  506. "authorized principals");
  507. }
  508. struct passwd *
  509. getpwnamallow(struct ssh *ssh, const char *user)
  510. {
  511. #ifdef HAVE_LOGIN_CAP
  512. extern login_cap_t *lc;
  513. #ifdef BSD_AUTH
  514. auth_session_t *as;
  515. #endif
  516. #endif
  517. struct passwd *pw;
  518. struct connection_info *ci;
  519. ci = get_connection_info(ssh, 1, options.use_dns);
  520. ci->user = user;
  521. parse_server_match_config(&options, &includes, ci);
  522. log_change_level(options.log_level);
  523. process_permitopen(ssh, &options);
  524. #if defined(_AIX) && defined(HAVE_SETAUTHDB)
  525. aix_setauthdb(user);
  526. #endif
  527. pw = getpwnam(user);
  528. #if defined(_AIX) && defined(HAVE_SETAUTHDB)
  529. aix_restoreauthdb();
  530. #endif
  531. if (pw == NULL) {
  532. logit("Invalid user %.100s from %.100s port %d",
  533. user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
  534. #ifdef CUSTOM_FAILED_LOGIN
  535. record_failed_login(ssh, user,
  536. auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
  537. #endif
  538. return (NULL);
  539. }
  540. if (!allowed_user(ssh, pw))
  541. return (NULL);
  542. #ifdef HAVE_LOGIN_CAP
  543. if ((lc = login_getclass(pw->pw_class)) == NULL) {
  544. debug("unable to get login class: %s", user);
  545. return (NULL);
  546. }
  547. #ifdef BSD_AUTH
  548. if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
  549. auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
  550. debug("Approval failure for %s", user);
  551. pw = NULL;
  552. }
  553. if (as != NULL)
  554. auth_close(as);
  555. #endif
  556. #endif
  557. if (pw != NULL)
  558. return (pwcopy(pw));
  559. return (NULL);
  560. }
  561. /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
  562. int
  563. auth_key_is_revoked(struct sshkey *key)
  564. {
  565. char *fp = NULL;
  566. int r;
  567. if (options.revoked_keys_file == NULL)
  568. return 0;
  569. if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
  570. SSH_FP_DEFAULT)) == NULL) {
  571. r = SSH_ERR_ALLOC_FAIL;
  572. error("%s: fingerprint key: %s", __func__, ssh_err(r));
  573. goto out;
  574. }
  575. r = sshkey_check_revoked(key, options.revoked_keys_file);
  576. switch (r) {
  577. case 0:
  578. break; /* not revoked */
  579. case SSH_ERR_KEY_REVOKED:
  580. error("Authentication key %s %s revoked by file %s",
  581. sshkey_type(key), fp, options.revoked_keys_file);
  582. goto out;
  583. default:
  584. error("Error checking authentication key %s %s in "
  585. "revoked keys file %s: %s", sshkey_type(key), fp,
  586. options.revoked_keys_file, ssh_err(r));
  587. goto out;
  588. }
  589. /* Success */
  590. r = 0;
  591. out:
  592. free(fp);
  593. return r == 0 ? 0 : 1;
  594. }
  595. void
  596. auth_debug_add(const char *fmt,...)
  597. {
  598. char buf[1024];
  599. va_list args;
  600. int r;
  601. if (auth_debug == NULL)
  602. return;
  603. va_start(args, fmt);
  604. vsnprintf(buf, sizeof(buf), fmt, args);
  605. va_end(args);
  606. if ((r = sshbuf_put_cstring(auth_debug, buf)) != 0)
  607. fatal("%s: sshbuf_put_cstring: %s", __func__, ssh_err(r));
  608. }
  609. void
  610. auth_debug_send(struct ssh *ssh)
  611. {
  612. char *msg;
  613. int r;
  614. if (auth_debug == NULL)
  615. return;
  616. while (sshbuf_len(auth_debug) != 0) {
  617. if ((r = sshbuf_get_cstring(auth_debug, &msg, NULL)) != 0)
  618. fatal("%s: sshbuf_get_cstring: %s",
  619. __func__, ssh_err(r));
  620. ssh_packet_send_debug(ssh, "%s", msg);
  621. free(msg);
  622. }
  623. }
  624. void
  625. auth_debug_reset(void)
  626. {
  627. if (auth_debug != NULL)
  628. sshbuf_reset(auth_debug);
  629. else if ((auth_debug = sshbuf_new()) == NULL)
  630. fatal("%s: sshbuf_new failed", __func__);
  631. }
  632. struct passwd *
  633. fakepw(void)
  634. {
  635. static struct passwd fake;
  636. memset(&fake, 0, sizeof(fake));
  637. fake.pw_name = "NOUSER";
  638. fake.pw_passwd =
  639. "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
  640. #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
  641. fake.pw_gecos = "NOUSER";
  642. #endif
  643. fake.pw_uid = privsep_pw == NULL ? (uid_t)-1 : privsep_pw->pw_uid;
  644. fake.pw_gid = privsep_pw == NULL ? (gid_t)-1 : privsep_pw->pw_gid;
  645. #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
  646. fake.pw_class = "";
  647. #endif
  648. fake.pw_dir = "/nonexist";
  649. fake.pw_shell = "/nonexist";
  650. return (&fake);
  651. }
  652. /*
  653. * Returns the remote DNS hostname as a string. The returned string must not
  654. * be freed. NB. this will usually trigger a DNS query the first time it is
  655. * called.
  656. * This function does additional checks on the hostname to mitigate some
  657. * attacks on legacy rhosts-style authentication.
  658. * XXX is RhostsRSAAuthentication vulnerable to these?
  659. * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
  660. */
  661. static char *
  662. remote_hostname(struct ssh *ssh)
  663. {
  664. struct sockaddr_storage from;
  665. socklen_t fromlen;
  666. struct addrinfo hints, *ai, *aitop;
  667. char name[NI_MAXHOST], ntop2[NI_MAXHOST];
  668. const char *ntop = ssh_remote_ipaddr(ssh);
  669. /* Get IP address of client. */
  670. fromlen = sizeof(from);
  671. memset(&from, 0, sizeof(from));
  672. if (getpeername(ssh_packet_get_connection_in(ssh),
  673. (struct sockaddr *)&from, &fromlen) == -1) {
  674. debug("getpeername failed: %.100s", strerror(errno));
  675. return xstrdup(ntop);
  676. }
  677. ipv64_normalise_mapped(&from, &fromlen);
  678. if (from.ss_family == AF_INET6)
  679. fromlen = sizeof(struct sockaddr_in6);
  680. debug3("Trying to reverse map address %.100s.", ntop);
  681. /* Map the IP address to a host name. */
  682. if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
  683. NULL, 0, NI_NAMEREQD) != 0) {
  684. /* Host name not found. Use ip address. */
  685. return xstrdup(ntop);
  686. }
  687. /*
  688. * if reverse lookup result looks like a numeric hostname,
  689. * someone is trying to trick us by PTR record like following:
  690. * 1.1.1.10.in-addr.arpa. IN PTR 2.3.4.5
  691. */
  692. memset(&hints, 0, sizeof(hints));
  693. hints.ai_socktype = SOCK_DGRAM; /*dummy*/
  694. hints.ai_flags = AI_NUMERICHOST;
  695. if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
  696. logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
  697. name, ntop);
  698. freeaddrinfo(ai);
  699. return xstrdup(ntop);
  700. }
  701. /* Names are stored in lowercase. */
  702. lowercase(name);
  703. /*
  704. * Map it back to an IP address and check that the given
  705. * address actually is an address of this host. This is
  706. * necessary because anyone with access to a name server can
  707. * define arbitrary names for an IP address. Mapping from
  708. * name to IP address can be trusted better (but can still be
  709. * fooled if the intruder has access to the name server of
  710. * the domain).
  711. */
  712. memset(&hints, 0, sizeof(hints));
  713. hints.ai_family = from.ss_family;
  714. hints.ai_socktype = SOCK_STREAM;
  715. if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
  716. logit("reverse mapping checking getaddrinfo for %.700s "
  717. "[%s] failed.", name, ntop);
  718. return xstrdup(ntop);
  719. }
  720. /* Look for the address from the list of addresses. */
  721. for (ai = aitop; ai; ai = ai->ai_next) {
  722. if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
  723. sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
  724. (strcmp(ntop, ntop2) == 0))
  725. break;
  726. }
  727. freeaddrinfo(aitop);
  728. /* If we reached the end of the list, the address was not there. */
  729. if (ai == NULL) {
  730. /* Address not found for the host name. */
  731. logit("Address %.100s maps to %.600s, but this does not "
  732. "map back to the address.", ntop, name);
  733. return xstrdup(ntop);
  734. }
  735. return xstrdup(name);
  736. }
  737. /*
  738. * Return the canonical name of the host in the other side of the current
  739. * connection. The host name is cached, so it is efficient to call this
  740. * several times.
  741. */
  742. const char *
  743. auth_get_canonical_hostname(struct ssh *ssh, int use_dns)
  744. {
  745. static char *dnsname;
  746. if (!use_dns)
  747. return ssh_remote_ipaddr(ssh);
  748. else if (dnsname != NULL)
  749. return dnsname;
  750. else {
  751. dnsname = remote_hostname(ssh);
  752. return dnsname;
  753. }
  754. }
  755. /*
  756. * Runs command in a subprocess with a minimal environment.
  757. * Returns pid on success, 0 on failure.
  758. * The child stdout and stderr maybe captured, left attached or sent to
  759. * /dev/null depending on the contents of flags.
  760. * "tag" is prepended to log messages.
  761. * NB. "command" is only used for logging; the actual command executed is
  762. * av[0].
  763. */
  764. //pid_t
  765. //subprocess(const char *tag, struct passwd *pw, const char *command,
  766. // int ac, char **av, FILE **child, u_int flags)
  767. //{
  768. // FILE *f = NULL;
  769. // struct stat st;
  770. // int fd, devnull, p[2], i;
  771. // pid_t pid;
  772. // char *cp, errmsg[512];
  773. // u_int envsize;
  774. // char **child_env;
  775. // if (child != NULL)
  776. // *child = NULL;
  777. // debug3("%s: %s command \"%s\" running as %s (flags 0x%x)", __func__,
  778. // tag, command, pw->pw_name, flags);
  779. /* Check consistency */
  780. // if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
  781. // (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
  782. // error("%s: inconsistent flags", __func__);
  783. // return 0;
  784. // }
  785. // if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
  786. // error("%s: inconsistent flags/output", __func__);
  787. // return 0;
  788. // }
  789. /*
  790. * If executing an explicit binary, then verify the it exists
  791. * and appears safe-ish to execute
  792. */
  793. // if (!path_absolute(av[0])) {
  794. // error("%s path is not absolute", tag);
  795. // return 0;
  796. // }
  797. // temporarily_use_uid(pw);
  798. // if (stat(av[0], &st) == -1) {
  799. // error("Could not stat %s \"%s\": %s", tag,
  800. // av[0], strerror(errno));
  801. // restore_uid();
  802. // return 0;
  803. // }
  804. // if (safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
  805. // error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
  806. // restore_uid();
  807. // return 0;
  808. // }
  809. /* Prepare to keep the child's stdout if requested */
  810. // if (pipe(p) == -1) {
  811. // error("%s: pipe: %s", tag, strerror(errno));
  812. // restore_uid();
  813. // return 0;
  814. // }
  815. // restore_uid();
  816. // switch ((pid = fork())) {
  817. // case -1: /* error */
  818. // error("%s: fork: %s", tag, strerror(errno));
  819. // close(p[0]);
  820. // close(p[1]);
  821. // return 0;
  822. // case 0: /* child */
  823. /* Prepare a minimal environment for the child. */
  824. // envsize = 5;
  825. // child_env = xcalloc(sizeof(*child_env), envsize);
  826. // child_set_env(&child_env, &envsize, "PATH", _PATH_STDPATH);
  827. // child_set_env(&child_env, &envsize, "USER", pw->pw_name);
  828. // child_set_env(&child_env, &envsize, "LOGNAME", pw->pw_name);
  829. // child_set_env(&child_env, &envsize, "HOME", pw->pw_dir);
  830. // if ((cp = getenv("LANG")) != NULL)
  831. // child_set_env(&child_env, &envsize, "LANG", cp);
  832. // for (i = 0; i < NSIG; i++)
  833. // ssh_signal(i, SIG_DFL);
  834. // if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
  835. // error("%s: open %s: %s", tag, _PATH_DEVNULL,
  836. // strerror(errno));
  837. // _exit(1);
  838. // }
  839. // if (dup2(devnull, STDIN_FILENO) == -1) {
  840. // error("%s: dup2: %s", tag, strerror(errno));
  841. // _exit(1);
  842. // }
  843. /* Set up stdout as requested; leave stderr in place for now. */
  844. // fd = -1;
  845. // if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
  846. // fd = p[1];
  847. // else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
  848. // fd = devnull;
  849. // if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
  850. // error("%s: dup2: %s", tag, strerror(errno));
  851. // _exit(1);
  852. // }
  853. // closefrom(STDERR_FILENO + 1);
  854. /* Don't use permanently_set_uid() here to avoid fatal() */
  855. // if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) {
  856. // error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
  857. // strerror(errno));
  858. // _exit(1);
  859. // }
  860. // if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) {
  861. // error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
  862. // strerror(errno));
  863. // _exit(1);
  864. // }
  865. /* stdin is pointed to /dev/null at this point */
  866. // if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
  867. // dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
  868. // error("%s: dup2: %s", tag, strerror(errno));
  869. // _exit(1);
  870. // }
  871. //#ifdef WITH_SELINUX
  872. // if (sshd_selinux_setup_env_variables() < 0) {
  873. // error ("failed to copy environment: %s",
  874. // strerror(errno));
  875. // _exit(127);
  876. // }
  877. //#endif
  878. // execve(av[0], av, child_env);
  879. // error("%s exec \"%s\": %s", tag, command, strerror(errno));
  880. // _exit(127);
  881. // default: /* parent */
  882. // break;
  883. // }
  884. // close(p[1]);
  885. // if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
  886. // close(p[0]);
  887. // else if ((f = fdopen(p[0], "r")) == NULL) {
  888. // error("%s: fdopen: %s", tag, strerror(errno));
  889. // close(p[0]);
  890. // /* Don't leave zombie child */
  891. // kill(pid, SIGTERM);
  892. // while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
  893. // ;
  894. // return 0;
  895. // }
  896. // /* Success */
  897. // debug3("%s: %s pid %ld", __func__, tag, (long)pid);
  898. // if (child != NULL)
  899. // *child = f;
  900. // return pid;
  901. //}
  902. /* These functions link key/cert options to the auth framework */
  903. /* Log sshauthopt options locally and (optionally) for remote transmission */
  904. void
  905. auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote)
  906. {
  907. int do_env = options.permit_user_env && opts->nenv > 0;
  908. int do_permitopen = opts->npermitopen > 0 &&
  909. (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0;
  910. int do_permitlisten = opts->npermitlisten > 0 &&
  911. (options.allow_tcp_forwarding & FORWARD_REMOTE) != 0;
  912. size_t i;
  913. char msg[1024], buf[64];
  914. snprintf(buf, sizeof(buf), "%d", opts->force_tun_device);
  915. /* Try to keep this alphabetically sorted */
  916. snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
  917. opts->permit_agent_forwarding_flag ? " agent-forwarding" : "",
  918. opts->force_command == NULL ? "" : " command",
  919. do_env ? " environment" : "",
  920. opts->valid_before == 0 ? "" : "expires",
  921. opts->no_require_user_presence ? " no-touch-required" : "",
  922. do_permitopen ? " permitopen" : "",
  923. do_permitlisten ? " permitlisten" : "",
  924. opts->permit_port_forwarding_flag ? " port-forwarding" : "",
  925. opts->cert_principals == NULL ? "" : " principals",
  926. opts->permit_pty_flag ? " pty" : "",
  927. opts->require_verify ? " uv" : "",
  928. opts->force_tun_device == -1 ? "" : " tun=",
  929. opts->force_tun_device == -1 ? "" : buf,
  930. opts->permit_user_rc ? " user-rc" : "",
  931. opts->permit_x11_forwarding_flag ? " x11-forwarding" : "");
  932. debug("%s: %s", loc, msg);
  933. if (do_remote)
  934. auth_debug_add("%s: %s", loc, msg);
  935. if (options.permit_user_env) {
  936. for (i = 0; i < opts->nenv; i++) {
  937. debug("%s: environment: %s", loc, opts->env[i]);
  938. if (do_remote) {
  939. auth_debug_add("%s: environment: %s",
  940. loc, opts->env[i]);
  941. }
  942. }
  943. }
  944. /* Go into a little more details for the local logs. */
  945. if (opts->valid_before != 0) {
  946. format_absolute_time(opts->valid_before, buf, sizeof(buf));
  947. debug("%s: expires at %s", loc, buf);
  948. }
  949. if (opts->cert_principals != NULL) {
  950. debug("%s: authorized principals: \"%s\"",
  951. loc, opts->cert_principals);
  952. }
  953. if (opts->force_command != NULL)
  954. debug("%s: forced command: \"%s\"", loc, opts->force_command);
  955. if (do_permitopen) {
  956. for (i = 0; i < opts->npermitopen; i++) {
  957. debug("%s: permitted open: %s",
  958. loc, opts->permitopen[i]);
  959. }
  960. }
  961. if (do_permitlisten) {
  962. for (i = 0; i < opts->npermitlisten; i++) {
  963. debug("%s: permitted listen: %s",
  964. loc, opts->permitlisten[i]);
  965. }
  966. }
  967. }
  968. /* Activate a new set of key/cert options; merging with what is there. */
  969. int
  970. auth_activate_options(struct ssh *ssh, struct sshauthopt *opts)
  971. {
  972. struct sshauthopt *old = auth_opts;
  973. const char *emsg = NULL;
  974. debug("%s: setting new authentication options", __func__);
  975. if ((auth_opts = sshauthopt_merge(old, opts, &emsg)) == NULL) {
  976. error("Inconsistent authentication options: %s", emsg);
  977. return -1;
  978. }
  979. return 0;
  980. }
  981. /* Disable forwarding, etc for the session */
  982. void
  983. auth_restrict_session(struct ssh *ssh)
  984. {
  985. struct sshauthopt *restricted;
  986. debug("%s: restricting session", __func__);
  987. /* A blank sshauthopt defaults to permitting nothing */
  988. restricted = sshauthopt_new();
  989. restricted->permit_pty_flag = 1;
  990. restricted->restricted = 1;
  991. if (auth_activate_options(ssh, restricted) != 0)
  992. fatal("%s: failed to restrict session", __func__);
  993. sshauthopt_free(restricted);
  994. }
  995. int
  996. auth_authorise_keyopts(struct ssh *ssh, struct passwd *pw,
  997. struct sshauthopt *opts, int allow_cert_authority, const char *loc)
  998. {
  999. const char *remote_ip = ssh_remote_ipaddr(ssh);
  1000. const char *remote_host = auth_get_canonical_hostname(ssh,
  1001. options.use_dns);
  1002. time_t now = time(NULL);
  1003. char buf[64];
  1004. /*
  1005. * Check keys/principals file expiry time.
  1006. * NB. validity interval in certificate is handled elsewhere.
  1007. */
  1008. if (opts->valid_before && now > 0 &&
  1009. opts->valid_before < (uint64_t)now) {
  1010. format_absolute_time(opts->valid_before, buf, sizeof(buf));
  1011. debug("%s: entry expired at %s", loc, buf);
  1012. auth_debug_add("%s: entry expired at %s", loc, buf);
  1013. return -1;
  1014. }
  1015. /* Consistency checks */
  1016. if (opts->cert_principals != NULL && !opts->cert_authority) {
  1017. debug("%s: principals on non-CA key", loc);
  1018. auth_debug_add("%s: principals on non-CA key", loc);
  1019. /* deny access */
  1020. return -1;
  1021. }
  1022. /* cert-authority flag isn't valid in authorized_principals files */
  1023. if (!allow_cert_authority && opts->cert_authority) {
  1024. debug("%s: cert-authority flag invalid here", loc);
  1025. auth_debug_add("%s: cert-authority flag invalid here", loc);
  1026. /* deny access */
  1027. return -1;
  1028. }
  1029. /* Perform from= checks */
  1030. if (opts->required_from_host_keys != NULL) {
  1031. switch (match_host_and_ip(remote_host, remote_ip,
  1032. opts->required_from_host_keys )) {
  1033. case 1:
  1034. /* Host name matches. */
  1035. break;
  1036. case -1:
  1037. default:
  1038. debug("%s: invalid from criteria", loc);
  1039. auth_debug_add("%s: invalid from criteria", loc);
  1040. /* FALLTHROUGH */
  1041. case 0:
  1042. logit("%s: Authentication tried for %.100s with "
  1043. "correct key but not from a permitted "
  1044. "host (host=%.200s, ip=%.200s, required=%.200s).",
  1045. loc, pw->pw_name, remote_host, remote_ip,
  1046. opts->required_from_host_keys);
  1047. auth_debug_add("%s: Your host '%.200s' is not "
  1048. "permitted to use this key for login.",
  1049. loc, remote_host);
  1050. /* deny access */
  1051. return -1;
  1052. }
  1053. }
  1054. /* Check source-address restriction from certificate */
  1055. if (opts->required_from_host_cert != NULL) {
  1056. switch (addr_match_cidr_list(remote_ip,
  1057. opts->required_from_host_cert)) {
  1058. case 1:
  1059. /* accepted */
  1060. break;
  1061. case -1:
  1062. default:
  1063. /* invalid */
  1064. error("%s: Certificate source-address invalid",
  1065. loc);
  1066. /* FALLTHROUGH */
  1067. case 0:
  1068. logit("%s: Authentication tried for %.100s with valid "
  1069. "certificate but not from a permitted source "
  1070. "address (%.200s).", loc, pw->pw_name, remote_ip);
  1071. auth_debug_add("%s: Your address '%.200s' is not "
  1072. "permitted to use this certificate for login.",
  1073. loc, remote_ip);
  1074. return -1;
  1075. }
  1076. }
  1077. /*
  1078. *
  1079. * XXX this is spammy. We should report remotely only for keys
  1080. * that are successful in actual auth attempts, and not PK_OK
  1081. * tests.
  1082. */
  1083. auth_log_authopts(loc, opts, 1);
  1084. return 0;
  1085. }