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