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