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