]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssh/monitor.c
Import tzdata 2019c.
[FreeBSD/FreeBSD.git] / crypto / openssh / monitor.c
1 /* $OpenBSD: monitor.c,v 1.167 2017/02/03 23:05:57 djm Exp $ */
2 /*
3  * Copyright 2002 Niels Provos <provos@citi.umich.edu>
4  * Copyright 2002 Markus Friedl <markus@openbsd.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include "includes.h"
29
30 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include "openbsd-compat/sys-tree.h"
33 #include <sys/wait.h>
34
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <limits.h>
38 #ifdef HAVE_PATHS_H
39 #include <paths.h>
40 #endif
41 #include <pwd.h>
42 #include <signal.h>
43 #ifdef HAVE_STDINT_H
44 #include <stdint.h>
45 #endif
46 #include <stdlib.h>
47 #include <string.h>
48 #include <stdarg.h>
49 #include <stdio.h>
50 #include <unistd.h>
51 #ifdef HAVE_POLL_H
52 #include <poll.h>
53 #else
54 # ifdef HAVE_SYS_POLL_H
55 #  include <sys/poll.h>
56 # endif
57 #endif
58
59 #ifdef SKEY
60 #include <skey.h>
61 #endif
62
63 #ifdef WITH_OPENSSL
64 #include <openssl/dh.h>
65 #endif
66
67 #include "openbsd-compat/sys-queue.h"
68 #include "atomicio.h"
69 #include "xmalloc.h"
70 #include "ssh.h"
71 #include "key.h"
72 #include "buffer.h"
73 #include "hostfile.h"
74 #include "auth.h"
75 #include "cipher.h"
76 #include "kex.h"
77 #include "dh.h"
78 #include "auth-pam.h"
79 #ifdef TARGET_OS_MAC    /* XXX Broken krb5 headers on Mac */
80 #undef TARGET_OS_MAC
81 #include "zlib.h"
82 #define TARGET_OS_MAC 1
83 #else
84 #include "zlib.h"
85 #endif
86 #include "packet.h"
87 #include "auth-options.h"
88 #include "sshpty.h"
89 #include "channels.h"
90 #include "session.h"
91 #include "sshlogin.h"
92 #include "canohost.h"
93 #include "log.h"
94 #include "misc.h"
95 #include "servconf.h"
96 #include "monitor.h"
97 #ifdef GSSAPI
98 #include "ssh-gss.h"
99 #endif
100 #include "monitor_wrap.h"
101 #include "monitor_fdpass.h"
102 #include "compat.h"
103 #include "ssh2.h"
104 #include "authfd.h"
105 #include "match.h"
106 #include "ssherr.h"
107
108 #ifdef GSSAPI
109 static Gssctxt *gsscontext = NULL;
110 #endif
111
112 /* Imports */
113 extern ServerOptions options;
114 extern u_int utmp_len;
115 extern u_char session_id[];
116 extern Buffer auth_debug;
117 extern int auth_debug_init;
118 extern Buffer loginmsg;
119
120 /* State exported from the child */
121 static struct sshbuf *child_state;
122
123 /* Functions on the monitor that answer unprivileged requests */
124
125 int mm_answer_moduli(int, Buffer *);
126 int mm_answer_sign(int, Buffer *);
127 int mm_answer_pwnamallow(int, Buffer *);
128 int mm_answer_auth2_read_banner(int, Buffer *);
129 int mm_answer_authserv(int, Buffer *);
130 int mm_answer_authpassword(int, Buffer *);
131 int mm_answer_bsdauthquery(int, Buffer *);
132 int mm_answer_bsdauthrespond(int, Buffer *);
133 int mm_answer_skeyquery(int, Buffer *);
134 int mm_answer_skeyrespond(int, Buffer *);
135 int mm_answer_keyallowed(int, Buffer *);
136 int mm_answer_keyverify(int, Buffer *);
137 int mm_answer_pty(int, Buffer *);
138 int mm_answer_pty_cleanup(int, Buffer *);
139 int mm_answer_term(int, Buffer *);
140 int mm_answer_rsa_keyallowed(int, Buffer *);
141 int mm_answer_rsa_challenge(int, Buffer *);
142 int mm_answer_rsa_response(int, Buffer *);
143 int mm_answer_sesskey(int, Buffer *);
144 int mm_answer_sessid(int, Buffer *);
145
146 #ifdef USE_PAM
147 int mm_answer_pam_start(int, Buffer *);
148 int mm_answer_pam_account(int, Buffer *);
149 int mm_answer_pam_init_ctx(int, Buffer *);
150 int mm_answer_pam_query(int, Buffer *);
151 int mm_answer_pam_respond(int, Buffer *);
152 int mm_answer_pam_free_ctx(int, Buffer *);
153 #endif
154
155 #ifdef GSSAPI
156 int mm_answer_gss_setup_ctx(int, Buffer *);
157 int mm_answer_gss_accept_ctx(int, Buffer *);
158 int mm_answer_gss_userok(int, Buffer *);
159 int mm_answer_gss_checkmic(int, Buffer *);
160 #endif
161
162 #ifdef SSH_AUDIT_EVENTS
163 int mm_answer_audit_event(int, Buffer *);
164 int mm_answer_audit_command(int, Buffer *);
165 #endif
166
167 static int monitor_read_log(struct monitor *);
168
169 static Authctxt *authctxt;
170
171 /* local state for key verify */
172 static u_char *key_blob = NULL;
173 static u_int key_bloblen = 0;
174 static int key_blobtype = MM_NOKEY;
175 static char *hostbased_cuser = NULL;
176 static char *hostbased_chost = NULL;
177 static char *auth_method = "unknown";
178 static char *auth_submethod = NULL;
179 static u_int session_id2_len = 0;
180 static u_char *session_id2 = NULL;
181 static pid_t monitor_child_pid;
182
183 struct mon_table {
184         enum monitor_reqtype type;
185         int flags;
186         int (*f)(int, Buffer *);
187 };
188
189 #define MON_ISAUTH      0x0004  /* Required for Authentication */
190 #define MON_AUTHDECIDE  0x0008  /* Decides Authentication */
191 #define MON_ONCE        0x0010  /* Disable after calling */
192 #define MON_ALOG        0x0020  /* Log auth attempt without authenticating */
193
194 #define MON_AUTH        (MON_ISAUTH|MON_AUTHDECIDE)
195
196 #define MON_PERMIT      0x1000  /* Request is permitted */
197
198 struct mon_table mon_dispatch_proto20[] = {
199 #ifdef WITH_OPENSSL
200     {MONITOR_REQ_MODULI, MON_ONCE, mm_answer_moduli},
201 #endif
202     {MONITOR_REQ_SIGN, MON_ONCE, mm_answer_sign},
203     {MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow},
204     {MONITOR_REQ_AUTHSERV, MON_ONCE, mm_answer_authserv},
205     {MONITOR_REQ_AUTH2_READ_BANNER, MON_ONCE, mm_answer_auth2_read_banner},
206     {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
207 #ifdef USE_PAM
208     {MONITOR_REQ_PAM_START, MON_ONCE, mm_answer_pam_start},
209     {MONITOR_REQ_PAM_ACCOUNT, 0, mm_answer_pam_account},
210     {MONITOR_REQ_PAM_INIT_CTX, MON_ONCE, mm_answer_pam_init_ctx},
211     {MONITOR_REQ_PAM_QUERY, 0, mm_answer_pam_query},
212     {MONITOR_REQ_PAM_RESPOND, MON_ONCE, mm_answer_pam_respond},
213     {MONITOR_REQ_PAM_FREE_CTX, MON_ONCE|MON_AUTHDECIDE, mm_answer_pam_free_ctx},
214 #endif
215 #ifdef SSH_AUDIT_EVENTS
216     {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
217 #endif
218 #ifdef BSD_AUTH
219     {MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery},
220     {MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond},
221 #endif
222 #ifdef SKEY
223     {MONITOR_REQ_SKEYQUERY, MON_ISAUTH, mm_answer_skeyquery},
224     {MONITOR_REQ_SKEYRESPOND, MON_AUTH, mm_answer_skeyrespond},
225 #endif
226     {MONITOR_REQ_KEYALLOWED, MON_ISAUTH, mm_answer_keyallowed},
227     {MONITOR_REQ_KEYVERIFY, MON_AUTH, mm_answer_keyverify},
228 #ifdef GSSAPI
229     {MONITOR_REQ_GSSSETUP, MON_ISAUTH, mm_answer_gss_setup_ctx},
230     {MONITOR_REQ_GSSSTEP, 0, mm_answer_gss_accept_ctx},
231     {MONITOR_REQ_GSSUSEROK, MON_ONCE|MON_AUTHDECIDE, mm_answer_gss_userok},
232     {MONITOR_REQ_GSSCHECKMIC, MON_ONCE, mm_answer_gss_checkmic},
233 #endif
234     {0, 0, NULL}
235 };
236
237 struct mon_table mon_dispatch_postauth20[] = {
238 #ifdef WITH_OPENSSL
239     {MONITOR_REQ_MODULI, 0, mm_answer_moduli},
240 #endif
241     {MONITOR_REQ_SIGN, 0, mm_answer_sign},
242     {MONITOR_REQ_PTY, 0, mm_answer_pty},
243     {MONITOR_REQ_PTYCLEANUP, 0, mm_answer_pty_cleanup},
244     {MONITOR_REQ_TERM, 0, mm_answer_term},
245 #ifdef SSH_AUDIT_EVENTS
246     {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
247     {MONITOR_REQ_AUDIT_COMMAND, MON_PERMIT, mm_answer_audit_command},
248 #endif
249     {0, 0, NULL}
250 };
251
252 struct mon_table *mon_dispatch;
253
254 /* Specifies if a certain message is allowed at the moment */
255
256 static void
257 monitor_permit(struct mon_table *ent, enum monitor_reqtype type, int permit)
258 {
259         while (ent->f != NULL) {
260                 if (ent->type == type) {
261                         ent->flags &= ~MON_PERMIT;
262                         ent->flags |= permit ? MON_PERMIT : 0;
263                         return;
264                 }
265                 ent++;
266         }
267 }
268
269 static void
270 monitor_permit_authentications(int permit)
271 {
272         struct mon_table *ent = mon_dispatch;
273
274         while (ent->f != NULL) {
275                 if (ent->flags & MON_AUTH) {
276                         ent->flags &= ~MON_PERMIT;
277                         ent->flags |= permit ? MON_PERMIT : 0;
278                 }
279                 ent++;
280         }
281 }
282
283 void
284 monitor_child_preauth(Authctxt *_authctxt, struct monitor *pmonitor)
285 {
286         struct ssh *ssh = active_state; /* XXX */
287         struct mon_table *ent;
288         int authenticated = 0, partial = 0;
289
290         debug3("preauth child monitor started");
291
292         close(pmonitor->m_recvfd);
293         close(pmonitor->m_log_sendfd);
294         pmonitor->m_log_sendfd = pmonitor->m_recvfd = -1;
295
296         authctxt = _authctxt;
297         memset(authctxt, 0, sizeof(*authctxt));
298
299         authctxt->loginmsg = &loginmsg;
300
301         mon_dispatch = mon_dispatch_proto20;
302         /* Permit requests for moduli and signatures */
303         monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
304         monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
305
306         /* The first few requests do not require asynchronous access */
307         while (!authenticated) {
308                 partial = 0;
309                 auth_method = "unknown";
310                 auth_submethod = NULL;
311                 authenticated = (monitor_read(pmonitor, mon_dispatch, &ent) == 1);
312
313                 /* Special handling for multiple required authentications */
314                 if (options.num_auth_methods != 0) {
315                         if (authenticated &&
316                             !auth2_update_methods_lists(authctxt,
317                             auth_method, auth_submethod)) {
318                                 debug3("%s: method %s: partial", __func__,
319                                     auth_method);
320                                 authenticated = 0;
321                                 partial = 1;
322                         }
323                 }
324
325                 if (authenticated) {
326                         if (!(ent->flags & MON_AUTHDECIDE))
327                                 fatal("%s: unexpected authentication from %d",
328                                     __func__, ent->type);
329                         if (authctxt->pw->pw_uid == 0 &&
330                             !auth_root_allowed(auth_method))
331                                 authenticated = 0;
332 #ifdef USE_PAM
333                         /* PAM needs to perform account checks after auth */
334                         if (options.use_pam && authenticated) {
335                                 Buffer m;
336
337                                 buffer_init(&m);
338                                 mm_request_receive_expect(pmonitor->m_sendfd,
339                                     MONITOR_REQ_PAM_ACCOUNT, &m);
340                                 authenticated = mm_answer_pam_account(pmonitor->m_sendfd, &m);
341                                 buffer_free(&m);
342                         }
343 #endif
344                 }
345                 if (ent->flags & (MON_AUTHDECIDE|MON_ALOG)) {
346                         auth_log(authctxt, authenticated, partial,
347                             auth_method, auth_submethod);
348                         if (!partial && !authenticated)
349                                 authctxt->failures++;
350                 }
351         }
352
353         if (!authctxt->valid)
354                 fatal("%s: authenticated invalid user", __func__);
355         if (strcmp(auth_method, "unknown") == 0)
356                 fatal("%s: authentication method name unknown", __func__);
357
358         debug("%s: %s has been authenticated by privileged process",
359             __func__, authctxt->user);
360         ssh_packet_set_log_preamble(ssh, "user %s", authctxt->user);
361
362         mm_get_keystate(pmonitor);
363
364         /* Drain any buffered messages from the child */
365         while (pmonitor->m_log_recvfd != -1 && monitor_read_log(pmonitor) == 0)
366                 ;
367
368         close(pmonitor->m_sendfd);
369         close(pmonitor->m_log_recvfd);
370         pmonitor->m_sendfd = pmonitor->m_log_recvfd = -1;
371 }
372
373 static void
374 monitor_set_child_handler(pid_t pid)
375 {
376         monitor_child_pid = pid;
377 }
378
379 static void
380 monitor_child_handler(int sig)
381 {
382         kill(monitor_child_pid, sig);
383 }
384
385 void
386 monitor_child_postauth(struct monitor *pmonitor)
387 {
388         close(pmonitor->m_recvfd);
389         pmonitor->m_recvfd = -1;
390
391         monitor_set_child_handler(pmonitor->m_pid);
392         signal(SIGHUP, &monitor_child_handler);
393         signal(SIGTERM, &monitor_child_handler);
394         signal(SIGINT, &monitor_child_handler);
395 #ifdef SIGXFSZ
396         signal(SIGXFSZ, SIG_IGN);
397 #endif
398
399         mon_dispatch = mon_dispatch_postauth20;
400
401         /* Permit requests for moduli and signatures */
402         monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
403         monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
404         monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
405
406         if (!no_pty_flag) {
407                 monitor_permit(mon_dispatch, MONITOR_REQ_PTY, 1);
408                 monitor_permit(mon_dispatch, MONITOR_REQ_PTYCLEANUP, 1);
409         }
410
411         for (;;)
412                 monitor_read(pmonitor, mon_dispatch, NULL);
413 }
414
415 static int
416 monitor_read_log(struct monitor *pmonitor)
417 {
418         Buffer logmsg;
419         u_int len, level;
420         char *msg;
421
422         buffer_init(&logmsg);
423
424         /* Read length */
425         buffer_append_space(&logmsg, 4);
426         if (atomicio(read, pmonitor->m_log_recvfd,
427             buffer_ptr(&logmsg), buffer_len(&logmsg)) != buffer_len(&logmsg)) {
428                 if (errno == EPIPE) {
429                         buffer_free(&logmsg);
430                         debug("%s: child log fd closed", __func__);
431                         close(pmonitor->m_log_recvfd);
432                         pmonitor->m_log_recvfd = -1;
433                         return -1;
434                 }
435                 fatal("%s: log fd read: %s", __func__, strerror(errno));
436         }
437         len = buffer_get_int(&logmsg);
438         if (len <= 4 || len > 8192)
439                 fatal("%s: invalid log message length %u", __func__, len);
440
441         /* Read severity, message */
442         buffer_clear(&logmsg);
443         buffer_append_space(&logmsg, len);
444         if (atomicio(read, pmonitor->m_log_recvfd,
445             buffer_ptr(&logmsg), buffer_len(&logmsg)) != buffer_len(&logmsg))
446                 fatal("%s: log fd read: %s", __func__, strerror(errno));
447
448         /* Log it */
449         level = buffer_get_int(&logmsg);
450         msg = buffer_get_string(&logmsg, NULL);
451         if (log_level_name(level) == NULL)
452                 fatal("%s: invalid log level %u (corrupted message?)",
453                     __func__, level);
454         do_log2(level, "%s [preauth]", msg);
455
456         buffer_free(&logmsg);
457         free(msg);
458
459         return 0;
460 }
461
462 int
463 monitor_read(struct monitor *pmonitor, struct mon_table *ent,
464     struct mon_table **pent)
465 {
466         Buffer m;
467         int ret;
468         u_char type;
469         struct pollfd pfd[2];
470
471         for (;;) {
472                 memset(&pfd, 0, sizeof(pfd));
473                 pfd[0].fd = pmonitor->m_sendfd;
474                 pfd[0].events = POLLIN;
475                 pfd[1].fd = pmonitor->m_log_recvfd;
476                 pfd[1].events = pfd[1].fd == -1 ? 0 : POLLIN;
477                 if (poll(pfd, pfd[1].fd == -1 ? 1 : 2, -1) == -1) {
478                         if (errno == EINTR || errno == EAGAIN)
479                                 continue;
480                         fatal("%s: poll: %s", __func__, strerror(errno));
481                 }
482                 if (pfd[1].revents) {
483                         /*
484                          * Drain all log messages before processing next
485                          * monitor request.
486                          */
487                         monitor_read_log(pmonitor);
488                         continue;
489                 }
490                 if (pfd[0].revents)
491                         break;  /* Continues below */
492         }
493
494         buffer_init(&m);
495
496         mm_request_receive(pmonitor->m_sendfd, &m);
497         type = buffer_get_char(&m);
498
499         debug3("%s: checking request %d", __func__, type);
500
501         while (ent->f != NULL) {
502                 if (ent->type == type)
503                         break;
504                 ent++;
505         }
506
507         if (ent->f != NULL) {
508                 if (!(ent->flags & MON_PERMIT))
509                         fatal("%s: unpermitted request %d", __func__,
510                             type);
511                 ret = (*ent->f)(pmonitor->m_sendfd, &m);
512                 buffer_free(&m);
513
514                 /* The child may use this request only once, disable it */
515                 if (ent->flags & MON_ONCE) {
516                         debug2("%s: %d used once, disabling now", __func__,
517                             type);
518                         ent->flags &= ~MON_PERMIT;
519                 }
520
521                 if (pent != NULL)
522                         *pent = ent;
523
524                 return ret;
525         }
526
527         fatal("%s: unsupported request: %d", __func__, type);
528
529         /* NOTREACHED */
530         return (-1);
531 }
532
533 /* allowed key state */
534 static int
535 monitor_allowed_key(u_char *blob, u_int bloblen)
536 {
537         /* make sure key is allowed */
538         if (key_blob == NULL || key_bloblen != bloblen ||
539             timingsafe_bcmp(key_blob, blob, key_bloblen))
540                 return (0);
541         return (1);
542 }
543
544 static void
545 monitor_reset_key_state(void)
546 {
547         /* reset state */
548         free(key_blob);
549         free(hostbased_cuser);
550         free(hostbased_chost);
551         key_blob = NULL;
552         key_bloblen = 0;
553         key_blobtype = MM_NOKEY;
554         hostbased_cuser = NULL;
555         hostbased_chost = NULL;
556 }
557
558 #ifdef WITH_OPENSSL
559 int
560 mm_answer_moduli(int sock, Buffer *m)
561 {
562         DH *dh;
563         int min, want, max;
564
565         min = buffer_get_int(m);
566         want = buffer_get_int(m);
567         max = buffer_get_int(m);
568
569         debug3("%s: got parameters: %d %d %d",
570             __func__, min, want, max);
571         /* We need to check here, too, in case the child got corrupted */
572         if (max < min || want < min || max < want)
573                 fatal("%s: bad parameters: %d %d %d",
574                     __func__, min, want, max);
575
576         buffer_clear(m);
577
578         dh = choose_dh(min, want, max);
579         if (dh == NULL) {
580                 buffer_put_char(m, 0);
581                 return (0);
582         } else {
583                 /* Send first bignum */
584                 buffer_put_char(m, 1);
585                 buffer_put_bignum2(m, dh->p);
586                 buffer_put_bignum2(m, dh->g);
587
588                 DH_free(dh);
589         }
590         mm_request_send(sock, MONITOR_ANS_MODULI, m);
591         return (0);
592 }
593 #endif
594
595 int
596 mm_answer_sign(int sock, Buffer *m)
597 {
598         struct ssh *ssh = active_state;         /* XXX */
599         extern int auth_sock;                   /* XXX move to state struct? */
600         struct sshkey *key;
601         struct sshbuf *sigbuf = NULL;
602         u_char *p = NULL, *signature = NULL;
603         char *alg = NULL;
604         size_t datlen, siglen, alglen;
605         int r, is_proof = 0;
606         u_int keyid;
607         const char proof_req[] = "hostkeys-prove-00@openssh.com";
608
609         debug3("%s", __func__);
610
611         if ((r = sshbuf_get_u32(m, &keyid)) != 0 ||
612             (r = sshbuf_get_string(m, &p, &datlen)) != 0 ||
613             (r = sshbuf_get_cstring(m, &alg, &alglen)) != 0)
614                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
615         if (keyid > INT_MAX)
616                 fatal("%s: invalid key ID", __func__);
617
618         /*
619          * Supported KEX types use SHA1 (20 bytes), SHA256 (32 bytes),
620          * SHA384 (48 bytes) and SHA512 (64 bytes).
621          *
622          * Otherwise, verify the signature request is for a hostkey
623          * proof.
624          *
625          * XXX perform similar check for KEX signature requests too?
626          * it's not trivial, since what is signed is the hash, rather
627          * than the full kex structure...
628          */
629         if (datlen != 20 && datlen != 32 && datlen != 48 && datlen != 64) {
630                 /*
631                  * Construct expected hostkey proof and compare it to what
632                  * the client sent us.
633                  */
634                 if (session_id2_len == 0) /* hostkeys is never first */
635                         fatal("%s: bad data length: %zu", __func__, datlen);
636                 if ((key = get_hostkey_public_by_index(keyid, ssh)) == NULL)
637                         fatal("%s: no hostkey for index %d", __func__, keyid);
638                 if ((sigbuf = sshbuf_new()) == NULL)
639                         fatal("%s: sshbuf_new", __func__);
640                 if ((r = sshbuf_put_cstring(sigbuf, proof_req)) != 0 ||
641                     (r = sshbuf_put_string(sigbuf, session_id2,
642                     session_id2_len)) != 0 ||
643                     (r = sshkey_puts(key, sigbuf)) != 0)
644                         fatal("%s: couldn't prepare private key "
645                             "proof buffer: %s", __func__, ssh_err(r));
646                 if (datlen != sshbuf_len(sigbuf) ||
647                     memcmp(p, sshbuf_ptr(sigbuf), sshbuf_len(sigbuf)) != 0)
648                         fatal("%s: bad data length: %zu, hostkey proof len %zu",
649                             __func__, datlen, sshbuf_len(sigbuf));
650                 sshbuf_free(sigbuf);
651                 is_proof = 1;
652         }
653
654         /* save session id, it will be passed on the first call */
655         if (session_id2_len == 0) {
656                 session_id2_len = datlen;
657                 session_id2 = xmalloc(session_id2_len);
658                 memcpy(session_id2, p, session_id2_len);
659         }
660
661         if ((key = get_hostkey_by_index(keyid)) != NULL) {
662                 if ((r = sshkey_sign(key, &signature, &siglen, p, datlen, alg,
663                     datafellows)) != 0)
664                         fatal("%s: sshkey_sign failed: %s",
665                             __func__, ssh_err(r));
666         } else if ((key = get_hostkey_public_by_index(keyid, ssh)) != NULL &&
667             auth_sock > 0) {
668                 if ((r = ssh_agent_sign(auth_sock, key, &signature, &siglen,
669                     p, datlen, alg, datafellows)) != 0) {
670                         fatal("%s: ssh_agent_sign failed: %s",
671                             __func__, ssh_err(r));
672                 }
673         } else
674                 fatal("%s: no hostkey from index %d", __func__, keyid);
675
676         debug3("%s: %s signature %p(%zu)", __func__,
677             is_proof ? "KEX" : "hostkey proof", signature, siglen);
678
679         sshbuf_reset(m);
680         if ((r = sshbuf_put_string(m, signature, siglen)) != 0)
681                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
682
683         free(alg);
684         free(p);
685         free(signature);
686
687         mm_request_send(sock, MONITOR_ANS_SIGN, m);
688
689         /* Turn on permissions for getpwnam */
690         monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
691
692         return (0);
693 }
694
695 /* Retrieves the password entry and also checks if the user is permitted */
696
697 int
698 mm_answer_pwnamallow(int sock, Buffer *m)
699 {
700         struct ssh *ssh = active_state; /* XXX */
701         char *username;
702         struct passwd *pwent;
703         int allowed = 0;
704         u_int i;
705
706         debug3("%s", __func__);
707
708         if (authctxt->attempt++ != 0)
709                 fatal("%s: multiple attempts for getpwnam", __func__);
710
711         username = buffer_get_string(m, NULL);
712
713         pwent = getpwnamallow(username);
714
715         authctxt->user = xstrdup(username);
716         setproctitle("%s [priv]", pwent ? username : "unknown");
717         free(username);
718
719         buffer_clear(m);
720
721         if (pwent == NULL) {
722                 buffer_put_char(m, 0);
723                 authctxt->pw = fakepw();
724                 goto out;
725         }
726
727         allowed = 1;
728         authctxt->pw = pwent;
729         authctxt->valid = 1;
730
731         buffer_put_char(m, 1);
732         buffer_put_string(m, pwent, sizeof(struct passwd));
733         buffer_put_cstring(m, pwent->pw_name);
734         buffer_put_cstring(m, "*");
735 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
736         buffer_put_cstring(m, pwent->pw_gecos);
737 #endif
738 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
739         buffer_put_cstring(m, pwent->pw_class);
740 #endif
741         buffer_put_cstring(m, pwent->pw_dir);
742         buffer_put_cstring(m, pwent->pw_shell);
743
744  out:
745         ssh_packet_set_log_preamble(ssh, "%suser %s",
746             authctxt->valid ? "authenticating" : "invalid ", authctxt->user);
747         buffer_put_string(m, &options, sizeof(options));
748
749 #define M_CP_STROPT(x) do { \
750                 if (options.x != NULL) \
751                         buffer_put_cstring(m, options.x); \
752         } while (0)
753 #define M_CP_STRARRAYOPT(x, nx) do { \
754                 for (i = 0; i < options.nx; i++) \
755                         buffer_put_cstring(m, options.x[i]); \
756         } while (0)
757         /* See comment in servconf.h */
758         COPY_MATCH_STRING_OPTS();
759 #undef M_CP_STROPT
760 #undef M_CP_STRARRAYOPT
761
762         /* Create valid auth method lists */
763         if (auth2_setup_methods_lists(authctxt) != 0) {
764                 /*
765                  * The monitor will continue long enough to let the child
766                  * run to it's packet_disconnect(), but it must not allow any
767                  * authentication to succeed.
768                  */
769                 debug("%s: no valid authentication method lists", __func__);
770         }
771
772         debug3("%s: sending MONITOR_ANS_PWNAM: %d", __func__, allowed);
773         mm_request_send(sock, MONITOR_ANS_PWNAM, m);
774
775         /* Allow service/style information on the auth context */
776         monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
777         monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
778
779 #ifdef USE_PAM
780         if (options.use_pam)
781                 monitor_permit(mon_dispatch, MONITOR_REQ_PAM_START, 1);
782 #endif
783
784         return (0);
785 }
786
787 int mm_answer_auth2_read_banner(int sock, Buffer *m)
788 {
789         char *banner;
790
791         buffer_clear(m);
792         banner = auth2_read_banner();
793         buffer_put_cstring(m, banner != NULL ? banner : "");
794         mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m);
795         free(banner);
796
797         return (0);
798 }
799
800 int
801 mm_answer_authserv(int sock, Buffer *m)
802 {
803         monitor_permit_authentications(1);
804
805         authctxt->service = buffer_get_string(m, NULL);
806         authctxt->style = buffer_get_string(m, NULL);
807         debug3("%s: service=%s, style=%s",
808             __func__, authctxt->service, authctxt->style);
809
810         if (strlen(authctxt->style) == 0) {
811                 free(authctxt->style);
812                 authctxt->style = NULL;
813         }
814
815         return (0);
816 }
817
818 int
819 mm_answer_authpassword(int sock, Buffer *m)
820 {
821         static int call_count;
822         char *passwd;
823         int authenticated;
824         u_int plen;
825
826         if (!options.password_authentication)
827                 fatal("%s: password authentication not enabled", __func__);
828         passwd = buffer_get_string(m, &plen);
829         /* Only authenticate if the context is valid */
830         authenticated = options.password_authentication &&
831             auth_password(authctxt, passwd);
832         explicit_bzero(passwd, strlen(passwd));
833         free(passwd);
834
835         buffer_clear(m);
836         buffer_put_int(m, authenticated);
837 #ifdef USE_PAM
838         buffer_put_int(m, sshpam_get_maxtries_reached());
839 #endif
840
841         debug3("%s: sending result %d", __func__, authenticated);
842         mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m);
843
844         call_count++;
845         if (plen == 0 && call_count == 1)
846                 auth_method = "none";
847         else
848                 auth_method = "password";
849
850         /* Causes monitor loop to terminate if authenticated */
851         return (authenticated);
852 }
853
854 #ifdef BSD_AUTH
855 int
856 mm_answer_bsdauthquery(int sock, Buffer *m)
857 {
858         char *name, *infotxt;
859         u_int numprompts;
860         u_int *echo_on;
861         char **prompts;
862         u_int success;
863
864         if (!options.kbd_interactive_authentication)
865                 fatal("%s: kbd-int authentication not enabled", __func__);
866         success = bsdauth_query(authctxt, &name, &infotxt, &numprompts,
867             &prompts, &echo_on) < 0 ? 0 : 1;
868
869         buffer_clear(m);
870         buffer_put_int(m, success);
871         if (success)
872                 buffer_put_cstring(m, prompts[0]);
873
874         debug3("%s: sending challenge success: %u", __func__, success);
875         mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m);
876
877         if (success) {
878                 free(name);
879                 free(infotxt);
880                 free(prompts);
881                 free(echo_on);
882         }
883
884         return (0);
885 }
886
887 int
888 mm_answer_bsdauthrespond(int sock, Buffer *m)
889 {
890         char *response;
891         int authok;
892
893         if (!options.kbd_interactive_authentication)
894                 fatal("%s: kbd-int authentication not enabled", __func__);
895         if (authctxt->as == NULL)
896                 fatal("%s: no bsd auth session", __func__);
897
898         response = buffer_get_string(m, NULL);
899         authok = options.challenge_response_authentication &&
900             auth_userresponse(authctxt->as, response, 0);
901         authctxt->as = NULL;
902         debug3("%s: <%s> = <%d>", __func__, response, authok);
903         free(response);
904
905         buffer_clear(m);
906         buffer_put_int(m, authok);
907
908         debug3("%s: sending authenticated: %d", __func__, authok);
909         mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m);
910
911         auth_method = "keyboard-interactive";
912         auth_submethod = "bsdauth";
913
914         return (authok != 0);
915 }
916 #endif
917
918 #ifdef SKEY
919 int
920 mm_answer_skeyquery(int sock, Buffer *m)
921 {
922         struct skey skey;
923         char challenge[1024];
924         u_int success;
925
926         success = _compat_skeychallenge(&skey, authctxt->user, challenge,
927             sizeof(challenge)) < 0 ? 0 : 1;
928
929         buffer_clear(m);
930         buffer_put_int(m, success);
931         if (success)
932                 buffer_put_cstring(m, challenge);
933
934         debug3("%s: sending challenge success: %u", __func__, success);
935         mm_request_send(sock, MONITOR_ANS_SKEYQUERY, m);
936
937         return (0);
938 }
939
940 int
941 mm_answer_skeyrespond(int sock, Buffer *m)
942 {
943         char *response;
944         int authok;
945
946         response = buffer_get_string(m, NULL);
947
948         authok = (options.challenge_response_authentication &&
949             authctxt->valid &&
950             skey_haskey(authctxt->pw->pw_name) == 0 &&
951             skey_passcheck(authctxt->pw->pw_name, response) != -1);
952
953         free(response);
954
955         buffer_clear(m);
956         buffer_put_int(m, authok);
957
958         debug3("%s: sending authenticated: %d", __func__, authok);
959         mm_request_send(sock, MONITOR_ANS_SKEYRESPOND, m);
960
961         auth_method = "keyboard-interactive";
962         auth_submethod = "skey";
963
964         return (authok != 0);
965 }
966 #endif
967
968 #ifdef USE_PAM
969 int
970 mm_answer_pam_start(int sock, Buffer *m)
971 {
972         if (!options.use_pam)
973                 fatal("UsePAM not set, but ended up in %s anyway", __func__);
974
975         start_pam(authctxt);
976
977         monitor_permit(mon_dispatch, MONITOR_REQ_PAM_ACCOUNT, 1);
978         if (options.kbd_interactive_authentication)
979                 monitor_permit(mon_dispatch, MONITOR_REQ_PAM_INIT_CTX, 1);
980
981         return (0);
982 }
983
984 int
985 mm_answer_pam_account(int sock, Buffer *m)
986 {
987         u_int ret;
988
989         if (!options.use_pam)
990                 fatal("%s: PAM not enabled", __func__);
991
992         ret = do_pam_account();
993
994         buffer_put_int(m, ret);
995         buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg));
996
997         mm_request_send(sock, MONITOR_ANS_PAM_ACCOUNT, m);
998
999         return (ret);
1000 }
1001
1002 static void *sshpam_ctxt, *sshpam_authok;
1003 extern KbdintDevice sshpam_device;
1004
1005 int
1006 mm_answer_pam_init_ctx(int sock, Buffer *m)
1007 {
1008         debug3("%s", __func__);
1009         if (!options.kbd_interactive_authentication)
1010                 fatal("%s: kbd-int authentication not enabled", __func__);
1011         if (sshpam_ctxt != NULL)
1012                 fatal("%s: already called", __func__);
1013         sshpam_ctxt = (sshpam_device.init_ctx)(authctxt);
1014         sshpam_authok = NULL;
1015         buffer_clear(m);
1016         if (sshpam_ctxt != NULL) {
1017                 monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1);
1018                 monitor_permit(mon_dispatch, MONITOR_REQ_PAM_QUERY, 1);
1019                 buffer_put_int(m, 1);
1020         } else {
1021                 buffer_put_int(m, 0);
1022         }
1023         mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m);
1024         return (0);
1025 }
1026
1027 int
1028 mm_answer_pam_query(int sock, Buffer *m)
1029 {
1030         char *name = NULL, *info = NULL, **prompts = NULL;
1031         u_int i, num = 0, *echo_on = 0;
1032         int ret;
1033
1034         debug3("%s", __func__);
1035         sshpam_authok = NULL;
1036         if (sshpam_ctxt == NULL)
1037                 fatal("%s: no context", __func__);
1038         ret = (sshpam_device.query)(sshpam_ctxt, &name, &info,
1039             &num, &prompts, &echo_on);
1040         if (ret == 0 && num == 0)
1041                 sshpam_authok = sshpam_ctxt;
1042         if (num > 1 || name == NULL || info == NULL)
1043                 fatal("sshpam_device.query failed");
1044         monitor_permit(mon_dispatch, MONITOR_REQ_PAM_RESPOND, 1);
1045         buffer_clear(m);
1046         buffer_put_int(m, ret);
1047         buffer_put_cstring(m, name);
1048         free(name);
1049         buffer_put_cstring(m, info);
1050         free(info);
1051         buffer_put_int(m, sshpam_get_maxtries_reached());
1052         buffer_put_int(m, num);
1053         for (i = 0; i < num; ++i) {
1054                 buffer_put_cstring(m, prompts[i]);
1055                 free(prompts[i]);
1056                 buffer_put_int(m, echo_on[i]);
1057         }
1058         free(prompts);
1059         free(echo_on);
1060         auth_method = "keyboard-interactive";
1061         auth_submethod = "pam";
1062         mm_request_send(sock, MONITOR_ANS_PAM_QUERY, m);
1063         return (0);
1064 }
1065
1066 int
1067 mm_answer_pam_respond(int sock, Buffer *m)
1068 {
1069         char **resp;
1070         u_int i, num;
1071         int ret;
1072
1073         debug3("%s", __func__);
1074         if (sshpam_ctxt == NULL)
1075                 fatal("%s: no context", __func__);
1076         sshpam_authok = NULL;
1077         num = buffer_get_int(m);
1078         if (num > 0) {
1079                 resp = xcalloc(num, sizeof(char *));
1080                 for (i = 0; i < num; ++i)
1081                         resp[i] = buffer_get_string(m, NULL);
1082                 ret = (sshpam_device.respond)(sshpam_ctxt, num, resp);
1083                 for (i = 0; i < num; ++i)
1084                         free(resp[i]);
1085                 free(resp);
1086         } else {
1087                 ret = (sshpam_device.respond)(sshpam_ctxt, num, NULL);
1088         }
1089         buffer_clear(m);
1090         buffer_put_int(m, ret);
1091         mm_request_send(sock, MONITOR_ANS_PAM_RESPOND, m);
1092         auth_method = "keyboard-interactive";
1093         auth_submethod = "pam";
1094         if (ret == 0)
1095                 sshpam_authok = sshpam_ctxt;
1096         return (0);
1097 }
1098
1099 int
1100 mm_answer_pam_free_ctx(int sock, Buffer *m)
1101 {
1102         int r = sshpam_authok != NULL && sshpam_authok == sshpam_ctxt;
1103
1104         debug3("%s", __func__);
1105         if (sshpam_ctxt == NULL)
1106                 fatal("%s: no context", __func__);
1107         (sshpam_device.free_ctx)(sshpam_ctxt);
1108         sshpam_ctxt = sshpam_authok = NULL;
1109         buffer_clear(m);
1110         mm_request_send(sock, MONITOR_ANS_PAM_FREE_CTX, m);
1111         /* Allow another attempt */
1112         monitor_permit(mon_dispatch, MONITOR_REQ_PAM_INIT_CTX, 1);
1113         auth_method = "keyboard-interactive";
1114         auth_submethod = "pam";
1115         return r;
1116 }
1117 #endif
1118
1119 int
1120 mm_answer_keyallowed(int sock, Buffer *m)
1121 {
1122         Key *key;
1123         char *cuser, *chost;
1124         u_char *blob;
1125         u_int bloblen, pubkey_auth_attempt;
1126         enum mm_keytype type = 0;
1127         int allowed = 0;
1128
1129         debug3("%s entering", __func__);
1130
1131         type = buffer_get_int(m);
1132         cuser = buffer_get_string(m, NULL);
1133         chost = buffer_get_string(m, NULL);
1134         blob = buffer_get_string(m, &bloblen);
1135         pubkey_auth_attempt = buffer_get_int(m);
1136
1137         key = key_from_blob(blob, bloblen);
1138
1139         debug3("%s: key_from_blob: %p", __func__, key);
1140
1141         if (key != NULL && authctxt->valid) {
1142                 /* These should not make it past the privsep child */
1143                 if (key_type_plain(key->type) == KEY_RSA &&
1144                     (datafellows & SSH_BUG_RSASIGMD5) != 0)
1145                         fatal("%s: passed a SSH_BUG_RSASIGMD5 key", __func__);
1146
1147                 switch (type) {
1148                 case MM_USERKEY:
1149                         allowed = options.pubkey_authentication &&
1150                             !auth2_userkey_already_used(authctxt, key) &&
1151                             match_pattern_list(sshkey_ssh_name(key),
1152                             options.pubkey_key_types, 0) == 1 &&
1153                             user_key_allowed(authctxt->pw, key,
1154                             pubkey_auth_attempt);
1155                         pubkey_auth_info(authctxt, key, NULL);
1156                         auth_method = "publickey";
1157                         if (options.pubkey_authentication &&
1158                             (!pubkey_auth_attempt || allowed != 1))
1159                                 auth_clear_options();
1160                         break;
1161                 case MM_HOSTKEY:
1162                         allowed = options.hostbased_authentication &&
1163                             match_pattern_list(sshkey_ssh_name(key),
1164                             options.hostbased_key_types, 0) == 1 &&
1165                             hostbased_key_allowed(authctxt->pw,
1166                             cuser, chost, key);
1167                         pubkey_auth_info(authctxt, key,
1168                             "client user \"%.100s\", client host \"%.100s\"",
1169                             cuser, chost);
1170                         auth_method = "hostbased";
1171                         break;
1172                 default:
1173                         fatal("%s: unknown key type %d", __func__, type);
1174                         break;
1175                 }
1176         }
1177
1178         debug3("%s: key %p is %s",
1179             __func__, key, allowed ? "allowed" : "not allowed");
1180
1181         if (key != NULL)
1182                 key_free(key);
1183
1184         /* clear temporarily storage (used by verify) */
1185         monitor_reset_key_state();
1186
1187         if (allowed) {
1188                 /* Save temporarily for comparison in verify */
1189                 key_blob = blob;
1190                 key_bloblen = bloblen;
1191                 key_blobtype = type;
1192                 hostbased_cuser = cuser;
1193                 hostbased_chost = chost;
1194         } else {
1195                 /* Log failed attempt */
1196                 auth_log(authctxt, 0, 0, auth_method, NULL);
1197                 free(blob);
1198                 free(cuser);
1199                 free(chost);
1200         }
1201
1202         buffer_clear(m);
1203         buffer_put_int(m, allowed);
1204         buffer_put_int(m, forced_command != NULL);
1205
1206         mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m);
1207
1208         return (0);
1209 }
1210
1211 static int
1212 monitor_valid_userblob(u_char *data, u_int datalen)
1213 {
1214         Buffer b;
1215         u_char *p;
1216         char *userstyle, *cp;
1217         u_int len;
1218         int fail = 0;
1219
1220         buffer_init(&b);
1221         buffer_append(&b, data, datalen);
1222
1223         if (datafellows & SSH_OLD_SESSIONID) {
1224                 p = buffer_ptr(&b);
1225                 len = buffer_len(&b);
1226                 if ((session_id2 == NULL) ||
1227                     (len < session_id2_len) ||
1228                     (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1229                         fail++;
1230                 buffer_consume(&b, session_id2_len);
1231         } else {
1232                 p = buffer_get_string(&b, &len);
1233                 if ((session_id2 == NULL) ||
1234                     (len != session_id2_len) ||
1235                     (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1236                         fail++;
1237                 free(p);
1238         }
1239         if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
1240                 fail++;
1241         cp = buffer_get_cstring(&b, NULL);
1242         xasprintf(&userstyle, "%s%s%s", authctxt->user,
1243             authctxt->style ? ":" : "",
1244             authctxt->style ? authctxt->style : "");
1245         if (strcmp(userstyle, cp) != 0) {
1246                 logit("wrong user name passed to monitor: "
1247                     "expected %s != %.100s", userstyle, cp);
1248                 fail++;
1249         }
1250         free(userstyle);
1251         free(cp);
1252         buffer_skip_string(&b);
1253         if (datafellows & SSH_BUG_PKAUTH) {
1254                 if (!buffer_get_char(&b))
1255                         fail++;
1256         } else {
1257                 cp = buffer_get_cstring(&b, NULL);
1258                 if (strcmp("publickey", cp) != 0)
1259                         fail++;
1260                 free(cp);
1261                 if (!buffer_get_char(&b))
1262                         fail++;
1263                 buffer_skip_string(&b);
1264         }
1265         buffer_skip_string(&b);
1266         if (buffer_len(&b) != 0)
1267                 fail++;
1268         buffer_free(&b);
1269         return (fail == 0);
1270 }
1271
1272 static int
1273 monitor_valid_hostbasedblob(u_char *data, u_int datalen, char *cuser,
1274     char *chost)
1275 {
1276         Buffer b;
1277         char *p, *userstyle;
1278         u_int len;
1279         int fail = 0;
1280
1281         buffer_init(&b);
1282         buffer_append(&b, data, datalen);
1283
1284         p = buffer_get_string(&b, &len);
1285         if ((session_id2 == NULL) ||
1286             (len != session_id2_len) ||
1287             (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1288                 fail++;
1289         free(p);
1290
1291         if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
1292                 fail++;
1293         p = buffer_get_cstring(&b, NULL);
1294         xasprintf(&userstyle, "%s%s%s", authctxt->user,
1295             authctxt->style ? ":" : "",
1296             authctxt->style ? authctxt->style : "");
1297         if (strcmp(userstyle, p) != 0) {
1298                 logit("wrong user name passed to monitor: expected %s != %.100s",
1299                     userstyle, p);
1300                 fail++;
1301         }
1302         free(userstyle);
1303         free(p);
1304         buffer_skip_string(&b); /* service */
1305         p = buffer_get_cstring(&b, NULL);
1306         if (strcmp(p, "hostbased") != 0)
1307                 fail++;
1308         free(p);
1309         buffer_skip_string(&b); /* pkalg */
1310         buffer_skip_string(&b); /* pkblob */
1311
1312         /* verify client host, strip trailing dot if necessary */
1313         p = buffer_get_string(&b, NULL);
1314         if (((len = strlen(p)) > 0) && p[len - 1] == '.')
1315                 p[len - 1] = '\0';
1316         if (strcmp(p, chost) != 0)
1317                 fail++;
1318         free(p);
1319
1320         /* verify client user */
1321         p = buffer_get_string(&b, NULL);
1322         if (strcmp(p, cuser) != 0)
1323                 fail++;
1324         free(p);
1325
1326         if (buffer_len(&b) != 0)
1327                 fail++;
1328         buffer_free(&b);
1329         return (fail == 0);
1330 }
1331
1332 int
1333 mm_answer_keyverify(int sock, Buffer *m)
1334 {
1335         Key *key;
1336         u_char *signature, *data, *blob;
1337         u_int signaturelen, datalen, bloblen;
1338         int verified = 0;
1339         int valid_data = 0;
1340
1341         blob = buffer_get_string(m, &bloblen);
1342         signature = buffer_get_string(m, &signaturelen);
1343         data = buffer_get_string(m, &datalen);
1344
1345         if (hostbased_cuser == NULL || hostbased_chost == NULL ||
1346           !monitor_allowed_key(blob, bloblen))
1347                 fatal("%s: bad key, not previously allowed", __func__);
1348
1349         key = key_from_blob(blob, bloblen);
1350         if (key == NULL)
1351                 fatal("%s: bad public key blob", __func__);
1352
1353         switch (key_blobtype) {
1354         case MM_USERKEY:
1355                 valid_data = monitor_valid_userblob(data, datalen);
1356                 break;
1357         case MM_HOSTKEY:
1358                 valid_data = monitor_valid_hostbasedblob(data, datalen,
1359                     hostbased_cuser, hostbased_chost);
1360                 break;
1361         default:
1362                 valid_data = 0;
1363                 break;
1364         }
1365         if (!valid_data)
1366                 fatal("%s: bad signature data blob", __func__);
1367
1368         verified = key_verify(key, signature, signaturelen, data, datalen);
1369         debug3("%s: key %p signature %s",
1370             __func__, key, (verified == 1) ? "verified" : "unverified");
1371
1372         /* If auth was successful then record key to ensure it isn't reused */
1373         if (verified == 1 && key_blobtype == MM_USERKEY)
1374                 auth2_record_userkey(authctxt, key);
1375         else
1376                 key_free(key);
1377
1378         free(blob);
1379         free(signature);
1380         free(data);
1381
1382         auth_method = key_blobtype == MM_USERKEY ? "publickey" : "hostbased";
1383
1384         monitor_reset_key_state();
1385
1386         buffer_clear(m);
1387         buffer_put_int(m, verified);
1388         mm_request_send(sock, MONITOR_ANS_KEYVERIFY, m);
1389
1390         return (verified == 1);
1391 }
1392
1393 static void
1394 mm_record_login(Session *s, struct passwd *pw)
1395 {
1396         struct ssh *ssh = active_state; /* XXX */
1397         socklen_t fromlen;
1398         struct sockaddr_storage from;
1399
1400         /*
1401          * Get IP address of client. If the connection is not a socket, let
1402          * the address be 0.0.0.0.
1403          */
1404         memset(&from, 0, sizeof(from));
1405         fromlen = sizeof(from);
1406         if (packet_connection_is_on_socket()) {
1407                 if (getpeername(packet_get_connection_in(),
1408                     (struct sockaddr *)&from, &fromlen) < 0) {
1409                         debug("getpeername: %.100s", strerror(errno));
1410                         cleanup_exit(255);
1411                 }
1412         }
1413         /* Record that there was a login on that tty from the remote host. */
1414         record_login(s->pid, s->tty, pw->pw_name, pw->pw_uid,
1415             session_get_remote_name_or_ip(ssh, utmp_len, options.use_dns),
1416             (struct sockaddr *)&from, fromlen);
1417 }
1418
1419 static void
1420 mm_session_close(Session *s)
1421 {
1422         debug3("%s: session %d pid %ld", __func__, s->self, (long)s->pid);
1423         if (s->ttyfd != -1) {
1424                 debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ptyfd);
1425                 session_pty_cleanup2(s);
1426         }
1427         session_unused(s->self);
1428 }
1429
1430 int
1431 mm_answer_pty(int sock, Buffer *m)
1432 {
1433         extern struct monitor *pmonitor;
1434         Session *s;
1435         int res, fd0;
1436
1437         debug3("%s entering", __func__);
1438
1439         buffer_clear(m);
1440         s = session_new();
1441         if (s == NULL)
1442                 goto error;
1443         s->authctxt = authctxt;
1444         s->pw = authctxt->pw;
1445         s->pid = pmonitor->m_pid;
1446         res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty));
1447         if (res == 0)
1448                 goto error;
1449         pty_setowner(authctxt->pw, s->tty);
1450
1451         buffer_put_int(m, 1);
1452         buffer_put_cstring(m, s->tty);
1453
1454         /* We need to trick ttyslot */
1455         if (dup2(s->ttyfd, 0) == -1)
1456                 fatal("%s: dup2", __func__);
1457
1458         mm_record_login(s, authctxt->pw);
1459
1460         /* Now we can close the file descriptor again */
1461         close(0);
1462
1463         /* send messages generated by record_login */
1464         buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg));
1465         buffer_clear(&loginmsg);
1466
1467         mm_request_send(sock, MONITOR_ANS_PTY, m);
1468
1469         if (mm_send_fd(sock, s->ptyfd) == -1 ||
1470             mm_send_fd(sock, s->ttyfd) == -1)
1471                 fatal("%s: send fds failed", __func__);
1472
1473         /* make sure nothing uses fd 0 */
1474         if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) < 0)
1475                 fatal("%s: open(/dev/null): %s", __func__, strerror(errno));
1476         if (fd0 != 0)
1477                 error("%s: fd0 %d != 0", __func__, fd0);
1478
1479         /* slave is not needed */
1480         close(s->ttyfd);
1481         s->ttyfd = s->ptyfd;
1482         /* no need to dup() because nobody closes ptyfd */
1483         s->ptymaster = s->ptyfd;
1484
1485         debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ttyfd);
1486
1487         return (0);
1488
1489  error:
1490         if (s != NULL)
1491                 mm_session_close(s);
1492         buffer_put_int(m, 0);
1493         mm_request_send(sock, MONITOR_ANS_PTY, m);
1494         return (0);
1495 }
1496
1497 int
1498 mm_answer_pty_cleanup(int sock, Buffer *m)
1499 {
1500         Session *s;
1501         char *tty;
1502
1503         debug3("%s entering", __func__);
1504
1505         tty = buffer_get_string(m, NULL);
1506         if ((s = session_by_tty(tty)) != NULL)
1507                 mm_session_close(s);
1508         buffer_clear(m);
1509         free(tty);
1510         return (0);
1511 }
1512
1513 int
1514 mm_answer_term(int sock, Buffer *req)
1515 {
1516         extern struct monitor *pmonitor;
1517         int res, status;
1518
1519         debug3("%s: tearing down sessions", __func__);
1520
1521         /* The child is terminating */
1522         session_destroy_all(&mm_session_close);
1523
1524 #ifdef USE_PAM
1525         if (options.use_pam)
1526                 sshpam_cleanup();
1527 #endif
1528
1529         while (waitpid(pmonitor->m_pid, &status, 0) == -1)
1530                 if (errno != EINTR)
1531                         exit(1);
1532
1533         res = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
1534
1535         /* Terminate process */
1536         exit(res);
1537 }
1538
1539 #ifdef SSH_AUDIT_EVENTS
1540 /* Report that an audit event occurred */
1541 int
1542 mm_answer_audit_event(int socket, Buffer *m)
1543 {
1544         ssh_audit_event_t event;
1545
1546         debug3("%s entering", __func__);
1547
1548         event = buffer_get_int(m);
1549         switch(event) {
1550         case SSH_AUTH_FAIL_PUBKEY:
1551         case SSH_AUTH_FAIL_HOSTBASED:
1552         case SSH_AUTH_FAIL_GSSAPI:
1553         case SSH_LOGIN_EXCEED_MAXTRIES:
1554         case SSH_LOGIN_ROOT_DENIED:
1555         case SSH_CONNECTION_CLOSE:
1556         case SSH_INVALID_USER:
1557                 audit_event(event);
1558                 break;
1559         default:
1560                 fatal("Audit event type %d not permitted", event);
1561         }
1562
1563         return (0);
1564 }
1565
1566 int
1567 mm_answer_audit_command(int socket, Buffer *m)
1568 {
1569         u_int len;
1570         char *cmd;
1571
1572         debug3("%s entering", __func__);
1573         cmd = buffer_get_string(m, &len);
1574         /* sanity check command, if so how? */
1575         audit_run_command(cmd);
1576         free(cmd);
1577         return (0);
1578 }
1579 #endif /* SSH_AUDIT_EVENTS */
1580
1581 void
1582 monitor_apply_keystate(struct monitor *pmonitor)
1583 {
1584         struct ssh *ssh = active_state; /* XXX */
1585         struct kex *kex;
1586         int r;
1587
1588         debug3("%s: packet_set_state", __func__);
1589         if ((r = ssh_packet_set_state(ssh, child_state)) != 0)
1590                 fatal("%s: packet_set_state: %s", __func__, ssh_err(r));
1591         sshbuf_free(child_state);
1592         child_state = NULL;
1593
1594         if ((kex = ssh->kex) != NULL) {
1595                 /* XXX set callbacks */
1596 #ifdef WITH_OPENSSL
1597                 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1598                 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1599                 kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
1600                 kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
1601                 kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
1602                 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1603                 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1604 # ifdef OPENSSL_HAS_ECC
1605                 kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
1606 # endif
1607 #endif /* WITH_OPENSSL */
1608                 kex->kex[KEX_C25519_SHA256] = kexc25519_server;
1609                 kex->load_host_public_key=&get_hostkey_public_by_type;
1610                 kex->load_host_private_key=&get_hostkey_private_by_type;
1611                 kex->host_key_index=&get_hostkey_index;
1612                 kex->sign = sshd_hostkey_sign;
1613         }
1614 }
1615
1616 /* This function requries careful sanity checking */
1617
1618 void
1619 mm_get_keystate(struct monitor *pmonitor)
1620 {
1621         debug3("%s: Waiting for new keys", __func__);
1622
1623         if ((child_state = sshbuf_new()) == NULL)
1624                 fatal("%s: sshbuf_new failed", __func__);
1625         mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT,
1626             child_state);
1627         debug3("%s: GOT new keys", __func__);
1628 }
1629
1630
1631 /* XXX */
1632
1633 #define FD_CLOSEONEXEC(x) do { \
1634         if (fcntl(x, F_SETFD, FD_CLOEXEC) == -1) \
1635                 fatal("fcntl(%d, F_SETFD)", x); \
1636 } while (0)
1637
1638 static void
1639 monitor_openfds(struct monitor *mon, int do_logfds)
1640 {
1641         int pair[2];
1642
1643         if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
1644                 fatal("%s: socketpair: %s", __func__, strerror(errno));
1645         FD_CLOSEONEXEC(pair[0]);
1646         FD_CLOSEONEXEC(pair[1]);
1647         mon->m_recvfd = pair[0];
1648         mon->m_sendfd = pair[1];
1649
1650         if (do_logfds) {
1651                 if (pipe(pair) == -1)
1652                         fatal("%s: pipe: %s", __func__, strerror(errno));
1653                 FD_CLOSEONEXEC(pair[0]);
1654                 FD_CLOSEONEXEC(pair[1]);
1655                 mon->m_log_recvfd = pair[0];
1656                 mon->m_log_sendfd = pair[1];
1657         } else
1658                 mon->m_log_recvfd = mon->m_log_sendfd = -1;
1659 }
1660
1661 #define MM_MEMSIZE      65536
1662
1663 struct monitor *
1664 monitor_init(void)
1665 {
1666         struct monitor *mon;
1667
1668         mon = xcalloc(1, sizeof(*mon));
1669         monitor_openfds(mon, 1);
1670
1671         return mon;
1672 }
1673
1674 void
1675 monitor_reinit(struct monitor *mon)
1676 {
1677         monitor_openfds(mon, 0);
1678 }
1679
1680 #ifdef GSSAPI
1681 int
1682 mm_answer_gss_setup_ctx(int sock, Buffer *m)
1683 {
1684         gss_OID_desc goid;
1685         OM_uint32 major;
1686         u_int len;
1687
1688         if (!options.gss_authentication)
1689                 fatal("%s: GSSAPI authentication not enabled", __func__);
1690
1691         goid.elements = buffer_get_string(m, &len);
1692         goid.length = len;
1693
1694         major = ssh_gssapi_server_ctx(&gsscontext, &goid);
1695
1696         free(goid.elements);
1697
1698         buffer_clear(m);
1699         buffer_put_int(m, major);
1700
1701         mm_request_send(sock, MONITOR_ANS_GSSSETUP, m);
1702
1703         /* Now we have a context, enable the step */
1704         monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 1);
1705
1706         return (0);
1707 }
1708
1709 int
1710 mm_answer_gss_accept_ctx(int sock, Buffer *m)
1711 {
1712         gss_buffer_desc in;
1713         gss_buffer_desc out = GSS_C_EMPTY_BUFFER;
1714         OM_uint32 major, minor;
1715         OM_uint32 flags = 0; /* GSI needs this */
1716         u_int len;
1717
1718         if (!options.gss_authentication)
1719                 fatal("%s: GSSAPI authentication not enabled", __func__);
1720
1721         in.value = buffer_get_string(m, &len);
1722         in.length = len;
1723         major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags);
1724         free(in.value);
1725
1726         buffer_clear(m);
1727         buffer_put_int(m, major);
1728         buffer_put_string(m, out.value, out.length);
1729         buffer_put_int(m, flags);
1730         mm_request_send(sock, MONITOR_ANS_GSSSTEP, m);
1731
1732         gss_release_buffer(&minor, &out);
1733
1734         if (major == GSS_S_COMPLETE) {
1735                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
1736                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1737                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
1738         }
1739         return (0);
1740 }
1741
1742 int
1743 mm_answer_gss_checkmic(int sock, Buffer *m)
1744 {
1745         gss_buffer_desc gssbuf, mic;
1746         OM_uint32 ret;
1747         u_int len;
1748
1749         if (!options.gss_authentication)
1750                 fatal("%s: GSSAPI authentication not enabled", __func__);
1751
1752         gssbuf.value = buffer_get_string(m, &len);
1753         gssbuf.length = len;
1754         mic.value = buffer_get_string(m, &len);
1755         mic.length = len;
1756
1757         ret = ssh_gssapi_checkmic(gsscontext, &gssbuf, &mic);
1758
1759         free(gssbuf.value);
1760         free(mic.value);
1761
1762         buffer_clear(m);
1763         buffer_put_int(m, ret);
1764
1765         mm_request_send(sock, MONITOR_ANS_GSSCHECKMIC, m);
1766
1767         if (!GSS_ERROR(ret))
1768                 monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1769
1770         return (0);
1771 }
1772
1773 int
1774 mm_answer_gss_userok(int sock, Buffer *m)
1775 {
1776         int authenticated;
1777
1778         if (!options.gss_authentication)
1779                 fatal("%s: GSSAPI authentication not enabled", __func__);
1780
1781         authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user);
1782
1783         buffer_clear(m);
1784         buffer_put_int(m, authenticated);
1785
1786         debug3("%s: sending result %d", __func__, authenticated);
1787         mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m);
1788
1789         auth_method = "gssapi-with-mic";
1790
1791         /* Monitor loop will terminate if authenticated */
1792         return (authenticated);
1793 }
1794 #endif /* GSSAPI */
1795