]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssh/auth2.c
ssh: Update to OpenSSH 9.3p1
[FreeBSD/FreeBSD.git] / crypto / openssh / auth2.c
1 /* $OpenBSD: auth2.c,v 1.166 2023/03/08 04:43:12 guenther 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
26 #include "includes.h"
27
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/uio.h>
31
32 #include <fcntl.h>
33 #include <limits.h>
34 #include <pwd.h>
35 #include <stdarg.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <time.h>
39
40 #include "stdlib.h"
41 #include "atomicio.h"
42 #include "xmalloc.h"
43 #include "ssh2.h"
44 #include "packet.h"
45 #include "log.h"
46 #include "sshbuf.h"
47 #include "misc.h"
48 #include "servconf.h"
49 #include "sshkey.h"
50 #include "hostfile.h"
51 #include "auth.h"
52 #include "dispatch.h"
53 #include "pathnames.h"
54 #include "ssherr.h"
55 #include "blacklist_client.h"
56 #ifdef GSSAPI
57 #include "ssh-gss.h"
58 #endif
59 #include "monitor_wrap.h"
60 #include "digest.h"
61
62 /* import */
63 extern ServerOptions options;
64 extern struct sshbuf *loginmsg;
65
66 /* methods */
67
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;
73 #ifdef GSSAPI
74 extern Authmethod method_gssapi;
75 #endif
76
77 Authmethod *authmethods[] = {
78         &method_none,
79         &method_pubkey,
80 #ifdef GSSAPI
81         &method_gssapi,
82 #endif
83         &method_passwd,
84         &method_kbdint,
85         &method_hostbased,
86         NULL
87 };
88
89 /* protocol */
90
91 static int input_service_request(int, u_int32_t, struct ssh *);
92 static int input_userauth_request(int, u_int32_t, struct ssh *);
93
94 /* helper */
95 static Authmethod *authmethod_byname(const char *);
96 static Authmethod *authmethod_lookup(Authctxt *, const char *);
97 static char *authmethods_get(Authctxt *authctxt);
98
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 *);
104
105 char *
106 auth2_read_banner(void)
107 {
108         struct stat st;
109         char *banner = NULL;
110         size_t len, n;
111         int fd;
112
113         if ((fd = open(options.banner, O_RDONLY)) == -1)
114                 return (NULL);
115         if (fstat(fd, &st) == -1) {
116                 close(fd);
117                 return (NULL);
118         }
119         if (st.st_size <= 0 || st.st_size > 1*1024*1024) {
120                 close(fd);
121                 return (NULL);
122         }
123
124         len = (size_t)st.st_size;               /* truncate */
125         banner = xmalloc(len + 1);
126         n = atomicio(read, fd, banner, len);
127         close(fd);
128
129         if (n != len) {
130                 free(banner);
131                 return (NULL);
132         }
133         banner[n] = '\0';
134
135         return (banner);
136 }
137
138 static void
139 userauth_send_banner(struct ssh *ssh, const char *msg)
140 {
141         int r;
142
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__);
149 }
150
151 static void
152 userauth_banner(struct ssh *ssh)
153 {
154         char *banner = NULL;
155
156         if (options.banner == NULL)
157                 return;
158
159         if ((banner = PRIVSEP(auth2_read_banner())) == NULL)
160                 goto done;
161         userauth_send_banner(ssh, banner);
162
163 done:
164         free(banner);
165 }
166
167 /*
168  * loop until authctxt->success == TRUE
169  */
170 void
171 do_authentication2(struct ssh *ssh)
172 {
173         Authctxt *authctxt = ssh->authctxt;
174
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;
179 }
180
181 static int
182 input_service_request(int type, u_int32_t seq, struct ssh *ssh)
183 {
184         Authctxt *authctxt = ssh->authctxt;
185         char *service = NULL;
186         int r, acceptit = 0;
187
188         if ((r = sshpkt_get_cstring(ssh, &service, NULL)) != 0 ||
189             (r = sshpkt_get_end(ssh)) != 0)
190                 goto out;
191
192         if (authctxt == NULL)
193                 fatal("input_service_request: no authctxt");
194
195         if (strcmp(service, "ssh-userauth") == 0) {
196                 if (!authctxt->success) {
197                         acceptit = 1;
198                         /* now we can handle user-auth requests */
199                         ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_REQUEST,
200                             &input_userauth_request);
201                 }
202         }
203         /* XXX all other service requests are denied */
204
205         if (acceptit) {
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)
210                         goto out;
211         } else {
212                 debug("bad service request %s", service);
213                 ssh_packet_disconnect(ssh, "bad service request %s", service);
214         }
215         r = 0;
216  out:
217         free(service);
218         return r;
219 }
220
221 #define MIN_FAIL_DELAY_SECONDS 0.005
222 static double
223 user_specific_delay(const char *user)
224 {
225         char b[512];
226         size_t len = ssh_digest_bytes(SSH_DIGEST_SHA512);
227         u_char *hash = xmalloc(len);
228         double delay;
229
230         (void)snprintf(b, sizeof b, "%llu%s",
231             (unsigned long long)options.timing_secret, user);
232         if (ssh_digest_memory(SSH_DIGEST_SHA512, b, strlen(b), hash, len) != 0)
233                 fatal_f("ssh_digest_memory");
234         /* 0-4.2 ms of delay */
235         delay = (double)PEEK_U32(hash) / 1000 / 1000 / 1000 / 1000;
236         freezero(hash, len);
237         debug3_f("user specific delay %0.3lfms", delay/1000);
238         return MIN_FAIL_DELAY_SECONDS + delay;
239 }
240
241 static void
242 ensure_minimum_time_since(double start, double seconds)
243 {
244         struct timespec ts;
245         double elapsed = monotime_double() - start, req = seconds, remain;
246
247         /* if we've already passed the requested time, scale up */
248         while ((remain = seconds - elapsed) < 0.0)
249                 seconds *= 2;
250
251         ts.tv_sec = remain;
252         ts.tv_nsec = (remain - ts.tv_sec) * 1000000000;
253         debug3_f("elapsed %0.3lfms, delaying %0.3lfms (requested %0.3lfms)",
254             elapsed*1000, remain*1000, req*1000);
255         nanosleep(&ts, NULL);
256 }
257
258 static int
259 input_userauth_request(int type, u_int32_t seq, struct ssh *ssh)
260 {
261         Authctxt *authctxt = ssh->authctxt;
262         Authmethod *m = NULL;
263         char *user = NULL, *service = NULL, *method = NULL, *style = NULL;
264         int r, authenticated = 0;
265         double tstart = monotime_double();
266
267         if (authctxt == NULL)
268                 fatal("input_userauth_request: no authctxt");
269
270         if ((r = sshpkt_get_cstring(ssh, &user, NULL)) != 0 ||
271             (r = sshpkt_get_cstring(ssh, &service, NULL)) != 0 ||
272             (r = sshpkt_get_cstring(ssh, &method, NULL)) != 0)
273                 goto out;
274         debug("userauth-request for user %s service %s method %s", user, service, method);
275         debug("attempt %d failures %d", authctxt->attempt, authctxt->failures);
276
277         if ((style = strchr(user, ':')) != NULL)
278                 *style++ = 0;
279
280         if (authctxt->attempt >= 1024)
281                 auth_maxtries_exceeded(ssh);
282         if (authctxt->attempt++ == 0) {
283                 /* setup auth context */
284                 authctxt->pw = PRIVSEP(getpwnamallow(ssh, user));
285                 authctxt->user = xstrdup(user);
286                 if (authctxt->pw && strcmp(service, "ssh-connection")==0) {
287                         authctxt->valid = 1;
288                         debug2_f("setting up authctxt for %s", user);
289                 } else {
290                         authctxt->valid = 0;
291                         /* Invalid user, fake password information */
292                         authctxt->pw = fakepw();
293 #ifdef SSH_AUDIT_EVENTS
294                         PRIVSEP(audit_event(ssh, SSH_INVALID_USER));
295 #endif
296                 }
297 #ifdef USE_PAM
298                 if (options.use_pam)
299                         PRIVSEP(start_pam(ssh));
300 #endif
301                 ssh_packet_set_log_preamble(ssh, "%suser %s",
302                     authctxt->valid ? "authenticating " : "invalid ", user);
303                 setproctitle("%s%s", authctxt->valid ? user : "unknown",
304                     use_privsep ? " [net]" : "");
305                 authctxt->service = xstrdup(service);
306                 authctxt->style = style ? xstrdup(style) : NULL;
307                 if (use_privsep)
308                         mm_inform_authserv(service, style);
309                 userauth_banner(ssh);
310                 if (auth2_setup_methods_lists(authctxt) != 0)
311                         ssh_packet_disconnect(ssh,
312                             "no authentication methods enabled");
313         } else if (strcmp(user, authctxt->user) != 0 ||
314             strcmp(service, authctxt->service) != 0) {
315                 ssh_packet_disconnect(ssh, "Change of username or service "
316                     "not allowed: (%s,%s) -> (%s,%s)",
317                     authctxt->user, authctxt->service, user, service);
318         }
319         /* reset state */
320         auth2_challenge_stop(ssh);
321
322 #ifdef GSSAPI
323         /* XXX move to auth2_gssapi_stop() */
324         ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, NULL);
325         ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, NULL);
326 #endif
327
328         auth2_authctxt_reset_info(authctxt);
329         authctxt->postponed = 0;
330         authctxt->server_caused_failure = 0;
331
332         /* try to authenticate user */
333         m = authmethod_lookup(authctxt, method);
334         if (m != NULL && authctxt->failures < options.max_authtries) {
335                 debug2("input_userauth_request: try method %s", method);
336                 authenticated = m->userauth(ssh, method);
337         }
338         if (!authctxt->authenticated)
339                 ensure_minimum_time_since(tstart,
340                     user_specific_delay(authctxt->user));
341         userauth_finish(ssh, authenticated, method, NULL);
342         r = 0;
343  out:
344         free(service);
345         free(user);
346         free(method);
347         return r;
348 }
349
350 void
351 userauth_finish(struct ssh *ssh, int authenticated, const char *packet_method,
352     const char *submethod)
353 {
354         Authctxt *authctxt = ssh->authctxt;
355         Authmethod *m = NULL;
356         const char *method = packet_method;
357         char *methods;
358         int r, partial = 0;
359
360         if (authenticated) {
361                 if (!authctxt->valid) {
362                         fatal("INTERNAL ERROR: authenticated invalid user %s",
363                             authctxt->user);
364                 }
365                 if (authctxt->postponed)
366                         fatal("INTERNAL ERROR: authenticated and postponed");
367                 /* prefer primary authmethod name to possible synonym */
368                 if ((m = authmethod_byname(method)) == NULL)
369                         fatal("INTERNAL ERROR: bad method %s", method);
370                 method = m->name;
371         }
372
373         /* Special handling for root */
374         if (authenticated && authctxt->pw->pw_uid == 0 &&
375             !auth_root_allowed(ssh, method)) {
376                 authenticated = 0;
377 #ifdef SSH_AUDIT_EVENTS
378                 PRIVSEP(audit_event(ssh, SSH_LOGIN_ROOT_DENIED));
379 #endif
380         }
381
382         if (authenticated && options.num_auth_methods != 0) {
383                 if (!auth2_update_methods_lists(authctxt, method, submethod)) {
384                         authenticated = 0;
385                         partial = 1;
386                 }
387         }
388
389         /* Log before sending the reply */
390         auth_log(ssh, authenticated, partial, method, submethod);
391
392         /* Update information exposed to session */
393         if (authenticated || partial)
394                 auth2_update_session_info(authctxt, method, submethod);
395
396         if (authctxt->postponed)
397                 return;
398
399 #ifdef USE_PAM
400         if (options.use_pam && authenticated) {
401                 int r, success = PRIVSEP(do_pam_account());
402
403                 /* If PAM returned a message, send it to the user. */
404                 if (sshbuf_len(loginmsg) > 0) {
405                         if ((r = sshbuf_put(loginmsg, "\0", 1)) != 0)
406                                 fatal("%s: buffer error: %s",
407                                     __func__, ssh_err(r));
408                         userauth_send_banner(ssh, sshbuf_ptr(loginmsg));
409                         if ((r = ssh_packet_write_wait(ssh)) != 0) {
410                                 sshpkt_fatal(ssh, r,
411                                     "%s: send PAM banner", __func__);
412                         }
413                 }
414                 if (!success) {
415                         fatal("Access denied for user %s by PAM account "
416                             "configuration", authctxt->user);
417                 }
418         }
419 #endif
420
421         if (authenticated == 1) {
422                 /* turn off userauth */
423                 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_REQUEST,
424                     &dispatch_protocol_ignore);
425                 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_SUCCESS)) != 0 ||
426                     (r = sshpkt_send(ssh)) != 0 ||
427                     (r = ssh_packet_write_wait(ssh)) != 0)
428                         fatal_fr(r, "send success packet");
429                 /* now we can break out */
430                 authctxt->success = 1;
431                 ssh_packet_set_log_preamble(ssh, "user %s", authctxt->user);
432         } else {
433                 /* Allow initial try of "none" auth without failure penalty */
434                 if (!partial && !authctxt->server_caused_failure &&
435                     (authctxt->attempt > 1 || strcmp(method, "none") != 0)) {
436                         authctxt->failures++;
437                         BLACKLIST_NOTIFY(ssh, BLACKLIST_AUTH_FAIL, "ssh");
438                 }
439                 if (authctxt->failures >= options.max_authtries) {
440 #ifdef SSH_AUDIT_EVENTS
441                         PRIVSEP(audit_event(ssh, SSH_LOGIN_EXCEED_MAXTRIES));
442 #endif
443                         auth_maxtries_exceeded(ssh);
444                 }
445                 methods = authmethods_get(authctxt);
446                 debug3_f("failure partial=%d next methods=\"%s\"",
447                     partial, methods);
448                 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_FAILURE)) != 0 ||
449                     (r = sshpkt_put_cstring(ssh, methods)) != 0 ||
450                     (r = sshpkt_put_u8(ssh, partial)) != 0 ||
451                     (r = sshpkt_send(ssh)) != 0 ||
452                     (r = ssh_packet_write_wait(ssh)) != 0)
453                         fatal_fr(r, "send failure packet");
454                 free(methods);
455         }
456 }
457
458 /*
459  * Checks whether method is allowed by at least one AuthenticationMethods
460  * methods list. Returns 1 if allowed, or no methods lists configured.
461  * 0 otherwise.
462  */
463 int
464 auth2_method_allowed(Authctxt *authctxt, const char *method,
465     const char *submethod)
466 {
467         u_int i;
468
469         /*
470          * NB. authctxt->num_auth_methods might be zero as a result of
471          * auth2_setup_methods_lists(), so check the configuration.
472          */
473         if (options.num_auth_methods == 0)
474                 return 1;
475         for (i = 0; i < authctxt->num_auth_methods; i++) {
476                 if (list_starts_with(authctxt->auth_methods[i], method,
477                     submethod) != MATCH_NONE)
478                         return 1;
479         }
480         return 0;
481 }
482
483 static char *
484 authmethods_get(Authctxt *authctxt)
485 {
486         struct sshbuf *b;
487         char *list;
488         int i, r;
489
490         if ((b = sshbuf_new()) == NULL)
491                 fatal_f("sshbuf_new failed");
492         for (i = 0; authmethods[i] != NULL; i++) {
493                 if (strcmp(authmethods[i]->name, "none") == 0)
494                         continue;
495                 if (authmethods[i]->enabled == NULL ||
496                     *(authmethods[i]->enabled) == 0)
497                         continue;
498                 if (!auth2_method_allowed(authctxt, authmethods[i]->name,
499                     NULL))
500                         continue;
501                 if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) ? "," : "",
502                     authmethods[i]->name)) != 0)
503                         fatal_fr(r, "buffer error");
504         }
505         if ((list = sshbuf_dup_string(b)) == NULL)
506                 fatal_f("sshbuf_dup_string failed");
507         sshbuf_free(b);
508         return list;
509 }
510
511 static Authmethod *
512 authmethod_byname(const char *name)
513 {
514         int i;
515
516         if (name == NULL)
517                 fatal_f("NULL authentication method name");
518         for (i = 0; authmethods[i] != NULL; i++) {
519                 if (strcmp(name, authmethods[i]->name) == 0 ||
520                     (authmethods[i]->synonym != NULL &&
521                     strcmp(name, authmethods[i]->synonym) == 0))
522                         return authmethods[i];
523         }
524         debug_f("unrecognized authentication method name: %s", name);
525         return NULL;
526 }
527
528 static Authmethod *
529 authmethod_lookup(Authctxt *authctxt, const char *name)
530 {
531         Authmethod *method;
532
533         if ((method = authmethod_byname(name)) == NULL)
534                 return NULL;
535
536         if (method->enabled == NULL || *(method->enabled) == 0) {
537                 debug3_f("method %s not enabled", name);
538                 return NULL;
539         }
540         if (!auth2_method_allowed(authctxt, method->name, NULL)) {
541                 debug3_f("method %s not allowed "
542                     "by AuthenticationMethods", name);
543                 return NULL;
544         }
545         return method;
546 }
547
548 /*
549  * Check a comma-separated list of methods for validity. Is need_enable is
550  * non-zero, then also require that the methods are enabled.
551  * Returns 0 on success or -1 if the methods list is invalid.
552  */
553 int
554 auth2_methods_valid(const char *_methods, int need_enable)
555 {
556         char *methods, *omethods, *method, *p;
557         u_int i, found;
558         int ret = -1;
559
560         if (*_methods == '\0') {
561                 error("empty authentication method list");
562                 return -1;
563         }
564         omethods = methods = xstrdup(_methods);
565         while ((method = strsep(&methods, ",")) != NULL) {
566                 for (found = i = 0; !found && authmethods[i] != NULL; i++) {
567                         if ((p = strchr(method, ':')) != NULL)
568                                 *p = '\0';
569                         if (strcmp(method, authmethods[i]->name) != 0)
570                                 continue;
571                         if (need_enable) {
572                                 if (authmethods[i]->enabled == NULL ||
573                                     *(authmethods[i]->enabled) == 0) {
574                                         error("Disabled method \"%s\" in "
575                                             "AuthenticationMethods list \"%s\"",
576                                             method, _methods);
577                                         goto out;
578                                 }
579                         }
580                         found = 1;
581                         break;
582                 }
583                 if (!found) {
584                         error("Unknown authentication method \"%s\" in list",
585                             method);
586                         goto out;
587                 }
588         }
589         ret = 0;
590  out:
591         free(omethods);
592         return ret;
593 }
594
595 /*
596  * Prune the AuthenticationMethods supplied in the configuration, removing
597  * any methods lists that include disabled methods. Note that this might
598  * leave authctxt->num_auth_methods == 0, even when multiple required auth
599  * has been requested. For this reason, all tests for whether multiple is
600  * enabled should consult options.num_auth_methods directly.
601  */
602 int
603 auth2_setup_methods_lists(Authctxt *authctxt)
604 {
605         u_int i;
606
607         /* First, normalise away the "any" pseudo-method */
608         if (options.num_auth_methods == 1 &&
609             strcmp(options.auth_methods[0], "any") == 0) {
610                 free(options.auth_methods[0]);
611                 options.auth_methods[0] = NULL;
612                 options.num_auth_methods = 0;
613         }
614
615         if (options.num_auth_methods == 0)
616                 return 0;
617         debug3_f("checking methods");
618         authctxt->auth_methods = xcalloc(options.num_auth_methods,
619             sizeof(*authctxt->auth_methods));
620         authctxt->num_auth_methods = 0;
621         for (i = 0; i < options.num_auth_methods; i++) {
622                 if (auth2_methods_valid(options.auth_methods[i], 1) != 0) {
623                         logit("Authentication methods list \"%s\" contains "
624                             "disabled method, skipping",
625                             options.auth_methods[i]);
626                         continue;
627                 }
628                 debug("authentication methods list %d: %s",
629                     authctxt->num_auth_methods, options.auth_methods[i]);
630                 authctxt->auth_methods[authctxt->num_auth_methods++] =
631                     xstrdup(options.auth_methods[i]);
632         }
633         if (authctxt->num_auth_methods == 0) {
634                 error("No AuthenticationMethods left after eliminating "
635                     "disabled methods");
636                 return -1;
637         }
638         return 0;
639 }
640
641 static int
642 list_starts_with(const char *methods, const char *method,
643     const char *submethod)
644 {
645         size_t l = strlen(method);
646         int match;
647         const char *p;
648
649         if (strncmp(methods, method, l) != 0)
650                 return MATCH_NONE;
651         p = methods + l;
652         match = MATCH_METHOD;
653         if (*p == ':') {
654                 if (!submethod)
655                         return MATCH_PARTIAL;
656                 l = strlen(submethod);
657                 p += 1;
658                 if (strncmp(submethod, p, l))
659                         return MATCH_NONE;
660                 p += l;
661                 match = MATCH_BOTH;
662         }
663         if (*p != ',' && *p != '\0')
664                 return MATCH_NONE;
665         return match;
666 }
667
668 /*
669  * Remove method from the start of a comma-separated list of methods.
670  * Returns 0 if the list of methods did not start with that method or 1
671  * if it did.
672  */
673 static int
674 remove_method(char **methods, const char *method, const char *submethod)
675 {
676         char *omethods = *methods, *p;
677         size_t l = strlen(method);
678         int match;
679
680         match = list_starts_with(omethods, method, submethod);
681         if (match != MATCH_METHOD && match != MATCH_BOTH)
682                 return 0;
683         p = omethods + l;
684         if (submethod && match == MATCH_BOTH)
685                 p += 1 + strlen(submethod); /* include colon */
686         if (*p == ',')
687                 p++;
688         *methods = xstrdup(p);
689         free(omethods);
690         return 1;
691 }
692
693 /*
694  * Called after successful authentication. Will remove the successful method
695  * from the start of each list in which it occurs. If it was the last method
696  * in any list, then authentication is deemed successful.
697  * Returns 1 if the method completed any authentication list or 0 otherwise.
698  */
699 int
700 auth2_update_methods_lists(Authctxt *authctxt, const char *method,
701     const char *submethod)
702 {
703         u_int i, found = 0;
704
705         debug3_f("updating methods list after \"%s\"", method);
706         for (i = 0; i < authctxt->num_auth_methods; i++) {
707                 if (!remove_method(&(authctxt->auth_methods[i]), method,
708                     submethod))
709                         continue;
710                 found = 1;
711                 if (*authctxt->auth_methods[i] == '\0') {
712                         debug2("authentication methods list %d complete", i);
713                         return 1;
714                 }
715                 debug3("authentication methods list %d remaining: \"%s\"",
716                     i, authctxt->auth_methods[i]);
717         }
718         /* This should not happen, but would be bad if it did */
719         if (!found)
720                 fatal_f("method not in AuthenticationMethods");
721         return 0;
722 }
723
724 /* Reset method-specific information */
725 void auth2_authctxt_reset_info(Authctxt *authctxt)
726 {
727         sshkey_free(authctxt->auth_method_key);
728         free(authctxt->auth_method_info);
729         authctxt->auth_method_key = NULL;
730         authctxt->auth_method_info = NULL;
731 }
732
733 /* Record auth method-specific information for logs */
734 void
735 auth2_record_info(Authctxt *authctxt, const char *fmt, ...)
736 {
737         va_list ap;
738         int i;
739
740         free(authctxt->auth_method_info);
741         authctxt->auth_method_info = NULL;
742
743         va_start(ap, fmt);
744         i = vasprintf(&authctxt->auth_method_info, fmt, ap);
745         va_end(ap);
746
747         if (i == -1)
748                 fatal_f("vasprintf failed");
749 }
750
751 /*
752  * Records a public key used in authentication. This is used for logging
753  * and to ensure that the same key is not subsequently accepted again for
754  * multiple authentication.
755  */
756 void
757 auth2_record_key(Authctxt *authctxt, int authenticated,
758     const struct sshkey *key)
759 {
760         struct sshkey **tmp, *dup;
761         int r;
762
763         if ((r = sshkey_from_private(key, &dup)) != 0)
764                 fatal_fr(r, "copy key");
765         sshkey_free(authctxt->auth_method_key);
766         authctxt->auth_method_key = dup;
767
768         if (!authenticated)
769                 return;
770
771         /* If authenticated, make sure we don't accept this key again */
772         if ((r = sshkey_from_private(key, &dup)) != 0)
773                 fatal_fr(r, "copy key");
774         if (authctxt->nprev_keys >= INT_MAX ||
775             (tmp = recallocarray(authctxt->prev_keys, authctxt->nprev_keys,
776             authctxt->nprev_keys + 1, sizeof(*authctxt->prev_keys))) == NULL)
777                 fatal_f("reallocarray failed");
778         authctxt->prev_keys = tmp;
779         authctxt->prev_keys[authctxt->nprev_keys] = dup;
780         authctxt->nprev_keys++;
781
782 }
783
784 /* Checks whether a key has already been previously used for authentication */
785 int
786 auth2_key_already_used(Authctxt *authctxt, const struct sshkey *key)
787 {
788         u_int i;
789         char *fp;
790
791         for (i = 0; i < authctxt->nprev_keys; i++) {
792                 if (sshkey_equal_public(key, authctxt->prev_keys[i])) {
793                         fp = sshkey_fingerprint(authctxt->prev_keys[i],
794                             options.fingerprint_hash, SSH_FP_DEFAULT);
795                         debug3_f("key already used: %s %s",
796                             sshkey_type(authctxt->prev_keys[i]),
797                             fp == NULL ? "UNKNOWN" : fp);
798                         free(fp);
799                         return 1;
800                 }
801         }
802         return 0;
803 }
804
805 /*
806  * Updates authctxt->session_info with details of authentication. Should be
807  * whenever an authentication method succeeds.
808  */
809 void
810 auth2_update_session_info(Authctxt *authctxt, const char *method,
811     const char *submethod)
812 {
813         int r;
814
815         if (authctxt->session_info == NULL) {
816                 if ((authctxt->session_info = sshbuf_new()) == NULL)
817                         fatal_f("sshbuf_new");
818         }
819
820         /* Append method[/submethod] */
821         if ((r = sshbuf_putf(authctxt->session_info, "%s%s%s",
822             method, submethod == NULL ? "" : "/",
823             submethod == NULL ? "" : submethod)) != 0)
824                 fatal_fr(r, "append method");
825
826         /* Append key if present */
827         if (authctxt->auth_method_key != NULL) {
828                 if ((r = sshbuf_put_u8(authctxt->session_info, ' ')) != 0 ||
829                     (r = sshkey_format_text(authctxt->auth_method_key,
830                     authctxt->session_info)) != 0)
831                         fatal_fr(r, "append key");
832         }
833
834         if (authctxt->auth_method_info != NULL) {
835                 /* Ensure no ambiguity here */
836                 if (strchr(authctxt->auth_method_info, '\n') != NULL)
837                         fatal_f("auth_method_info contains \\n");
838                 if ((r = sshbuf_put_u8(authctxt->session_info, ' ')) != 0 ||
839                     (r = sshbuf_putf(authctxt->session_info, "%s",
840                     authctxt->auth_method_info)) != 0) {
841                         fatal_fr(r, "append method info");
842                 }
843         }
844         if ((r = sshbuf_put_u8(authctxt->session_info, '\n')) != 0)
845                 fatal_fr(r, "append");
846 }
847