1 /* $OpenBSD: auth2.c,v 1.164 2022/02/23 11:18:13 djm Exp $ */
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
28 #include <sys/types.h>
54 #include "pathnames.h"
56 #include "blacklist_client.h"
60 #include "monitor_wrap.h"
64 extern ServerOptions options;
65 extern struct sshbuf *loginmsg;
69 extern Authmethod method_none;
70 extern Authmethod method_pubkey;
71 extern Authmethod method_passwd;
72 extern Authmethod method_kbdint;
73 extern Authmethod method_hostbased;
75 extern Authmethod method_gssapi;
78 Authmethod *authmethods[] = {
92 static int input_service_request(int, u_int32_t, struct ssh *);
93 static int input_userauth_request(int, u_int32_t, struct ssh *);
96 static Authmethod *authmethod_byname(const char *);
97 static Authmethod *authmethod_lookup(Authctxt *, const char *);
98 static char *authmethods_get(Authctxt *authctxt);
100 #define MATCH_NONE 0 /* method or submethod mismatch */
101 #define MATCH_METHOD 1 /* method matches (no submethod specified) */
102 #define MATCH_BOTH 2 /* method and submethod match */
103 #define MATCH_PARTIAL 3 /* method matches, submethod can't be checked */
104 static int list_starts_with(const char *, const char *, const char *);
107 auth2_read_banner(void)
114 if ((fd = open(options.banner, O_RDONLY)) == -1)
116 if (fstat(fd, &st) == -1) {
120 if (st.st_size <= 0 || st.st_size > 1*1024*1024) {
125 len = (size_t)st.st_size; /* truncate */
126 banner = xmalloc(len + 1);
127 n = atomicio(read, fd, banner, len);
140 userauth_send_banner(struct ssh *ssh, const char *msg)
144 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_BANNER)) != 0 ||
145 (r = sshpkt_put_cstring(ssh, msg)) != 0 ||
146 (r = sshpkt_put_cstring(ssh, "")) != 0 || /* language, unused */
147 (r = sshpkt_send(ssh)) != 0)
148 fatal_fr(r, "send packet");
149 debug("%s: sent", __func__);
153 userauth_banner(struct ssh *ssh)
157 if (options.banner == NULL)
160 if ((banner = PRIVSEP(auth2_read_banner())) == NULL)
162 userauth_send_banner(ssh, banner);
169 * loop until authctxt->success == TRUE
172 do_authentication2(struct ssh *ssh)
174 Authctxt *authctxt = ssh->authctxt;
176 ssh_dispatch_init(ssh, &dispatch_protocol_error);
177 ssh_dispatch_set(ssh, SSH2_MSG_SERVICE_REQUEST, &input_service_request);
178 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &authctxt->success);
179 ssh->authctxt = NULL;
184 input_service_request(int type, u_int32_t seq, struct ssh *ssh)
186 Authctxt *authctxt = ssh->authctxt;
187 char *service = NULL;
190 if ((r = sshpkt_get_cstring(ssh, &service, NULL)) != 0 ||
191 (r = sshpkt_get_end(ssh)) != 0)
194 if (authctxt == NULL)
195 fatal("input_service_request: no authctxt");
197 if (strcmp(service, "ssh-userauth") == 0) {
198 if (!authctxt->success) {
200 /* now we can handle user-auth requests */
201 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_REQUEST,
202 &input_userauth_request);
205 /* XXX all other service requests are denied */
208 if ((r = sshpkt_start(ssh, SSH2_MSG_SERVICE_ACCEPT)) != 0 ||
209 (r = sshpkt_put_cstring(ssh, service)) != 0 ||
210 (r = sshpkt_send(ssh)) != 0 ||
211 (r = ssh_packet_write_wait(ssh)) != 0)
214 debug("bad service request %s", service);
215 ssh_packet_disconnect(ssh, "bad service request %s", service);
223 #define MIN_FAIL_DELAY_SECONDS 0.005
225 user_specific_delay(const char *user)
228 size_t len = ssh_digest_bytes(SSH_DIGEST_SHA512);
229 u_char *hash = xmalloc(len);
232 (void)snprintf(b, sizeof b, "%llu%s",
233 (unsigned long long)options.timing_secret, user);
234 if (ssh_digest_memory(SSH_DIGEST_SHA512, b, strlen(b), hash, len) != 0)
235 fatal_f("ssh_digest_memory");
236 /* 0-4.2 ms of delay */
237 delay = (double)PEEK_U32(hash) / 1000 / 1000 / 1000 / 1000;
239 debug3_f("user specific delay %0.3lfms", delay/1000);
240 return MIN_FAIL_DELAY_SECONDS + delay;
244 ensure_minimum_time_since(double start, double seconds)
247 double elapsed = monotime_double() - start, req = seconds, remain;
249 /* if we've already passed the requested time, scale up */
250 while ((remain = seconds - elapsed) < 0.0)
254 ts.tv_nsec = (remain - ts.tv_sec) * 1000000000;
255 debug3_f("elapsed %0.3lfms, delaying %0.3lfms (requested %0.3lfms)",
256 elapsed*1000, remain*1000, req*1000);
257 nanosleep(&ts, NULL);
262 input_userauth_request(int type, u_int32_t seq, struct ssh *ssh)
264 Authctxt *authctxt = ssh->authctxt;
265 Authmethod *m = NULL;
266 char *user = NULL, *service = NULL, *method = NULL, *style = NULL;
267 int r, authenticated = 0;
268 double tstart = monotime_double();
270 if (authctxt == NULL)
271 fatal("input_userauth_request: no authctxt");
273 if ((r = sshpkt_get_cstring(ssh, &user, NULL)) != 0 ||
274 (r = sshpkt_get_cstring(ssh, &service, NULL)) != 0 ||
275 (r = sshpkt_get_cstring(ssh, &method, NULL)) != 0)
277 debug("userauth-request for user %s service %s method %s", user, service, method);
278 debug("attempt %d failures %d", authctxt->attempt, authctxt->failures);
280 if ((style = strchr(user, ':')) != NULL)
283 if (authctxt->attempt >= 1024)
284 auth_maxtries_exceeded(ssh);
285 if (authctxt->attempt++ == 0) {
286 /* setup auth context */
287 authctxt->pw = PRIVSEP(getpwnamallow(ssh, user));
288 authctxt->user = xstrdup(user);
289 if (authctxt->pw && strcmp(service, "ssh-connection")==0) {
291 debug2_f("setting up authctxt for %s", user);
294 /* Invalid user, fake password information */
295 authctxt->pw = fakepw();
296 #ifdef SSH_AUDIT_EVENTS
297 PRIVSEP(audit_event(ssh, SSH_INVALID_USER));
302 PRIVSEP(start_pam(ssh));
304 ssh_packet_set_log_preamble(ssh, "%suser %s",
305 authctxt->valid ? "authenticating " : "invalid ", user);
306 setproctitle("%s%s", authctxt->valid ? user : "unknown",
307 use_privsep ? " [net]" : "");
308 authctxt->service = xstrdup(service);
309 authctxt->style = style ? xstrdup(style) : NULL;
311 mm_inform_authserv(service, style);
312 userauth_banner(ssh);
313 if (auth2_setup_methods_lists(authctxt) != 0)
314 ssh_packet_disconnect(ssh,
315 "no authentication methods enabled");
316 } else if (strcmp(user, authctxt->user) != 0 ||
317 strcmp(service, authctxt->service) != 0) {
318 ssh_packet_disconnect(ssh, "Change of username or service "
319 "not allowed: (%s,%s) -> (%s,%s)",
320 authctxt->user, authctxt->service, user, service);
323 auth2_challenge_stop(ssh);
326 /* XXX move to auth2_gssapi_stop() */
327 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, NULL);
328 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, NULL);
331 auth2_authctxt_reset_info(authctxt);
332 authctxt->postponed = 0;
333 authctxt->server_caused_failure = 0;
335 /* try to authenticate user */
336 m = authmethod_lookup(authctxt, method);
337 if (m != NULL && authctxt->failures < options.max_authtries) {
338 debug2("input_userauth_request: try method %s", method);
339 authenticated = m->userauth(ssh, method);
341 if (!authctxt->authenticated)
342 ensure_minimum_time_since(tstart,
343 user_specific_delay(authctxt->user));
344 userauth_finish(ssh, authenticated, method, NULL);
354 userauth_finish(struct ssh *ssh, int authenticated, const char *packet_method,
355 const char *submethod)
357 Authctxt *authctxt = ssh->authctxt;
358 Authmethod *m = NULL;
359 const char *method = packet_method;
364 if (!authctxt->valid) {
365 fatal("INTERNAL ERROR: authenticated invalid user %s",
368 if (authctxt->postponed)
369 fatal("INTERNAL ERROR: authenticated and postponed");
370 /* prefer primary authmethod name to possible synonym */
371 if ((m = authmethod_byname(method)) == NULL)
372 fatal("INTERNAL ERROR: bad method %s", method);
376 /* Special handling for root */
377 if (authenticated && authctxt->pw->pw_uid == 0 &&
378 !auth_root_allowed(ssh, method)) {
380 #ifdef SSH_AUDIT_EVENTS
381 PRIVSEP(audit_event(ssh, SSH_LOGIN_ROOT_DENIED));
385 if (authenticated && options.num_auth_methods != 0) {
386 if (!auth2_update_methods_lists(authctxt, method, submethod)) {
392 /* Log before sending the reply */
393 auth_log(ssh, authenticated, partial, method, submethod);
395 /* Update information exposed to session */
396 if (authenticated || partial)
397 auth2_update_session_info(authctxt, method, submethod);
399 if (authctxt->postponed)
403 if (options.use_pam && authenticated) {
404 int r, success = PRIVSEP(do_pam_account());
406 /* If PAM returned a message, send it to the user. */
407 if (sshbuf_len(loginmsg) > 0) {
408 if ((r = sshbuf_put(loginmsg, "\0", 1)) != 0)
409 fatal("%s: buffer error: %s",
410 __func__, ssh_err(r));
411 userauth_send_banner(ssh, sshbuf_ptr(loginmsg));
412 if ((r = ssh_packet_write_wait(ssh)) != 0) {
414 "%s: send PAM banner", __func__);
418 fatal("Access denied for user %s by PAM account "
419 "configuration", authctxt->user);
424 if (authenticated == 1) {
425 /* turn off userauth */
426 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_REQUEST,
427 &dispatch_protocol_ignore);
428 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_SUCCESS)) != 0 ||
429 (r = sshpkt_send(ssh)) != 0 ||
430 (r = ssh_packet_write_wait(ssh)) != 0)
431 fatal_fr(r, "send success packet");
432 /* now we can break out */
433 authctxt->success = 1;
434 ssh_packet_set_log_preamble(ssh, "user %s", authctxt->user);
436 /* Allow initial try of "none" auth without failure penalty */
437 if (!partial && !authctxt->server_caused_failure &&
438 (authctxt->attempt > 1 || strcmp(method, "none") != 0)) {
439 authctxt->failures++;
440 BLACKLIST_NOTIFY(ssh, BLACKLIST_AUTH_FAIL, "ssh");
442 if (authctxt->failures >= options.max_authtries) {
443 #ifdef SSH_AUDIT_EVENTS
444 PRIVSEP(audit_event(ssh, SSH_LOGIN_EXCEED_MAXTRIES));
446 auth_maxtries_exceeded(ssh);
448 methods = authmethods_get(authctxt);
449 debug3_f("failure partial=%d next methods=\"%s\"",
451 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_FAILURE)) != 0 ||
452 (r = sshpkt_put_cstring(ssh, methods)) != 0 ||
453 (r = sshpkt_put_u8(ssh, partial)) != 0 ||
454 (r = sshpkt_send(ssh)) != 0 ||
455 (r = ssh_packet_write_wait(ssh)) != 0)
456 fatal_fr(r, "send failure packet");
462 * Checks whether method is allowed by at least one AuthenticationMethods
463 * methods list. Returns 1 if allowed, or no methods lists configured.
467 auth2_method_allowed(Authctxt *authctxt, const char *method,
468 const char *submethod)
473 * NB. authctxt->num_auth_methods might be zero as a result of
474 * auth2_setup_methods_lists(), so check the configuration.
476 if (options.num_auth_methods == 0)
478 for (i = 0; i < authctxt->num_auth_methods; i++) {
479 if (list_starts_with(authctxt->auth_methods[i], method,
480 submethod) != MATCH_NONE)
487 authmethods_get(Authctxt *authctxt)
493 if ((b = sshbuf_new()) == NULL)
494 fatal_f("sshbuf_new failed");
495 for (i = 0; authmethods[i] != NULL; i++) {
496 if (strcmp(authmethods[i]->name, "none") == 0)
498 if (authmethods[i]->enabled == NULL ||
499 *(authmethods[i]->enabled) == 0)
501 if (!auth2_method_allowed(authctxt, authmethods[i]->name,
504 if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) ? "," : "",
505 authmethods[i]->name)) != 0)
506 fatal_fr(r, "buffer error");
508 if ((list = sshbuf_dup_string(b)) == NULL)
509 fatal_f("sshbuf_dup_string failed");
515 authmethod_byname(const char *name)
520 fatal_f("NULL authentication method name");
521 for (i = 0; authmethods[i] != NULL; i++) {
522 if (strcmp(name, authmethods[i]->name) == 0 ||
523 (authmethods[i]->synonym != NULL &&
524 strcmp(name, authmethods[i]->synonym) == 0))
525 return authmethods[i];
527 debug_f("unrecognized authentication method name: %s", name);
532 authmethod_lookup(Authctxt *authctxt, const char *name)
536 if ((method = authmethod_byname(name)) == NULL)
539 if (method->enabled == NULL || *(method->enabled) == 0) {
540 debug3_f("method %s not enabled", name);
543 if (!auth2_method_allowed(authctxt, method->name, NULL)) {
544 debug3_f("method %s not allowed "
545 "by AuthenticationMethods", name);
552 * Check a comma-separated list of methods for validity. Is need_enable is
553 * non-zero, then also require that the methods are enabled.
554 * Returns 0 on success or -1 if the methods list is invalid.
557 auth2_methods_valid(const char *_methods, int need_enable)
559 char *methods, *omethods, *method, *p;
563 if (*_methods == '\0') {
564 error("empty authentication method list");
567 omethods = methods = xstrdup(_methods);
568 while ((method = strsep(&methods, ",")) != NULL) {
569 for (found = i = 0; !found && authmethods[i] != NULL; i++) {
570 if ((p = strchr(method, ':')) != NULL)
572 if (strcmp(method, authmethods[i]->name) != 0)
575 if (authmethods[i]->enabled == NULL ||
576 *(authmethods[i]->enabled) == 0) {
577 error("Disabled method \"%s\" in "
578 "AuthenticationMethods list \"%s\"",
587 error("Unknown authentication method \"%s\" in list",
599 * Prune the AuthenticationMethods supplied in the configuration, removing
600 * any methods lists that include disabled methods. Note that this might
601 * leave authctxt->num_auth_methods == 0, even when multiple required auth
602 * has been requested. For this reason, all tests for whether multiple is
603 * enabled should consult options.num_auth_methods directly.
606 auth2_setup_methods_lists(Authctxt *authctxt)
610 /* First, normalise away the "any" pseudo-method */
611 if (options.num_auth_methods == 1 &&
612 strcmp(options.auth_methods[0], "any") == 0) {
613 free(options.auth_methods[0]);
614 options.auth_methods[0] = NULL;
615 options.num_auth_methods = 0;
618 if (options.num_auth_methods == 0)
620 debug3_f("checking methods");
621 authctxt->auth_methods = xcalloc(options.num_auth_methods,
622 sizeof(*authctxt->auth_methods));
623 authctxt->num_auth_methods = 0;
624 for (i = 0; i < options.num_auth_methods; i++) {
625 if (auth2_methods_valid(options.auth_methods[i], 1) != 0) {
626 logit("Authentication methods list \"%s\" contains "
627 "disabled method, skipping",
628 options.auth_methods[i]);
631 debug("authentication methods list %d: %s",
632 authctxt->num_auth_methods, options.auth_methods[i]);
633 authctxt->auth_methods[authctxt->num_auth_methods++] =
634 xstrdup(options.auth_methods[i]);
636 if (authctxt->num_auth_methods == 0) {
637 error("No AuthenticationMethods left after eliminating "
645 list_starts_with(const char *methods, const char *method,
646 const char *submethod)
648 size_t l = strlen(method);
652 if (strncmp(methods, method, l) != 0)
655 match = MATCH_METHOD;
658 return MATCH_PARTIAL;
659 l = strlen(submethod);
661 if (strncmp(submethod, p, l))
666 if (*p != ',' && *p != '\0')
672 * Remove method from the start of a comma-separated list of methods.
673 * Returns 0 if the list of methods did not start with that method or 1
677 remove_method(char **methods, const char *method, const char *submethod)
679 char *omethods = *methods, *p;
680 size_t l = strlen(method);
683 match = list_starts_with(omethods, method, submethod);
684 if (match != MATCH_METHOD && match != MATCH_BOTH)
687 if (submethod && match == MATCH_BOTH)
688 p += 1 + strlen(submethod); /* include colon */
691 *methods = xstrdup(p);
697 * Called after successful authentication. Will remove the successful method
698 * from the start of each list in which it occurs. If it was the last method
699 * in any list, then authentication is deemed successful.
700 * Returns 1 if the method completed any authentication list or 0 otherwise.
703 auth2_update_methods_lists(Authctxt *authctxt, const char *method,
704 const char *submethod)
708 debug3_f("updating methods list after \"%s\"", method);
709 for (i = 0; i < authctxt->num_auth_methods; i++) {
710 if (!remove_method(&(authctxt->auth_methods[i]), method,
714 if (*authctxt->auth_methods[i] == '\0') {
715 debug2("authentication methods list %d complete", i);
718 debug3("authentication methods list %d remaining: \"%s\"",
719 i, authctxt->auth_methods[i]);
721 /* This should not happen, but would be bad if it did */
723 fatal_f("method not in AuthenticationMethods");
727 /* Reset method-specific information */
728 void auth2_authctxt_reset_info(Authctxt *authctxt)
730 sshkey_free(authctxt->auth_method_key);
731 free(authctxt->auth_method_info);
732 authctxt->auth_method_key = NULL;
733 authctxt->auth_method_info = NULL;
736 /* Record auth method-specific information for logs */
738 auth2_record_info(Authctxt *authctxt, const char *fmt, ...)
743 free(authctxt->auth_method_info);
744 authctxt->auth_method_info = NULL;
747 i = vasprintf(&authctxt->auth_method_info, fmt, ap);
751 fatal_f("vasprintf failed");
755 * Records a public key used in authentication. This is used for logging
756 * and to ensure that the same key is not subsequently accepted again for
757 * multiple authentication.
760 auth2_record_key(Authctxt *authctxt, int authenticated,
761 const struct sshkey *key)
763 struct sshkey **tmp, *dup;
766 if ((r = sshkey_from_private(key, &dup)) != 0)
767 fatal_fr(r, "copy key");
768 sshkey_free(authctxt->auth_method_key);
769 authctxt->auth_method_key = dup;
774 /* If authenticated, make sure we don't accept this key again */
775 if ((r = sshkey_from_private(key, &dup)) != 0)
776 fatal_fr(r, "copy key");
777 if (authctxt->nprev_keys >= INT_MAX ||
778 (tmp = recallocarray(authctxt->prev_keys, authctxt->nprev_keys,
779 authctxt->nprev_keys + 1, sizeof(*authctxt->prev_keys))) == NULL)
780 fatal_f("reallocarray failed");
781 authctxt->prev_keys = tmp;
782 authctxt->prev_keys[authctxt->nprev_keys] = dup;
783 authctxt->nprev_keys++;
787 /* Checks whether a key has already been previously used for authentication */
789 auth2_key_already_used(Authctxt *authctxt, const struct sshkey *key)
794 for (i = 0; i < authctxt->nprev_keys; i++) {
795 if (sshkey_equal_public(key, authctxt->prev_keys[i])) {
796 fp = sshkey_fingerprint(authctxt->prev_keys[i],
797 options.fingerprint_hash, SSH_FP_DEFAULT);
798 debug3_f("key already used: %s %s",
799 sshkey_type(authctxt->prev_keys[i]),
800 fp == NULL ? "UNKNOWN" : fp);
809 * Updates authctxt->session_info with details of authentication. Should be
810 * whenever an authentication method succeeds.
813 auth2_update_session_info(Authctxt *authctxt, const char *method,
814 const char *submethod)
818 if (authctxt->session_info == NULL) {
819 if ((authctxt->session_info = sshbuf_new()) == NULL)
820 fatal_f("sshbuf_new");
823 /* Append method[/submethod] */
824 if ((r = sshbuf_putf(authctxt->session_info, "%s%s%s",
825 method, submethod == NULL ? "" : "/",
826 submethod == NULL ? "" : submethod)) != 0)
827 fatal_fr(r, "append method");
829 /* Append key if present */
830 if (authctxt->auth_method_key != NULL) {
831 if ((r = sshbuf_put_u8(authctxt->session_info, ' ')) != 0 ||
832 (r = sshkey_format_text(authctxt->auth_method_key,
833 authctxt->session_info)) != 0)
834 fatal_fr(r, "append key");
837 if (authctxt->auth_method_info != NULL) {
838 /* Ensure no ambiguity here */
839 if (strchr(authctxt->auth_method_info, '\n') != NULL)
840 fatal_f("auth_method_info contains \\n");
841 if ((r = sshbuf_put_u8(authctxt->session_info, ' ')) != 0 ||
842 (r = sshbuf_putf(authctxt->session_info, "%s",
843 authctxt->auth_method_info)) != 0) {
844 fatal_fr(r, "append method info");
847 if ((r = sshbuf_put_u8(authctxt->session_info, '\n')) != 0)
848 fatal_fr(r, "append");