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