1 /* $OpenBSD: auth2.c,v 1.167 2023/08/28 09:48:11 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>
53 #include "pathnames.h"
55 #include "blacklist_client.h"
59 #include "monitor_wrap.h"
63 extern ServerOptions options;
64 extern struct sshbuf *loginmsg;
68 extern Authmethod method_none;
69 extern Authmethod method_pubkey;
70 extern Authmethod method_passwd;
71 extern Authmethod method_kbdint;
72 extern Authmethod method_hostbased;
74 extern Authmethod method_gssapi;
77 Authmethod *authmethods[] = {
91 static int input_service_request(int, u_int32_t, struct ssh *);
92 static int input_userauth_request(int, u_int32_t, struct ssh *);
95 static Authmethod *authmethod_byname(const char *);
96 static Authmethod *authmethod_lookup(Authctxt *, const char *);
97 static char *authmethods_get(Authctxt *authctxt);
99 #define MATCH_NONE 0 /* method or submethod mismatch */
100 #define MATCH_METHOD 1 /* method matches (no submethod specified) */
101 #define MATCH_BOTH 2 /* method and submethod match */
102 #define MATCH_PARTIAL 3 /* method matches, submethod can't be checked */
103 static int list_starts_with(const char *, const char *, const char *);
106 auth2_read_banner(void)
113 if ((fd = open(options.banner, O_RDONLY)) == -1)
115 if (fstat(fd, &st) == -1) {
119 if (st.st_size <= 0 || st.st_size > 1*1024*1024) {
124 len = (size_t)st.st_size; /* truncate */
125 banner = xmalloc(len + 1);
126 n = atomicio(read, fd, banner, len);
139 userauth_send_banner(struct ssh *ssh, const char *msg)
143 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_BANNER)) != 0 ||
144 (r = sshpkt_put_cstring(ssh, msg)) != 0 ||
145 (r = sshpkt_put_cstring(ssh, "")) != 0 || /* language, unused */
146 (r = sshpkt_send(ssh)) != 0)
147 fatal_fr(r, "send packet");
148 debug("%s: sent", __func__);
152 userauth_banner(struct ssh *ssh)
156 if (options.banner == NULL)
159 if ((banner = PRIVSEP(auth2_read_banner())) == NULL)
161 userauth_send_banner(ssh, banner);
168 * loop until authctxt->success == TRUE
171 do_authentication2(struct ssh *ssh)
173 Authctxt *authctxt = ssh->authctxt;
175 ssh_dispatch_init(ssh, &dispatch_protocol_error);
176 ssh_dispatch_set(ssh, SSH2_MSG_SERVICE_REQUEST, &input_service_request);
177 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &authctxt->success);
178 ssh->authctxt = NULL;
182 input_service_request(int type, u_int32_t seq, struct ssh *ssh)
184 Authctxt *authctxt = ssh->authctxt;
185 char *service = NULL;
188 if ((r = sshpkt_get_cstring(ssh, &service, NULL)) != 0 ||
189 (r = sshpkt_get_end(ssh)) != 0)
192 if (authctxt == NULL)
193 fatal("input_service_request: no authctxt");
195 if (strcmp(service, "ssh-userauth") == 0) {
196 if (!authctxt->success) {
198 /* now we can handle user-auth requests */
199 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_REQUEST,
200 &input_userauth_request);
203 /* XXX all other service requests are denied */
206 if ((r = sshpkt_start(ssh, SSH2_MSG_SERVICE_ACCEPT)) != 0 ||
207 (r = sshpkt_put_cstring(ssh, service)) != 0 ||
208 (r = sshpkt_send(ssh)) != 0 ||
209 (r = ssh_packet_write_wait(ssh)) != 0)
212 debug("bad service request %s", service);
213 ssh_packet_disconnect(ssh, "bad service request %s", service);
221 #define MIN_FAIL_DELAY_SECONDS 0.005
222 #define MAX_FAIL_DELAY_SECONDS 5.0
224 user_specific_delay(const char *user)
227 size_t len = ssh_digest_bytes(SSH_DIGEST_SHA512);
228 u_char *hash = xmalloc(len);
231 (void)snprintf(b, sizeof b, "%llu%s",
232 (unsigned long long)options.timing_secret, user);
233 if (ssh_digest_memory(SSH_DIGEST_SHA512, b, strlen(b), hash, len) != 0)
234 fatal_f("ssh_digest_memory");
235 /* 0-4.2 ms of delay */
236 delay = (double)PEEK_U32(hash) / 1000 / 1000 / 1000 / 1000;
238 debug3_f("user specific delay %0.3lfms", delay/1000);
239 return MIN_FAIL_DELAY_SECONDS + delay;
243 ensure_minimum_time_since(double start, double seconds)
246 double elapsed = monotime_double() - start, req = seconds, remain;
248 if (elapsed > MAX_FAIL_DELAY_SECONDS) {
249 debug3_f("elapsed %0.3lfms exceeded the max delay "
250 "requested %0.3lfms)", elapsed*1000, req*1000);
254 /* if we've already passed the requested time, scale up */
255 while ((remain = seconds - elapsed) < 0.0)
259 ts.tv_nsec = (remain - ts.tv_sec) * 1000000000;
260 debug3_f("elapsed %0.3lfms, delaying %0.3lfms (requested %0.3lfms)",
261 elapsed*1000, remain*1000, req*1000);
262 nanosleep(&ts, NULL);
266 input_userauth_request(int type, u_int32_t seq, struct ssh *ssh)
268 Authctxt *authctxt = ssh->authctxt;
269 Authmethod *m = NULL;
270 char *user = NULL, *service = NULL, *method = NULL, *style = NULL;
271 int r, authenticated = 0;
272 double tstart = monotime_double();
274 if (authctxt == NULL)
275 fatal("input_userauth_request: no authctxt");
277 if ((r = sshpkt_get_cstring(ssh, &user, NULL)) != 0 ||
278 (r = sshpkt_get_cstring(ssh, &service, NULL)) != 0 ||
279 (r = sshpkt_get_cstring(ssh, &method, NULL)) != 0)
281 debug("userauth-request for user %s service %s method %s", user, service, method);
282 debug("attempt %d failures %d", authctxt->attempt, authctxt->failures);
284 if ((style = strchr(user, ':')) != NULL)
287 if (authctxt->attempt >= 1024)
288 auth_maxtries_exceeded(ssh);
289 if (authctxt->attempt++ == 0) {
290 /* setup auth context */
291 authctxt->pw = PRIVSEP(getpwnamallow(ssh, user));
292 authctxt->user = xstrdup(user);
293 if (authctxt->pw && strcmp(service, "ssh-connection")==0) {
295 debug2_f("setting up authctxt for %s", user);
298 /* Invalid user, fake password information */
299 authctxt->pw = fakepw();
300 #ifdef SSH_AUDIT_EVENTS
301 PRIVSEP(audit_event(ssh, SSH_INVALID_USER));
306 PRIVSEP(start_pam(ssh));
308 ssh_packet_set_log_preamble(ssh, "%suser %s",
309 authctxt->valid ? "authenticating " : "invalid ", user);
310 setproctitle("%s%s", authctxt->valid ? user : "unknown",
311 use_privsep ? " [net]" : "");
312 authctxt->service = xstrdup(service);
313 authctxt->style = style ? xstrdup(style) : NULL;
315 mm_inform_authserv(service, style);
316 userauth_banner(ssh);
317 if (auth2_setup_methods_lists(authctxt) != 0)
318 ssh_packet_disconnect(ssh,
319 "no authentication methods enabled");
320 } else if (strcmp(user, authctxt->user) != 0 ||
321 strcmp(service, authctxt->service) != 0) {
322 ssh_packet_disconnect(ssh, "Change of username or service "
323 "not allowed: (%s,%s) -> (%s,%s)",
324 authctxt->user, authctxt->service, user, service);
327 auth2_challenge_stop(ssh);
330 /* XXX move to auth2_gssapi_stop() */
331 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, NULL);
332 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, NULL);
335 auth2_authctxt_reset_info(authctxt);
336 authctxt->postponed = 0;
337 authctxt->server_caused_failure = 0;
339 /* try to authenticate user */
340 m = authmethod_lookup(authctxt, method);
341 if (m != NULL && authctxt->failures < options.max_authtries) {
342 debug2("input_userauth_request: try method %s", method);
343 authenticated = m->userauth(ssh, method);
345 if (!authctxt->authenticated && strcmp(method, "none") != 0)
346 ensure_minimum_time_since(tstart,
347 user_specific_delay(authctxt->user));
348 userauth_finish(ssh, authenticated, method, NULL);
358 userauth_finish(struct ssh *ssh, int authenticated, const char *packet_method,
359 const char *submethod)
361 Authctxt *authctxt = ssh->authctxt;
362 Authmethod *m = NULL;
363 const char *method = packet_method;
368 if (!authctxt->valid) {
369 fatal("INTERNAL ERROR: authenticated invalid user %s",
372 if (authctxt->postponed)
373 fatal("INTERNAL ERROR: authenticated and postponed");
374 /* prefer primary authmethod name to possible synonym */
375 if ((m = authmethod_byname(method)) == NULL)
376 fatal("INTERNAL ERROR: bad method %s", method);
380 /* Special handling for root */
381 if (authenticated && authctxt->pw->pw_uid == 0 &&
382 !auth_root_allowed(ssh, method)) {
384 #ifdef SSH_AUDIT_EVENTS
385 PRIVSEP(audit_event(ssh, SSH_LOGIN_ROOT_DENIED));
389 if (authenticated && options.num_auth_methods != 0) {
390 if (!auth2_update_methods_lists(authctxt, method, submethod)) {
396 /* Log before sending the reply */
397 auth_log(ssh, authenticated, partial, method, submethod);
399 /* Update information exposed to session */
400 if (authenticated || partial)
401 auth2_update_session_info(authctxt, method, submethod);
403 if (authctxt->postponed)
407 if (options.use_pam && authenticated) {
408 int r, success = PRIVSEP(do_pam_account());
410 /* If PAM returned a message, send it to the user. */
411 if (sshbuf_len(loginmsg) > 0) {
412 if ((r = sshbuf_put(loginmsg, "\0", 1)) != 0)
413 fatal("%s: buffer error: %s",
414 __func__, ssh_err(r));
415 userauth_send_banner(ssh, sshbuf_ptr(loginmsg));
416 if ((r = ssh_packet_write_wait(ssh)) != 0) {
418 "%s: send PAM banner", __func__);
422 fatal("Access denied for user %s by PAM account "
423 "configuration", authctxt->user);
428 if (authenticated == 1) {
429 /* turn off userauth */
430 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_REQUEST,
431 &dispatch_protocol_ignore);
432 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_SUCCESS)) != 0 ||
433 (r = sshpkt_send(ssh)) != 0 ||
434 (r = ssh_packet_write_wait(ssh)) != 0)
435 fatal_fr(r, "send success packet");
436 /* now we can break out */
437 authctxt->success = 1;
438 ssh_packet_set_log_preamble(ssh, "user %s", authctxt->user);
440 /* Allow initial try of "none" auth without failure penalty */
441 if (!partial && !authctxt->server_caused_failure &&
442 (authctxt->attempt > 1 || strcmp(method, "none") != 0)) {
443 authctxt->failures++;
444 BLACKLIST_NOTIFY(ssh, BLACKLIST_AUTH_FAIL, "ssh");
446 if (authctxt->failures >= options.max_authtries) {
447 #ifdef SSH_AUDIT_EVENTS
448 PRIVSEP(audit_event(ssh, SSH_LOGIN_EXCEED_MAXTRIES));
450 auth_maxtries_exceeded(ssh);
452 methods = authmethods_get(authctxt);
453 debug3_f("failure partial=%d next methods=\"%s\"",
455 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_FAILURE)) != 0 ||
456 (r = sshpkt_put_cstring(ssh, methods)) != 0 ||
457 (r = sshpkt_put_u8(ssh, partial)) != 0 ||
458 (r = sshpkt_send(ssh)) != 0 ||
459 (r = ssh_packet_write_wait(ssh)) != 0)
460 fatal_fr(r, "send failure packet");
466 * Checks whether method is allowed by at least one AuthenticationMethods
467 * methods list. Returns 1 if allowed, or no methods lists configured.
471 auth2_method_allowed(Authctxt *authctxt, const char *method,
472 const char *submethod)
477 * NB. authctxt->num_auth_methods might be zero as a result of
478 * auth2_setup_methods_lists(), so check the configuration.
480 if (options.num_auth_methods == 0)
482 for (i = 0; i < authctxt->num_auth_methods; i++) {
483 if (list_starts_with(authctxt->auth_methods[i], method,
484 submethod) != MATCH_NONE)
491 authmethods_get(Authctxt *authctxt)
497 if ((b = sshbuf_new()) == NULL)
498 fatal_f("sshbuf_new failed");
499 for (i = 0; authmethods[i] != NULL; i++) {
500 if (strcmp(authmethods[i]->name, "none") == 0)
502 if (authmethods[i]->enabled == NULL ||
503 *(authmethods[i]->enabled) == 0)
505 if (!auth2_method_allowed(authctxt, authmethods[i]->name,
508 if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) ? "," : "",
509 authmethods[i]->name)) != 0)
510 fatal_fr(r, "buffer error");
512 if ((list = sshbuf_dup_string(b)) == NULL)
513 fatal_f("sshbuf_dup_string failed");
519 authmethod_byname(const char *name)
524 fatal_f("NULL authentication method name");
525 for (i = 0; authmethods[i] != NULL; i++) {
526 if (strcmp(name, authmethods[i]->name) == 0 ||
527 (authmethods[i]->synonym != NULL &&
528 strcmp(name, authmethods[i]->synonym) == 0))
529 return authmethods[i];
531 debug_f("unrecognized authentication method name: %s", name);
536 authmethod_lookup(Authctxt *authctxt, const char *name)
540 if ((method = authmethod_byname(name)) == NULL)
543 if (method->enabled == NULL || *(method->enabled) == 0) {
544 debug3_f("method %s not enabled", name);
547 if (!auth2_method_allowed(authctxt, method->name, NULL)) {
548 debug3_f("method %s not allowed "
549 "by AuthenticationMethods", name);
556 * Check a comma-separated list of methods for validity. Is need_enable is
557 * non-zero, then also require that the methods are enabled.
558 * Returns 0 on success or -1 if the methods list is invalid.
561 auth2_methods_valid(const char *_methods, int need_enable)
563 char *methods, *omethods, *method, *p;
567 if (*_methods == '\0') {
568 error("empty authentication method list");
571 omethods = methods = xstrdup(_methods);
572 while ((method = strsep(&methods, ",")) != NULL) {
573 for (found = i = 0; !found && authmethods[i] != NULL; i++) {
574 if ((p = strchr(method, ':')) != NULL)
576 if (strcmp(method, authmethods[i]->name) != 0)
579 if (authmethods[i]->enabled == NULL ||
580 *(authmethods[i]->enabled) == 0) {
581 error("Disabled method \"%s\" in "
582 "AuthenticationMethods list \"%s\"",
591 error("Unknown authentication method \"%s\" in list",
603 * Prune the AuthenticationMethods supplied in the configuration, removing
604 * any methods lists that include disabled methods. Note that this might
605 * leave authctxt->num_auth_methods == 0, even when multiple required auth
606 * has been requested. For this reason, all tests for whether multiple is
607 * enabled should consult options.num_auth_methods directly.
610 auth2_setup_methods_lists(Authctxt *authctxt)
614 /* First, normalise away the "any" pseudo-method */
615 if (options.num_auth_methods == 1 &&
616 strcmp(options.auth_methods[0], "any") == 0) {
617 free(options.auth_methods[0]);
618 options.auth_methods[0] = NULL;
619 options.num_auth_methods = 0;
622 if (options.num_auth_methods == 0)
624 debug3_f("checking methods");
625 authctxt->auth_methods = xcalloc(options.num_auth_methods,
626 sizeof(*authctxt->auth_methods));
627 authctxt->num_auth_methods = 0;
628 for (i = 0; i < options.num_auth_methods; i++) {
629 if (auth2_methods_valid(options.auth_methods[i], 1) != 0) {
630 logit("Authentication methods list \"%s\" contains "
631 "disabled method, skipping",
632 options.auth_methods[i]);
635 debug("authentication methods list %d: %s",
636 authctxt->num_auth_methods, options.auth_methods[i]);
637 authctxt->auth_methods[authctxt->num_auth_methods++] =
638 xstrdup(options.auth_methods[i]);
640 if (authctxt->num_auth_methods == 0) {
641 error("No AuthenticationMethods left after eliminating "
649 list_starts_with(const char *methods, const char *method,
650 const char *submethod)
652 size_t l = strlen(method);
656 if (strncmp(methods, method, l) != 0)
659 match = MATCH_METHOD;
662 return MATCH_PARTIAL;
663 l = strlen(submethod);
665 if (strncmp(submethod, p, l))
670 if (*p != ',' && *p != '\0')
676 * Remove method from the start of a comma-separated list of methods.
677 * Returns 0 if the list of methods did not start with that method or 1
681 remove_method(char **methods, const char *method, const char *submethod)
683 char *omethods = *methods, *p;
684 size_t l = strlen(method);
687 match = list_starts_with(omethods, method, submethod);
688 if (match != MATCH_METHOD && match != MATCH_BOTH)
691 if (submethod && match == MATCH_BOTH)
692 p += 1 + strlen(submethod); /* include colon */
695 *methods = xstrdup(p);
701 * Called after successful authentication. Will remove the successful method
702 * from the start of each list in which it occurs. If it was the last method
703 * in any list, then authentication is deemed successful.
704 * Returns 1 if the method completed any authentication list or 0 otherwise.
707 auth2_update_methods_lists(Authctxt *authctxt, const char *method,
708 const char *submethod)
712 debug3_f("updating methods list after \"%s\"", method);
713 for (i = 0; i < authctxt->num_auth_methods; i++) {
714 if (!remove_method(&(authctxt->auth_methods[i]), method,
718 if (*authctxt->auth_methods[i] == '\0') {
719 debug2("authentication methods list %d complete", i);
722 debug3("authentication methods list %d remaining: \"%s\"",
723 i, authctxt->auth_methods[i]);
725 /* This should not happen, but would be bad if it did */
727 fatal_f("method not in AuthenticationMethods");
731 /* Reset method-specific information */
732 void auth2_authctxt_reset_info(Authctxt *authctxt)
734 sshkey_free(authctxt->auth_method_key);
735 free(authctxt->auth_method_info);
736 authctxt->auth_method_key = NULL;
737 authctxt->auth_method_info = NULL;
740 /* Record auth method-specific information for logs */
742 auth2_record_info(Authctxt *authctxt, const char *fmt, ...)
747 free(authctxt->auth_method_info);
748 authctxt->auth_method_info = NULL;
751 i = vasprintf(&authctxt->auth_method_info, fmt, ap);
755 fatal_f("vasprintf failed");
759 * Records a public key used in authentication. This is used for logging
760 * and to ensure that the same key is not subsequently accepted again for
761 * multiple authentication.
764 auth2_record_key(Authctxt *authctxt, int authenticated,
765 const struct sshkey *key)
767 struct sshkey **tmp, *dup;
770 if ((r = sshkey_from_private(key, &dup)) != 0)
771 fatal_fr(r, "copy key");
772 sshkey_free(authctxt->auth_method_key);
773 authctxt->auth_method_key = dup;
778 /* If authenticated, make sure we don't accept this key again */
779 if ((r = sshkey_from_private(key, &dup)) != 0)
780 fatal_fr(r, "copy key");
781 if (authctxt->nprev_keys >= INT_MAX ||
782 (tmp = recallocarray(authctxt->prev_keys, authctxt->nprev_keys,
783 authctxt->nprev_keys + 1, sizeof(*authctxt->prev_keys))) == NULL)
784 fatal_f("reallocarray failed");
785 authctxt->prev_keys = tmp;
786 authctxt->prev_keys[authctxt->nprev_keys] = dup;
787 authctxt->nprev_keys++;
791 /* Checks whether a key has already been previously used for authentication */
793 auth2_key_already_used(Authctxt *authctxt, const struct sshkey *key)
798 for (i = 0; i < authctxt->nprev_keys; i++) {
799 if (sshkey_equal_public(key, authctxt->prev_keys[i])) {
800 fp = sshkey_fingerprint(authctxt->prev_keys[i],
801 options.fingerprint_hash, SSH_FP_DEFAULT);
802 debug3_f("key already used: %s %s",
803 sshkey_type(authctxt->prev_keys[i]),
804 fp == NULL ? "UNKNOWN" : fp);
813 * Updates authctxt->session_info with details of authentication. Should be
814 * whenever an authentication method succeeds.
817 auth2_update_session_info(Authctxt *authctxt, const char *method,
818 const char *submethod)
822 if (authctxt->session_info == NULL) {
823 if ((authctxt->session_info = sshbuf_new()) == NULL)
824 fatal_f("sshbuf_new");
827 /* Append method[/submethod] */
828 if ((r = sshbuf_putf(authctxt->session_info, "%s%s%s",
829 method, submethod == NULL ? "" : "/",
830 submethod == NULL ? "" : submethod)) != 0)
831 fatal_fr(r, "append method");
833 /* Append key if present */
834 if (authctxt->auth_method_key != NULL) {
835 if ((r = sshbuf_put_u8(authctxt->session_info, ' ')) != 0 ||
836 (r = sshkey_format_text(authctxt->auth_method_key,
837 authctxt->session_info)) != 0)
838 fatal_fr(r, "append key");
841 if (authctxt->auth_method_info != NULL) {
842 /* Ensure no ambiguity here */
843 if (strchr(authctxt->auth_method_info, '\n') != NULL)
844 fatal_f("auth_method_info contains \\n");
845 if ((r = sshbuf_put_u8(authctxt->session_info, ' ')) != 0 ||
846 (r = sshbuf_putf(authctxt->session_info, "%s",
847 authctxt->auth_method_info)) != 0) {
848 fatal_fr(r, "append method info");
851 if ((r = sshbuf_put_u8(authctxt->session_info, '\n')) != 0)
852 fatal_fr(r, "append");