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