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