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