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