]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssh/monitor.c
Fix misleading log messages upon successful sshd login.
[FreeBSD/FreeBSD.git] / crypto / openssh / monitor.c
1 /* $OpenBSD: monitor.c,v 1.186 2018/07/20 03:46:34 djm Exp $ */
2 /*
3  * Copyright 2002 Niels Provos <provos@citi.umich.edu>
4  * Copyright 2002 Markus Friedl <markus@openbsd.org>
5  * 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
30 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include <sys/wait.h>
33
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <limits.h>
37 #ifdef HAVE_PATHS_H
38 #include <paths.h>
39 #endif
40 #include <pwd.h>
41 #include <signal.h>
42 #ifdef HAVE_STDINT_H
43 #include <stdint.h>
44 #endif
45 #include <stdlib.h>
46 #include <string.h>
47 #include <stdarg.h>
48 #include <stdio.h>
49 #include <unistd.h>
50 #ifdef HAVE_POLL_H
51 #include <poll.h>
52 #else
53 # ifdef HAVE_SYS_POLL_H
54 #  include <sys/poll.h>
55 # endif
56 #endif
57
58 #ifdef WITH_OPENSSL
59 #include <openssl/dh.h>
60 #endif
61
62 #include "openbsd-compat/sys-tree.h"
63 #include "openbsd-compat/sys-queue.h"
64 #include "openbsd-compat/openssl-compat.h"
65
66 #include "atomicio.h"
67 #include "xmalloc.h"
68 #include "ssh.h"
69 #include "sshkey.h"
70 #include "sshbuf.h"
71 #include "hostfile.h"
72 #include "auth.h"
73 #include "cipher.h"
74 #include "kex.h"
75 #include "dh.h"
76 #include "auth-pam.h"
77 #include "packet.h"
78 #include "auth-options.h"
79 #include "sshpty.h"
80 #include "channels.h"
81 #include "session.h"
82 #include "sshlogin.h"
83 #include "canohost.h"
84 #include "log.h"
85 #include "misc.h"
86 #include "servconf.h"
87 #include "monitor.h"
88 #ifdef GSSAPI
89 #include "ssh-gss.h"
90 #endif
91 #include "monitor_wrap.h"
92 #include "monitor_fdpass.h"
93 #include "compat.h"
94 #include "ssh2.h"
95 #include "authfd.h"
96 #include "match.h"
97 #include "ssherr.h"
98
99 #ifdef GSSAPI
100 static Gssctxt *gsscontext = NULL;
101 #endif
102
103 /* Imports */
104 extern ServerOptions options;
105 extern u_int utmp_len;
106 extern u_char session_id[];
107 extern struct sshbuf *loginmsg;
108 extern struct sshauthopt *auth_opts; /* XXX move to permanent ssh->authctxt? */
109
110 /* State exported from the child */
111 static struct sshbuf *child_state;
112
113 /* Functions on the monitor that answer unprivileged requests */
114
115 int mm_answer_moduli(int, struct sshbuf *);
116 int mm_answer_sign(int, struct sshbuf *);
117 #ifdef HAVE_LOGIN_CAP
118 int mm_answer_login_getpwclass(int, struct sshbuf *);
119 #endif
120 int mm_answer_pwnamallow(int, struct sshbuf *);
121 int mm_answer_auth2_read_banner(int, struct sshbuf *);
122 int mm_answer_authserv(int, struct sshbuf *);
123 int mm_answer_authpassword(int, struct sshbuf *);
124 int mm_answer_bsdauthquery(int, struct sshbuf *);
125 int mm_answer_bsdauthrespond(int, struct sshbuf *);
126 int mm_answer_keyallowed(int, struct sshbuf *);
127 int mm_answer_keyverify(int, struct sshbuf *);
128 int mm_answer_pty(int, struct sshbuf *);
129 int mm_answer_pty_cleanup(int, struct sshbuf *);
130 int mm_answer_term(int, struct sshbuf *);
131 int mm_answer_rsa_keyallowed(int, struct sshbuf *);
132 int mm_answer_rsa_challenge(int, struct sshbuf *);
133 int mm_answer_rsa_response(int, struct sshbuf *);
134 int mm_answer_sesskey(int, struct sshbuf *);
135 int mm_answer_sessid(int, struct sshbuf *);
136
137 #ifdef USE_PAM
138 int mm_answer_pam_start(int, struct sshbuf *);
139 int mm_answer_pam_account(int, struct sshbuf *);
140 int mm_answer_pam_init_ctx(int, struct sshbuf *);
141 int mm_answer_pam_query(int, struct sshbuf *);
142 int mm_answer_pam_respond(int, struct sshbuf *);
143 int mm_answer_pam_free_ctx(int, struct sshbuf *);
144 #endif
145
146 #ifdef GSSAPI
147 int mm_answer_gss_setup_ctx(int, struct sshbuf *);
148 int mm_answer_gss_accept_ctx(int, struct sshbuf *);
149 int mm_answer_gss_userok(int, struct sshbuf *);
150 int mm_answer_gss_checkmic(int, struct sshbuf *);
151 #endif
152
153 #ifdef SSH_AUDIT_EVENTS
154 int mm_answer_audit_event(int, struct sshbuf *);
155 int mm_answer_audit_command(int, struct sshbuf *);
156 #endif
157
158 static int monitor_read_log(struct monitor *);
159
160 static Authctxt *authctxt;
161
162 /* local state for key verify */
163 static u_char *key_blob = NULL;
164 static size_t key_bloblen = 0;
165 static int key_blobtype = MM_NOKEY;
166 static struct sshauthopt *key_opts = NULL;
167 static char *hostbased_cuser = NULL;
168 static char *hostbased_chost = NULL;
169 static char *auth_method = "unknown";
170 static char *auth_submethod = NULL;
171 static u_int session_id2_len = 0;
172 static u_char *session_id2 = NULL;
173 static pid_t monitor_child_pid;
174
175 struct mon_table {
176         enum monitor_reqtype type;
177         int flags;
178         int (*f)(int, struct sshbuf *);
179 };
180
181 #define MON_ISAUTH      0x0004  /* Required for Authentication */
182 #define MON_AUTHDECIDE  0x0008  /* Decides Authentication */
183 #define MON_ONCE        0x0010  /* Disable after calling */
184 #define MON_ALOG        0x0020  /* Log auth attempt without authenticating */
185
186 #define MON_AUTH        (MON_ISAUTH|MON_AUTHDECIDE)
187
188 #define MON_PERMIT      0x1000  /* Request is permitted */
189
190 struct mon_table mon_dispatch_proto20[] = {
191 #ifdef WITH_OPENSSL
192     {MONITOR_REQ_MODULI, MON_ONCE, mm_answer_moduli},
193 #endif
194     {MONITOR_REQ_SIGN, MON_ONCE, mm_answer_sign},
195 #ifdef HAVE_LOGIN_CAP
196     {MONITOR_REQ_GETPWCLASS, MON_ISAUTH, mm_answer_login_getpwclass},
197 #endif
198     {MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow},
199     {MONITOR_REQ_AUTHSERV, MON_ONCE, mm_answer_authserv},
200     {MONITOR_REQ_AUTH2_READ_BANNER, MON_ONCE, mm_answer_auth2_read_banner},
201     {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
202 #ifdef USE_PAM
203     {MONITOR_REQ_PAM_START, MON_ONCE, mm_answer_pam_start},
204     {MONITOR_REQ_PAM_ACCOUNT, 0, mm_answer_pam_account},
205     {MONITOR_REQ_PAM_INIT_CTX, MON_ONCE, mm_answer_pam_init_ctx},
206     {MONITOR_REQ_PAM_QUERY, 0, mm_answer_pam_query},
207     {MONITOR_REQ_PAM_RESPOND, MON_ONCE, mm_answer_pam_respond},
208     {MONITOR_REQ_PAM_FREE_CTX, MON_ONCE|MON_AUTHDECIDE, mm_answer_pam_free_ctx},
209 #endif
210 #ifdef SSH_AUDIT_EVENTS
211     {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
212 #endif
213 #ifdef BSD_AUTH
214     {MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery},
215     {MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond},
216 #endif
217     {MONITOR_REQ_KEYALLOWED, MON_ISAUTH, mm_answer_keyallowed},
218     {MONITOR_REQ_KEYVERIFY, MON_AUTH, mm_answer_keyverify},
219 #ifdef GSSAPI
220     {MONITOR_REQ_GSSSETUP, MON_ISAUTH, mm_answer_gss_setup_ctx},
221     {MONITOR_REQ_GSSSTEP, 0, mm_answer_gss_accept_ctx},
222     {MONITOR_REQ_GSSUSEROK, MON_ONCE|MON_AUTHDECIDE, mm_answer_gss_userok},
223     {MONITOR_REQ_GSSCHECKMIC, MON_ONCE, mm_answer_gss_checkmic},
224 #endif
225     {0, 0, NULL}
226 };
227
228 struct mon_table mon_dispatch_postauth20[] = {
229 #ifdef WITH_OPENSSL
230     {MONITOR_REQ_MODULI, 0, mm_answer_moduli},
231 #endif
232     {MONITOR_REQ_SIGN, 0, mm_answer_sign},
233     {MONITOR_REQ_PTY, 0, mm_answer_pty},
234     {MONITOR_REQ_PTYCLEANUP, 0, mm_answer_pty_cleanup},
235     {MONITOR_REQ_TERM, 0, mm_answer_term},
236 #ifdef SSH_AUDIT_EVENTS
237     {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
238     {MONITOR_REQ_AUDIT_COMMAND, MON_PERMIT, mm_answer_audit_command},
239 #endif
240     {0, 0, NULL}
241 };
242
243 struct mon_table *mon_dispatch;
244
245 /* Specifies if a certain message is allowed at the moment */
246 static void
247 monitor_permit(struct mon_table *ent, enum monitor_reqtype type, int permit)
248 {
249         while (ent->f != NULL) {
250                 if (ent->type == type) {
251                         ent->flags &= ~MON_PERMIT;
252                         ent->flags |= permit ? MON_PERMIT : 0;
253                         return;
254                 }
255                 ent++;
256         }
257 }
258
259 static void
260 monitor_permit_authentications(int permit)
261 {
262         struct mon_table *ent = mon_dispatch;
263
264         while (ent->f != NULL) {
265                 if (ent->flags & MON_AUTH) {
266                         ent->flags &= ~MON_PERMIT;
267                         ent->flags |= permit ? MON_PERMIT : 0;
268                 }
269                 ent++;
270         }
271 }
272
273 void
274 monitor_child_preauth(Authctxt *_authctxt, struct monitor *pmonitor)
275 {
276         struct ssh *ssh = active_state; /* XXX */
277         struct mon_table *ent;
278         int authenticated = 0, partial = 0;
279
280         debug3("preauth child monitor started");
281
282         if (pmonitor->m_recvfd >= 0)
283                 close(pmonitor->m_recvfd);
284         if (pmonitor->m_log_sendfd >= 0)
285                 close(pmonitor->m_log_sendfd);
286         pmonitor->m_log_sendfd = pmonitor->m_recvfd = -1;
287
288         authctxt = _authctxt;
289         memset(authctxt, 0, sizeof(*authctxt));
290         ssh->authctxt = authctxt;
291
292         authctxt->loginmsg = loginmsg;
293
294         mon_dispatch = mon_dispatch_proto20;
295         /* Permit requests for moduli and signatures */
296         monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
297         monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
298
299         /* The first few requests do not require asynchronous access */
300         while (!authenticated) {
301                 partial = 0;
302                 auth_method = "unknown";
303                 auth_submethod = NULL;
304                 auth2_authctxt_reset_info(authctxt);
305
306                 authenticated = (monitor_read(pmonitor, mon_dispatch, &ent) == 1);
307
308                 /* Special handling for multiple required authentications */
309                 if (options.num_auth_methods != 0) {
310                         if (authenticated &&
311                             !auth2_update_methods_lists(authctxt,
312                             auth_method, auth_submethod)) {
313                                 debug3("%s: method %s: partial", __func__,
314                                     auth_method);
315                                 authenticated = 0;
316                                 partial = 1;
317                         }
318                 }
319
320                 if (authenticated) {
321                         if (!(ent->flags & MON_AUTHDECIDE))
322                                 fatal("%s: unexpected authentication from %d",
323                                     __func__, ent->type);
324                         if (authctxt->pw->pw_uid == 0 &&
325                             !auth_root_allowed(ssh, auth_method))
326                                 authenticated = 0;
327 #ifdef USE_PAM
328                         /* PAM needs to perform account checks after auth */
329                         if (options.use_pam && authenticated) {
330                                 struct sshbuf *m;
331
332                                 if ((m = sshbuf_new()) == NULL)
333                                         fatal("%s: sshbuf_new failed",
334                                             __func__);
335                                 mm_request_receive_expect(pmonitor->m_sendfd,
336                                     MONITOR_REQ_PAM_ACCOUNT, m);
337                                 authenticated = mm_answer_pam_account(
338                                     pmonitor->m_sendfd, m);
339                                 sshbuf_free(m);
340                         }
341 #endif
342                 }
343                 if (ent->flags & (MON_AUTHDECIDE|MON_ALOG)) {
344                         auth_log(authctxt, authenticated, partial,
345                             auth_method, auth_submethod);
346                         if (!partial && !authenticated)
347                                 authctxt->failures++;
348                         if (authenticated || partial) {
349                                 auth2_update_session_info(authctxt,
350                                     auth_method, auth_submethod);
351                         }
352                 }
353         }
354
355         if (!authctxt->valid)
356                 fatal("%s: authenticated invalid user", __func__);
357         if (strcmp(auth_method, "unknown") == 0)
358                 fatal("%s: authentication method name unknown", __func__);
359
360         debug("%s: %s has been authenticated by privileged process",
361             __func__, authctxt->user);
362         ssh->authctxt = NULL;
363         ssh_packet_set_log_preamble(ssh, "user %s", authctxt->user);
364
365         mm_get_keystate(pmonitor);
366
367         /* Drain any buffered messages from the child */
368         while (pmonitor->m_log_recvfd != -1 && monitor_read_log(pmonitor) == 0)
369                 ;
370
371         if (pmonitor->m_recvfd >= 0)
372                 close(pmonitor->m_recvfd);
373         if (pmonitor->m_log_sendfd >= 0)
374                 close(pmonitor->m_log_sendfd);
375         pmonitor->m_sendfd = pmonitor->m_log_recvfd = -1;
376 }
377
378 static void
379 monitor_set_child_handler(pid_t pid)
380 {
381         monitor_child_pid = pid;
382 }
383
384 static void
385 monitor_child_handler(int sig)
386 {
387         kill(monitor_child_pid, sig);
388 }
389
390 void
391 monitor_child_postauth(struct monitor *pmonitor)
392 {
393         close(pmonitor->m_recvfd);
394         pmonitor->m_recvfd = -1;
395
396         monitor_set_child_handler(pmonitor->m_pid);
397         signal(SIGHUP, &monitor_child_handler);
398         signal(SIGTERM, &monitor_child_handler);
399         signal(SIGINT, &monitor_child_handler);
400 #ifdef SIGXFSZ
401         signal(SIGXFSZ, SIG_IGN);
402 #endif
403
404         mon_dispatch = mon_dispatch_postauth20;
405
406         /* Permit requests for moduli and signatures */
407         monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
408         monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
409         monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
410
411         if (auth_opts->permit_pty_flag) {
412                 monitor_permit(mon_dispatch, MONITOR_REQ_PTY, 1);
413                 monitor_permit(mon_dispatch, MONITOR_REQ_PTYCLEANUP, 1);
414         }
415
416         for (;;)
417                 monitor_read(pmonitor, mon_dispatch, NULL);
418 }
419
420 static int
421 monitor_read_log(struct monitor *pmonitor)
422 {
423         struct sshbuf *logmsg;
424         u_int len, level;
425         char *msg;
426         u_char *p;
427         int r;
428
429         if ((logmsg = sshbuf_new()) == NULL)
430                 fatal("%s: sshbuf_new", __func__);
431
432         /* Read length */
433         if ((r = sshbuf_reserve(logmsg, 4, &p)) != 0)
434                 fatal("%s: reserve: %s", __func__, ssh_err(r));
435         if (atomicio(read, pmonitor->m_log_recvfd, p, 4) != 4) {
436                 if (errno == EPIPE) {
437                         sshbuf_free(logmsg);
438                         debug("%s: child log fd closed", __func__);
439                         close(pmonitor->m_log_recvfd);
440                         pmonitor->m_log_recvfd = -1;
441                         return -1;
442                 }
443                 fatal("%s: log fd read: %s", __func__, strerror(errno));
444         }
445         if ((r = sshbuf_get_u32(logmsg, &len)) != 0)
446                 fatal("%s: get len: %s", __func__, ssh_err(r));
447         if (len <= 4 || len > 8192)
448                 fatal("%s: invalid log message length %u", __func__, len);
449
450         /* Read severity, message */
451         sshbuf_reset(logmsg);
452         if ((r = sshbuf_reserve(logmsg, len, &p)) != 0)
453                 fatal("%s: reserve: %s", __func__, ssh_err(r));
454         if (atomicio(read, pmonitor->m_log_recvfd, p, len) != len)
455                 fatal("%s: log fd read: %s", __func__, strerror(errno));
456         if ((r = sshbuf_get_u32(logmsg, &level)) != 0 ||
457             (r = sshbuf_get_cstring(logmsg, &msg, NULL)) != 0)
458                 fatal("%s: decode: %s", __func__, ssh_err(r));
459
460         /* Log it */
461         if (log_level_name(level) == NULL)
462                 fatal("%s: invalid log level %u (corrupted message?)",
463                     __func__, level);
464         do_log2(level, "%s [preauth]", msg);
465
466         sshbuf_free(logmsg);
467         free(msg);
468
469         return 0;
470 }
471
472 int
473 monitor_read(struct monitor *pmonitor, struct mon_table *ent,
474     struct mon_table **pent)
475 {
476         struct sshbuf *m;
477         int r, ret;
478         u_char type;
479         struct pollfd pfd[2];
480
481         for (;;) {
482                 memset(&pfd, 0, sizeof(pfd));
483                 pfd[0].fd = pmonitor->m_sendfd;
484                 pfd[0].events = POLLIN;
485                 pfd[1].fd = pmonitor->m_log_recvfd;
486                 pfd[1].events = pfd[1].fd == -1 ? 0 : POLLIN;
487                 if (poll(pfd, pfd[1].fd == -1 ? 1 : 2, -1) == -1) {
488                         if (errno == EINTR || errno == EAGAIN)
489                                 continue;
490                         fatal("%s: poll: %s", __func__, strerror(errno));
491                 }
492                 if (pfd[1].revents) {
493                         /*
494                          * Drain all log messages before processing next
495                          * monitor request.
496                          */
497                         monitor_read_log(pmonitor);
498                         continue;
499                 }
500                 if (pfd[0].revents)
501                         break;  /* Continues below */
502         }
503
504         if ((m = sshbuf_new()) == NULL)
505                 fatal("%s: sshbuf_new", __func__);
506
507         mm_request_receive(pmonitor->m_sendfd, m);
508         if ((r = sshbuf_get_u8(m, &type)) != 0)
509                 fatal("%s: decode: %s", __func__, ssh_err(r));
510
511         debug3("%s: checking request %d", __func__, type);
512
513         while (ent->f != NULL) {
514                 if (ent->type == type)
515                         break;
516                 ent++;
517         }
518
519         if (ent->f != NULL) {
520                 if (!(ent->flags & MON_PERMIT))
521                         fatal("%s: unpermitted request %d", __func__,
522                             type);
523                 ret = (*ent->f)(pmonitor->m_sendfd, m);
524                 sshbuf_free(m);
525
526                 /* The child may use this request only once, disable it */
527                 if (ent->flags & MON_ONCE) {
528                         debug2("%s: %d used once, disabling now", __func__,
529                             type);
530                         ent->flags &= ~MON_PERMIT;
531                 }
532
533                 if (pent != NULL)
534                         *pent = ent;
535
536                 return ret;
537         }
538
539         fatal("%s: unsupported request: %d", __func__, type);
540
541         /* NOTREACHED */
542         return (-1);
543 }
544
545 /* allowed key state */
546 static int
547 monitor_allowed_key(u_char *blob, u_int bloblen)
548 {
549         /* make sure key is allowed */
550         if (key_blob == NULL || key_bloblen != bloblen ||
551             timingsafe_bcmp(key_blob, blob, key_bloblen))
552                 return (0);
553         return (1);
554 }
555
556 static void
557 monitor_reset_key_state(void)
558 {
559         /* reset state */
560         free(key_blob);
561         free(hostbased_cuser);
562         free(hostbased_chost);
563         sshauthopt_free(key_opts);
564         key_blob = NULL;
565         key_bloblen = 0;
566         key_blobtype = MM_NOKEY;
567         key_opts = NULL;
568         hostbased_cuser = NULL;
569         hostbased_chost = NULL;
570 }
571
572 #ifdef WITH_OPENSSL
573 int
574 mm_answer_moduli(int sock, struct sshbuf *m)
575 {
576         DH *dh;
577         const BIGNUM *dh_p, *dh_g;
578         int r;
579         u_int min, want, max;
580
581         if ((r = sshbuf_get_u32(m, &min)) != 0 ||
582             (r = sshbuf_get_u32(m, &want)) != 0 ||
583             (r = sshbuf_get_u32(m, &max)) != 0)
584                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
585
586         debug3("%s: got parameters: %d %d %d",
587             __func__, min, want, max);
588         /* We need to check here, too, in case the child got corrupted */
589         if (max < min || want < min || max < want)
590                 fatal("%s: bad parameters: %d %d %d",
591                     __func__, min, want, max);
592
593         sshbuf_reset(m);
594
595         dh = choose_dh(min, want, max);
596         if (dh == NULL) {
597                 if ((r = sshbuf_put_u8(m, 0)) != 0)
598                         fatal("%s: buffer error: %s", __func__, ssh_err(r));
599                 return (0);
600         } else {
601                 /* Send first bignum */
602                 DH_get0_pqg(dh, &dh_p, NULL, &dh_g);
603                 if ((r = sshbuf_put_u8(m, 1)) != 0 ||
604                     (r = sshbuf_put_bignum2(m, dh_p)) != 0 ||
605                     (r = sshbuf_put_bignum2(m, dh_g)) != 0)
606                         fatal("%s: buffer error: %s", __func__, ssh_err(r));
607
608                 DH_free(dh);
609         }
610         mm_request_send(sock, MONITOR_ANS_MODULI, m);
611         return (0);
612 }
613 #endif
614
615 int
616 mm_answer_sign(int sock, struct sshbuf *m)
617 {
618         struct ssh *ssh = active_state;         /* XXX */
619         extern int auth_sock;                   /* XXX move to state struct? */
620         struct sshkey *key;
621         struct sshbuf *sigbuf = NULL;
622         u_char *p = NULL, *signature = NULL;
623         char *alg = NULL;
624         size_t datlen, siglen, alglen;
625         int r, is_proof = 0;
626         u_int keyid, compat;
627         const char proof_req[] = "hostkeys-prove-00@openssh.com";
628
629         debug3("%s", __func__);
630
631         if ((r = sshbuf_get_u32(m, &keyid)) != 0 ||
632             (r = sshbuf_get_string(m, &p, &datlen)) != 0 ||
633             (r = sshbuf_get_cstring(m, &alg, &alglen)) != 0 ||
634             (r = sshbuf_get_u32(m, &compat)) != 0)
635                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
636         if (keyid > INT_MAX)
637                 fatal("%s: invalid key ID", __func__);
638
639         /*
640          * Supported KEX types use SHA1 (20 bytes), SHA256 (32 bytes),
641          * SHA384 (48 bytes) and SHA512 (64 bytes).
642          *
643          * Otherwise, verify the signature request is for a hostkey
644          * proof.
645          *
646          * XXX perform similar check for KEX signature requests too?
647          * it's not trivial, since what is signed is the hash, rather
648          * than the full kex structure...
649          */
650         if (datlen != 20 && datlen != 32 && datlen != 48 && datlen != 64) {
651                 /*
652                  * Construct expected hostkey proof and compare it to what
653                  * the client sent us.
654                  */
655                 if (session_id2_len == 0) /* hostkeys is never first */
656                         fatal("%s: bad data length: %zu", __func__, datlen);
657                 if ((key = get_hostkey_public_by_index(keyid, ssh)) == NULL)
658                         fatal("%s: no hostkey for index %d", __func__, keyid);
659                 if ((sigbuf = sshbuf_new()) == NULL)
660                         fatal("%s: sshbuf_new", __func__);
661                 if ((r = sshbuf_put_cstring(sigbuf, proof_req)) != 0 ||
662                     (r = sshbuf_put_string(sigbuf, session_id2,
663                     session_id2_len)) != 0 ||
664                     (r = sshkey_puts(key, sigbuf)) != 0)
665                         fatal("%s: couldn't prepare private key "
666                             "proof buffer: %s", __func__, ssh_err(r));
667                 if (datlen != sshbuf_len(sigbuf) ||
668                     memcmp(p, sshbuf_ptr(sigbuf), sshbuf_len(sigbuf)) != 0)
669                         fatal("%s: bad data length: %zu, hostkey proof len %zu",
670                             __func__, datlen, sshbuf_len(sigbuf));
671                 sshbuf_free(sigbuf);
672                 is_proof = 1;
673         }
674
675         /* save session id, it will be passed on the first call */
676         if (session_id2_len == 0) {
677                 session_id2_len = datlen;
678                 session_id2 = xmalloc(session_id2_len);
679                 memcpy(session_id2, p, session_id2_len);
680         }
681
682         if ((key = get_hostkey_by_index(keyid)) != NULL) {
683                 if ((r = sshkey_sign(key, &signature, &siglen, p, datlen, alg,
684                     compat)) != 0)
685                         fatal("%s: sshkey_sign failed: %s",
686                             __func__, ssh_err(r));
687         } else if ((key = get_hostkey_public_by_index(keyid, ssh)) != NULL &&
688             auth_sock > 0) {
689                 if ((r = ssh_agent_sign(auth_sock, key, &signature, &siglen,
690                     p, datlen, alg, compat)) != 0) {
691                         fatal("%s: ssh_agent_sign failed: %s",
692                             __func__, ssh_err(r));
693                 }
694         } else
695                 fatal("%s: no hostkey from index %d", __func__, keyid);
696
697         debug3("%s: %s signature %p(%zu)", __func__,
698             is_proof ? "KEX" : "hostkey proof", signature, siglen);
699
700         sshbuf_reset(m);
701         if ((r = sshbuf_put_string(m, signature, siglen)) != 0)
702                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
703
704         free(alg);
705         free(p);
706         free(signature);
707
708         mm_request_send(sock, MONITOR_ANS_SIGN, m);
709
710         /* Turn on permissions for getpwnam */
711         monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
712
713         return (0);
714 }
715
716 #ifdef HAVE_LOGIN_CAP
717 int
718 mm_answer_login_getpwclass(int sock, struct sshbuf *m)
719 {
720         login_cap_t *lc;
721         struct passwd *pw;
722         int r;
723         u_int len;
724
725         debug3("%s", __func__);
726
727         pw = sshbuf_get_passwd(m);
728         if (pw == NULL)
729                 fatal("%s: receive get struct passwd failed", __func__);
730
731         lc = login_getpwclass(pw);
732
733         sshbuf_reset(m);
734
735         if (lc == NULL) {
736                 if (r = sshbuf_put_u8(m, 0) != 0)
737                         fatal("%s: buffer error: %s", __func__, ssh_err(r));
738                 goto out;
739         }
740
741         if ((r = sshbuf_put_u8(m, 1)) != 0 ||
742             (r = sshbuf_put_cstring(m, lc->lc_class)) != 0 ||
743             (r = sshbuf_put_cstring(m, lc->lc_cap)) != 0 ||
744             (r = sshbuf_put_cstring(m, lc->lc_style)) != 0)
745                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
746
747         login_close(lc);
748  out:
749         debug3("%s: sending MONITOR_ANS_GETPWCLASS", __func__);
750         mm_request_send(sock, MONITOR_ANS_GETPWCLASS, m);
751
752         sshbuf_free_passwd(pw);
753
754         return (0);
755 }
756 #endif
757
758 /* Retrieves the password entry and also checks if the user is permitted */
759
760 int
761 mm_answer_pwnamallow(int sock, struct sshbuf *m)
762 {
763         struct ssh *ssh = active_state; /* XXX */
764         char *username;
765         struct passwd *pwent;
766         int r, allowed = 0;
767         u_int i;
768
769         debug3("%s", __func__);
770
771         if (authctxt->attempt++ != 0)
772                 fatal("%s: multiple attempts for getpwnam", __func__);
773
774         if ((r = sshbuf_get_cstring(m, &username, NULL)) != 0)
775                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
776
777         pwent = getpwnamallow(username);
778
779         authctxt->user = xstrdup(username);
780         setproctitle("%s [priv]", pwent ? username : "unknown");
781         free(username);
782
783         sshbuf_reset(m);
784
785         if (pwent == NULL) {
786                 if ((r = sshbuf_put_u8(m, 0)) != 0)
787                         fatal("%s: buffer error: %s", __func__, ssh_err(r));
788                 authctxt->pw = fakepw();
789                 goto out;
790         }
791
792         allowed = 1;
793         authctxt->pw = pwent;
794         authctxt->valid = 1;
795
796         if ((r = sshbuf_put_u8(m, 1)) != 0 ||
797             (r = sshbuf_put_passwd(m, pwent)) != 0)
798                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
799
800  out:
801         ssh_packet_set_log_preamble(ssh, "%suser %s",
802             authctxt->valid ? "authenticating" : "invalid ", authctxt->user);
803         if ((r = sshbuf_put_string(m, &options, sizeof(options))) != 0)
804                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
805
806 #define M_CP_STROPT(x) do { \
807                 if (options.x != NULL) { \
808                         if ((r = sshbuf_put_cstring(m, options.x)) != 0) \
809                                 fatal("%s: buffer error: %s", \
810                                     __func__, ssh_err(r)); \
811                 } \
812         } while (0)
813 #define M_CP_STRARRAYOPT(x, nx) do { \
814                 for (i = 0; i < options.nx; i++) { \
815                         if ((r = sshbuf_put_cstring(m, options.x[i])) != 0) \
816                                 fatal("%s: buffer error: %s", \
817                                     __func__, ssh_err(r)); \
818                 } \
819         } while (0)
820         /* See comment in servconf.h */
821         COPY_MATCH_STRING_OPTS();
822 #undef M_CP_STROPT
823 #undef M_CP_STRARRAYOPT
824
825         /* Create valid auth method lists */
826         if (auth2_setup_methods_lists(authctxt) != 0) {
827                 /*
828                  * The monitor will continue long enough to let the child
829                  * run to it's packet_disconnect(), but it must not allow any
830                  * authentication to succeed.
831                  */
832                 debug("%s: no valid authentication method lists", __func__);
833         }
834
835         debug3("%s: sending MONITOR_ANS_PWNAM: %d", __func__, allowed);
836         mm_request_send(sock, MONITOR_ANS_PWNAM, m);
837
838         /* Allow service/style information on the auth context */
839         monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
840         monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
841
842 #ifdef USE_PAM
843         if (options.use_pam)
844                 monitor_permit(mon_dispatch, MONITOR_REQ_PAM_START, 1);
845 #endif
846
847         return (0);
848 }
849
850 int mm_answer_auth2_read_banner(int sock, struct sshbuf *m)
851 {
852         char *banner;
853         int r;
854
855         sshbuf_reset(m);
856         banner = auth2_read_banner();
857         if ((r = sshbuf_put_cstring(m, banner != NULL ? banner : "")) != 0)
858                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
859         mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m);
860         free(banner);
861
862         return (0);
863 }
864
865 int
866 mm_answer_authserv(int sock, struct sshbuf *m)
867 {
868         int r;
869
870         monitor_permit_authentications(1);
871
872         if ((r = sshbuf_get_cstring(m, &authctxt->service, NULL)) != 0 ||
873             (r = sshbuf_get_cstring(m, &authctxt->style, NULL)) != 0)
874                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
875         debug3("%s: service=%s, style=%s",
876             __func__, authctxt->service, authctxt->style);
877
878         if (strlen(authctxt->style) == 0) {
879                 free(authctxt->style);
880                 authctxt->style = NULL;
881         }
882
883         return (0);
884 }
885
886 int
887 mm_answer_authpassword(int sock, struct sshbuf *m)
888 {
889         struct ssh *ssh = active_state; /* XXX */
890         static int call_count;
891         char *passwd;
892         int r, authenticated;
893         size_t plen;
894
895         if (!options.password_authentication)
896                 fatal("%s: password authentication not enabled", __func__);
897         if ((r = sshbuf_get_cstring(m, &passwd, &plen)) != 0)
898                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
899         /* Only authenticate if the context is valid */
900         authenticated = options.password_authentication &&
901             auth_password(ssh, passwd);
902         explicit_bzero(passwd, plen);
903         free(passwd);
904
905         sshbuf_reset(m);
906         if ((r = sshbuf_put_u32(m, authenticated)) != 0)
907                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
908 #ifdef USE_PAM
909         if ((r = sshbuf_put_u32(m, sshpam_get_maxtries_reached())) != 0)
910                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
911 #endif
912
913         debug3("%s: sending result %d", __func__, authenticated);
914         mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m);
915
916         call_count++;
917         if (plen == 0 && call_count == 1)
918                 auth_method = "none";
919         else
920                 auth_method = "password";
921
922         /* Causes monitor loop to terminate if authenticated */
923         return (authenticated);
924 }
925
926 #ifdef BSD_AUTH
927 int
928 mm_answer_bsdauthquery(int sock, struct sshbuf *m)
929 {
930         char *name, *infotxt;
931         u_int numprompts, *echo_on, success;
932         char **prompts;
933         int r;
934
935         if (!options.kbd_interactive_authentication)
936                 fatal("%s: kbd-int authentication not enabled", __func__);
937         success = bsdauth_query(authctxt, &name, &infotxt, &numprompts,
938             &prompts, &echo_on) < 0 ? 0 : 1;
939
940         sshbuf_reset(m);
941         if ((r = sshbuf_put_u32(m, success)) != 0)
942                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
943         if (success) {
944                 if ((r = sshbuf_put_cstring(m, prompts[0])) != 0)
945                         fatal("%s: buffer error: %s", __func__, ssh_err(r));
946         }
947
948         debug3("%s: sending challenge success: %u", __func__, success);
949         mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m);
950
951         if (success) {
952                 free(name);
953                 free(infotxt);
954                 free(prompts);
955                 free(echo_on);
956         }
957
958         return (0);
959 }
960
961 int
962 mm_answer_bsdauthrespond(int sock, struct sshbuf *m)
963 {
964         char *response;
965         int r, authok;
966
967         if (!options.kbd_interactive_authentication)
968                 fatal("%s: kbd-int authentication not enabled", __func__);
969         if (authctxt->as == NULL)
970                 fatal("%s: no bsd auth session", __func__);
971
972         if ((r = sshbuf_get_cstring(m, &response, NULL)) != 0)
973                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
974         authok = options.challenge_response_authentication &&
975             auth_userresponse(authctxt->as, response, 0);
976         authctxt->as = NULL;
977         debug3("%s: <%s> = <%d>", __func__, response, authok);
978         free(response);
979
980         sshbuf_reset(m);
981         if ((r = sshbuf_put_u32(m, authok)) != 0)
982                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
983
984         debug3("%s: sending authenticated: %d", __func__, authok);
985         mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m);
986
987         auth_method = "keyboard-interactive";
988         auth_submethod = "bsdauth";
989
990         return (authok != 0);
991 }
992 #endif
993
994 #ifdef USE_PAM
995 int
996 mm_answer_pam_start(int sock, struct sshbuf *m)
997 {
998         if (!options.use_pam)
999                 fatal("UsePAM not set, but ended up in %s anyway", __func__);
1000
1001         start_pam(authctxt);
1002
1003         monitor_permit(mon_dispatch, MONITOR_REQ_PAM_ACCOUNT, 1);
1004         if (options.kbd_interactive_authentication)
1005                 monitor_permit(mon_dispatch, MONITOR_REQ_PAM_INIT_CTX, 1);
1006
1007         return (0);
1008 }
1009
1010 int
1011 mm_answer_pam_account(int sock, struct sshbuf *m)
1012 {
1013         u_int ret;
1014         int r;
1015
1016         if (!options.use_pam)
1017                 fatal("%s: PAM not enabled", __func__);
1018
1019         ret = do_pam_account();
1020
1021         if ((r = sshbuf_put_u32(m, ret)) != 0 ||
1022             (r = sshbuf_put_stringb(m, loginmsg)) != 0)
1023                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1024
1025         mm_request_send(sock, MONITOR_ANS_PAM_ACCOUNT, m);
1026
1027         return (ret);
1028 }
1029
1030 static void *sshpam_ctxt, *sshpam_authok;
1031 extern KbdintDevice sshpam_device;
1032
1033 int
1034 mm_answer_pam_init_ctx(int sock, struct sshbuf *m)
1035 {
1036         u_int ok = 0;
1037         int r;
1038
1039         debug3("%s", __func__);
1040         if (!options.kbd_interactive_authentication)
1041                 fatal("%s: kbd-int authentication not enabled", __func__);
1042         if (sshpam_ctxt != NULL)
1043                 fatal("%s: already called", __func__);
1044         sshpam_ctxt = (sshpam_device.init_ctx)(authctxt);
1045         sshpam_authok = NULL;
1046         sshbuf_reset(m);
1047         if (sshpam_ctxt != NULL) {
1048                 monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1);
1049                 monitor_permit(mon_dispatch, MONITOR_REQ_PAM_QUERY, 1);
1050                 ok = 1;
1051         }
1052         if ((r = sshbuf_put_u32(m, ok)) != 0)
1053                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1054         mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m);
1055         return (0);
1056 }
1057
1058 int
1059 mm_answer_pam_query(int sock, struct sshbuf *m)
1060 {
1061         char *name = NULL, *info = NULL, **prompts = NULL;
1062         u_int i, num = 0, *echo_on = 0;
1063         int r, ret;
1064
1065         debug3("%s", __func__);
1066         sshpam_authok = NULL;
1067         if (sshpam_ctxt == NULL)
1068                 fatal("%s: no context", __func__);
1069         ret = (sshpam_device.query)(sshpam_ctxt, &name, &info,
1070             &num, &prompts, &echo_on);
1071         if (ret == 0 && num == 0)
1072                 sshpam_authok = sshpam_ctxt;
1073         if (num > 1 || name == NULL || info == NULL)
1074                 fatal("sshpam_device.query failed");
1075         monitor_permit(mon_dispatch, MONITOR_REQ_PAM_RESPOND, 1);
1076         sshbuf_reset(m);
1077         if ((r = sshbuf_put_u32(m, ret)) != 0 ||
1078             (r = sshbuf_put_cstring(m, name)) != 0 ||
1079             (r = sshbuf_put_cstring(m, info)) != 0 ||
1080             (r = sshbuf_put_u32(m, sshpam_get_maxtries_reached())) != 0 ||
1081             (r = sshbuf_put_u32(m, num)) != 0)
1082                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1083         free(name);
1084         free(info);
1085         for (i = 0; i < num; ++i) {
1086                 if ((r = sshbuf_put_cstring(m, prompts[i])) != 0 ||
1087                     (r = sshbuf_put_u32(m, echo_on[i])) != 0)
1088                         fatal("%s: buffer error: %s", __func__, ssh_err(r));
1089                 free(prompts[i]);
1090         }
1091         free(prompts);
1092         free(echo_on);
1093         auth_method = "keyboard-interactive";
1094         auth_submethod = "pam";
1095         mm_request_send(sock, MONITOR_ANS_PAM_QUERY, m);
1096         return (0);
1097 }
1098
1099 int
1100 mm_answer_pam_respond(int sock, struct sshbuf *m)
1101 {
1102         char **resp;
1103         u_int i, num;
1104         int r, ret;
1105
1106         debug3("%s", __func__);
1107         if (sshpam_ctxt == NULL)
1108                 fatal("%s: no context", __func__);
1109         sshpam_authok = NULL;
1110         if ((r = sshbuf_get_u32(m, &num)) != 0)
1111                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1112         if (num > 0) {
1113                 resp = xcalloc(num, sizeof(char *));
1114                 for (i = 0; i < num; ++i) {
1115                         if ((r = sshbuf_get_cstring(m, &(resp[i]), NULL)) != 0)
1116                                 fatal("%s: buffer error: %s",
1117                                     __func__, ssh_err(r));
1118                 }
1119                 ret = (sshpam_device.respond)(sshpam_ctxt, num, resp);
1120                 for (i = 0; i < num; ++i)
1121                         free(resp[i]);
1122                 free(resp);
1123         } else {
1124                 ret = (sshpam_device.respond)(sshpam_ctxt, num, NULL);
1125         }
1126         sshbuf_reset(m);
1127         if ((r = sshbuf_put_u32(m, ret)) != 0)
1128                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1129         mm_request_send(sock, MONITOR_ANS_PAM_RESPOND, m);
1130         auth_method = "keyboard-interactive";
1131         auth_submethod = "pam";
1132         if (ret == 0)
1133                 sshpam_authok = sshpam_ctxt;
1134         return (0);
1135 }
1136
1137 int
1138 mm_answer_pam_free_ctx(int sock, struct sshbuf *m)
1139 {
1140         int r = sshpam_authok != NULL && sshpam_authok == sshpam_ctxt;
1141
1142         debug3("%s", __func__);
1143         if (sshpam_ctxt == NULL)
1144                 fatal("%s: no context", __func__);
1145         (sshpam_device.free_ctx)(sshpam_ctxt);
1146         sshpam_ctxt = sshpam_authok = NULL;
1147         sshbuf_reset(m);
1148         mm_request_send(sock, MONITOR_ANS_PAM_FREE_CTX, m);
1149         /* Allow another attempt */
1150         monitor_permit(mon_dispatch, MONITOR_REQ_PAM_INIT_CTX, 1);
1151         auth_method = "keyboard-interactive";
1152         auth_submethod = "pam";
1153         return r;
1154 }
1155 #endif
1156
1157 int
1158 mm_answer_keyallowed(int sock, struct sshbuf *m)
1159 {
1160         struct ssh *ssh = active_state; /* XXX */
1161         struct sshkey *key = NULL;
1162         char *cuser, *chost;
1163         u_int pubkey_auth_attempt;
1164         enum mm_keytype type = 0;
1165         int r, allowed = 0;
1166         struct sshauthopt *opts = NULL;
1167
1168         debug3("%s entering", __func__);
1169         if ((r = sshbuf_get_u32(m, &type)) != 0 ||
1170             (r = sshbuf_get_cstring(m, &cuser, NULL)) != 0 ||
1171             (r = sshbuf_get_cstring(m, &chost, NULL)) != 0 ||
1172             (r = sshkey_froms(m, &key)) != 0 ||
1173             (r = sshbuf_get_u32(m, &pubkey_auth_attempt)) != 0)
1174                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1175
1176         debug3("%s: key_from_blob: %p", __func__, key);
1177
1178         if (key != NULL && authctxt->valid) {
1179                 /* These should not make it past the privsep child */
1180                 if (sshkey_type_plain(key->type) == KEY_RSA &&
1181                     (datafellows & SSH_BUG_RSASIGMD5) != 0)
1182                         fatal("%s: passed a SSH_BUG_RSASIGMD5 key", __func__);
1183
1184                 switch (type) {
1185                 case MM_USERKEY:
1186                         auth_method = "publickey";
1187                         if (!options.pubkey_authentication)
1188                                 break;
1189                         if (auth2_key_already_used(authctxt, key))
1190                                 break;
1191                         if (match_pattern_list(sshkey_ssh_name(key),
1192                             options.pubkey_key_types, 0) != 1)
1193                                 break;
1194                         allowed = user_key_allowed(ssh, authctxt->pw, key,
1195                             pubkey_auth_attempt, &opts);
1196                         break;
1197                 case MM_HOSTKEY:
1198                         auth_method = "hostbased";
1199                         if (!options.hostbased_authentication)
1200                                 break;
1201                         if (auth2_key_already_used(authctxt, key))
1202                                 break;
1203                         if (match_pattern_list(sshkey_ssh_name(key),
1204                             options.hostbased_key_types, 0) != 1)
1205                                 break;
1206                         allowed = hostbased_key_allowed(authctxt->pw,
1207                             cuser, chost, key);
1208                         auth2_record_info(authctxt,
1209                             "client user \"%.100s\", client host \"%.100s\"",
1210                             cuser, chost);
1211                         break;
1212                 default:
1213                         fatal("%s: unknown key type %d", __func__, type);
1214                         break;
1215                 }
1216         }
1217
1218         debug3("%s: %s authentication%s: %s key is %s", __func__,
1219             auth_method, pubkey_auth_attempt ? "" : " test",
1220             (key == NULL || !authctxt->valid) ? "invalid" : sshkey_type(key),
1221             allowed ? "allowed" : "not allowed");
1222
1223         auth2_record_key(authctxt, 0, key);
1224
1225         /* clear temporarily storage (used by verify) */
1226         monitor_reset_key_state();
1227
1228         if (allowed) {
1229                 /* Save temporarily for comparison in verify */
1230                 if ((r = sshkey_to_blob(key, &key_blob, &key_bloblen)) != 0)
1231                         fatal("%s: buffer error: %s", __func__, ssh_err(r));
1232                 key_blobtype = type;
1233                 key_opts = opts;
1234                 hostbased_cuser = cuser;
1235                 hostbased_chost = chost;
1236         } else {
1237                 /* Log failed attempt */
1238                 auth_log(authctxt, 0, 0, auth_method, NULL);
1239                 free(cuser);
1240                 free(chost);
1241         }
1242         sshkey_free(key);
1243
1244         sshbuf_reset(m);
1245         if ((r = sshbuf_put_u32(m, allowed)) != 0)
1246                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1247         if (opts != NULL && (r = sshauthopt_serialise(opts, m, 1)) != 0)
1248                 fatal("%s: sshauthopt_serialise: %s", __func__, ssh_err(r));
1249         mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m);
1250
1251         if (!allowed)
1252                 sshauthopt_free(opts);
1253
1254         return (0);
1255 }
1256
1257 static int
1258 monitor_valid_userblob(u_char *data, u_int datalen)
1259 {
1260         struct sshbuf *b;
1261         const u_char *p;
1262         char *userstyle, *cp;
1263         size_t len;
1264         u_char type;
1265         int r, fail = 0;
1266
1267         if ((b = sshbuf_new()) == NULL)
1268                 fatal("%s: sshbuf_new", __func__);
1269         if ((r = sshbuf_put(b, data, datalen)) != 0)
1270                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1271
1272         if (datafellows & SSH_OLD_SESSIONID) {
1273                 p = sshbuf_ptr(b);
1274                 len = sshbuf_len(b);
1275                 if ((session_id2 == NULL) ||
1276                     (len < session_id2_len) ||
1277                     (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1278                         fail++;
1279                 if ((r = sshbuf_consume(b, session_id2_len)) != 0)
1280                         fatal("%s: buffer error: %s", __func__, ssh_err(r));
1281         } else {
1282                 if ((r = sshbuf_get_string_direct(b, &p, &len)) != 0)
1283                         fatal("%s: buffer error: %s", __func__, ssh_err(r));
1284                 if ((session_id2 == NULL) ||
1285                     (len != session_id2_len) ||
1286                     (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1287                         fail++;
1288         }
1289         if ((r = sshbuf_get_u8(b, &type)) != 0)
1290                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1291         if (type != SSH2_MSG_USERAUTH_REQUEST)
1292                 fail++;
1293         if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1294                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1295         xasprintf(&userstyle, "%s%s%s", authctxt->user,
1296             authctxt->style ? ":" : "",
1297             authctxt->style ? authctxt->style : "");
1298         if (strcmp(userstyle, cp) != 0) {
1299                 logit("wrong user name passed to monitor: "
1300                     "expected %s != %.100s", userstyle, cp);
1301                 fail++;
1302         }
1303         free(userstyle);
1304         free(cp);
1305         if ((r = sshbuf_skip_string(b)) != 0 || /* service */
1306             (r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1307                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1308         if (strcmp("publickey", cp) != 0)
1309                 fail++;
1310         free(cp);
1311         if ((r = sshbuf_get_u8(b, &type)) != 0)
1312                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1313         if (type == 0)
1314                 fail++;
1315         if ((r = sshbuf_skip_string(b)) != 0 || /* pkalg */
1316             (r = sshbuf_skip_string(b)) != 0)   /* pkblob */
1317                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1318         if (sshbuf_len(b) != 0)
1319                 fail++;
1320         sshbuf_free(b);
1321         return (fail == 0);
1322 }
1323
1324 static int
1325 monitor_valid_hostbasedblob(u_char *data, u_int datalen, char *cuser,
1326     char *chost)
1327 {
1328         struct sshbuf *b;
1329         const u_char *p;
1330         char *cp, *userstyle;
1331         size_t len;
1332         int r, fail = 0;
1333         u_char type;
1334
1335         if ((b = sshbuf_new()) == NULL)
1336                 fatal("%s: sshbuf_new", __func__);
1337         if ((r = sshbuf_put(b, data, datalen)) != 0 ||
1338             (r = sshbuf_get_string_direct(b, &p, &len)) != 0)
1339                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1340
1341         if ((session_id2 == NULL) ||
1342             (len != session_id2_len) ||
1343             (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1344                 fail++;
1345
1346         if ((r = sshbuf_get_u8(b, &type)) != 0)
1347                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1348         if (type != SSH2_MSG_USERAUTH_REQUEST)
1349                 fail++;
1350         if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1351                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1352         xasprintf(&userstyle, "%s%s%s", authctxt->user,
1353             authctxt->style ? ":" : "",
1354             authctxt->style ? authctxt->style : "");
1355         if (strcmp(userstyle, cp) != 0) {
1356                 logit("wrong user name passed to monitor: "
1357                     "expected %s != %.100s", userstyle, cp);
1358                 fail++;
1359         }
1360         free(userstyle);
1361         free(cp);
1362         if ((r = sshbuf_skip_string(b)) != 0 || /* service */
1363             (r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1364                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1365         if (strcmp(cp, "hostbased") != 0)
1366                 fail++;
1367         free(cp);
1368         if ((r = sshbuf_skip_string(b)) != 0 || /* pkalg */
1369             (r = sshbuf_skip_string(b)) != 0)   /* pkblob */
1370                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1371
1372         /* verify client host, strip trailing dot if necessary */
1373         if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1374                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1375         if (((len = strlen(cp)) > 0) && cp[len - 1] == '.')
1376                 cp[len - 1] = '\0';
1377         if (strcmp(cp, chost) != 0)
1378                 fail++;
1379         free(cp);
1380
1381         /* verify client user */
1382         if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1383                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1384         if (strcmp(cp, cuser) != 0)
1385                 fail++;
1386         free(cp);
1387
1388         if (sshbuf_len(b) != 0)
1389                 fail++;
1390         sshbuf_free(b);
1391         return (fail == 0);
1392 }
1393
1394 int
1395 mm_answer_keyverify(int sock, struct sshbuf *m)
1396 {
1397         struct ssh *ssh = active_state; /* XXX */
1398         struct sshkey *key;
1399         u_char *signature, *data, *blob;
1400         char *sigalg;
1401         size_t signaturelen, datalen, bloblen;
1402         int r, ret, valid_data = 0, encoded_ret;
1403
1404         if ((r = sshbuf_get_string(m, &blob, &bloblen)) != 0 ||
1405             (r = sshbuf_get_string(m, &signature, &signaturelen)) != 0 ||
1406             (r = sshbuf_get_string(m, &data, &datalen)) != 0 ||
1407             (r = sshbuf_get_cstring(m, &sigalg, NULL)) != 0)
1408                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1409
1410         if (hostbased_cuser == NULL || hostbased_chost == NULL ||
1411           !monitor_allowed_key(blob, bloblen))
1412                 fatal("%s: bad key, not previously allowed", __func__);
1413
1414         /* Empty signature algorithm means NULL. */
1415         if (*sigalg == '\0') {
1416                 free(sigalg);
1417                 sigalg = NULL;
1418         }
1419
1420         /* XXX use sshkey_froms here; need to change key_blob, etc. */
1421         if ((r = sshkey_from_blob(blob, bloblen, &key)) != 0)
1422                 fatal("%s: bad public key blob: %s", __func__, ssh_err(r));
1423
1424         switch (key_blobtype) {
1425         case MM_USERKEY:
1426                 valid_data = monitor_valid_userblob(data, datalen);
1427                 auth_method = "publickey";
1428                 break;
1429         case MM_HOSTKEY:
1430                 valid_data = monitor_valid_hostbasedblob(data, datalen,
1431                     hostbased_cuser, hostbased_chost);
1432                 auth_method = "hostbased";
1433                 break;
1434         default:
1435                 valid_data = 0;
1436                 break;
1437         }
1438         if (!valid_data)
1439                 fatal("%s: bad signature data blob", __func__);
1440
1441         ret = sshkey_verify(key, signature, signaturelen, data, datalen,
1442             sigalg, active_state->compat);
1443         debug3("%s: %s %p signature %s", __func__, auth_method, key,
1444             (ret == 0) ? "verified" : "unverified");
1445         auth2_record_key(authctxt, ret == 0, key);
1446
1447         free(blob);
1448         free(signature);
1449         free(data);
1450         free(sigalg);
1451
1452         if (key_blobtype == MM_USERKEY)
1453                 auth_activate_options(ssh, key_opts);
1454         monitor_reset_key_state();
1455
1456         sshkey_free(key);
1457         sshbuf_reset(m);
1458
1459         /* encode ret != 0 as positive integer, since we're sending u32 */
1460         encoded_ret = (ret != 0);
1461         if ((r = sshbuf_put_u32(m, encoded_ret)) != 0)
1462                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1463         mm_request_send(sock, MONITOR_ANS_KEYVERIFY, m);
1464
1465         return ret == 0;
1466 }
1467
1468 static void
1469 mm_record_login(Session *s, struct passwd *pw)
1470 {
1471         struct ssh *ssh = active_state; /* XXX */
1472         socklen_t fromlen;
1473         struct sockaddr_storage from;
1474
1475         /*
1476          * Get IP address of client. If the connection is not a socket, let
1477          * the address be 0.0.0.0.
1478          */
1479         memset(&from, 0, sizeof(from));
1480         fromlen = sizeof(from);
1481         if (packet_connection_is_on_socket()) {
1482                 if (getpeername(packet_get_connection_in(),
1483                     (struct sockaddr *)&from, &fromlen) < 0) {
1484                         debug("getpeername: %.100s", strerror(errno));
1485                         cleanup_exit(255);
1486                 }
1487         }
1488         /* Record that there was a login on that tty from the remote host. */
1489         record_login(s->pid, s->tty, pw->pw_name, pw->pw_uid,
1490             session_get_remote_name_or_ip(ssh, utmp_len, options.use_dns),
1491             (struct sockaddr *)&from, fromlen);
1492 }
1493
1494 static void
1495 mm_session_close(Session *s)
1496 {
1497         debug3("%s: session %d pid %ld", __func__, s->self, (long)s->pid);
1498         if (s->ttyfd != -1) {
1499                 debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ptyfd);
1500                 session_pty_cleanup2(s);
1501         }
1502         session_unused(s->self);
1503 }
1504
1505 int
1506 mm_answer_pty(int sock, struct sshbuf *m)
1507 {
1508         extern struct monitor *pmonitor;
1509         Session *s;
1510         int r, res, fd0;
1511
1512         debug3("%s entering", __func__);
1513
1514         sshbuf_reset(m);
1515         s = session_new();
1516         if (s == NULL)
1517                 goto error;
1518         s->authctxt = authctxt;
1519         s->pw = authctxt->pw;
1520         s->pid = pmonitor->m_pid;
1521         res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty));
1522         if (res == 0)
1523                 goto error;
1524         pty_setowner(authctxt->pw, s->tty);
1525
1526         if ((r = sshbuf_put_u32(m, 1)) != 0 ||
1527             (r = sshbuf_put_cstring(m, s->tty)) != 0)
1528                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1529
1530         /* We need to trick ttyslot */
1531         if (dup2(s->ttyfd, 0) == -1)
1532                 fatal("%s: dup2", __func__);
1533
1534         mm_record_login(s, authctxt->pw);
1535
1536         /* Now we can close the file descriptor again */
1537         close(0);
1538
1539         /* send messages generated by record_login */
1540         if ((r = sshbuf_put_stringb(m, loginmsg)) != 0)
1541                 fatal("%s: put login message: %s", __func__, ssh_err(r));
1542         sshbuf_reset(loginmsg);
1543
1544         mm_request_send(sock, MONITOR_ANS_PTY, m);
1545
1546         if (mm_send_fd(sock, s->ptyfd) == -1 ||
1547             mm_send_fd(sock, s->ttyfd) == -1)
1548                 fatal("%s: send fds failed", __func__);
1549
1550         /* make sure nothing uses fd 0 */
1551         if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) < 0)
1552                 fatal("%s: open(/dev/null): %s", __func__, strerror(errno));
1553         if (fd0 != 0)
1554                 error("%s: fd0 %d != 0", __func__, fd0);
1555
1556         /* slave is not needed */
1557         close(s->ttyfd);
1558         s->ttyfd = s->ptyfd;
1559         /* no need to dup() because nobody closes ptyfd */
1560         s->ptymaster = s->ptyfd;
1561
1562         debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ttyfd);
1563
1564         return (0);
1565
1566  error:
1567         if (s != NULL)
1568                 mm_session_close(s);
1569         if ((r = sshbuf_put_u32(m, 0)) != 0)
1570                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1571         mm_request_send(sock, MONITOR_ANS_PTY, m);
1572         return (0);
1573 }
1574
1575 int
1576 mm_answer_pty_cleanup(int sock, struct sshbuf *m)
1577 {
1578         Session *s;
1579         char *tty;
1580         int r;
1581
1582         debug3("%s entering", __func__);
1583
1584         if ((r = sshbuf_get_cstring(m, &tty, NULL)) != 0)
1585                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1586         if ((s = session_by_tty(tty)) != NULL)
1587                 mm_session_close(s);
1588         sshbuf_reset(m);
1589         free(tty);
1590         return (0);
1591 }
1592
1593 int
1594 mm_answer_term(int sock, struct sshbuf *req)
1595 {
1596         struct ssh *ssh = active_state; /* XXX */
1597         extern struct monitor *pmonitor;
1598         int res, status;
1599
1600         debug3("%s: tearing down sessions", __func__);
1601
1602         /* The child is terminating */
1603         session_destroy_all(ssh, &mm_session_close);
1604
1605 #ifdef USE_PAM
1606         if (options.use_pam)
1607                 sshpam_cleanup();
1608 #endif
1609
1610         while (waitpid(pmonitor->m_pid, &status, 0) == -1)
1611                 if (errno != EINTR)
1612                         exit(1);
1613
1614         res = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
1615
1616         /* Terminate process */
1617         exit(res);
1618 }
1619
1620 #ifdef SSH_AUDIT_EVENTS
1621 /* Report that an audit event occurred */
1622 int
1623 mm_answer_audit_event(int socket, struct sshbuf *m)
1624 {
1625         u_int n;
1626         ssh_audit_event_t event;
1627         int r;
1628
1629         debug3("%s entering", __func__);
1630
1631         if ((r = sshbuf_get_u32(m, &n)) != 0)
1632                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1633         event = (ssh_audit_event_t)n;
1634         switch (event) {
1635         case SSH_AUTH_FAIL_PUBKEY:
1636         case SSH_AUTH_FAIL_HOSTBASED:
1637         case SSH_AUTH_FAIL_GSSAPI:
1638         case SSH_LOGIN_EXCEED_MAXTRIES:
1639         case SSH_LOGIN_ROOT_DENIED:
1640         case SSH_CONNECTION_CLOSE:
1641         case SSH_INVALID_USER:
1642                 audit_event(event);
1643                 break;
1644         default:
1645                 fatal("Audit event type %d not permitted", event);
1646         }
1647
1648         return (0);
1649 }
1650
1651 int
1652 mm_answer_audit_command(int socket, struct sshbuf *m)
1653 {
1654         char *cmd;
1655         int r;
1656
1657         debug3("%s entering", __func__);
1658         if ((r = sshbuf_get_cstring(m, &cmd, NULL)) != 0)
1659                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1660         /* sanity check command, if so how? */
1661         audit_run_command(cmd);
1662         free(cmd);
1663         return (0);
1664 }
1665 #endif /* SSH_AUDIT_EVENTS */
1666
1667 void
1668 monitor_clear_keystate(struct monitor *pmonitor)
1669 {
1670         struct ssh *ssh = active_state; /* XXX */
1671
1672         ssh_clear_newkeys(ssh, MODE_IN);
1673         ssh_clear_newkeys(ssh, MODE_OUT);
1674         sshbuf_free(child_state);
1675         child_state = NULL;
1676 }
1677
1678 void
1679 monitor_apply_keystate(struct monitor *pmonitor)
1680 {
1681         struct ssh *ssh = active_state; /* XXX */
1682         struct kex *kex;
1683         int r;
1684
1685         debug3("%s: packet_set_state", __func__);
1686         if ((r = ssh_packet_set_state(ssh, child_state)) != 0)
1687                 fatal("%s: packet_set_state: %s", __func__, ssh_err(r));
1688         sshbuf_free(child_state);
1689         child_state = NULL;
1690
1691         if ((kex = ssh->kex) != NULL) {
1692                 /* XXX set callbacks */
1693 #ifdef WITH_OPENSSL
1694                 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1695                 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1696                 kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
1697                 kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
1698                 kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
1699                 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1700                 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1701 # ifdef OPENSSL_HAS_ECC
1702                 kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
1703 # endif
1704 #endif /* WITH_OPENSSL */
1705                 kex->kex[KEX_C25519_SHA256] = kexc25519_server;
1706                 kex->load_host_public_key=&get_hostkey_public_by_type;
1707                 kex->load_host_private_key=&get_hostkey_private_by_type;
1708                 kex->host_key_index=&get_hostkey_index;
1709                 kex->sign = sshd_hostkey_sign;
1710         }
1711 }
1712
1713 /* This function requries careful sanity checking */
1714
1715 void
1716 mm_get_keystate(struct monitor *pmonitor)
1717 {
1718         debug3("%s: Waiting for new keys", __func__);
1719
1720         if ((child_state = sshbuf_new()) == NULL)
1721                 fatal("%s: sshbuf_new failed", __func__);
1722         mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT,
1723             child_state);
1724         debug3("%s: GOT new keys", __func__);
1725 }
1726
1727
1728 /* XXX */
1729
1730 #define FD_CLOSEONEXEC(x) do { \
1731         if (fcntl(x, F_SETFD, FD_CLOEXEC) == -1) \
1732                 fatal("fcntl(%d, F_SETFD)", x); \
1733 } while (0)
1734
1735 static void
1736 monitor_openfds(struct monitor *mon, int do_logfds)
1737 {
1738         int pair[2];
1739 #ifdef SO_ZEROIZE
1740         int on = 1;
1741 #endif
1742
1743         if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
1744                 fatal("%s: socketpair: %s", __func__, strerror(errno));
1745 #ifdef SO_ZEROIZE
1746         if (setsockopt(pair[0], SOL_SOCKET, SO_ZEROIZE, &on, sizeof(on)) < 0)
1747                 error("setsockopt SO_ZEROIZE(0): %.100s", strerror(errno));
1748         if (setsockopt(pair[1], SOL_SOCKET, SO_ZEROIZE, &on, sizeof(on)) < 0)
1749                 error("setsockopt SO_ZEROIZE(1): %.100s", strerror(errno));
1750 #endif
1751         FD_CLOSEONEXEC(pair[0]);
1752         FD_CLOSEONEXEC(pair[1]);
1753         mon->m_recvfd = pair[0];
1754         mon->m_sendfd = pair[1];
1755
1756         if (do_logfds) {
1757                 if (pipe(pair) == -1)
1758                         fatal("%s: pipe: %s", __func__, strerror(errno));
1759                 FD_CLOSEONEXEC(pair[0]);
1760                 FD_CLOSEONEXEC(pair[1]);
1761                 mon->m_log_recvfd = pair[0];
1762                 mon->m_log_sendfd = pair[1];
1763         } else
1764                 mon->m_log_recvfd = mon->m_log_sendfd = -1;
1765 }
1766
1767 #define MM_MEMSIZE      65536
1768
1769 struct monitor *
1770 monitor_init(void)
1771 {
1772         struct monitor *mon;
1773
1774         mon = xcalloc(1, sizeof(*mon));
1775         monitor_openfds(mon, 1);
1776
1777         return mon;
1778 }
1779
1780 void
1781 monitor_reinit(struct monitor *mon)
1782 {
1783         monitor_openfds(mon, 0);
1784 }
1785
1786 #ifdef GSSAPI
1787 int
1788 mm_answer_gss_setup_ctx(int sock, struct sshbuf *m)
1789 {
1790         gss_OID_desc goid;
1791         OM_uint32 major;
1792         size_t len;
1793         u_char *p;
1794         int r;
1795
1796         if (!options.gss_authentication)
1797                 fatal("%s: GSSAPI authentication not enabled", __func__);
1798
1799         if ((r = sshbuf_get_string(m, &p, &len)) != 0)
1800                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1801         goid.elements = p;
1802         goid.length = len;
1803
1804         major = ssh_gssapi_server_ctx(&gsscontext, &goid);
1805
1806         free(goid.elements);
1807
1808         sshbuf_reset(m);
1809         if ((r = sshbuf_put_u32(m, major)) != 0)
1810                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1811
1812         mm_request_send(sock, MONITOR_ANS_GSSSETUP, m);
1813
1814         /* Now we have a context, enable the step */
1815         monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 1);
1816
1817         return (0);
1818 }
1819
1820 int
1821 mm_answer_gss_accept_ctx(int sock, struct sshbuf *m)
1822 {
1823         gss_buffer_desc in;
1824         gss_buffer_desc out = GSS_C_EMPTY_BUFFER;
1825         OM_uint32 major, minor;
1826         OM_uint32 flags = 0; /* GSI needs this */
1827         int r;
1828
1829         if (!options.gss_authentication)
1830                 fatal("%s: GSSAPI authentication not enabled", __func__);
1831
1832         if ((r = ssh_gssapi_get_buffer_desc(m, &in)) != 0)
1833                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1834         major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags);
1835         free(in.value);
1836
1837         sshbuf_reset(m);
1838         if ((r = sshbuf_put_u32(m, major)) != 0 ||
1839             (r = sshbuf_put_string(m, out.value, out.length)) != 0 ||
1840             (r = sshbuf_put_u32(m, flags)) != 0)
1841                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1842         mm_request_send(sock, MONITOR_ANS_GSSSTEP, m);
1843
1844         gss_release_buffer(&minor, &out);
1845
1846         if (major == GSS_S_COMPLETE) {
1847                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
1848                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1849                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
1850         }
1851         return (0);
1852 }
1853
1854 int
1855 mm_answer_gss_checkmic(int sock, struct sshbuf *m)
1856 {
1857         gss_buffer_desc gssbuf, mic;
1858         OM_uint32 ret;
1859         int r;
1860
1861         if (!options.gss_authentication)
1862                 fatal("%s: GSSAPI authentication not enabled", __func__);
1863
1864         if ((r = ssh_gssapi_get_buffer_desc(m, &gssbuf)) != 0 ||
1865             (r = ssh_gssapi_get_buffer_desc(m, &mic)) != 0)
1866                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1867
1868         ret = ssh_gssapi_checkmic(gsscontext, &gssbuf, &mic);
1869
1870         free(gssbuf.value);
1871         free(mic.value);
1872
1873         sshbuf_reset(m);
1874         if ((r = sshbuf_put_u32(m, ret)) != 0)
1875                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1876
1877         mm_request_send(sock, MONITOR_ANS_GSSCHECKMIC, m);
1878
1879         if (!GSS_ERROR(ret))
1880                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1881
1882         return (0);
1883 }
1884
1885 int
1886 mm_answer_gss_userok(int sock, struct sshbuf *m)
1887 {
1888         int r, authenticated;
1889         const char *displayname;
1890
1891         if (!options.gss_authentication)
1892                 fatal("%s: GSSAPI authentication not enabled", __func__);
1893
1894         authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user);
1895
1896         sshbuf_reset(m);
1897         if ((r = sshbuf_put_u32(m, authenticated)) != 0)
1898                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1899
1900         debug3("%s: sending result %d", __func__, authenticated);
1901         mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m);
1902
1903         auth_method = "gssapi-with-mic";
1904
1905         if ((displayname = ssh_gssapi_displayname()) != NULL)
1906                 auth2_record_info(authctxt, "%s", displayname);
1907
1908         /* Monitor loop will terminate if authenticated */
1909         return (authenticated);
1910 }
1911 #endif /* GSSAPI */
1912