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