1184610Salfred/* $OpenBSD: monitor.c,v 1.127 2013/07/19 07:37:48 markus Exp $ */
2184610Salfred/*
3184610Salfred * Copyright 2002 Niels Provos <provos@citi.umich.edu>
4184610Salfred * Copyright 2002 Markus Friedl <markus@openbsd.org>
5230132Suqs * All rights reserved.
6184610Salfred *
7184610Salfred * Redistribution and use in source and binary forms, with or without
8184610Salfred * modification, are permitted provided that the following conditions
9184610Salfred * are met:
10184610Salfred * 1. Redistributions of source code must retain the above copyright
11184610Salfred *    notice, this list of conditions and the following disclaimer.
12184610Salfred * 2. Redistributions in binary form must reproduce the above copyright
13184610Salfred *    notice, this list of conditions and the following disclaimer in the
14184610Salfred *    documentation and/or other materials provided with the distribution.
15184610Salfred *
16184610Salfred * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17184610Salfred * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18184610Salfred * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19184610Salfred * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20184610Salfred * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21184610Salfred * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22184610Salfred * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23184610Salfred * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24184610Salfred * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25184610Salfred * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26184610Salfred */
27184610Salfred
28184610Salfred#include "includes.h"
29184610Salfred
30184610Salfred#include <sys/types.h>
31184610Salfred#include <sys/param.h>
32184610Salfred#include <sys/socket.h>
33184610Salfred#include "openbsd-compat/sys-tree.h"
34184610Salfred#include <sys/wait.h>
35184610Salfred
36184610Salfred#include <errno.h>
37194677Sthompsa#include <fcntl.h>
38194677Sthompsa#ifdef HAVE_PATHS_H
39194677Sthompsa#include <paths.h>
40194677Sthompsa#endif
41194677Sthompsa#include <pwd.h>
42194677Sthompsa#include <signal.h>
43194677Sthompsa#include <stdarg.h>
44194677Sthompsa#include <stdlib.h>
45194677Sthompsa#include <string.h>
46194677Sthompsa#include <unistd.h>
47194677Sthompsa#ifdef HAVE_POLL_H
48194677Sthompsa#include <poll.h>
49194677Sthompsa#else
50194677Sthompsa# ifdef HAVE_SYS_POLL_H
51194677Sthompsa#  include <sys/poll.h>
52194677Sthompsa# endif
53194677Sthompsa#endif
54194677Sthompsa
55194677Sthompsa#ifdef SKEY
56188942Sthompsa#include <skey.h>
57194677Sthompsa#endif
58194677Sthompsa
59188942Sthompsa#include <openssl/dh.h>
60194677Sthompsa
61184610Salfred#include "openbsd-compat/sys-queue.h"
62194228Sthompsa#include "atomicio.h"
63188942Sthompsa#include "xmalloc.h"
64188942Sthompsa#include "ssh.h"
65184610Salfred#include "key.h"
66188942Sthompsa#include "buffer.h"
67184610Salfred#include "hostfile.h"
68184610Salfred#include "auth.h"
69184610Salfred#include "cipher.h"
70184610Salfred#include "kex.h"
71184610Salfred#include "dh.h"
72187259Sthompsa#ifdef TARGET_OS_MAC	/* XXX Broken krb5 headers on Mac */
73187259Sthompsa#undef TARGET_OS_MAC
74187259Sthompsa#include "zlib.h"
75188413Sthompsa#define TARGET_OS_MAC 1
76187259Sthompsa#else
77187259Sthompsa#include "zlib.h"
78184610Salfred#endif
79192984Sthompsa#include "packet.h"
80192984Sthompsa#include "auth-options.h"
81184610Salfred#include "sshpty.h"
82192984Sthompsa#include "channels.h"
83192984Sthompsa#include "session.h"
84189265Sthompsa#include "sshlogin.h"
85184610Salfred#include "canohost.h"
86184610Salfred#include "log.h"
87184610Salfred#include "servconf.h"
88184610Salfred#include "monitor.h"
89184610Salfred#include "monitor_mm.h"
90184610Salfred#ifdef GSSAPI
91184610Salfred#include "ssh-gss.h"
92184610Salfred#endif
93184610Salfred#include "monitor_wrap.h"
94184610Salfred#include "monitor_fdpass.h"
95184610Salfred#include "misc.h"
96184610Salfred#include "compat.h"
97184610Salfred#include "ssh2.h"
98184610Salfred#include "jpake.h"
99184610Salfred#include "roaming.h"
100184610Salfred#include "authfd.h"
101184610Salfred
102184610Salfred#ifdef GSSAPI
103184610Salfredstatic Gssctxt *gsscontext = NULL;
104184610Salfred#endif
105184610Salfred
106184610Salfred/* Imports */
107184610Salfredextern ServerOptions options;
108184610Salfredextern u_int utmp_len;
109184610Salfredextern Newkeys *current_keys[];
110184610Salfredextern z_stream incoming_stream;
111184610Salfredextern z_stream outgoing_stream;
112184610Salfredextern u_char session_id[];
113184610Salfredextern Buffer auth_debug;
114239180Shselaskyextern int auth_debug_init;
115184610Salfredextern Buffer loginmsg;
116193045Sthompsa
117193045Sthompsa/* State exported from the child */
118184610Salfred
119239180Shselaskystruct {
120192984Sthompsa	z_stream incoming;
121192984Sthompsa	z_stream outgoing;
122192984Sthompsa	u_char *keyin;
123192984Sthompsa	u_int keyinlen;
124192984Sthompsa	u_char *keyout;
125185948Sthompsa	u_int keyoutlen;
126192984Sthompsa	u_char *ivin;
127192984Sthompsa	u_int ivinlen;
128197570Sthompsa	u_char *ivout;
129184610Salfred	u_int ivoutlen;
130192984Sthompsa	u_char *ssh1key;
131184610Salfred	u_int ssh1keylen;
132187259Sthompsa	int ssh1cipher;
133184610Salfred	int ssh1protoflags;
134184610Salfred	u_char *input;
135184610Salfred	u_int ilen;
136192984Sthompsa	u_char *output;
137190734Sthompsa	u_int olen;
138190734Sthompsa	u_int64_t sent_bytes;
139184610Salfred	u_int64_t recv_bytes;
140184610Salfred} child_state;
141187259Sthompsa
142184610Salfred/* Functions on the monitor that answer unprivileged requests */
143184610Salfred
144184610Salfredint mm_answer_moduli(int, Buffer *);
145190734Sthompsaint mm_answer_sign(int, Buffer *);
146190734Sthompsaint mm_answer_pwnamallow(int, Buffer *);
147190734Sthompsaint mm_answer_auth2_read_banner(int, Buffer *);
148184610Salfredint mm_answer_authserv(int, Buffer *);
149184610Salfredint mm_answer_authpassword(int, Buffer *);
150184610Salfredint mm_answer_bsdauthquery(int, Buffer *);
151192984Sthompsaint mm_answer_bsdauthrespond(int, Buffer *);
152194228Sthompsaint mm_answer_skeyquery(int, Buffer *);
153194228Sthompsaint mm_answer_skeyrespond(int, Buffer *);
154194228Sthompsaint mm_answer_keyallowed(int, Buffer *);
155194228Sthompsaint mm_answer_keyverify(int, Buffer *);
156194228Sthompsaint mm_answer_pty(int, Buffer *);
157194228Sthompsaint mm_answer_pty_cleanup(int, Buffer *);
158194228Sthompsaint mm_answer_term(int, Buffer *);
159197570Sthompsaint mm_answer_rsa_keyallowed(int, Buffer *);
160239180Shselaskyint mm_answer_rsa_challenge(int, Buffer *);
161184610Salfredint mm_answer_rsa_response(int, Buffer *);
162184610Salfredint mm_answer_sesskey(int, Buffer *);
163184610Salfredint mm_answer_sessid(int, Buffer *);
164184610Salfredint mm_answer_jpake_get_pwdata(int, Buffer *);
165184610Salfredint mm_answer_jpake_step1(int, Buffer *);
166184610Salfredint mm_answer_jpake_step2(int, Buffer *);
167239180Shselaskyint mm_answer_jpake_key_confirm(int, Buffer *);
168239180Shselaskyint mm_answer_jpake_check_confirm(int, Buffer *);
169184610Salfred
170184610Salfred#ifdef USE_PAM
171184610Salfredint mm_answer_pam_start(int, Buffer *);
172184610Salfredint mm_answer_pam_account(int, Buffer *);
173184610Salfredint mm_answer_pam_init_ctx(int, Buffer *);
174184610Salfredint mm_answer_pam_query(int, Buffer *);
175184610Salfredint mm_answer_pam_respond(int, Buffer *);
176184610Salfredint mm_answer_pam_free_ctx(int, Buffer *);
177184610Salfred#endif
178184610Salfred
179189275Sthompsa#ifdef GSSAPI
180188942Sthompsaint mm_answer_gss_setup_ctx(int, Buffer *);
181188942Sthompsaint mm_answer_gss_accept_ctx(int, Buffer *);
182212122Sthompsaint mm_answer_gss_userok(int, Buffer *);
183184610Salfredint mm_answer_gss_checkmic(int, Buffer *);
184184610Salfred#endif
185184610Salfred
186184610Salfred#ifdef SSH_AUDIT_EVENTS
187223486Shselaskyint mm_answer_audit_event(int, Buffer *);
188184610Salfredint mm_answer_audit_command(int, Buffer *);
189184610Salfred#endif
190184610Salfred
191184610Salfredstatic int monitor_read_log(struct monitor *);
192184610Salfred
193184610Salfredstatic Authctxt *authctxt;
194184610Salfredstatic BIGNUM *ssh1_challenge = NULL;	/* used for ssh1 rsa auth */
195184610Salfred
196184610Salfred/* local state for key verify */
197192984Sthompsastatic u_char *key_blob = NULL;
198184610Salfredstatic u_int key_bloblen = 0;
199192499Sthompsastatic int key_blobtype = MM_NOKEY;
200184610Salfredstatic char *hostbased_cuser = NULL;
201184610Salfredstatic char *hostbased_chost = NULL;
202184610Salfredstatic char *auth_method = "unknown";
203184610Salfredstatic char *auth_submethod = NULL;
204184610Salfredstatic u_int session_id2_len = 0;
205184610Salfredstatic u_char *session_id2 = NULL;
206184610Salfredstatic pid_t monitor_child_pid;
207184610Salfred
208194228Sthompsastruct mon_table {
209184610Salfred	enum monitor_reqtype type;
210184610Salfred	int flags;
211184610Salfred	int (*f)(int, Buffer *);
212184610Salfred};
213184610Salfred
214192984Sthompsa#define MON_ISAUTH	0x0004	/* Required for Authentication */
215184610Salfred#define MON_AUTHDECIDE	0x0008	/* Decides Authentication */
216184610Salfred#define MON_ONCE	0x0010	/* Disable after calling */
217184610Salfred#define MON_ALOG	0x0020	/* Log auth attempt without authenticating */
218184610Salfred
219184610Salfred#define MON_AUTH	(MON_ISAUTH|MON_AUTHDECIDE)
220184610Salfred
221184610Salfred#define MON_PERMIT	0x1000	/* Request is permitted */
222184610Salfred
223194228Sthompsastruct mon_table mon_dispatch_proto20[] = {
224189265Sthompsa    {MONITOR_REQ_MODULI, MON_ONCE, mm_answer_moduli},
225239180Shselasky    {MONITOR_REQ_SIGN, MON_ONCE, mm_answer_sign},
226184610Salfred    {MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow},
227184610Salfred    {MONITOR_REQ_AUTHSERV, MON_ONCE, mm_answer_authserv},
228184610Salfred    {MONITOR_REQ_AUTH2_READ_BANNER, MON_ONCE, mm_answer_auth2_read_banner},
229184610Salfred    {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
230184610Salfred#ifdef USE_PAM
231184610Salfred    {MONITOR_REQ_PAM_START, MON_ONCE, mm_answer_pam_start},
232184610Salfred    {MONITOR_REQ_PAM_ACCOUNT, 0, mm_answer_pam_account},
233184610Salfred    {MONITOR_REQ_PAM_INIT_CTX, MON_ISAUTH, mm_answer_pam_init_ctx},
234184610Salfred    {MONITOR_REQ_PAM_QUERY, MON_ISAUTH, mm_answer_pam_query},
235184610Salfred    {MONITOR_REQ_PAM_RESPOND, MON_ISAUTH, mm_answer_pam_respond},
236184610Salfred    {MONITOR_REQ_PAM_FREE_CTX, MON_ONCE|MON_AUTHDECIDE, mm_answer_pam_free_ctx},
237184610Salfred#endif
238184610Salfred#ifdef SSH_AUDIT_EVENTS
239184610Salfred    {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
240184610Salfred#endif
241184610Salfred#ifdef BSD_AUTH
242194228Sthompsa    {MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery},
243184610Salfred    {MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond},
244184610Salfred#endif
245184610Salfred#ifdef SKEY
246184610Salfred    {MONITOR_REQ_SKEYQUERY, MON_ISAUTH, mm_answer_skeyquery},
247184610Salfred    {MONITOR_REQ_SKEYRESPOND, MON_AUTH, mm_answer_skeyrespond},
248184610Salfred#endif
249194228Sthompsa    {MONITOR_REQ_KEYALLOWED, MON_ISAUTH, mm_answer_keyallowed},
250184610Salfred    {MONITOR_REQ_KEYVERIFY, MON_AUTH, mm_answer_keyverify},
251184610Salfred#ifdef GSSAPI
252184610Salfred    {MONITOR_REQ_GSSSETUP, MON_ISAUTH, mm_answer_gss_setup_ctx},
253184610Salfred    {MONITOR_REQ_GSSSTEP, MON_ISAUTH, mm_answer_gss_accept_ctx},
254184610Salfred    {MONITOR_REQ_GSSUSEROK, MON_AUTH, mm_answer_gss_userok},
255184610Salfred    {MONITOR_REQ_GSSCHECKMIC, MON_ISAUTH, mm_answer_gss_checkmic},
256184610Salfred#endif
257184610Salfred#ifdef JPAKE
258184610Salfred    {MONITOR_REQ_JPAKE_GET_PWDATA, MON_ONCE, mm_answer_jpake_get_pwdata},
259184610Salfred    {MONITOR_REQ_JPAKE_STEP1, MON_ISAUTH, mm_answer_jpake_step1},
260184610Salfred    {MONITOR_REQ_JPAKE_STEP2, MON_ONCE, mm_answer_jpake_step2},
261184610Salfred    {MONITOR_REQ_JPAKE_KEY_CONFIRM, MON_ONCE, mm_answer_jpake_key_confirm},
262184610Salfred    {MONITOR_REQ_JPAKE_CHECK_CONFIRM, MON_AUTH, mm_answer_jpake_check_confirm},
263184610Salfred#endif
264184610Salfred    {0, 0, NULL}
265184610Salfred};
266184610Salfred
267184610Salfredstruct mon_table mon_dispatch_postauth20[] = {
268184610Salfred    {MONITOR_REQ_MODULI, 0, mm_answer_moduli},
269194228Sthompsa    {MONITOR_REQ_SIGN, 0, mm_answer_sign},
270187259Sthompsa    {MONITOR_REQ_PTY, 0, mm_answer_pty},
271189265Sthompsa    {MONITOR_REQ_PTYCLEANUP, 0, mm_answer_pty_cleanup},
272184610Salfred    {MONITOR_REQ_TERM, 0, mm_answer_term},
273184610Salfred#ifdef SSH_AUDIT_EVENTS
274199816Sthompsa    {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
275184610Salfred    {MONITOR_REQ_AUDIT_COMMAND, MON_PERMIT, mm_answer_audit_command},
276184610Salfred#endif
277194228Sthompsa    {0, 0, NULL}
278189265Sthompsa};
279184610Salfred
280184610Salfredstruct mon_table mon_dispatch_proto15[] = {
281184610Salfred    {MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow},
282214843Sn_hibma    {MONITOR_REQ_SESSKEY, MON_ONCE, mm_answer_sesskey},
283214843Sn_hibma    {MONITOR_REQ_SESSID, MON_ONCE, mm_answer_sessid},
284184610Salfred    {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
285184610Salfred    {MONITOR_REQ_RSAKEYALLOWED, MON_ISAUTH|MON_ALOG, mm_answer_rsa_keyallowed},
286184610Salfred    {MONITOR_REQ_KEYALLOWED, MON_ISAUTH|MON_ALOG, mm_answer_keyallowed},
287214843Sn_hibma    {MONITOR_REQ_RSACHALLENGE, MON_ONCE, mm_answer_rsa_challenge},
288184610Salfred    {MONITOR_REQ_RSARESPONSE, MON_ONCE|MON_AUTHDECIDE, mm_answer_rsa_response},
289184610Salfred#ifdef BSD_AUTH
290184610Salfred    {MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery},
291184610Salfred    {MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond},
292184610Salfred#endif
293184610Salfred#ifdef SKEY
294184610Salfred    {MONITOR_REQ_SKEYQUERY, MON_ISAUTH, mm_answer_skeyquery},
295184610Salfred    {MONITOR_REQ_SKEYRESPOND, MON_AUTH, mm_answer_skeyrespond},
296184610Salfred#endif
297184610Salfred#ifdef USE_PAM
298184610Salfred    {MONITOR_REQ_PAM_START, MON_ONCE, mm_answer_pam_start},
299184610Salfred    {MONITOR_REQ_PAM_ACCOUNT, 0, mm_answer_pam_account},
300184610Salfred    {MONITOR_REQ_PAM_INIT_CTX, MON_ISAUTH, mm_answer_pam_init_ctx},
301184610Salfred    {MONITOR_REQ_PAM_QUERY, MON_ISAUTH, mm_answer_pam_query},
302184610Salfred    {MONITOR_REQ_PAM_RESPOND, MON_ISAUTH, mm_answer_pam_respond},
303214761Sn_hibma    {MONITOR_REQ_PAM_FREE_CTX, MON_ONCE|MON_AUTHDECIDE, mm_answer_pam_free_ctx},
304194228Sthompsa#endif
305184610Salfred#ifdef SSH_AUDIT_EVENTS
306184610Salfred    {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
307184610Salfred#endif
308184610Salfred    {0, 0, NULL}
309239180Shselasky};
310239180Shselasky
311184610Salfredstruct mon_table mon_dispatch_postauth15[] = {
312239180Shselasky    {MONITOR_REQ_PTY, MON_ONCE, mm_answer_pty},
313239180Shselasky    {MONITOR_REQ_PTYCLEANUP, MON_ONCE, mm_answer_pty_cleanup},
314239180Shselasky    {MONITOR_REQ_TERM, 0, mm_answer_term},
315239180Shselasky#ifdef SSH_AUDIT_EVENTS
316239180Shselasky    {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
317239180Shselasky    {MONITOR_REQ_AUDIT_COMMAND, MON_PERMIT|MON_ONCE, mm_answer_audit_command},
318239180Shselasky#endif
319239180Shselasky    {0, 0, NULL}
320239180Shselasky};
321239180Shselasky
322239180Shselaskystruct mon_table *mon_dispatch;
323239180Shselasky
324239180Shselasky/* Specifies if a certain message is allowed at the moment */
325239180Shselasky
326239180Shselaskystatic void
327239180Shselaskymonitor_permit(struct mon_table *ent, enum monitor_reqtype type, int permit)
328239180Shselasky{
329239180Shselasky	while (ent->f != NULL) {
330192984Sthompsa		if (ent->type == type) {
331184610Salfred			ent->flags &= ~MON_PERMIT;
332184610Salfred			ent->flags |= permit ? MON_PERMIT : 0;
333184610Salfred			return;
334184610Salfred		}
335184610Salfred		ent++;
336184610Salfred	}
337184610Salfred}
338184610Salfred
339192984Sthompsastatic void
340184610Salfredmonitor_permit_authentications(int permit)
341184610Salfred{
342184610Salfred	struct mon_table *ent = mon_dispatch;
343194228Sthompsa
344184610Salfred	while (ent->f != NULL) {
345184610Salfred		if (ent->flags & MON_AUTH) {
346184610Salfred			ent->flags &= ~MON_PERMIT;
347192984Sthompsa			ent->flags |= permit ? MON_PERMIT : 0;
348184610Salfred		}
349184610Salfred		ent++;
350184610Salfred	}
351194228Sthompsa}
352184610Salfred
353184610Salfredvoid
354184610Salfredmonitor_child_preauth(Authctxt *_authctxt, struct monitor *pmonitor)
355192984Sthompsa{
356184610Salfred	struct mon_table *ent;
357184610Salfred	int authenticated = 0, partial = 0;
358184610Salfred
359194228Sthompsa	debug3("preauth child monitor started");
360184610Salfred
361184610Salfred	close(pmonitor->m_recvfd);
362184610Salfred	close(pmonitor->m_log_sendfd);
363192984Sthompsa	pmonitor->m_log_sendfd = pmonitor->m_recvfd = -1;
364184610Salfred
365184610Salfred	authctxt = _authctxt;
366184610Salfred	memset(authctxt, 0, sizeof(*authctxt));
367194228Sthompsa
368184610Salfred	authctxt->loginmsg = &loginmsg;
369184610Salfred
370184610Salfred	if (compat20) {
371194677Sthompsa		mon_dispatch = mon_dispatch_proto20;
372184610Salfred
373194677Sthompsa		/* Permit requests for moduli and signatures */
374192984Sthompsa		monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
375194677Sthompsa		monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
376184610Salfred	} else {
377184610Salfred		mon_dispatch = mon_dispatch_proto15;
378184610Salfred
379184610Salfred		monitor_permit(mon_dispatch, MONITOR_REQ_SESSKEY, 1);
380194677Sthompsa	}
381194677Sthompsa
382194677Sthompsa	/* The first few requests do not require asynchronous access */
383184610Salfred	while (!authenticated) {
384184610Salfred		partial = 0;
385184610Salfred		auth_method = "unknown";
386184610Salfred		auth_submethod = NULL;
387184610Salfred		authenticated = (monitor_read(pmonitor, mon_dispatch, &ent) == 1);
388184610Salfred
389184610Salfred		/* Special handling for multiple required authentications */
390184610Salfred		if (options.num_auth_methods != 0) {
391184610Salfred			if (!compat20)
392184610Salfred				fatal("AuthenticationMethods is not supported"
393184610Salfred				    "with SSH protocol 1");
394184610Salfred			if (authenticated &&
395184610Salfred			    !auth2_update_methods_lists(authctxt,
396184610Salfred			    auth_method, auth_submethod)) {
397184610Salfred				debug3("%s: method %s: partial", __func__,
398184610Salfred				    auth_method);
399184610Salfred				authenticated = 0;
400194677Sthompsa				partial = 1;
401184610Salfred			}
402184610Salfred		}
403184610Salfred
404184610Salfred		if (authenticated) {
405184610Salfred			if (!(ent->flags & MON_AUTHDECIDE))
406184610Salfred				fatal("%s: unexpected authentication from %d",
407184610Salfred				    __func__, ent->type);
408184610Salfred			if (authctxt->pw->pw_uid == 0 &&
409184610Salfred			    !auth_root_allowed(auth_method))
410184610Salfred				authenticated = 0;
411184610Salfred#ifdef USE_PAM
412184610Salfred			/* PAM needs to perform account checks after auth */
413184610Salfred			if (options.use_pam && authenticated) {
414184610Salfred				Buffer m;
415184610Salfred
416184610Salfred				buffer_init(&m);
417184610Salfred				mm_request_receive_expect(pmonitor->m_sendfd,
418184610Salfred				    MONITOR_REQ_PAM_ACCOUNT, &m);
419184610Salfred				authenticated = mm_answer_pam_account(pmonitor->m_sendfd, &m);
420184610Salfred				buffer_free(&m);
421184610Salfred			}
422194677Sthompsa#endif
423194677Sthompsa		}
424184610Salfred		if (ent->flags & (MON_AUTHDECIDE|MON_ALOG)) {
425194677Sthompsa			auth_log(authctxt, authenticated, partial,
426194677Sthompsa			    auth_method, auth_submethod);
427194677Sthompsa			if (!authenticated)
428194228Sthompsa				authctxt->failures++;
429184610Salfred		}
430184610Salfred#ifdef JPAKE
431184610Salfred		/* Cleanup JPAKE context after authentication */
432184610Salfred		if (ent->flags & MON_AUTHDECIDE) {
433194677Sthompsa			if (authctxt->jpake_ctx != NULL) {
434184610Salfred				jpake_free(authctxt->jpake_ctx);
435184610Salfred				authctxt->jpake_ctx = NULL;
436184610Salfred			}
437194677Sthompsa		}
438184610Salfred#endif
439184610Salfred	}
440184610Salfred
441184610Salfred	if (!authctxt->valid)
442184610Salfred		fatal("%s: authenticated invalid user", __func__);
443184610Salfred	if (strcmp(auth_method, "unknown") == 0)
444184610Salfred		fatal("%s: authentication method name unknown", __func__);
445192984Sthompsa
446184610Salfred	debug("%s: %s has been authenticated by privileged process",
447193045Sthompsa	    __func__, authctxt->user);
448184610Salfred
449184610Salfred	mm_get_keystate(pmonitor);
450184610Salfred
451184610Salfred	/* Drain any buffered messages from the child */
452184610Salfred	while (pmonitor->m_log_recvfd != -1 && monitor_read_log(pmonitor) == 0)
453184610Salfred		;
454184610Salfred
455184610Salfred	close(pmonitor->m_sendfd);
456184610Salfred	close(pmonitor->m_log_recvfd);
457184610Salfred	pmonitor->m_sendfd = pmonitor->m_log_recvfd = -1;
458184610Salfred}
459184610Salfred
460184610Salfredstatic void
461184610Salfredmonitor_set_child_handler(pid_t pid)
462184610Salfred{
463184610Salfred	monitor_child_pid = pid;
464184610Salfred}
465184610Salfred
466184610Salfredstatic void
467184610Salfredmonitor_child_handler(int sig)
468194228Sthompsa{
469188413Sthompsa	kill(monitor_child_pid, sig);
470184610Salfred}
471184610Salfred
472194228Sthompsavoid
473184610Salfredmonitor_child_postauth(struct monitor *pmonitor)
474184610Salfred{
475184610Salfred	close(pmonitor->m_recvfd);
476184610Salfred	pmonitor->m_recvfd = -1;
477192984Sthompsa
478184610Salfred	monitor_set_child_handler(pmonitor->m_pid);
479184610Salfred	signal(SIGHUP, &monitor_child_handler);
480184610Salfred	signal(SIGTERM, &monitor_child_handler);
481184610Salfred	signal(SIGINT, &monitor_child_handler);
482184610Salfred
483184610Salfred	if (compat20) {
484184610Salfred		mon_dispatch = mon_dispatch_postauth20;
485184610Salfred
486184610Salfred		/* Permit requests for moduli and signatures */
487184610Salfred		monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
488184610Salfred		monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
489184610Salfred		monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
490184610Salfred	} else {
491184610Salfred		mon_dispatch = mon_dispatch_postauth15;
492184610Salfred		monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
493184610Salfred	}
494184610Salfred	if (!no_pty_flag) {
495184610Salfred		monitor_permit(mon_dispatch, MONITOR_REQ_PTY, 1);
496184610Salfred		monitor_permit(mon_dispatch, MONITOR_REQ_PTYCLEANUP, 1);
497184610Salfred	}
498184610Salfred
499184610Salfred	for (;;)
500184610Salfred		monitor_read(pmonitor, mon_dispatch, NULL);
501184610Salfred}
502184610Salfred
503184610Salfredvoid
504184610Salfredmonitor_sync(struct monitor *pmonitor)
505192984Sthompsa{
506184610Salfred	if (options.compression) {
507184610Salfred		/* The member allocation is not visible, so sync it */
508184610Salfred		mm_share_sync(&pmonitor->m_zlib, &pmonitor->m_zback);
509184610Salfred	}
510184610Salfred}
511184610Salfred
512184610Salfredstatic int
513184610Salfredmonitor_read_log(struct monitor *pmonitor)
514184610Salfred{
515184610Salfred	Buffer logmsg;
516184610Salfred	u_int len, level;
517184610Salfred	char *msg;
518184610Salfred
519184610Salfred	buffer_init(&logmsg);
520184610Salfred
521184610Salfred	/* Read length */
522184610Salfred	buffer_append_space(&logmsg, 4);
523184610Salfred	if (atomicio(read, pmonitor->m_log_recvfd,
524184610Salfred	    buffer_ptr(&logmsg), buffer_len(&logmsg)) != buffer_len(&logmsg)) {
525184610Salfred		if (errno == EPIPE) {
526184610Salfred			buffer_free(&logmsg);
527184610Salfred			debug("%s: child log fd closed", __func__);
528184610Salfred			close(pmonitor->m_log_recvfd);
529184610Salfred			pmonitor->m_log_recvfd = -1;
530184610Salfred			return -1;
531184610Salfred		}
532184610Salfred		fatal("%s: log fd read: %s", __func__, strerror(errno));
533184610Salfred	}
534184610Salfred	len = buffer_get_int(&logmsg);
535184610Salfred	if (len <= 4 || len > 8192)
536184610Salfred		fatal("%s: invalid log message length %u", __func__, len);
537184610Salfred
538184610Salfred	/* Read severity, message */
539184610Salfred	buffer_clear(&logmsg);
540194677Sthompsa	buffer_append_space(&logmsg, len);
541184610Salfred	if (atomicio(read, pmonitor->m_log_recvfd,
542194677Sthompsa	    buffer_ptr(&logmsg), buffer_len(&logmsg)) != buffer_len(&logmsg))
543194677Sthompsa		fatal("%s: log fd read: %s", __func__, strerror(errno));
544184610Salfred
545184610Salfred	/* Log it */
546233774Shselasky	level = buffer_get_int(&logmsg);
547194677Sthompsa	msg = buffer_get_string(&logmsg, NULL);
548184610Salfred	if (log_level_name(level) == NULL)
549194677Sthompsa		fatal("%s: invalid log level %u (corrupted message?)",
550194677Sthompsa		    __func__, level);
551194677Sthompsa	do_log2(level, "%s [preauth]", msg);
552184610Salfred
553184610Salfred	buffer_free(&logmsg);
554184610Salfred	free(msg);
555184610Salfred
556194677Sthompsa	return 0;
557184610Salfred}
558184610Salfred
559194677Sthompsaint
560184610Salfredmonitor_read(struct monitor *pmonitor, struct mon_table *ent,
561184610Salfred    struct mon_table **pent)
562184610Salfred{
563184610Salfred	Buffer m;
564194677Sthompsa	int ret;
565184610Salfred	u_char type;
566184610Salfred	struct pollfd pfd[2];
567184610Salfred
568184610Salfred	for (;;) {
569184610Salfred		bzero(&pfd, sizeof(pfd));
570194677Sthompsa		pfd[0].fd = pmonitor->m_sendfd;
571184610Salfred		pfd[0].events = POLLIN;
572184610Salfred		pfd[1].fd = pmonitor->m_log_recvfd;
573194677Sthompsa		pfd[1].events = pfd[1].fd == -1 ? 0 : POLLIN;
574184610Salfred		if (poll(pfd, pfd[1].fd == -1 ? 1 : 2, -1) == -1) {
575184610Salfred			if (errno == EINTR || errno == EAGAIN)
576184610Salfred				continue;
577184610Salfred			fatal("%s: poll: %s", __func__, strerror(errno));
578194677Sthompsa		}
579184610Salfred		if (pfd[1].revents) {
580184610Salfred			/*
581184610Salfred			 * Drain all log messages before processing next
582184610Salfred			 * monitor request.
583184610Salfred			 */
584199816Sthompsa			monitor_read_log(pmonitor);
585184610Salfred			continue;
586184610Salfred		}
587184610Salfred		if (pfd[0].revents)
588194677Sthompsa			break;  /* Continues below */
589194677Sthompsa	}
590194677Sthompsa
591194677Sthompsa	buffer_init(&m);
592194677Sthompsa
593184610Salfred	mm_request_receive(pmonitor->m_sendfd, &m);
594184610Salfred	type = buffer_get_char(&m);
595194677Sthompsa
596194228Sthompsa	debug3("%s: checking request %d", __func__, type);
597184610Salfred
598184610Salfred	while (ent->f != NULL) {
599184610Salfred		if (ent->type == type)
600194677Sthompsa			break;
601188413Sthompsa		ent++;
602194677Sthompsa	}
603188413Sthompsa
604184610Salfred	if (ent->f != NULL) {
605184610Salfred		if (!(ent->flags & MON_PERMIT))
606184610Salfred			fatal("%s: unpermitted request %d", __func__,
607184610Salfred			    type);
608184610Salfred		ret = (*ent->f)(pmonitor->m_sendfd, &m);
609197570Sthompsa		buffer_free(&m);
610197570Sthompsa
611197570Sthompsa		/* The child may use this request only once, disable it */
612197570Sthompsa		if (ent->flags & MON_ONCE) {
613197570Sthompsa			debug2("%s: %d used once, disabling now", __func__,
614197570Sthompsa			    type);
615197570Sthompsa			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 */
631static int
632monitor_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
641static void
642monitor_reset_key_state(void)
643{
644	/* reset state */
645	free(key_blob);
646	free(hostbased_cuser);
647	free(hostbased_chost);
648	key_blob = NULL;
649	key_bloblen = 0;
650	key_blobtype = MM_NOKEY;
651	hostbased_cuser = NULL;
652	hostbased_chost = NULL;
653}
654
655int
656mm_answer_moduli(int sock, Buffer *m)
657{
658	DH *dh;
659	int min, want, max;
660
661	min = buffer_get_int(m);
662	want = buffer_get_int(m);
663	max = buffer_get_int(m);
664
665	debug3("%s: got parameters: %d %d %d",
666	    __func__, min, want, max);
667	/* We need to check here, too, in case the child got corrupted */
668	if (max < min || want < min || max < want)
669		fatal("%s: bad parameters: %d %d %d",
670		    __func__, min, want, max);
671
672	buffer_clear(m);
673
674	dh = choose_dh(min, want, max);
675	if (dh == NULL) {
676		buffer_put_char(m, 0);
677		return (0);
678	} else {
679		/* Send first bignum */
680		buffer_put_char(m, 1);
681		buffer_put_bignum2(m, dh->p);
682		buffer_put_bignum2(m, dh->g);
683
684		DH_free(dh);
685	}
686	mm_request_send(sock, MONITOR_ANS_MODULI, m);
687	return (0);
688}
689
690extern AuthenticationConnection *auth_conn;
691
692int
693mm_answer_sign(int sock, Buffer *m)
694{
695	Key *key;
696	u_char *p;
697	u_char *signature;
698	u_int siglen, datlen;
699	int keyid;
700
701	debug3("%s", __func__);
702
703	keyid = buffer_get_int(m);
704	p = buffer_get_string(m, &datlen);
705
706	/*
707	 * Supported KEX types use SHA1 (20 bytes), SHA256 (32 bytes),
708	 * SHA384 (48 bytes) and SHA512 (64 bytes).
709	 */
710	if (datlen != 20 && datlen != 32 && datlen != 48 && datlen != 64)
711		fatal("%s: data length incorrect: %u", __func__, datlen);
712
713	/* save session id, it will be passed on the first call */
714	if (session_id2_len == 0) {
715		session_id2_len = datlen;
716		session_id2 = xmalloc(session_id2_len);
717		memcpy(session_id2, p, session_id2_len);
718	}
719
720	if ((key = get_hostkey_by_index(keyid)) != NULL) {
721		if (key_sign(key, &signature, &siglen, p, datlen) < 0)
722			fatal("%s: key_sign failed", __func__);
723	} else if ((key = get_hostkey_public_by_index(keyid)) != NULL &&
724	    auth_conn != NULL) {
725		if (ssh_agent_sign(auth_conn, key, &signature, &siglen, p,
726		    datlen) < 0)
727			fatal("%s: ssh_agent_sign failed", __func__);
728	} else
729		fatal("%s: no hostkey from index %d", __func__, keyid);
730
731	debug3("%s: signature %p(%u)", __func__, signature, siglen);
732
733	buffer_clear(m);
734	buffer_put_string(m, signature, siglen);
735
736	free(p);
737	free(signature);
738
739	mm_request_send(sock, MONITOR_ANS_SIGN, m);
740
741	/* Turn on permissions for getpwnam */
742	monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
743
744	return (0);
745}
746
747/* Retrieves the password entry and also checks if the user is permitted */
748
749int
750mm_answer_pwnamallow(int sock, Buffer *m)
751{
752	char *username;
753	struct passwd *pwent;
754	int allowed = 0;
755	u_int i;
756
757	debug3("%s", __func__);
758
759	if (authctxt->attempt++ != 0)
760		fatal("%s: multiple attempts for getpwnam", __func__);
761
762	username = buffer_get_string(m, NULL);
763
764	pwent = getpwnamallow(username);
765
766	authctxt->user = xstrdup(username);
767	setproctitle("%s [priv]", pwent ? username : "unknown");
768	free(username);
769
770	buffer_clear(m);
771
772	if (pwent == NULL) {
773		buffer_put_char(m, 0);
774		authctxt->pw = fakepw();
775		goto out;
776	}
777
778	allowed = 1;
779	authctxt->pw = pwent;
780	authctxt->valid = 1;
781
782	buffer_put_char(m, 1);
783	buffer_put_string(m, pwent, sizeof(struct passwd));
784	buffer_put_cstring(m, pwent->pw_name);
785	buffer_put_cstring(m, "*");
786#ifdef HAVE_STRUCT_PASSWD_PW_GECOS
787	buffer_put_cstring(m, pwent->pw_gecos);
788#endif
789#ifdef HAVE_STRUCT_PASSWD_PW_CLASS
790	buffer_put_cstring(m, pwent->pw_class);
791#endif
792	buffer_put_cstring(m, pwent->pw_dir);
793	buffer_put_cstring(m, pwent->pw_shell);
794
795 out:
796	buffer_put_string(m, &options, sizeof(options));
797
798#define M_CP_STROPT(x) do { \
799		if (options.x != NULL) \
800			buffer_put_cstring(m, options.x); \
801	} while (0)
802#define M_CP_STRARRAYOPT(x, nx) do { \
803		for (i = 0; i < options.nx; i++) \
804			buffer_put_cstring(m, options.x[i]); \
805	} while (0)
806	/* See comment in servconf.h */
807	COPY_MATCH_STRING_OPTS();
808#undef M_CP_STROPT
809#undef M_CP_STRARRAYOPT
810
811	/* Create valid auth method lists */
812	if (compat20 && auth2_setup_methods_lists(authctxt) != 0) {
813		/*
814		 * The monitor will continue long enough to let the child
815		 * run to it's packet_disconnect(), but it must not allow any
816		 * authentication to succeed.
817		 */
818		debug("%s: no valid authentication method lists", __func__);
819	}
820
821	debug3("%s: sending MONITOR_ANS_PWNAM: %d", __func__, allowed);
822	mm_request_send(sock, MONITOR_ANS_PWNAM, m);
823
824	/* For SSHv1 allow authentication now */
825	if (!compat20)
826		monitor_permit_authentications(1);
827	else {
828		/* Allow service/style information on the auth context */
829		monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
830		monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
831	}
832#ifdef USE_PAM
833	if (options.use_pam)
834		monitor_permit(mon_dispatch, MONITOR_REQ_PAM_START, 1);
835#endif
836
837	return (0);
838}
839
840int mm_answer_auth2_read_banner(int sock, Buffer *m)
841{
842	char *banner;
843
844	buffer_clear(m);
845	banner = auth2_read_banner();
846	buffer_put_cstring(m, banner != NULL ? banner : "");
847	mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m);
848	free(banner);
849
850	return (0);
851}
852
853int
854mm_answer_authserv(int sock, Buffer *m)
855{
856	monitor_permit_authentications(1);
857
858	authctxt->service = buffer_get_string(m, NULL);
859	authctxt->style = buffer_get_string(m, NULL);
860	debug3("%s: service=%s, style=%s",
861	    __func__, authctxt->service, authctxt->style);
862
863	if (strlen(authctxt->style) == 0) {
864		free(authctxt->style);
865		authctxt->style = NULL;
866	}
867
868	return (0);
869}
870
871int
872mm_answer_authpassword(int sock, Buffer *m)
873{
874	static int call_count;
875	char *passwd;
876	int authenticated;
877	u_int plen;
878
879	passwd = buffer_get_string(m, &plen);
880	/* Only authenticate if the context is valid */
881	authenticated = options.password_authentication &&
882	    auth_password(authctxt, passwd);
883	memset(passwd, 0, strlen(passwd));
884	free(passwd);
885
886	buffer_clear(m);
887	buffer_put_int(m, authenticated);
888
889	debug3("%s: sending result %d", __func__, authenticated);
890	mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m);
891
892	call_count++;
893	if (plen == 0 && call_count == 1)
894		auth_method = "none";
895	else
896		auth_method = "password";
897
898	/* Causes monitor loop to terminate if authenticated */
899	return (authenticated);
900}
901
902#ifdef BSD_AUTH
903int
904mm_answer_bsdauthquery(int sock, Buffer *m)
905{
906	char *name, *infotxt;
907	u_int numprompts;
908	u_int *echo_on;
909	char **prompts;
910	u_int success;
911
912	success = bsdauth_query(authctxt, &name, &infotxt, &numprompts,
913	    &prompts, &echo_on) < 0 ? 0 : 1;
914
915	buffer_clear(m);
916	buffer_put_int(m, success);
917	if (success)
918		buffer_put_cstring(m, prompts[0]);
919
920	debug3("%s: sending challenge success: %u", __func__, success);
921	mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m);
922
923	if (success) {
924		free(name);
925		free(infotxt);
926		free(prompts);
927		free(echo_on);
928	}
929
930	return (0);
931}
932
933int
934mm_answer_bsdauthrespond(int sock, Buffer *m)
935{
936	char *response;
937	int authok;
938
939	if (authctxt->as == 0)
940		fatal("%s: no bsd auth session", __func__);
941
942	response = buffer_get_string(m, NULL);
943	authok = options.challenge_response_authentication &&
944	    auth_userresponse(authctxt->as, response, 0);
945	authctxt->as = NULL;
946	debug3("%s: <%s> = <%d>", __func__, response, authok);
947	free(response);
948
949	buffer_clear(m);
950	buffer_put_int(m, authok);
951
952	debug3("%s: sending authenticated: %d", __func__, authok);
953	mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m);
954
955	if (compat20) {
956		auth_method = "keyboard-interactive";
957		auth_submethod = "bsdauth";
958	} else
959		auth_method = "bsdauth";
960
961	return (authok != 0);
962}
963#endif
964
965#ifdef SKEY
966int
967mm_answer_skeyquery(int sock, Buffer *m)
968{
969	struct skey skey;
970	char challenge[1024];
971	u_int success;
972
973	success = _compat_skeychallenge(&skey, authctxt->user, challenge,
974	    sizeof(challenge)) < 0 ? 0 : 1;
975
976	buffer_clear(m);
977	buffer_put_int(m, success);
978	if (success)
979		buffer_put_cstring(m, challenge);
980
981	debug3("%s: sending challenge success: %u", __func__, success);
982	mm_request_send(sock, MONITOR_ANS_SKEYQUERY, m);
983
984	return (0);
985}
986
987int
988mm_answer_skeyrespond(int sock, Buffer *m)
989{
990	char *response;
991	int authok;
992
993	response = buffer_get_string(m, NULL);
994
995	authok = (options.challenge_response_authentication &&
996	    authctxt->valid &&
997	    skey_haskey(authctxt->pw->pw_name) == 0 &&
998	    skey_passcheck(authctxt->pw->pw_name, response) != -1);
999
1000	free(response);
1001
1002	buffer_clear(m);
1003	buffer_put_int(m, authok);
1004
1005	debug3("%s: sending authenticated: %d", __func__, authok);
1006	mm_request_send(sock, MONITOR_ANS_SKEYRESPOND, m);
1007
1008	auth_method = "skey";
1009
1010	return (authok != 0);
1011}
1012#endif
1013
1014#ifdef USE_PAM
1015int
1016mm_answer_pam_start(int sock, Buffer *m)
1017{
1018	if (!options.use_pam)
1019		fatal("UsePAM not set, but ended up in %s anyway", __func__);
1020
1021	start_pam(authctxt);
1022
1023	monitor_permit(mon_dispatch, MONITOR_REQ_PAM_ACCOUNT, 1);
1024
1025	return (0);
1026}
1027
1028int
1029mm_answer_pam_account(int sock, Buffer *m)
1030{
1031	u_int ret;
1032
1033	if (!options.use_pam)
1034		fatal("UsePAM not set, but ended up in %s anyway", __func__);
1035
1036	ret = do_pam_account();
1037
1038	buffer_put_int(m, ret);
1039	buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg));
1040
1041	mm_request_send(sock, MONITOR_ANS_PAM_ACCOUNT, m);
1042
1043	return (ret);
1044}
1045
1046static void *sshpam_ctxt, *sshpam_authok;
1047extern KbdintDevice sshpam_device;
1048
1049int
1050mm_answer_pam_init_ctx(int sock, Buffer *m)
1051{
1052
1053	debug3("%s", __func__);
1054	authctxt->user = buffer_get_string(m, NULL);
1055	sshpam_ctxt = (sshpam_device.init_ctx)(authctxt);
1056	sshpam_authok = NULL;
1057	buffer_clear(m);
1058	if (sshpam_ctxt != NULL) {
1059		monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1);
1060		buffer_put_int(m, 1);
1061	} else {
1062		buffer_put_int(m, 0);
1063	}
1064	mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m);
1065	return (0);
1066}
1067
1068int
1069mm_answer_pam_query(int sock, Buffer *m)
1070{
1071	char *name = NULL, *info = NULL, **prompts = NULL;
1072	u_int i, num = 0, *echo_on = 0;
1073	int ret;
1074
1075	debug3("%s", __func__);
1076	sshpam_authok = NULL;
1077	ret = (sshpam_device.query)(sshpam_ctxt, &name, &info, &num, &prompts, &echo_on);
1078	if (ret == 0 && num == 0)
1079		sshpam_authok = sshpam_ctxt;
1080	if (num > 1 || name == NULL || info == NULL)
1081		ret = -1;
1082	buffer_clear(m);
1083	buffer_put_int(m, ret);
1084	buffer_put_cstring(m, name);
1085	free(name);
1086	buffer_put_cstring(m, info);
1087	free(info);
1088	buffer_put_int(m, num);
1089	for (i = 0; i < num; ++i) {
1090		buffer_put_cstring(m, prompts[i]);
1091		free(prompts[i]);
1092		buffer_put_int(m, echo_on[i]);
1093	}
1094	free(prompts);
1095	free(echo_on);
1096	auth_method = "keyboard-interactive";
1097	auth_submethod = "pam";
1098	mm_request_send(sock, MONITOR_ANS_PAM_QUERY, m);
1099	return (0);
1100}
1101
1102int
1103mm_answer_pam_respond(int sock, Buffer *m)
1104{
1105	char **resp;
1106	u_int i, num;
1107	int ret;
1108
1109	debug3("%s", __func__);
1110	sshpam_authok = NULL;
1111	num = buffer_get_int(m);
1112	if (num > 0) {
1113		resp = xcalloc(num, sizeof(char *));
1114		for (i = 0; i < num; ++i)
1115			resp[i] = buffer_get_string(m, NULL);
1116		ret = (sshpam_device.respond)(sshpam_ctxt, num, resp);
1117		for (i = 0; i < num; ++i)
1118			free(resp[i]);
1119		free(resp);
1120	} else {
1121		ret = (sshpam_device.respond)(sshpam_ctxt, num, NULL);
1122	}
1123	buffer_clear(m);
1124	buffer_put_int(m, ret);
1125	mm_request_send(sock, MONITOR_ANS_PAM_RESPOND, m);
1126	auth_method = "keyboard-interactive";
1127	auth_submethod = "pam";
1128	if (ret == 0)
1129		sshpam_authok = sshpam_ctxt;
1130	return (0);
1131}
1132
1133int
1134mm_answer_pam_free_ctx(int sock, Buffer *m)
1135{
1136
1137	debug3("%s", __func__);
1138	(sshpam_device.free_ctx)(sshpam_ctxt);
1139	buffer_clear(m);
1140	mm_request_send(sock, MONITOR_ANS_PAM_FREE_CTX, m);
1141	auth_method = "keyboard-interactive";
1142	auth_submethod = "pam";
1143	return (sshpam_authok == sshpam_ctxt);
1144}
1145#endif
1146
1147int
1148mm_answer_keyallowed(int sock, Buffer *m)
1149{
1150	Key *key;
1151	char *cuser, *chost;
1152	u_char *blob;
1153	u_int bloblen;
1154	enum mm_keytype type = 0;
1155	int allowed = 0;
1156
1157	debug3("%s entering", __func__);
1158
1159	type = buffer_get_int(m);
1160	cuser = buffer_get_string(m, NULL);
1161	chost = buffer_get_string(m, NULL);
1162	blob = buffer_get_string(m, &bloblen);
1163
1164	key = key_from_blob(blob, bloblen);
1165
1166	if ((compat20 && type == MM_RSAHOSTKEY) ||
1167	    (!compat20 && type != MM_RSAHOSTKEY))
1168		fatal("%s: key type and protocol mismatch", __func__);
1169
1170	debug3("%s: key_from_blob: %p", __func__, key);
1171
1172	if (key != NULL && authctxt->valid) {
1173		switch (type) {
1174		case MM_USERKEY:
1175			allowed = options.pubkey_authentication &&
1176			    user_key_allowed(authctxt->pw, key);
1177			pubkey_auth_info(authctxt, key, NULL);
1178			auth_method = "publickey";
1179			if (options.pubkey_authentication && allowed != 1)
1180				auth_clear_options();
1181			break;
1182		case MM_HOSTKEY:
1183			allowed = options.hostbased_authentication &&
1184			    hostbased_key_allowed(authctxt->pw,
1185			    cuser, chost, key);
1186			pubkey_auth_info(authctxt, key,
1187			    "client user \"%.100s\", client host \"%.100s\"",
1188			    cuser, chost);
1189			auth_method = "hostbased";
1190			break;
1191		case MM_RSAHOSTKEY:
1192			key->type = KEY_RSA1; /* XXX */
1193			allowed = options.rhosts_rsa_authentication &&
1194			    auth_rhosts_rsa_key_allowed(authctxt->pw,
1195			    cuser, chost, key);
1196			if (options.rhosts_rsa_authentication && allowed != 1)
1197				auth_clear_options();
1198			auth_method = "rsa";
1199			break;
1200		default:
1201			fatal("%s: unknown key type %d", __func__, type);
1202			break;
1203		}
1204	}
1205	if (key != NULL)
1206		key_free(key);
1207
1208	/* clear temporarily storage (used by verify) */
1209	monitor_reset_key_state();
1210
1211	if (allowed) {
1212		/* Save temporarily for comparison in verify */
1213		key_blob = blob;
1214		key_bloblen = bloblen;
1215		key_blobtype = type;
1216		hostbased_cuser = cuser;
1217		hostbased_chost = chost;
1218	} else {
1219		/* Log failed attempt */
1220		auth_log(authctxt, 0, 0, auth_method, NULL);
1221		free(blob);
1222		free(cuser);
1223		free(chost);
1224	}
1225
1226	debug3("%s: key %p is %s",
1227	    __func__, key, allowed ? "allowed" : "not allowed");
1228
1229	buffer_clear(m);
1230	buffer_put_int(m, allowed);
1231	buffer_put_int(m, forced_command != NULL);
1232
1233	mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m);
1234
1235	if (type == MM_RSAHOSTKEY)
1236		monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed);
1237
1238	return (0);
1239}
1240
1241static int
1242monitor_valid_userblob(u_char *data, u_int datalen)
1243{
1244	Buffer b;
1245	char *p, *userstyle;
1246	u_int len;
1247	int fail = 0;
1248
1249	buffer_init(&b);
1250	buffer_append(&b, data, datalen);
1251
1252	if (datafellows & SSH_OLD_SESSIONID) {
1253		p = buffer_ptr(&b);
1254		len = buffer_len(&b);
1255		if ((session_id2 == NULL) ||
1256		    (len < session_id2_len) ||
1257		    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1258			fail++;
1259		buffer_consume(&b, session_id2_len);
1260	} else {
1261		p = buffer_get_string(&b, &len);
1262		if ((session_id2 == NULL) ||
1263		    (len != session_id2_len) ||
1264		    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1265			fail++;
1266		free(p);
1267	}
1268	if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
1269		fail++;
1270	p = buffer_get_cstring(&b, NULL);
1271	xasprintf(&userstyle, "%s%s%s", authctxt->user,
1272	    authctxt->style ? ":" : "",
1273	    authctxt->style ? authctxt->style : "");
1274	if (strcmp(userstyle, p) != 0) {
1275		logit("wrong user name passed to monitor: expected %s != %.100s",
1276		    userstyle, p);
1277		fail++;
1278	}
1279	free(userstyle);
1280	free(p);
1281	buffer_skip_string(&b);
1282	if (datafellows & SSH_BUG_PKAUTH) {
1283		if (!buffer_get_char(&b))
1284			fail++;
1285	} else {
1286		p = buffer_get_cstring(&b, NULL);
1287		if (strcmp("publickey", p) != 0)
1288			fail++;
1289		free(p);
1290		if (!buffer_get_char(&b))
1291			fail++;
1292		buffer_skip_string(&b);
1293	}
1294	buffer_skip_string(&b);
1295	if (buffer_len(&b) != 0)
1296		fail++;
1297	buffer_free(&b);
1298	return (fail == 0);
1299}
1300
1301static int
1302monitor_valid_hostbasedblob(u_char *data, u_int datalen, char *cuser,
1303    char *chost)
1304{
1305	Buffer b;
1306	char *p, *userstyle;
1307	u_int len;
1308	int fail = 0;
1309
1310	buffer_init(&b);
1311	buffer_append(&b, data, datalen);
1312
1313	p = buffer_get_string(&b, &len);
1314	if ((session_id2 == NULL) ||
1315	    (len != session_id2_len) ||
1316	    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1317		fail++;
1318	free(p);
1319
1320	if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
1321		fail++;
1322	p = buffer_get_cstring(&b, NULL);
1323	xasprintf(&userstyle, "%s%s%s", authctxt->user,
1324	    authctxt->style ? ":" : "",
1325	    authctxt->style ? authctxt->style : "");
1326	if (strcmp(userstyle, p) != 0) {
1327		logit("wrong user name passed to monitor: expected %s != %.100s",
1328		    userstyle, p);
1329		fail++;
1330	}
1331	free(userstyle);
1332	free(p);
1333	buffer_skip_string(&b);	/* service */
1334	p = buffer_get_cstring(&b, NULL);
1335	if (strcmp(p, "hostbased") != 0)
1336		fail++;
1337	free(p);
1338	buffer_skip_string(&b);	/* pkalg */
1339	buffer_skip_string(&b);	/* pkblob */
1340
1341	/* verify client host, strip trailing dot if necessary */
1342	p = buffer_get_string(&b, NULL);
1343	if (((len = strlen(p)) > 0) && p[len - 1] == '.')
1344		p[len - 1] = '\0';
1345	if (strcmp(p, chost) != 0)
1346		fail++;
1347	free(p);
1348
1349	/* verify client user */
1350	p = buffer_get_string(&b, NULL);
1351	if (strcmp(p, cuser) != 0)
1352		fail++;
1353	free(p);
1354
1355	if (buffer_len(&b) != 0)
1356		fail++;
1357	buffer_free(&b);
1358	return (fail == 0);
1359}
1360
1361int
1362mm_answer_keyverify(int sock, Buffer *m)
1363{
1364	Key *key;
1365	u_char *signature, *data, *blob;
1366	u_int signaturelen, datalen, bloblen;
1367	int verified = 0;
1368	int valid_data = 0;
1369
1370	blob = buffer_get_string(m, &bloblen);
1371	signature = buffer_get_string(m, &signaturelen);
1372	data = buffer_get_string(m, &datalen);
1373
1374	if (hostbased_cuser == NULL || hostbased_chost == NULL ||
1375	  !monitor_allowed_key(blob, bloblen))
1376		fatal("%s: bad key, not previously allowed", __func__);
1377
1378	key = key_from_blob(blob, bloblen);
1379	if (key == NULL)
1380		fatal("%s: bad public key blob", __func__);
1381
1382	switch (key_blobtype) {
1383	case MM_USERKEY:
1384		valid_data = monitor_valid_userblob(data, datalen);
1385		break;
1386	case MM_HOSTKEY:
1387		valid_data = monitor_valid_hostbasedblob(data, datalen,
1388		    hostbased_cuser, hostbased_chost);
1389		break;
1390	default:
1391		valid_data = 0;
1392		break;
1393	}
1394	if (!valid_data)
1395		fatal("%s: bad signature data blob", __func__);
1396
1397	verified = key_verify(key, signature, signaturelen, data, datalen);
1398	debug3("%s: key %p signature %s",
1399	    __func__, key, (verified == 1) ? "verified" : "unverified");
1400
1401	key_free(key);
1402	free(blob);
1403	free(signature);
1404	free(data);
1405
1406	auth_method = key_blobtype == MM_USERKEY ? "publickey" : "hostbased";
1407
1408	monitor_reset_key_state();
1409
1410	buffer_clear(m);
1411	buffer_put_int(m, verified);
1412	mm_request_send(sock, MONITOR_ANS_KEYVERIFY, m);
1413
1414	return (verified == 1);
1415}
1416
1417static void
1418mm_record_login(Session *s, struct passwd *pw)
1419{
1420	socklen_t fromlen;
1421	struct sockaddr_storage from;
1422
1423	/*
1424	 * Get IP address of client. If the connection is not a socket, let
1425	 * the address be 0.0.0.0.
1426	 */
1427	memset(&from, 0, sizeof(from));
1428	fromlen = sizeof(from);
1429	if (packet_connection_is_on_socket()) {
1430		if (getpeername(packet_get_connection_in(),
1431		    (struct sockaddr *)&from, &fromlen) < 0) {
1432			debug("getpeername: %.100s", strerror(errno));
1433			cleanup_exit(255);
1434		}
1435	}
1436	/* Record that there was a login on that tty from the remote host. */
1437	record_login(s->pid, s->tty, pw->pw_name, pw->pw_uid,
1438	    get_remote_name_or_ip(utmp_len, options.use_dns),
1439	    (struct sockaddr *)&from, fromlen);
1440}
1441
1442static void
1443mm_session_close(Session *s)
1444{
1445	debug3("%s: session %d pid %ld", __func__, s->self, (long)s->pid);
1446	if (s->ttyfd != -1) {
1447		debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ptyfd);
1448		session_pty_cleanup2(s);
1449	}
1450	session_unused(s->self);
1451}
1452
1453int
1454mm_answer_pty(int sock, Buffer *m)
1455{
1456	extern struct monitor *pmonitor;
1457	Session *s;
1458	int res, fd0;
1459
1460	debug3("%s entering", __func__);
1461
1462	buffer_clear(m);
1463	s = session_new();
1464	if (s == NULL)
1465		goto error;
1466	s->authctxt = authctxt;
1467	s->pw = authctxt->pw;
1468	s->pid = pmonitor->m_pid;
1469	res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty));
1470	if (res == 0)
1471		goto error;
1472	pty_setowner(authctxt->pw, s->tty);
1473
1474	buffer_put_int(m, 1);
1475	buffer_put_cstring(m, s->tty);
1476
1477	/* We need to trick ttyslot */
1478	if (dup2(s->ttyfd, 0) == -1)
1479		fatal("%s: dup2", __func__);
1480
1481	mm_record_login(s, authctxt->pw);
1482
1483	/* Now we can close the file descriptor again */
1484	close(0);
1485
1486	/* send messages generated by record_login */
1487	buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg));
1488	buffer_clear(&loginmsg);
1489
1490	mm_request_send(sock, MONITOR_ANS_PTY, m);
1491
1492	if (mm_send_fd(sock, s->ptyfd) == -1 ||
1493	    mm_send_fd(sock, s->ttyfd) == -1)
1494		fatal("%s: send fds failed", __func__);
1495
1496	/* make sure nothing uses fd 0 */
1497	if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) < 0)
1498		fatal("%s: open(/dev/null): %s", __func__, strerror(errno));
1499	if (fd0 != 0)
1500		error("%s: fd0 %d != 0", __func__, fd0);
1501
1502	/* slave is not needed */
1503	close(s->ttyfd);
1504	s->ttyfd = s->ptyfd;
1505	/* no need to dup() because nobody closes ptyfd */
1506	s->ptymaster = s->ptyfd;
1507
1508	debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ttyfd);
1509
1510	return (0);
1511
1512 error:
1513	if (s != NULL)
1514		mm_session_close(s);
1515	buffer_put_int(m, 0);
1516	mm_request_send(sock, MONITOR_ANS_PTY, m);
1517	return (0);
1518}
1519
1520int
1521mm_answer_pty_cleanup(int sock, Buffer *m)
1522{
1523	Session *s;
1524	char *tty;
1525
1526	debug3("%s entering", __func__);
1527
1528	tty = buffer_get_string(m, NULL);
1529	if ((s = session_by_tty(tty)) != NULL)
1530		mm_session_close(s);
1531	buffer_clear(m);
1532	free(tty);
1533	return (0);
1534}
1535
1536int
1537mm_answer_sesskey(int sock, Buffer *m)
1538{
1539	BIGNUM *p;
1540	int rsafail;
1541
1542	/* Turn off permissions */
1543	monitor_permit(mon_dispatch, MONITOR_REQ_SESSKEY, 0);
1544
1545	if ((p = BN_new()) == NULL)
1546		fatal("%s: BN_new", __func__);
1547
1548	buffer_get_bignum2(m, p);
1549
1550	rsafail = ssh1_session_key(p);
1551
1552	buffer_clear(m);
1553	buffer_put_int(m, rsafail);
1554	buffer_put_bignum2(m, p);
1555
1556	BN_clear_free(p);
1557
1558	mm_request_send(sock, MONITOR_ANS_SESSKEY, m);
1559
1560	/* Turn on permissions for sessid passing */
1561	monitor_permit(mon_dispatch, MONITOR_REQ_SESSID, 1);
1562
1563	return (0);
1564}
1565
1566int
1567mm_answer_sessid(int sock, Buffer *m)
1568{
1569	int i;
1570
1571	debug3("%s entering", __func__);
1572
1573	if (buffer_len(m) != 16)
1574		fatal("%s: bad ssh1 session id", __func__);
1575	for (i = 0; i < 16; i++)
1576		session_id[i] = buffer_get_char(m);
1577
1578	/* Turn on permissions for getpwnam */
1579	monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
1580
1581	return (0);
1582}
1583
1584int
1585mm_answer_rsa_keyallowed(int sock, Buffer *m)
1586{
1587	BIGNUM *client_n;
1588	Key *key = NULL;
1589	u_char *blob = NULL;
1590	u_int blen = 0;
1591	int allowed = 0;
1592
1593	debug3("%s entering", __func__);
1594
1595	auth_method = "rsa";
1596	if (options.rsa_authentication && authctxt->valid) {
1597		if ((client_n = BN_new()) == NULL)
1598			fatal("%s: BN_new", __func__);
1599		buffer_get_bignum2(m, client_n);
1600		allowed = auth_rsa_key_allowed(authctxt->pw, client_n, &key);
1601		BN_clear_free(client_n);
1602	}
1603	buffer_clear(m);
1604	buffer_put_int(m, allowed);
1605	buffer_put_int(m, forced_command != NULL);
1606
1607	/* clear temporarily storage (used by generate challenge) */
1608	monitor_reset_key_state();
1609
1610	if (allowed && key != NULL) {
1611		key->type = KEY_RSA;	/* cheat for key_to_blob */
1612		if (key_to_blob(key, &blob, &blen) == 0)
1613			fatal("%s: key_to_blob failed", __func__);
1614		buffer_put_string(m, blob, blen);
1615
1616		/* Save temporarily for comparison in verify */
1617		key_blob = blob;
1618		key_bloblen = blen;
1619		key_blobtype = MM_RSAUSERKEY;
1620	}
1621	if (key != NULL)
1622		key_free(key);
1623
1624	mm_request_send(sock, MONITOR_ANS_RSAKEYALLOWED, m);
1625
1626	monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed);
1627	monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 0);
1628	return (0);
1629}
1630
1631int
1632mm_answer_rsa_challenge(int sock, Buffer *m)
1633{
1634	Key *key = NULL;
1635	u_char *blob;
1636	u_int blen;
1637
1638	debug3("%s entering", __func__);
1639
1640	if (!authctxt->valid)
1641		fatal("%s: authctxt not valid", __func__);
1642	blob = buffer_get_string(m, &blen);
1643	if (!monitor_allowed_key(blob, blen))
1644		fatal("%s: bad key, not previously allowed", __func__);
1645	if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY)
1646		fatal("%s: key type mismatch", __func__);
1647	if ((key = key_from_blob(blob, blen)) == NULL)
1648		fatal("%s: received bad key", __func__);
1649	if (key->type != KEY_RSA)
1650		fatal("%s: received bad key type %d", __func__, key->type);
1651	key->type = KEY_RSA1;
1652	if (ssh1_challenge)
1653		BN_clear_free(ssh1_challenge);
1654	ssh1_challenge = auth_rsa_generate_challenge(key);
1655
1656	buffer_clear(m);
1657	buffer_put_bignum2(m, ssh1_challenge);
1658
1659	debug3("%s sending reply", __func__);
1660	mm_request_send(sock, MONITOR_ANS_RSACHALLENGE, m);
1661
1662	monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 1);
1663
1664	free(blob);
1665	key_free(key);
1666	return (0);
1667}
1668
1669int
1670mm_answer_rsa_response(int sock, Buffer *m)
1671{
1672	Key *key = NULL;
1673	u_char *blob, *response;
1674	u_int blen, len;
1675	int success;
1676
1677	debug3("%s entering", __func__);
1678
1679	if (!authctxt->valid)
1680		fatal("%s: authctxt not valid", __func__);
1681	if (ssh1_challenge == NULL)
1682		fatal("%s: no ssh1_challenge", __func__);
1683
1684	blob = buffer_get_string(m, &blen);
1685	if (!monitor_allowed_key(blob, blen))
1686		fatal("%s: bad key, not previously allowed", __func__);
1687	if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY)
1688		fatal("%s: key type mismatch: %d", __func__, key_blobtype);
1689	if ((key = key_from_blob(blob, blen)) == NULL)
1690		fatal("%s: received bad key", __func__);
1691	response = buffer_get_string(m, &len);
1692	if (len != 16)
1693		fatal("%s: received bad response to challenge", __func__);
1694	success = auth_rsa_verify_response(key, ssh1_challenge, response);
1695
1696	free(blob);
1697	key_free(key);
1698	free(response);
1699
1700	auth_method = key_blobtype == MM_RSAUSERKEY ? "rsa" : "rhosts-rsa";
1701
1702	/* reset state */
1703	BN_clear_free(ssh1_challenge);
1704	ssh1_challenge = NULL;
1705	monitor_reset_key_state();
1706
1707	buffer_clear(m);
1708	buffer_put_int(m, success);
1709	mm_request_send(sock, MONITOR_ANS_RSARESPONSE, m);
1710
1711	return (success);
1712}
1713
1714int
1715mm_answer_term(int sock, Buffer *req)
1716{
1717	extern struct monitor *pmonitor;
1718	int res, status;
1719
1720	debug3("%s: tearing down sessions", __func__);
1721
1722	/* The child is terminating */
1723	session_destroy_all(&mm_session_close);
1724
1725#ifdef USE_PAM
1726	if (options.use_pam)
1727		sshpam_cleanup();
1728#endif
1729
1730	while (waitpid(pmonitor->m_pid, &status, 0) == -1)
1731		if (errno != EINTR)
1732			exit(1);
1733
1734	res = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
1735
1736	/* Terminate process */
1737	exit(res);
1738}
1739
1740#ifdef SSH_AUDIT_EVENTS
1741/* Report that an audit event occurred */
1742int
1743mm_answer_audit_event(int socket, Buffer *m)
1744{
1745	ssh_audit_event_t event;
1746
1747	debug3("%s entering", __func__);
1748
1749	event = buffer_get_int(m);
1750	switch(event) {
1751	case SSH_AUTH_FAIL_PUBKEY:
1752	case SSH_AUTH_FAIL_HOSTBASED:
1753	case SSH_AUTH_FAIL_GSSAPI:
1754	case SSH_LOGIN_EXCEED_MAXTRIES:
1755	case SSH_LOGIN_ROOT_DENIED:
1756	case SSH_CONNECTION_CLOSE:
1757	case SSH_INVALID_USER:
1758		audit_event(event);
1759		break;
1760	default:
1761		fatal("Audit event type %d not permitted", event);
1762	}
1763
1764	return (0);
1765}
1766
1767int
1768mm_answer_audit_command(int socket, Buffer *m)
1769{
1770	u_int len;
1771	char *cmd;
1772
1773	debug3("%s entering", __func__);
1774	cmd = buffer_get_string(m, &len);
1775	/* sanity check command, if so how? */
1776	audit_run_command(cmd);
1777	free(cmd);
1778	return (0);
1779}
1780#endif /* SSH_AUDIT_EVENTS */
1781
1782void
1783monitor_apply_keystate(struct monitor *pmonitor)
1784{
1785	if (compat20) {
1786		set_newkeys(MODE_IN);
1787		set_newkeys(MODE_OUT);
1788	} else {
1789		packet_set_protocol_flags(child_state.ssh1protoflags);
1790		packet_set_encryption_key(child_state.ssh1key,
1791		    child_state.ssh1keylen, child_state.ssh1cipher);
1792		free(child_state.ssh1key);
1793	}
1794
1795	/* for rc4 and other stateful ciphers */
1796	packet_set_keycontext(MODE_OUT, child_state.keyout);
1797	free(child_state.keyout);
1798	packet_set_keycontext(MODE_IN, child_state.keyin);
1799	free(child_state.keyin);
1800
1801	if (!compat20) {
1802		packet_set_iv(MODE_OUT, child_state.ivout);
1803		free(child_state.ivout);
1804		packet_set_iv(MODE_IN, child_state.ivin);
1805		free(child_state.ivin);
1806	}
1807
1808	memcpy(&incoming_stream, &child_state.incoming,
1809	    sizeof(incoming_stream));
1810	memcpy(&outgoing_stream, &child_state.outgoing,
1811	    sizeof(outgoing_stream));
1812
1813	/* Update with new address */
1814	if (options.compression)
1815		mm_init_compression(pmonitor->m_zlib);
1816
1817	if (options.rekey_limit || options.rekey_interval)
1818		packet_set_rekey_limits((u_int32_t)options.rekey_limit,
1819		    (time_t)options.rekey_interval);
1820
1821	/* Network I/O buffers */
1822	/* XXX inefficient for large buffers, need: buffer_init_from_string */
1823	buffer_clear(packet_get_input());
1824	buffer_append(packet_get_input(), child_state.input, child_state.ilen);
1825	memset(child_state.input, 0, child_state.ilen);
1826	free(child_state.input);
1827
1828	buffer_clear(packet_get_output());
1829	buffer_append(packet_get_output(), child_state.output,
1830		      child_state.olen);
1831	memset(child_state.output, 0, child_state.olen);
1832	free(child_state.output);
1833
1834	/* Roaming */
1835	if (compat20)
1836		roam_set_bytes(child_state.sent_bytes, child_state.recv_bytes);
1837}
1838
1839static Kex *
1840mm_get_kex(Buffer *m)
1841{
1842	Kex *kex;
1843	void *blob;
1844	u_int bloblen;
1845
1846	kex = xcalloc(1, sizeof(*kex));
1847	kex->session_id = buffer_get_string(m, &kex->session_id_len);
1848	if (session_id2 == NULL ||
1849	    kex->session_id_len != session_id2_len ||
1850	    timingsafe_bcmp(kex->session_id, session_id2, session_id2_len) != 0)
1851		fatal("mm_get_get: internal error: bad session id");
1852	kex->we_need = buffer_get_int(m);
1853	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1854	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1855	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1856	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1857	kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
1858	kex->server = 1;
1859	kex->hostkey_type = buffer_get_int(m);
1860	kex->kex_type = buffer_get_int(m);
1861	blob = buffer_get_string(m, &bloblen);
1862	buffer_init(&kex->my);
1863	buffer_append(&kex->my, blob, bloblen);
1864	free(blob);
1865	blob = buffer_get_string(m, &bloblen);
1866	buffer_init(&kex->peer);
1867	buffer_append(&kex->peer, blob, bloblen);
1868	free(blob);
1869	kex->done = 1;
1870	kex->flags = buffer_get_int(m);
1871	kex->client_version_string = buffer_get_string(m, NULL);
1872	kex->server_version_string = buffer_get_string(m, NULL);
1873	kex->load_host_public_key=&get_hostkey_public_by_type;
1874	kex->load_host_private_key=&get_hostkey_private_by_type;
1875	kex->host_key_index=&get_hostkey_index;
1876	kex->sign = sshd_hostkey_sign;
1877
1878	return (kex);
1879}
1880
1881/* This function requries careful sanity checking */
1882
1883void
1884mm_get_keystate(struct monitor *pmonitor)
1885{
1886	Buffer m;
1887	u_char *blob, *p;
1888	u_int bloblen, plen;
1889	u_int32_t seqnr, packets;
1890	u_int64_t blocks, bytes;
1891
1892	debug3("%s: Waiting for new keys", __func__);
1893
1894	buffer_init(&m);
1895	mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT, &m);
1896	if (!compat20) {
1897		child_state.ssh1protoflags = buffer_get_int(&m);
1898		child_state.ssh1cipher = buffer_get_int(&m);
1899		child_state.ssh1key = buffer_get_string(&m,
1900		    &child_state.ssh1keylen);
1901		child_state.ivout = buffer_get_string(&m,
1902		    &child_state.ivoutlen);
1903		child_state.ivin = buffer_get_string(&m, &child_state.ivinlen);
1904		goto skip;
1905	} else {
1906		/* Get the Kex for rekeying */
1907		*pmonitor->m_pkex = mm_get_kex(&m);
1908	}
1909
1910	blob = buffer_get_string(&m, &bloblen);
1911	current_keys[MODE_OUT] = mm_newkeys_from_blob(blob, bloblen);
1912	free(blob);
1913
1914	debug3("%s: Waiting for second key", __func__);
1915	blob = buffer_get_string(&m, &bloblen);
1916	current_keys[MODE_IN] = mm_newkeys_from_blob(blob, bloblen);
1917	free(blob);
1918
1919	/* Now get sequence numbers for the packets */
1920	seqnr = buffer_get_int(&m);
1921	blocks = buffer_get_int64(&m);
1922	packets = buffer_get_int(&m);
1923	bytes = buffer_get_int64(&m);
1924	packet_set_state(MODE_OUT, seqnr, blocks, packets, bytes);
1925	seqnr = buffer_get_int(&m);
1926	blocks = buffer_get_int64(&m);
1927	packets = buffer_get_int(&m);
1928	bytes = buffer_get_int64(&m);
1929	packet_set_state(MODE_IN, seqnr, blocks, packets, bytes);
1930
1931 skip:
1932	/* Get the key context */
1933	child_state.keyout = buffer_get_string(&m, &child_state.keyoutlen);
1934	child_state.keyin  = buffer_get_string(&m, &child_state.keyinlen);
1935
1936	debug3("%s: Getting compression state", __func__);
1937	/* Get compression state */
1938	p = buffer_get_string(&m, &plen);
1939	if (plen != sizeof(child_state.outgoing))
1940		fatal("%s: bad request size", __func__);
1941	memcpy(&child_state.outgoing, p, sizeof(child_state.outgoing));
1942	free(p);
1943
1944	p = buffer_get_string(&m, &plen);
1945	if (plen != sizeof(child_state.incoming))
1946		fatal("%s: bad request size", __func__);
1947	memcpy(&child_state.incoming, p, sizeof(child_state.incoming));
1948	free(p);
1949
1950	/* Network I/O buffers */
1951	debug3("%s: Getting Network I/O buffers", __func__);
1952	child_state.input = buffer_get_string(&m, &child_state.ilen);
1953	child_state.output = buffer_get_string(&m, &child_state.olen);
1954
1955	/* Roaming */
1956	if (compat20) {
1957		child_state.sent_bytes = buffer_get_int64(&m);
1958		child_state.recv_bytes = buffer_get_int64(&m);
1959	}
1960
1961	buffer_free(&m);
1962}
1963
1964
1965/* Allocation functions for zlib */
1966void *
1967mm_zalloc(struct mm_master *mm, u_int ncount, u_int size)
1968{
1969	size_t len = (size_t) size * ncount;
1970	void *address;
1971
1972	if (len == 0 || ncount > SIZE_T_MAX / size)
1973		fatal("%s: mm_zalloc(%u, %u)", __func__, ncount, size);
1974
1975	address = mm_malloc(mm, len);
1976
1977	return (address);
1978}
1979
1980void
1981mm_zfree(struct mm_master *mm, void *address)
1982{
1983	mm_free(mm, address);
1984}
1985
1986void
1987mm_init_compression(struct mm_master *mm)
1988{
1989	outgoing_stream.zalloc = (alloc_func)mm_zalloc;
1990	outgoing_stream.zfree = (free_func)mm_zfree;
1991	outgoing_stream.opaque = mm;
1992
1993	incoming_stream.zalloc = (alloc_func)mm_zalloc;
1994	incoming_stream.zfree = (free_func)mm_zfree;
1995	incoming_stream.opaque = mm;
1996}
1997
1998/* XXX */
1999
2000#define FD_CLOSEONEXEC(x) do { \
2001	if (fcntl(x, F_SETFD, FD_CLOEXEC) == -1) \
2002		fatal("fcntl(%d, F_SETFD)", x); \
2003} while (0)
2004
2005static void
2006monitor_openfds(struct monitor *mon, int do_logfds)
2007{
2008	int pair[2];
2009
2010	if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
2011		fatal("%s: socketpair: %s", __func__, strerror(errno));
2012	FD_CLOSEONEXEC(pair[0]);
2013	FD_CLOSEONEXEC(pair[1]);
2014	mon->m_recvfd = pair[0];
2015	mon->m_sendfd = pair[1];
2016
2017	if (do_logfds) {
2018		if (pipe(pair) == -1)
2019			fatal("%s: pipe: %s", __func__, strerror(errno));
2020		FD_CLOSEONEXEC(pair[0]);
2021		FD_CLOSEONEXEC(pair[1]);
2022		mon->m_log_recvfd = pair[0];
2023		mon->m_log_sendfd = pair[1];
2024	} else
2025		mon->m_log_recvfd = mon->m_log_sendfd = -1;
2026}
2027
2028#define MM_MEMSIZE	65536
2029
2030struct monitor *
2031monitor_init(void)
2032{
2033	struct monitor *mon;
2034
2035	mon = xcalloc(1, sizeof(*mon));
2036
2037	monitor_openfds(mon, 1);
2038
2039	/* Used to share zlib space across processes */
2040	if (options.compression) {
2041		mon->m_zback = mm_create(NULL, MM_MEMSIZE);
2042		mon->m_zlib = mm_create(mon->m_zback, 20 * MM_MEMSIZE);
2043
2044		/* Compression needs to share state across borders */
2045		mm_init_compression(mon->m_zlib);
2046	}
2047
2048	return mon;
2049}
2050
2051void
2052monitor_reinit(struct monitor *mon)
2053{
2054	monitor_openfds(mon, 0);
2055}
2056
2057#ifdef GSSAPI
2058int
2059mm_answer_gss_setup_ctx(int sock, Buffer *m)
2060{
2061	gss_OID_desc goid;
2062	OM_uint32 major;
2063	u_int len;
2064
2065	goid.elements = buffer_get_string(m, &len);
2066	goid.length = len;
2067
2068	major = ssh_gssapi_server_ctx(&gsscontext, &goid);
2069
2070	free(goid.elements);
2071
2072	buffer_clear(m);
2073	buffer_put_int(m, major);
2074
2075	mm_request_send(sock, MONITOR_ANS_GSSSETUP, m);
2076
2077	/* Now we have a context, enable the step */
2078	monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 1);
2079
2080	return (0);
2081}
2082
2083int
2084mm_answer_gss_accept_ctx(int sock, Buffer *m)
2085{
2086	gss_buffer_desc in;
2087	gss_buffer_desc out = GSS_C_EMPTY_BUFFER;
2088	OM_uint32 major, minor;
2089	OM_uint32 flags = 0; /* GSI needs this */
2090	u_int len;
2091
2092	in.value = buffer_get_string(m, &len);
2093	in.length = len;
2094	major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags);
2095	free(in.value);
2096
2097	buffer_clear(m);
2098	buffer_put_int(m, major);
2099	buffer_put_string(m, out.value, out.length);
2100	buffer_put_int(m, flags);
2101	mm_request_send(sock, MONITOR_ANS_GSSSTEP, m);
2102
2103	gss_release_buffer(&minor, &out);
2104
2105	if (major == GSS_S_COMPLETE) {
2106		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
2107		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
2108		monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
2109	}
2110	return (0);
2111}
2112
2113int
2114mm_answer_gss_checkmic(int sock, Buffer *m)
2115{
2116	gss_buffer_desc gssbuf, mic;
2117	OM_uint32 ret;
2118	u_int len;
2119
2120	gssbuf.value = buffer_get_string(m, &len);
2121	gssbuf.length = len;
2122	mic.value = buffer_get_string(m, &len);
2123	mic.length = len;
2124
2125	ret = ssh_gssapi_checkmic(gsscontext, &gssbuf, &mic);
2126
2127	free(gssbuf.value);
2128	free(mic.value);
2129
2130	buffer_clear(m);
2131	buffer_put_int(m, ret);
2132
2133	mm_request_send(sock, MONITOR_ANS_GSSCHECKMIC, m);
2134
2135	if (!GSS_ERROR(ret))
2136		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
2137
2138	return (0);
2139}
2140
2141int
2142mm_answer_gss_userok(int sock, Buffer *m)
2143{
2144	int authenticated;
2145
2146	authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user);
2147
2148	buffer_clear(m);
2149	buffer_put_int(m, authenticated);
2150
2151	debug3("%s: sending result %d", __func__, authenticated);
2152	mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m);
2153
2154	auth_method = "gssapi-with-mic";
2155
2156	/* Monitor loop will terminate if authenticated */
2157	return (authenticated);
2158}
2159#endif /* GSSAPI */
2160
2161#ifdef JPAKE
2162int
2163mm_answer_jpake_step1(int sock, Buffer *m)
2164{
2165	struct jpake_ctx *pctx;
2166	u_char *x3_proof, *x4_proof;
2167	u_int x3_proof_len, x4_proof_len;
2168
2169	if (!options.zero_knowledge_password_authentication)
2170		fatal("zero_knowledge_password_authentication disabled");
2171
2172	if (authctxt->jpake_ctx != NULL)
2173		fatal("%s: authctxt->jpake_ctx already set (%p)",
2174		    __func__, authctxt->jpake_ctx);
2175	authctxt->jpake_ctx = pctx = jpake_new();
2176
2177	jpake_step1(pctx->grp,
2178	    &pctx->server_id, &pctx->server_id_len,
2179	    &pctx->x3, &pctx->x4, &pctx->g_x3, &pctx->g_x4,
2180	    &x3_proof, &x3_proof_len,
2181	    &x4_proof, &x4_proof_len);
2182
2183	JPAKE_DEBUG_CTX((pctx, "step1 done in %s", __func__));
2184
2185	buffer_clear(m);
2186
2187	buffer_put_string(m, pctx->server_id, pctx->server_id_len);
2188	buffer_put_bignum2(m, pctx->g_x3);
2189	buffer_put_bignum2(m, pctx->g_x4);
2190	buffer_put_string(m, x3_proof, x3_proof_len);
2191	buffer_put_string(m, x4_proof, x4_proof_len);
2192
2193	debug3("%s: sending step1", __func__);
2194	mm_request_send(sock, MONITOR_ANS_JPAKE_STEP1, m);
2195
2196	bzero(x3_proof, x3_proof_len);
2197	bzero(x4_proof, x4_proof_len);
2198	free(x3_proof);
2199	free(x4_proof);
2200
2201	monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_GET_PWDATA, 1);
2202	monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_STEP1, 0);
2203
2204	return 0;
2205}
2206
2207int
2208mm_answer_jpake_get_pwdata(int sock, Buffer *m)
2209{
2210	struct jpake_ctx *pctx = authctxt->jpake_ctx;
2211	char *hash_scheme, *salt;
2212
2213	if (pctx == NULL)
2214		fatal("%s: pctx == NULL", __func__);
2215
2216	auth2_jpake_get_pwdata(authctxt, &pctx->s, &hash_scheme, &salt);
2217
2218	buffer_clear(m);
2219	/* pctx->s is sensitive, not returned to slave */
2220	buffer_put_cstring(m, hash_scheme);
2221	buffer_put_cstring(m, salt);
2222
2223	debug3("%s: sending pwdata", __func__);
2224	mm_request_send(sock, MONITOR_ANS_JPAKE_GET_PWDATA, m);
2225
2226	bzero(hash_scheme, strlen(hash_scheme));
2227	bzero(salt, strlen(salt));
2228	free(hash_scheme);
2229	free(salt);
2230
2231	monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_STEP2, 1);
2232
2233	return 0;
2234}
2235
2236int
2237mm_answer_jpake_step2(int sock, Buffer *m)
2238{
2239	struct jpake_ctx *pctx = authctxt->jpake_ctx;
2240	u_char *x1_proof, *x2_proof, *x4_s_proof;
2241	u_int x1_proof_len, x2_proof_len, x4_s_proof_len;
2242
2243	if (pctx == NULL)
2244		fatal("%s: pctx == NULL", __func__);
2245
2246	if ((pctx->g_x1 = BN_new()) == NULL ||
2247	    (pctx->g_x2 = BN_new()) == NULL)
2248		fatal("%s: BN_new", __func__);
2249	buffer_get_bignum2(m, pctx->g_x1);
2250	buffer_get_bignum2(m, pctx->g_x2);
2251	pctx->client_id = buffer_get_string(m, &pctx->client_id_len);
2252	x1_proof = buffer_get_string(m, &x1_proof_len);
2253	x2_proof = buffer_get_string(m, &x2_proof_len);
2254
2255	jpake_step2(pctx->grp, pctx->s, pctx->g_x3,
2256	    pctx->g_x1, pctx->g_x2, pctx->x4,
2257	    pctx->client_id, pctx->client_id_len,
2258	    pctx->server_id, pctx->server_id_len,
2259	    x1_proof, x1_proof_len,
2260	    x2_proof, x2_proof_len,
2261	    &pctx->b,
2262	    &x4_s_proof, &x4_s_proof_len);
2263
2264	JPAKE_DEBUG_CTX((pctx, "step2 done in %s", __func__));
2265
2266	bzero(x1_proof, x1_proof_len);
2267	bzero(x2_proof, x2_proof_len);
2268	free(x1_proof);
2269	free(x2_proof);
2270
2271	buffer_clear(m);
2272
2273	buffer_put_bignum2(m, pctx->b);
2274	buffer_put_string(m, x4_s_proof, x4_s_proof_len);
2275
2276	debug3("%s: sending step2", __func__);
2277	mm_request_send(sock, MONITOR_ANS_JPAKE_STEP2, m);
2278
2279	bzero(x4_s_proof, x4_s_proof_len);
2280	free(x4_s_proof);
2281
2282	monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_KEY_CONFIRM, 1);
2283
2284	return 0;
2285}
2286
2287int
2288mm_answer_jpake_key_confirm(int sock, Buffer *m)
2289{
2290	struct jpake_ctx *pctx = authctxt->jpake_ctx;
2291	u_char *x2_s_proof;
2292	u_int x2_s_proof_len;
2293
2294	if (pctx == NULL)
2295		fatal("%s: pctx == NULL", __func__);
2296
2297	if ((pctx->a = BN_new()) == NULL)
2298		fatal("%s: BN_new", __func__);
2299	buffer_get_bignum2(m, pctx->a);
2300	x2_s_proof = buffer_get_string(m, &x2_s_proof_len);
2301
2302	jpake_key_confirm(pctx->grp, pctx->s, pctx->a,
2303	    pctx->x4, pctx->g_x3, pctx->g_x4, pctx->g_x1, pctx->g_x2,
2304	    pctx->server_id, pctx->server_id_len,
2305	    pctx->client_id, pctx->client_id_len,
2306	    session_id2, session_id2_len,
2307	    x2_s_proof, x2_s_proof_len,
2308	    &pctx->k,
2309	    &pctx->h_k_sid_sessid, &pctx->h_k_sid_sessid_len);
2310
2311	JPAKE_DEBUG_CTX((pctx, "key_confirm done in %s", __func__));
2312
2313	bzero(x2_s_proof, x2_s_proof_len);
2314	buffer_clear(m);
2315
2316	/* pctx->k is sensitive, not sent */
2317	buffer_put_string(m, pctx->h_k_sid_sessid, pctx->h_k_sid_sessid_len);
2318
2319	debug3("%s: sending confirmation hash", __func__);
2320	mm_request_send(sock, MONITOR_ANS_JPAKE_KEY_CONFIRM, m);
2321
2322	monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_CHECK_CONFIRM, 1);
2323
2324	return 0;
2325}
2326
2327int
2328mm_answer_jpake_check_confirm(int sock, Buffer *m)
2329{
2330	int authenticated = 0;
2331	u_char *peer_confirm_hash;
2332	u_int peer_confirm_hash_len;
2333	struct jpake_ctx *pctx = authctxt->jpake_ctx;
2334
2335	if (pctx == NULL)
2336		fatal("%s: pctx == NULL", __func__);
2337
2338	peer_confirm_hash = buffer_get_string(m, &peer_confirm_hash_len);
2339
2340	authenticated = jpake_check_confirm(pctx->k,
2341	    pctx->client_id, pctx->client_id_len,
2342	    session_id2, session_id2_len,
2343	    peer_confirm_hash, peer_confirm_hash_len) && authctxt->valid;
2344
2345	JPAKE_DEBUG_CTX((pctx, "check_confirm done in %s", __func__));
2346
2347	bzero(peer_confirm_hash, peer_confirm_hash_len);
2348	free(peer_confirm_hash);
2349
2350	buffer_clear(m);
2351	buffer_put_int(m, authenticated);
2352
2353	debug3("%s: sending result %d", __func__, authenticated);
2354	mm_request_send(sock, MONITOR_ANS_JPAKE_CHECK_CONFIRM, m);
2355
2356	monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_STEP1, 1);
2357
2358	auth_method = "jpake-01@openssh.com";
2359	return authenticated;
2360}
2361
2362#endif /* JPAKE */
2363