1 /*        $NetBSD: monitor.c,v 1.49 2025/04/09 15:49:32 christos Exp $          */
2 /* $OpenBSD: monitor.c,v 1.247 2024/12/03 22:30:03 jsg Exp $ */
3 
4 /*
5  * Copyright 2002 Niels Provos <provos@citi.umich.edu>
6  * Copyright 2002 Markus Friedl <markus@openbsd.org>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include "includes.h"
31 __RCSID("$NetBSD: monitor.c,v 1.49 2025/04/09 15:49:32 christos Exp $");
32 #include <sys/types.h>
33 #include <sys/wait.h>
34 #include <sys/socket.h>
35 #include <sys/tree.h>
36 #include <sys/queue.h>
37 
38 #ifdef WITH_OPENSSL
39 #include <openssl/dh.h>
40 #endif
41 
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <limits.h>
45 #include <paths.h>
46 #include <poll.h>
47 #include <pwd.h>
48 #include <signal.h>
49 #include <stdarg.h>
50 #include <unistd.h>
51 #include <stdint.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 
57 #include "atomicio.h"
58 #include "xmalloc.h"
59 #include "ssh.h"
60 #include "sshkey.h"
61 #include "sshbuf.h"
62 #include "hostfile.h"
63 #include "auth.h"
64 #include "cipher.h"
65 #include "kex.h"
66 #include "dh.h"
67 #include "packet.h"
68 #include "auth-options.h"
69 #include "sshpty.h"
70 #include "channels.h"
71 #include "session.h"
72 #include "sshlogin.h"
73 #include "canohost.h"
74 #include "log.h"
75 #include "misc.h"
76 #include "servconf.h"
77 #include "monitor.h"
78 #ifdef GSSAPI
79 #include "ssh-gss.h"
80 #endif
81 #include "monitor_wrap.h"
82 #include "monitor_fdpass.h"
83 #include "compat.h"
84 #include "ssh2.h"
85 #include "authfd.h"
86 #include "match.h"
87 #include "ssherr.h"
88 #include "sk-api.h"
89 #include "srclimit.h"
90 
91 #include "pfilter.h"
92 
93 #ifdef GSSAPI
94 static Gssctxt *gsscontext = NULL;
95 #endif
96 
97 /* Imports */
98 extern ServerOptions options;
99 extern u_int utmp_len;
100 extern struct sshbuf *cfg;
101 extern struct sshbuf *loginmsg;
102 extern struct include_list includes;
103 extern struct sshauthopt *auth_opts; /* XXX move to permanent ssh->authctxt? */
104 
105 /* State exported from the child */
106 static struct sshbuf *child_state;
107 
108 /* Functions on the monitor that answer unprivileged requests */
109 
110 int mm_answer_moduli(struct ssh *, int, struct sshbuf *);
111 int mm_answer_sign(struct ssh *, int, struct sshbuf *);
112 int mm_answer_pwnamallow(struct ssh *, int, struct sshbuf *);
113 int mm_answer_auth2_read_banner(struct ssh *, int, struct sshbuf *);
114 int mm_answer_authserv(struct ssh *, int, struct sshbuf *);
115 int mm_answer_authpassword(struct ssh *, int, struct sshbuf *);
116 int mm_answer_bsdauthquery(struct ssh *, int, struct sshbuf *);
117 int mm_answer_bsdauthrespond(struct ssh *, int, struct sshbuf *);
118 int mm_answer_keyallowed(struct ssh *, int, struct sshbuf *);
119 int mm_answer_keyverify(struct ssh *, int, struct sshbuf *);
120 int mm_answer_pty(struct ssh *, int, struct sshbuf *);
121 int mm_answer_pty_cleanup(struct ssh *, int, struct sshbuf *);
122 int mm_answer_term(struct ssh *, int, struct sshbuf *);
123 int mm_answer_state(struct ssh *, int, struct sshbuf *);
124 
125 #ifdef USE_PAM
126 int mm_answer_pam_start(struct ssh *, int, struct sshbuf *);
127 int mm_answer_pam_account(struct ssh *, int, struct sshbuf *);
128 int mm_answer_pam_init_ctx(struct ssh *, int, struct sshbuf *);
129 int mm_answer_pam_query(struct ssh *, int, struct sshbuf *);
130 int mm_answer_pam_respond(struct ssh *, int, struct sshbuf *);
131 int mm_answer_pam_free_ctx(struct ssh *, int, struct sshbuf *);
132 #endif
133 
134 #ifdef KRB5
135 int mm_answer_krb5(struct ssh *, int, struct sshbuf *);
136 #endif
137 
138 #ifdef GSSAPI
139 int mm_answer_gss_setup_ctx(struct ssh *, int, struct sshbuf *);
140 int mm_answer_gss_accept_ctx(struct ssh *, int, struct sshbuf *);
141 int mm_answer_gss_userok(struct ssh *, int, struct sshbuf *);
142 int mm_answer_gss_checkmic(struct ssh *, int, struct sshbuf *);
143 #endif
144 
145 static Authctxt *authctxt;
146 
147 /* local state for key verify */
148 static u_char *key_blob = NULL;
149 static size_t key_bloblen = 0;
150 static u_int key_blobtype = MM_NOKEY;
151 static struct sshauthopt *key_opts = NULL;
152 static char *hostbased_cuser = NULL;
153 static char *hostbased_chost = NULL;
154 static const char *auth_method = "unknown";
155 static const char *auth_submethod = NULL;
156 static u_int session_id2_len = 0;
157 static u_char *session_id2 = NULL;
158 static pid_t monitor_child_pid;
159 int auth_attempted = 0;
160 
161 struct mon_table {
162           enum monitor_reqtype type;
163           int flags;
164           int (*f)(struct ssh *, int, struct sshbuf *);
165 };
166 
167 #define MON_ISAUTH  0x0004    /* Required for Authentication */
168 #define MON_AUTHDECIDE        0x0008    /* Decides Authentication */
169 #define MON_ONCE    0x0010    /* Disable after calling */
170 #define MON_ALOG    0x0020    /* Log auth attempt without authenticating */
171 
172 #define MON_AUTH    (MON_ISAUTH|MON_AUTHDECIDE)
173 
174 #define MON_PERMIT  0x1000    /* Request is permitted */
175 
176 static int monitor_read(struct ssh *, struct monitor *, struct mon_table *,
177     struct mon_table **);
178 static int monitor_read_log(struct monitor *);
179 
180 struct mon_table mon_dispatch_proto20[] = {
181     {MONITOR_REQ_STATE, MON_ONCE, mm_answer_state},
182 #ifdef WITH_OPENSSL
183     {MONITOR_REQ_MODULI, MON_ONCE, mm_answer_moduli},
184 #endif
185     {MONITOR_REQ_SIGN, MON_ONCE, mm_answer_sign},
186     {MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow},
187     {MONITOR_REQ_AUTHSERV, MON_ONCE, mm_answer_authserv},
188     {MONITOR_REQ_AUTH2_READ_BANNER, MON_ONCE, mm_answer_auth2_read_banner},
189     {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
190 #ifdef USE_PAM
191     {MONITOR_REQ_PAM_START, MON_ONCE, mm_answer_pam_start},
192     {MONITOR_REQ_PAM_ACCOUNT, 0, mm_answer_pam_account},
193     {MONITOR_REQ_PAM_INIT_CTX, MON_ISAUTH, mm_answer_pam_init_ctx},
194     {MONITOR_REQ_PAM_QUERY, MON_ISAUTH, mm_answer_pam_query},
195     {MONITOR_REQ_PAM_RESPOND, MON_ISAUTH, mm_answer_pam_respond},
196     {MONITOR_REQ_PAM_FREE_CTX, MON_ONCE|MON_AUTHDECIDE, mm_answer_pam_free_ctx},
197 #endif
198 #ifdef BSD_AUTH
199     {MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery},
200     {MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond},
201 #endif
202     {MONITOR_REQ_KEYALLOWED, MON_ISAUTH, mm_answer_keyallowed},
203     {MONITOR_REQ_KEYVERIFY, MON_AUTH, mm_answer_keyverify},
204 #ifdef KRB5
205     {MONITOR_REQ_KRB5, MON_ONCE|MON_AUTH, mm_answer_krb5},
206 #endif
207 #ifdef GSSAPI
208     {MONITOR_REQ_GSSSETUP, MON_ISAUTH, mm_answer_gss_setup_ctx},
209     {MONITOR_REQ_GSSSTEP, 0, mm_answer_gss_accept_ctx},
210     {MONITOR_REQ_GSSUSEROK, MON_ONCE|MON_AUTHDECIDE, mm_answer_gss_userok},
211     {MONITOR_REQ_GSSCHECKMIC, MON_ONCE, mm_answer_gss_checkmic},
212 #endif
213     {0, 0, NULL}
214 };
215 
216 struct mon_table mon_dispatch_postauth20[] = {
217     {MONITOR_REQ_STATE, MON_ONCE, mm_answer_state},
218 #ifdef WITH_OPENSSL
219     {MONITOR_REQ_MODULI, 0, mm_answer_moduli},
220 #endif
221     {MONITOR_REQ_SIGN, 0, mm_answer_sign},
222     {MONITOR_REQ_PTY, 0, mm_answer_pty},
223     {MONITOR_REQ_PTYCLEANUP, 0, mm_answer_pty_cleanup},
224     {MONITOR_REQ_TERM, 0, mm_answer_term},
225     {0, 0, NULL}
226 };
227 
228 struct mon_table *mon_dispatch;
229 
230 /* Specifies if a certain message is allowed at the moment */
231 static void
monitor_permit(struct mon_table * ent,enum monitor_reqtype type,int permit)232 monitor_permit(struct mon_table *ent, enum monitor_reqtype type, int permit)
233 {
234           while (ent->f != NULL) {
235                     if (ent->type == type) {
236                               ent->flags &= ~MON_PERMIT;
237                               ent->flags |= permit ? MON_PERMIT : 0;
238                               return;
239                     }
240                     ent++;
241           }
242 }
243 
244 static void
monitor_permit_authentications(int permit)245 monitor_permit_authentications(int permit)
246 {
247           struct mon_table *ent = mon_dispatch;
248 
249           while (ent->f != NULL) {
250                     if (ent->flags & MON_AUTH) {
251                               ent->flags &= ~MON_PERMIT;
252                               ent->flags |= permit ? MON_PERMIT : 0;
253                     }
254                     ent++;
255           }
256 }
257 
258 void
monitor_child_preauth(struct ssh * ssh,struct monitor * pmonitor)259 monitor_child_preauth(struct ssh *ssh, struct monitor *pmonitor)
260 {
261           struct mon_table *ent;
262           int authenticated = 0, partial = 0;
263 
264           debug3("preauth child monitor started");
265 
266           authctxt = (Authctxt *)ssh->authctxt;
267           if (pmonitor->m_recvfd >= 0)
268                     close(pmonitor->m_recvfd);
269           if (pmonitor->m_log_sendfd >= 0)
270                     close(pmonitor->m_log_sendfd);
271           pmonitor->m_log_sendfd = pmonitor->m_recvfd = -1;
272 
273           memset(authctxt, 0, sizeof(*authctxt));
274           ssh->authctxt = authctxt;
275 
276           mon_dispatch = mon_dispatch_proto20;
277           /* Permit requests for state, moduli and signatures */
278           monitor_permit(mon_dispatch, MONITOR_REQ_STATE, 1);
279           monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
280           monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
281 
282           /* The first few requests do not require asynchronous access */
283           while (!authenticated) {
284                     partial = 0;
285                     auth_method = "unknown";
286                     auth_submethod = NULL;
287                     auth2_authctxt_reset_info(authctxt);
288 
289                     authenticated = (monitor_read(ssh, pmonitor,
290                         mon_dispatch, &ent) == 1);
291 
292                     /* Record that auth was attempted to set exit status later */
293                     if ((ent->flags & MON_AUTH) != 0)
294                               auth_attempted = 1;
295 
296                     /* Special handling for multiple required authentications */
297                     if (options.num_auth_methods != 0) {
298                               if (authenticated &&
299                                   !auth2_update_methods_lists(authctxt,
300                                   auth_method, auth_submethod)) {
301                                         debug3_f("method %s: partial", auth_method);
302                                         authenticated = 0;
303                                         partial = 1;
304                               }
305                     }
306 
307                     if (authenticated) {
308                               if (!(ent->flags & MON_AUTHDECIDE))
309                                         fatal_f("unexpected authentication from %d",
310                                             ent->type);
311                               if (authctxt->pw->pw_uid == 0 &&
312                                   !auth_root_allowed(ssh, auth_method))
313                                         authenticated = 0;
314 #ifdef USE_PAM
315                               /* PAM needs to perform account checks after auth */
316                               if (options.use_pam && authenticated) {
317                                         struct sshbuf *m;
318 
319                                         if ((m = sshbuf_new()) == NULL)
320                                                   fatal("%s: sshbuf_new failed", __func__);
321 
322                                         mm_request_receive_expect(pmonitor->m_sendfd,
323                                             MONITOR_REQ_PAM_ACCOUNT, m);
324                                         authenticated = mm_answer_pam_account(ssh, pmonitor->m_sendfd, m);
325                                         sshbuf_free(m);
326                               }
327 #endif
328                     }
329                     if (ent->flags & (MON_AUTHDECIDE|MON_ALOG)) {
330                               auth_log(ssh, authenticated, partial,
331                                   auth_method, auth_submethod);
332                               if (!partial && !authenticated)
333                                         authctxt->failures++;
334                               if (authenticated || partial) {
335                                         auth2_update_session_info(authctxt,
336                                             auth_method, auth_submethod);
337                               }
338                     }
339                     if (authctxt->failures > options.max_authtries) {
340                               pfilter_notify(1);
341                               /* Shouldn't happen */
342                               fatal_f("privsep child made too many authentication "
343                                   "attempts");
344                     }
345           }
346 
347           if (!authctxt->valid) {
348                     pfilter_notify(1);
349                     fatal_f("authenticated invalid user");
350           }
351           if (strcmp(auth_method, "unknown") == 0) {
352                     pfilter_notify(1);
353                     fatal_f("authentication method name unknown");
354           }
355 
356           debug_f("user %s authenticated by privileged process", authctxt->user);
357           auth_attempted = 0;
358           ssh->authctxt = NULL;
359           ssh_packet_set_log_preamble(ssh, "user %s", authctxt->user);
360 
361           mm_get_keystate(ssh, pmonitor);
362 
363           /* Drain any buffered messages from the child */
364           while (pmonitor->m_log_recvfd != -1 && monitor_read_log(pmonitor) == 0)
365                     ;
366 
367           if (pmonitor->m_recvfd >= 0)
368                     close(pmonitor->m_recvfd);
369           if (pmonitor->m_log_sendfd >= 0)
370                     close(pmonitor->m_log_sendfd);
371           pmonitor->m_sendfd = pmonitor->m_log_recvfd = -1;
372 }
373 
374 static void
monitor_set_child_handler(pid_t pid)375 monitor_set_child_handler(pid_t pid)
376 {
377           monitor_child_pid = pid;
378 }
379 
380 static void
monitor_child_handler(int sig)381 monitor_child_handler(int sig)
382 {
383           kill(monitor_child_pid, sig);
384 }
385 
386 void
monitor_child_postauth(struct ssh * ssh,struct monitor * pmonitor)387 monitor_child_postauth(struct ssh *ssh, struct monitor *pmonitor)
388 {
389           close(pmonitor->m_recvfd);
390           pmonitor->m_recvfd = -1;
391 
392           monitor_set_child_handler(pmonitor->m_pid);
393           ssh_signal(SIGHUP, &monitor_child_handler);
394           ssh_signal(SIGTERM, &monitor_child_handler);
395           ssh_signal(SIGINT, &monitor_child_handler);
396 
397           mon_dispatch = mon_dispatch_postauth20;
398 
399           /* Permit requests for moduli and signatures */
400           monitor_permit(mon_dispatch, MONITOR_REQ_STATE, 1);
401           monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
402           monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
403           monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
404 
405           if (auth_opts->permit_pty_flag) {
406                     monitor_permit(mon_dispatch, MONITOR_REQ_PTY, 1);
407                     monitor_permit(mon_dispatch, MONITOR_REQ_PTYCLEANUP, 1);
408           }
409 
410           for (;;)
411                     monitor_read(ssh, pmonitor, mon_dispatch, NULL);
412 }
413 
414 static int
monitor_read_log(struct monitor * pmonitor)415 monitor_read_log(struct monitor *pmonitor)
416 {
417           struct sshbuf *logmsg;
418           u_int len, level, forced;
419           char *msg;
420           u_char *p;
421           int r;
422 
423           if ((logmsg = sshbuf_new()) == NULL)
424                     fatal_f("sshbuf_new");
425 
426           /* Read length */
427           if ((r = sshbuf_reserve(logmsg, 4, &p)) != 0)
428                     fatal_fr(r, "reserve len");
429           if (atomicio(read, pmonitor->m_log_recvfd, p, 4) != 4) {
430                     if (errno == EPIPE) {
431                               sshbuf_free(logmsg);
432                               debug_f("child log fd closed");
433                               close(pmonitor->m_log_recvfd);
434                               pmonitor->m_log_recvfd = -1;
435                               return -1;
436                     }
437                     fatal_f("log fd read: %s", strerror(errno));
438           }
439           if ((r = sshbuf_get_u32(logmsg, &len)) != 0)
440                     fatal_fr(r, "parse len");
441           if (len <= 4 || len > 8192)
442                     fatal_f("invalid log message length %u", len);
443 
444           /* Read severity, message */
445           sshbuf_reset(logmsg);
446           if ((r = sshbuf_reserve(logmsg, len, &p)) != 0)
447                     fatal_fr(r, "reserve msg");
448           if (atomicio(read, pmonitor->m_log_recvfd, p, len) != len)
449                     fatal_f("log fd read: %s", strerror(errno));
450           if ((r = sshbuf_get_u32(logmsg, &level)) != 0 ||
451               (r = sshbuf_get_u32(logmsg, &forced)) != 0 ||
452               (r = sshbuf_get_cstring(logmsg, &msg, NULL)) != 0)
453                     fatal_fr(r, "parse");
454 
455           /* Log it */
456           if (log_level_name(level) == NULL)
457                     fatal_f("invalid log level %u (corrupted message?)", level);
458           sshlogdirect(level, forced, "%s [%s]", msg,
459               mon_dispatch == mon_dispatch_postauth20 ? "postauth" : "preauth");
460 
461           sshbuf_free(logmsg);
462           free(msg);
463 
464           return 0;
465 }
466 
467 static int
monitor_read(struct ssh * ssh,struct monitor * pmonitor,struct mon_table * ent,struct mon_table ** pent)468 monitor_read(struct ssh *ssh, struct monitor *pmonitor, struct mon_table *ent,
469     struct mon_table **pent)
470 {
471           struct sshbuf *m;
472           int r, ret;
473           u_char type;
474           struct pollfd pfd[2];
475 
476           for (;;) {
477                     memset(&pfd, 0, sizeof(pfd));
478                     pfd[0].fd = pmonitor->m_sendfd;
479                     pfd[0].events = POLLIN;
480                     pfd[1].fd = pmonitor->m_log_recvfd;
481                     pfd[1].events = pfd[1].fd == -1 ? 0 : POLLIN;
482                     if (poll(pfd, pfd[1].fd == -1 ? 1 : 2, -1) == -1) {
483                               if (errno == EINTR || errno == EAGAIN)
484                                         continue;
485                               fatal_f("poll: %s", strerror(errno));
486                     }
487                     if (pfd[1].revents) {
488                               /*
489                                * Drain all log messages before processing next
490                                * monitor request.
491                                */
492                               monitor_read_log(pmonitor);
493                               continue;
494                     }
495                     if (pfd[0].revents)
496                               break;  /* Continues below */
497           }
498 
499           if ((m = sshbuf_new()) == NULL)
500                     fatal_f("sshbuf_new");
501 
502           mm_request_receive(pmonitor->m_sendfd, m);
503           if ((r = sshbuf_get_u8(m, &type)) != 0)
504                     fatal_fr(r, "parse type");
505 
506           debug3_f("checking request %d", type);
507 
508           while (ent->f != NULL) {
509                     if (ent->type == type)
510                               break;
511                     ent++;
512           }
513 
514           if (ent->f != NULL) {
515                     if (!(ent->flags & MON_PERMIT))
516                               fatal_f("unpermitted request %d", type);
517                     ret = (*ent->f)(ssh, pmonitor->m_sendfd, m);
518                     sshbuf_free(m);
519 
520                     /* The child may use this request only once, disable it */
521                     if (ent->flags & MON_ONCE) {
522                               debug2_f("%d used once, disabling now", type);
523                               ent->flags &= ~MON_PERMIT;
524                     }
525 
526                     if (pent != NULL)
527                               *pent = ent;
528 
529                     return ret;
530           }
531 
532           fatal_f("unsupported request: %d", type);
533 
534           /* NOTREACHED */
535           return (-1);
536 }
537 
538 /* allowed key state */
539 static int
monitor_allowed_key(const u_char * blob,u_int bloblen)540 monitor_allowed_key(const u_char *blob, u_int bloblen)
541 {
542           /* make sure key is allowed */
543           if (key_blob == NULL || key_bloblen != bloblen ||
544               timingsafe_bcmp(key_blob, blob, key_bloblen))
545                     return (0);
546           return (1);
547 }
548 
549 static void
monitor_reset_key_state(void)550 monitor_reset_key_state(void)
551 {
552           /* reset state */
553           free(key_blob);
554           free(hostbased_cuser);
555           free(hostbased_chost);
556           sshauthopt_free(key_opts);
557           key_blob = NULL;
558           key_bloblen = 0;
559           key_blobtype = MM_NOKEY;
560           key_opts = NULL;
561           hostbased_cuser = NULL;
562           hostbased_chost = NULL;
563 }
564 
565 int
mm_answer_state(struct ssh * ssh,int sock,struct sshbuf * m)566 mm_answer_state(struct ssh *ssh, int sock, struct sshbuf *m)
567 {
568           struct sshbuf *inc = NULL, *hostkeys = NULL;
569           struct sshbuf *opts = NULL, *confdata = NULL;
570           struct include_item *item = NULL;
571           int postauth;
572           int r;
573 
574           sshbuf_reset(m);
575 
576           debug_f("config len %zu", sshbuf_len(cfg));
577 
578           if ((m = sshbuf_new()) == NULL ||
579               (inc = sshbuf_new()) == NULL ||
580               (opts = sshbuf_new()) == NULL ||
581               (confdata = sshbuf_new()) == NULL)
582                     fatal_f("sshbuf_new failed");
583 
584           /* XXX unnecessary? */
585           /* pack includes into a string */
586           TAILQ_FOREACH(item, &includes, entry) {
587                     if ((r = sshbuf_put_cstring(inc, item->selector)) != 0 ||
588                         (r = sshbuf_put_cstring(inc, item->filename)) != 0 ||
589                         (r = sshbuf_put_stringb(inc, item->contents)) != 0)
590                               fatal_fr(r, "compose includes");
591           }
592 
593           hostkeys = pack_hostkeys();
594 
595           /*
596            * Protocol from monitor to unpriv privsep process:
597            *        string    configuration
598            *        uint64    timing_secret       XXX move delays to monitor and remove
599            *        string    host_keys[] {
600            *                  string public_key
601            *                  string certificate
602            *        }
603            *        string  server_banner
604            *        string  client_banner
605            *        string    included_files[] {
606            *                  string    selector
607            *                  string    filename
608            *                  string    contents
609            *        }
610            *        string    configuration_data (postauth)
611            *        string  keystate (postauth)
612            *        string  authenticated_user (postauth)
613            *        string  session_info (postauth)
614            *        string  authopts (postauth)
615            */
616           if ((r = sshbuf_put_stringb(m, cfg)) != 0 ||
617               (r = sshbuf_put_u64(m, options.timing_secret)) != 0 ||
618               (r = sshbuf_put_stringb(m, hostkeys)) != 0 ||
619               (r = sshbuf_put_stringb(m, ssh->kex->server_version)) != 0 ||
620               (r = sshbuf_put_stringb(m, ssh->kex->client_version)) != 0 ||
621               (r = sshbuf_put_stringb(m, inc)) != 0)
622                     fatal_fr(r, "compose config");
623 
624           postauth = (authctxt && authctxt->pw && authctxt->authenticated);
625           if (postauth) {
626                     /* XXX shouldn't be reachable */
627                     fatal_f("internal error: called in postauth");
628           }
629 
630           sshbuf_free(inc);
631           sshbuf_free(opts);
632           sshbuf_free(confdata);
633 
634           mm_request_send(sock, MONITOR_ANS_STATE, m);
635 
636           debug3_f("done");
637 
638           return (0);
639 }
640 
641 #ifdef WITH_OPENSSL
642 int
mm_answer_moduli(struct ssh * ssh,int sock,struct sshbuf * m)643 mm_answer_moduli(struct ssh *ssh, int sock, struct sshbuf *m)
644 {
645           DH *dh;
646           const BIGNUM *dh_p, *dh_g;
647           int r;
648           u_int min, want, max;
649 
650           if ((r = sshbuf_get_u32(m, &min)) != 0 ||
651               (r = sshbuf_get_u32(m, &want)) != 0 ||
652               (r = sshbuf_get_u32(m, &max)) != 0)
653                     fatal_fr(r, "parse");
654 
655           debug3_f("got parameters: %d %d %d", min, want, max);
656           /* We need to check here, too, in case the child got corrupted */
657           if (max < min || want < min || max < want)
658                     fatal_f("bad parameters: %d %d %d", min, want, max);
659 
660           sshbuf_reset(m);
661 
662           dh = choose_dh(min, want, max);
663           if (dh == NULL) {
664                     if ((r = sshbuf_put_u8(m, 0)) != 0)
665                               fatal_fr(r, "assemble empty");
666                     return (0);
667           } else {
668                     /* Send first bignum */
669                     DH_get0_pqg(dh, &dh_p, NULL, &dh_g);
670                     if ((r = sshbuf_put_u8(m, 1)) != 0 ||
671                         (r = sshbuf_put_bignum2(m, dh_p)) != 0 ||
672                         (r = sshbuf_put_bignum2(m, dh_g)) != 0)
673                               fatal_fr(r, "assemble");
674 
675                     DH_free(dh);
676           }
677           mm_request_send(sock, MONITOR_ANS_MODULI, m);
678           return (0);
679 }
680 #endif
681 
682 int
mm_answer_sign(struct ssh * ssh,int sock,struct sshbuf * m)683 mm_answer_sign(struct ssh *ssh, int sock, struct sshbuf *m)
684 {
685           extern int auth_sock;                             /* XXX move to state struct? */
686           struct sshkey *pubkey, *key;
687           struct sshbuf *sigbuf = NULL;
688           u_char *p = NULL, *signature = NULL;
689           char *alg = NULL;
690           size_t datlen, siglen;
691           int r, is_proof = 0, keyid;
692           u_int compat;
693           const char proof_req[] = "hostkeys-prove-00@openssh.com";
694 
695           debug3_f("entering");
696 
697           if ((r = sshkey_froms(m, &pubkey)) != 0 ||
698               (r = sshbuf_get_string(m, &p, &datlen)) != 0 ||
699               (r = sshbuf_get_cstring(m, &alg, NULL)) != 0 ||
700               (r = sshbuf_get_u32(m, &compat)) != 0)
701                     fatal_fr(r, "parse");
702 
703           if ((keyid = get_hostkey_index(pubkey, 1, ssh)) == -1)
704                     fatal_f("unknown hostkey");
705           debug_f("hostkey %s index %d", sshkey_ssh_name(pubkey), keyid);
706           sshkey_free(pubkey);
707 
708           /*
709            * Supported KEX types use SHA1 (20 bytes), SHA256 (32 bytes),
710            * SHA384 (48 bytes) and SHA512 (64 bytes).
711            *
712            * Otherwise, verify the signature request is for a hostkey
713            * proof.
714            *
715            * XXX perform similar check for KEX signature requests too?
716            * it's not trivial, since what is signed is the hash, rather
717            * than the full kex structure...
718            */
719           if (datlen != 20 && datlen != 32 && datlen != 48 && datlen != 64) {
720                     /*
721                      * Construct expected hostkey proof and compare it to what
722                      * the client sent us.
723                      */
724                     if (session_id2_len == 0) /* hostkeys is never first */
725                               fatal_f("bad data length: %zu", datlen);
726                     if ((key = get_hostkey_public_by_index(keyid, ssh)) == NULL)
727                               fatal_f("no hostkey for index %d", keyid);
728                     if ((sigbuf = sshbuf_new()) == NULL)
729                               fatal_f("sshbuf_new");
730                     if ((r = sshbuf_put_cstring(sigbuf, proof_req)) != 0 ||
731                         (r = sshbuf_put_string(sigbuf, session_id2,
732                         session_id2_len)) != 0 ||
733                         (r = sshkey_puts(key, sigbuf)) != 0)
734                               fatal_fr(r, "assemble private key proof");
735                     if (datlen != sshbuf_len(sigbuf) ||
736                         memcmp(p, sshbuf_ptr(sigbuf), sshbuf_len(sigbuf)) != 0)
737                               fatal_f("bad data length: %zu, hostkey proof len %zu",
738                                   datlen, sshbuf_len(sigbuf));
739                     sshbuf_free(sigbuf);
740                     is_proof = 1;
741           }
742 
743           /* save session id, it will be passed on the first call */
744           if (session_id2_len == 0) {
745                     session_id2_len = datlen;
746                     session_id2 = xmalloc(session_id2_len);
747                     memcpy(session_id2, p, session_id2_len);
748           }
749 
750           if ((key = get_hostkey_by_index(keyid)) != NULL) {
751                     if ((r = sshkey_sign(key, &signature, &siglen, p, datlen, alg,
752                         options.sk_provider, NULL, compat)) != 0)
753                               fatal_fr(r, "sign");
754           } else if ((key = get_hostkey_public_by_index(keyid, ssh)) != NULL &&
755               auth_sock > 0) {
756                     if ((r = ssh_agent_sign(auth_sock, key, &signature, &siglen,
757                         p, datlen, alg, compat)) != 0)
758                               fatal_fr(r, "agent sign");
759           } else
760                     fatal_f("no hostkey from index %d", keyid);
761 
762           debug3_f("%s %s signature len=%zu", alg,
763               is_proof ? "hostkey proof" : "KEX", siglen);
764 
765           sshbuf_reset(m);
766           if ((r = sshbuf_put_string(m, signature, siglen)) != 0)
767                     fatal_fr(r, "assemble");
768 
769           free(alg);
770           free(p);
771           free(signature);
772 
773           mm_request_send(sock, MONITOR_ANS_SIGN, m);
774 
775           /* Turn on permissions for getpwnam */
776           monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
777 
778           return (0);
779 }
780 
781 #define PUTPW(b, id) \
782           do { \
783                     if ((r = sshbuf_put_string(b, \
784                         &pwent->id, sizeof(pwent->id))) != 0) \
785                               fatal_fr(r, "assemble %s", #id); \
786           } while (0)
787 
788 void
mm_encode_server_options(struct sshbuf * m)789 mm_encode_server_options(struct sshbuf *m)
790 {
791           int r;
792           u_int i;
793 
794           /* XXX this leaks raw pointers to the unpriv child processes */
795           if ((r = sshbuf_put_string(m, &options, sizeof(options))) != 0)
796                     fatal_fr(r, "assemble options");
797 
798 #define M_CP_STROPT(x) do { \
799                     if (options.x != NULL && \
800                         (r = sshbuf_put_cstring(m, options.x)) != 0) \
801                               fatal_fr(r, "assemble %s", #x); \
802           } while (0)
803 #define M_CP_STRARRAYOPT(x, nx) do { \
804                     for (i = 0; i < options.nx; i++) { \
805                               if ((r = sshbuf_put_cstring(m, options.x[i])) != 0) \
806                                         fatal_fr(r, "assemble %s", #x); \
807                     } \
808           } while (0)
809           /* See comment in servconf.h */
810           COPY_MATCH_STRING_OPTS();
811 #undef M_CP_STROPT
812 #undef M_CP_STRARRAYOPT
813 }
814 
815 /* Retrieves the password entry and also checks if the user is permitted */
816 int
mm_answer_pwnamallow(struct ssh * ssh,int sock,struct sshbuf * m)817 mm_answer_pwnamallow(struct ssh *ssh, int sock, struct sshbuf *m)
818 {
819           struct passwd *pwent;
820           int r, allowed = 0;
821 
822           debug3_f("entering");
823 
824           if (authctxt->attempt++ != 0)
825                     fatal_f("multiple attempts for getpwnam");
826 
827           if ((r = sshbuf_get_cstring(m, &authctxt->user, NULL)) != 0)
828                     fatal_fr(r, "parse");
829 
830           pwent = getpwnamallow(ssh, authctxt->user);
831 
832           setproctitle("%s [priv]", pwent ? authctxt->user : "unknown");
833 
834           sshbuf_reset(m);
835 
836           if (pwent == NULL) {
837                     if ((r = sshbuf_put_u8(m, 0)) != 0)
838                               fatal_fr(r, "assemble fakepw");
839                     authctxt->pw = fakepw();
840                     goto out;
841           }
842 
843           allowed = 1;
844           authctxt->pw = pwent;
845           authctxt->valid = 1;
846 
847           /* XXX send fake class/dir/shell, etc. */
848           if ((r = sshbuf_put_u8(m, 1)) != 0)
849                     fatal_fr(r, "assemble ok");
850           PUTPW(m, pw_uid);
851           PUTPW(m, pw_gid);
852           PUTPW(m, pw_change);
853           PUTPW(m, pw_expire);
854           if ((r = sshbuf_put_cstring(m, pwent->pw_name)) != 0 ||
855               (r = sshbuf_put_cstring(m, "*")) != 0 ||
856               (r = sshbuf_put_cstring(m, pwent->pw_gecos)) != 0 ||
857               (r = sshbuf_put_cstring(m, pwent->pw_class)) != 0 ||
858               (r = sshbuf_put_cstring(m, pwent->pw_dir)) != 0 ||
859               (r = sshbuf_put_cstring(m, pwent->pw_shell)) != 0)
860                     fatal_fr(r, "assemble pw");
861 
862  out:
863           ssh_packet_set_log_preamble(ssh, "%suser %s",
864               authctxt->valid ? "authenticating" : "invalid ", authctxt->user);
865 
866           if (options.refuse_connection) {
867                     logit("administratively prohibited connection for "
868                         "%s%s from %.128s port %d",
869                         authctxt->valid ? "" : "invalid user ",
870                         authctxt->user, ssh_remote_ipaddr(ssh),
871                         ssh_remote_port(ssh));
872                     cleanup_exit(EXIT_CONFIG_REFUSED);
873           }
874 
875           /* Send active options to unpriv */
876           mm_encode_server_options(m);
877 
878           /* Create valid auth method lists */
879           if (auth2_setup_methods_lists(authctxt) != 0) {
880                     /*
881                      * The monitor will continue long enough to let the child
882                      * run to its packet_disconnect(), but it must not allow any
883                      * authentication to succeed.
884                      */
885                     debug_f("no valid authentication method lists");
886           }
887 
888           debug3_f("sending MONITOR_ANS_PWNAM: %d", allowed);
889           mm_request_send(sock, MONITOR_ANS_PWNAM, m);
890 
891           /* Allow service/style information on the auth context */
892           monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
893           monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
894 
895 #ifdef USE_PAM
896           if (options.use_pam)
897                     monitor_permit(mon_dispatch, MONITOR_REQ_PAM_START, 1);
898 #endif
899 
900           return (0);
901 }
902 
mm_answer_auth2_read_banner(struct ssh * ssh,int sock,struct sshbuf * m)903 int mm_answer_auth2_read_banner(struct ssh *ssh, int sock, struct sshbuf *m)
904 {
905           char *banner;
906           int r;
907 
908           sshbuf_reset(m);
909           banner = auth2_read_banner();
910           if ((r = sshbuf_put_cstring(m, banner != NULL ? banner : "")) != 0)
911                     fatal_fr(r, "assemble");
912           mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m);
913           free(banner);
914 
915           return (0);
916 }
917 
918 int
mm_answer_authserv(struct ssh * ssh,int sock,struct sshbuf * m)919 mm_answer_authserv(struct ssh *ssh, int sock, struct sshbuf *m)
920 {
921           int r;
922 
923           monitor_permit_authentications(1);
924 
925           if ((r = sshbuf_get_cstring(m, &authctxt->service, NULL)) != 0 ||
926               (r = sshbuf_get_cstring(m, &authctxt->style, NULL)) != 0)
927                     fatal_fr(r, "parse");
928           debug3_f("service=%s, style=%s", authctxt->service, authctxt->style);
929 
930           if (strlen(authctxt->style) == 0) {
931                     free(authctxt->style);
932                     authctxt->style = NULL;
933           }
934 
935           return (0);
936 }
937 
938 int
mm_answer_authpassword(struct ssh * ssh,int sock,struct sshbuf * m)939 mm_answer_authpassword(struct ssh *ssh, int sock, struct sshbuf *m)
940 {
941           static int call_count;
942           char *passwd;
943           int r, authenticated;
944           size_t plen;
945 
946           if (!options.password_authentication)
947                     fatal_f("password authentication not enabled");
948           if ((r = sshbuf_get_cstring(m, &passwd, &plen)) != 0)
949                     fatal_fr(r, "parse");
950           /* Only authenticate if the context is valid */
951           authenticated = options.password_authentication &&
952               auth_password(ssh, passwd);
953           freezero(passwd, plen);
954 
955           sshbuf_reset(m);
956           if ((r = sshbuf_put_u32(m, authenticated)) != 0)
957                     fatal_fr(r, "assemble");
958 #ifdef USE_PAM
959           if ((r = sshbuf_put_u32(m, sshpam_get_maxtries_reached())) != 0)
960                     fatal_fr(r, "assemble PAM");
961 #endif
962           debug3_f("sending result %d", authenticated);
963           mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m);
964 
965           call_count++;
966           if (plen == 0 && call_count == 1)
967                     auth_method = "none";
968           else
969                     auth_method = "password";
970 
971           /* Causes monitor loop to terminate if authenticated */
972           return (authenticated);
973 }
974 
975 #ifdef BSD_AUTH
976 int
mm_answer_bsdauthquery(struct ssh * ssh,int sock,struct sshbuf * m)977 mm_answer_bsdauthquery(struct ssh *ssh, int sock, struct sshbuf *m)
978 {
979           char *name, *infotxt;
980           u_int numprompts, *echo_on, success;
981           char **prompts;
982           int r;
983 
984           if (!options.kbd_interactive_authentication)
985                     fatal_f("kbd-int authentication not enabled");
986           success = bsdauth_query(authctxt, &name, &infotxt, &numprompts,
987               &prompts, &echo_on) < 0 ? 0 : 1;
988 
989           sshbuf_reset(m);
990           if ((r = sshbuf_put_u32(m, success)) != 0)
991                     fatal_fr(r, "assemble");
992           if (success) {
993                     if ((r = sshbuf_put_cstring(m, prompts[0])) != 0)
994                               fatal_fr(r, "assemble prompt");
995           }
996 
997           debug3_f("sending challenge success: %u", success);
998           mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m);
999 
1000           if (success) {
1001                     free(name);
1002                     free(infotxt);
1003                     free(prompts);
1004                     free(echo_on);
1005           }
1006 
1007           return (0);
1008 }
1009 
1010 int
mm_answer_bsdauthrespond(struct ssh * ssh,int sock,struct sshbuf * m)1011 mm_answer_bsdauthrespond(struct ssh *ssh, int sock, struct sshbuf *m)
1012 {
1013           char *response;
1014           int r, authok;
1015 
1016           if (!options.kbd_interactive_authentication)
1017                     fatal_f("kbd-int authentication not enabled");
1018           if (authctxt->as == NULL)
1019                     fatal_f("no bsd auth session");
1020 
1021           if ((r = sshbuf_get_cstring(m, &response, NULL)) != 0)
1022                     fatal_fr(r, "parse");
1023           authok = options.kbd_interactive_authentication &&
1024               auth_userresponse(authctxt->as, response, 0);
1025           authctxt->as = NULL;
1026           debug3_f("<%s> = <%d>", response, authok);
1027           free(response);
1028 
1029           sshbuf_reset(m);
1030           if ((r = sshbuf_put_u32(m, authok)) != 0)
1031                     fatal_fr(r, "assemble");
1032 
1033           debug3_f("sending authenticated: %d", authok);
1034           mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m);
1035 
1036           auth_method = "keyboard-interactive";
1037           auth_submethod = "bsdauth";
1038 
1039           return (authok != 0);
1040 }
1041 #endif
1042 
1043 #ifdef SKEY
1044 int
mm_answer_skeyquery(int sock,struct sshbuf * m)1045 mm_answer_skeyquery(int sock, struct sshbuf *m)
1046 {
1047           struct skey skey;
1048           char challenge[1024];
1049           u_int success;
1050 
1051           success = skeychallenge(&skey, authctxt->user, challenge,
1052               sizeof(challenge)) < 0 ? 0 : 1;
1053 
1054           sshbuf_reset(m);
1055           sshbuf_put_int(m, success);
1056           if (success)
1057                     sshbuf_put_cstring(m, challenge);
1058 
1059           debug3("%s: sending challenge success: %u", __func__, success);
1060           mm_request_send(sock, MONITOR_ANS_SKEYQUERY, m);
1061 
1062           return (0);
1063 }
1064 
1065 int
mm_answer_skeyrespond(int sock,struct sshbuf * m)1066 mm_answer_skeyrespond(int sock, struct sshbuf *m)
1067 {
1068           char *response;
1069           int authok;
1070           int r;
1071 
1072           if ((r = sshbuf_get_cstring(m, &response, NULL)) != 0)
1073                     fatal("%s: buffer error: %s", __func__, ssh_err(r));
1074 
1075           authok = (options.kbd_interactive_authentication &&
1076               authctxt->valid &&
1077               skey_haskey(authctxt->pw->pw_name) == 0 &&
1078               skey_passcheck(authctxt->pw->pw_name, response) != -1);
1079 
1080           free(response);
1081 
1082           sshbuf_reset(m);
1083           sshbuf_put_int(m, authok);
1084 
1085           debug3("%s: sending authenticated: %d", __func__, authok);
1086           mm_request_send(sock, MONITOR_ANS_SKEYRESPOND, m);
1087 
1088           auth_method = "skey";
1089           auth_submethod = "bsdauth";
1090 
1091           return (authok != 0);
1092 }
1093 #endif
1094 
1095 #ifdef USE_PAM
1096 int
mm_answer_pam_start(struct ssh * ssh,int sock,struct sshbuf * m)1097 mm_answer_pam_start(struct ssh *ssh, int sock, struct sshbuf *m)
1098 {
1099           if (!options.use_pam)
1100                     fatal("UsePAM not set, but ended up in %s anyway", __func__);
1101 
1102           start_pam(ssh);
1103 
1104           if (options.kbd_interactive_authentication)
1105               monitor_permit(mon_dispatch, MONITOR_REQ_PAM_ACCOUNT, 1);
1106 
1107           return (0);
1108 }
1109 
1110 int
mm_answer_pam_account(struct ssh * ssh,int sock,struct sshbuf * m)1111 mm_answer_pam_account(struct ssh *ssh, int sock, struct sshbuf *m)
1112 {
1113           u_int ret;
1114           int r;
1115 
1116           if (!options.use_pam)
1117                     fatal("UsePAM not set, but ended up in %s anyway", __func__);
1118 
1119           ret = do_pam_account();
1120 
1121           if ((r = sshbuf_put_u32(m, ret)) != 0 ||
1122               (r = sshbuf_put_stringb(m, loginmsg)) != 0)
1123                     fatal("%s: buffer error: %s", __func__, ssh_err(r));
1124 
1125           mm_request_send(sock, MONITOR_ANS_PAM_ACCOUNT, m);
1126 
1127           return (ret);
1128 }
1129 
1130 static void *sshpam_ctxt, *sshpam_authok;
1131 extern KbdintDevice sshpam_device;
1132 
1133 int
mm_answer_pam_init_ctx(struct ssh * ssh,int sock,struct sshbuf * m)1134 mm_answer_pam_init_ctx(struct ssh *ssh, int sock, struct sshbuf *m)
1135 {
1136           u_int ok = 0;
1137           int r;
1138 
1139           debug3("%s", __func__);
1140           if (!options.kbd_interactive_authentication)
1141                     fatal("%s: kbd-int authentication not enabled", __func__);
1142           if (sshpam_ctxt != NULL)
1143                     fatal("%s: already called", __func__);
1144           sshpam_ctxt = (sshpam_device.init_ctx)(ssh->authctxt);
1145           sshpam_authok = NULL;
1146           sshbuf_reset(m);
1147           if (sshpam_ctxt != NULL) {
1148                     monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1);
1149                     monitor_permit(mon_dispatch, MONITOR_REQ_PAM_QUERY, 1);
1150                     ok = 1;
1151           }
1152           if ((r = sshbuf_put_u32(m, ok)) != 0)
1153                     fatal("%s: buffer error: %s", __func__, ssh_err(r));
1154           mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m);
1155           return (0);
1156 }
1157 
1158 int
mm_answer_pam_query(struct ssh * ssh,int sock,struct sshbuf * m)1159 mm_answer_pam_query(struct ssh *ssh, int sock, struct sshbuf *m)
1160 {
1161           char *name, *info, **prompts;
1162           u_int i, num, *echo_on;
1163           int r, ret;
1164 
1165           debug3("%s", __func__);
1166           sshpam_authok = NULL;
1167           if (sshpam_ctxt == NULL)
1168                     fatal("%s: no context", __func__);
1169           ret = (sshpam_device.query)(sshpam_ctxt, &name, &info,
1170               &num, &prompts, &echo_on);
1171           if (ret == 0 && num == 0)
1172                     sshpam_authok = sshpam_ctxt;
1173           if (num > 1 || name == NULL || info == NULL)
1174                     fatal("sshpam_device.query failed");
1175           monitor_permit(mon_dispatch, MONITOR_REQ_PAM_RESPOND, 1);
1176           sshbuf_reset(m);
1177           if ((r = sshbuf_put_u32(m, ret)) != 0 ||
1178               (r = sshbuf_put_cstring(m, name)) != 0 ||
1179               (r = sshbuf_put_cstring(m, info)) != 0 ||
1180               (r = sshbuf_put_u32(m, sshpam_get_maxtries_reached())) != 0 ||
1181               (r = sshbuf_put_u32(m, num)) != 0)
1182                     fatal("%s: buffer error: %s", __func__, ssh_err(r));
1183           free(name);
1184           free(info);
1185           for (i = 0; i < num; ++i) {
1186                     if ((r = sshbuf_put_cstring(m, prompts[i])) != 0 ||
1187                         (r = sshbuf_put_u32(m, echo_on[i])) != 0)
1188                               fatal("%s: buffer error: %s", __func__, ssh_err(r));
1189                     free(prompts[i]);
1190           }
1191           free(prompts);
1192           free(echo_on);
1193           auth_method = "keyboard-interactive/pam";
1194           auth_submethod = "pam";
1195           mm_request_send(sock, MONITOR_ANS_PAM_QUERY, m);
1196           return (0);
1197 }
1198 
1199 int
mm_answer_pam_respond(struct ssh * ssh,int sock,struct sshbuf * m)1200 mm_answer_pam_respond(struct ssh *ssh, int sock, struct sshbuf *m)
1201 {
1202           char **resp;
1203           u_int i, num;
1204           int r, ret;
1205 
1206           debug3("%s", __func__);
1207           if (sshpam_ctxt == NULL)
1208                     fatal("%s: no context", __func__);
1209           sshpam_authok = NULL;
1210           if ((r = sshbuf_get_u32(m, &num)) != 0)
1211                     fatal("%s: buffer error: %s", __func__, ssh_err(r));
1212           if (num > PAM_MAX_NUM_MSG) {
1213                     fatal_f("Too many PAM messages, got %u, expected <= %u",
1214                         num, (unsigned)PAM_MAX_NUM_MSG);
1215           }
1216           if (num > 0) {
1217                     resp = xmalloc(num * sizeof(char *));
1218                     for (i = 0; i < num; ++i)
1219                               if ((r = sshbuf_get_cstring(m, &resp[i], NULL)) != 0)
1220                                         fatal("%s: buffer error: %s", __func__,
1221                                             ssh_err(r));
1222                     ret = (sshpam_device.respond)(sshpam_ctxt, num, resp);
1223                     for (i = 0; i < num; ++i)
1224                               free(resp[i]);
1225                     free(resp);
1226           } else {
1227                     ret = (sshpam_device.respond)(sshpam_ctxt, num, NULL);
1228           }
1229           sshbuf_reset(m);
1230           if ((r = sshbuf_put_u32(m, ret)) != 0)
1231                     fatal("%s: buffer error: %s", __func__, ssh_err(r));
1232           mm_request_send(sock, MONITOR_ANS_PAM_RESPOND, m);
1233           auth_method = "keyboard-interactive/pam";
1234           auth_submethod = "pam";
1235           if (ret == 0)
1236                     sshpam_authok = sshpam_ctxt;
1237           return (0);
1238 }
1239 
1240 int
mm_answer_pam_free_ctx(struct ssh * ssh,int sock,struct sshbuf * m)1241 mm_answer_pam_free_ctx(struct ssh *ssh, int sock, struct sshbuf *m)
1242 {
1243           int r = sshpam_authok != NULL && sshpam_authok == sshpam_ctxt;
1244 
1245           debug3("%s", __func__);
1246           if (sshpam_ctxt == NULL)
1247                     fatal("%s: no context", __func__);
1248           (sshpam_device.free_ctx)(sshpam_ctxt);
1249           sshpam_ctxt = sshpam_authok = NULL;
1250           sshbuf_reset(m);
1251           mm_request_send(sock, MONITOR_ANS_PAM_FREE_CTX, m);
1252           /* Allow another attempt */
1253           monitor_permit(mon_dispatch, MONITOR_REQ_PAM_INIT_CTX, 1);
1254           auth_method = "keyboard-interactive/pam";
1255           auth_submethod = "pam";
1256           return r;
1257 }
1258 #endif
1259 
1260 /*
1261  * Check that the key type appears in the supplied pattern list, ignoring
1262  * mismatches in the signature algorithm. (Signature algorithm checks are
1263  * performed in the unprivileged authentication code).
1264  * Returns 1 on success, 0 otherwise.
1265  */
1266 static int
key_base_type_match(const char * method,const struct sshkey * key,const char * list)1267 key_base_type_match(const char *method, const struct sshkey *key,
1268     const char *list)
1269 {
1270           char *s, *l, *ol = xstrdup(list);
1271           int found = 0;
1272 
1273           l = ol;
1274           for ((s = strsep(&l, ",")); s && *s != '\0'; (s = strsep(&l, ","))) {
1275                     if (sshkey_type_from_name(s) == key->type) {
1276                               found = 1;
1277                               break;
1278                     }
1279           }
1280           if (!found) {
1281                     error("%s key type %s is not in permitted list %s", method,
1282                         sshkey_ssh_name(key), list);
1283           }
1284 
1285           free(ol);
1286           return found;
1287 }
1288 
1289 int
mm_answer_keyallowed(struct ssh * ssh,int sock,struct sshbuf * m)1290 mm_answer_keyallowed(struct ssh *ssh, int sock, struct sshbuf *m)
1291 {
1292           struct sshkey *key = NULL;
1293           char *cuser, *chost;
1294           u_int pubkey_auth_attempt;
1295           u_int type = 0;
1296           int r, allowed = 0;
1297           struct sshauthopt *opts = NULL;
1298 
1299           debug3_f("entering");
1300           if ((r = sshbuf_get_u32(m, &type)) != 0 ||
1301               (r = sshbuf_get_cstring(m, &cuser, NULL)) != 0 ||
1302               (r = sshbuf_get_cstring(m, &chost, NULL)) != 0 ||
1303               (r = sshkey_froms(m, &key)) != 0 ||
1304               (r = sshbuf_get_u32(m, &pubkey_auth_attempt)) != 0)
1305                     fatal_fr(r, "parse");
1306 
1307           if (key != NULL && authctxt->valid) {
1308                     switch (type) {
1309                     case MM_USERKEY:
1310                               auth_method = "publickey";
1311                               if (!options.pubkey_authentication)
1312                                         break;
1313                               if (auth2_key_already_used(authctxt, key))
1314                                         break;
1315                               if (!key_base_type_match(auth_method, key,
1316                                   options.pubkey_accepted_algos))
1317                                         break;
1318                               allowed = user_key_allowed(ssh, authctxt->pw, key,
1319                                   pubkey_auth_attempt, &opts);
1320                               break;
1321                     case MM_HOSTKEY:
1322                               auth_method = "hostbased";
1323                               if (!options.hostbased_authentication)
1324                                         break;
1325                               if (auth2_key_already_used(authctxt, key))
1326                                         break;
1327                               if (!key_base_type_match(auth_method, key,
1328                                   options.hostbased_accepted_algos))
1329                                         break;
1330                               allowed = hostbased_key_allowed(ssh, authctxt->pw,
1331                                   cuser, chost, key);
1332                               auth2_record_info(authctxt,
1333                                   "client user \"%.100s\", client host \"%.100s\"",
1334                                   cuser, chost);
1335                               break;
1336                     default:
1337                               fatal_f("unknown key type %u", type);
1338                               break;
1339                     }
1340           }
1341 
1342           debug3_f("%s authentication%s: %s key is %s", auth_method,
1343               pubkey_auth_attempt ? "" : " test",
1344               (key == NULL || !authctxt->valid) ? "invalid" : sshkey_type(key),
1345               allowed ? "allowed" : "not allowed");
1346 
1347           auth2_record_key(authctxt, 0, key);
1348 
1349           /* clear temporarily storage (used by verify) */
1350           monitor_reset_key_state();
1351 
1352           if (allowed) {
1353                     /* Save temporarily for comparison in verify */
1354                     if ((r = sshkey_to_blob(key, &key_blob, &key_bloblen)) != 0)
1355                               fatal_fr(r, "sshkey_to_blob");
1356                     key_blobtype = type;
1357                     key_opts = opts;
1358                     hostbased_cuser = cuser;
1359                     hostbased_chost = chost;
1360           } else {
1361                     /* Log failed attempt */
1362                     auth_log(ssh, 0, 0, auth_method, NULL);
1363                     free(cuser);
1364                     free(chost);
1365           }
1366           sshkey_free(key);
1367 
1368           sshbuf_reset(m);
1369           if ((r = sshbuf_put_u32(m, allowed)) != 0)
1370                     fatal_fr(r, "assemble");
1371           if (opts != NULL && (r = sshauthopt_serialise(opts, m, 1)) != 0)
1372                     fatal_fr(r, "sshauthopt_serialise");
1373           mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m);
1374 
1375           if (!allowed)
1376                     sshauthopt_free(opts);
1377 
1378           return (0);
1379 }
1380 
1381 static int
monitor_valid_userblob(struct ssh * ssh,const u_char * data,u_int datalen)1382 monitor_valid_userblob(struct ssh *ssh, const u_char *data, u_int datalen)
1383 {
1384           struct sshbuf *b;
1385           struct sshkey *hostkey = NULL;
1386           const u_char *p;
1387           char *userstyle, *cp;
1388           size_t len;
1389           u_char type;
1390           int hostbound = 0, r, fail = 0;
1391 
1392           if ((b = sshbuf_from(data, datalen)) == NULL)
1393                     fatal_f("sshbuf_from");
1394 
1395           if (ssh->compat & SSH_OLD_SESSIONID) {
1396                     p = sshbuf_ptr(b);
1397                     len = sshbuf_len(b);
1398                     if ((session_id2 == NULL) ||
1399                         (len < session_id2_len) ||
1400                         (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1401                               fail++;
1402                     if ((r = sshbuf_consume(b, session_id2_len)) != 0)
1403                               fatal_fr(r, "consume");
1404           } else {
1405                     if ((r = sshbuf_get_string_direct(b, &p, &len)) != 0)
1406                               fatal_fr(r, "parse sessionid");
1407                     if ((session_id2 == NULL) ||
1408                         (len != session_id2_len) ||
1409                         (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1410                               fail++;
1411           }
1412           if ((r = sshbuf_get_u8(b, &type)) != 0)
1413                     fatal_fr(r, "parse type");
1414           if (type != SSH2_MSG_USERAUTH_REQUEST)
1415                     fail++;
1416           if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1417                     fatal_fr(r, "parse userstyle");
1418           xasprintf(&userstyle, "%s%s%s", authctxt->user,
1419               authctxt->style ? ":" : "",
1420               authctxt->style ? authctxt->style : "");
1421           if (strcmp(userstyle, cp) != 0) {
1422                     logit("wrong user name passed to monitor: "
1423                         "expected %s != %.100s", userstyle, cp);
1424                     fail++;
1425           }
1426           free(userstyle);
1427           free(cp);
1428           if ((r = sshbuf_skip_string(b)) != 0 || /* service */
1429               (r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1430                     fatal_fr(r, "parse method");
1431           if (strcmp("publickey", cp) != 0) {
1432                     if (strcmp("publickey-hostbound-v00@openssh.com", cp) == 0)
1433                               hostbound = 1;
1434                     else
1435                               fail++;
1436           }
1437           free(cp);
1438           if ((r = sshbuf_get_u8(b, &type)) != 0)
1439                     fatal_fr(r, "parse pktype");
1440           if (type == 0)
1441                     fail++;
1442           if ((r = sshbuf_skip_string(b)) != 0 || /* pkalg */
1443               (r = sshbuf_skip_string(b)) != 0 || /* pkblob */
1444               (hostbound && (r = sshkey_froms(b, &hostkey)) != 0))
1445                     fatal_fr(r, "parse pk");
1446           if (sshbuf_len(b) != 0)
1447                     fail++;
1448           sshbuf_free(b);
1449           if (hostkey != NULL) {
1450                     /*
1451                      * Ensure this is actually one of our hostkeys; unfortunately
1452                      * can't check ssh->kex->initial_hostkey directly at this point
1453                      * as packet state has not yet been exported to monitor.
1454                      */
1455                     if (get_hostkey_index(hostkey, 1, ssh) == -1)
1456                               fatal_f("hostbound hostkey does not match");
1457                     sshkey_free(hostkey);
1458           }
1459           return (fail == 0);
1460 }
1461 
1462 static int
monitor_valid_hostbasedblob(struct ssh * ssh,const u_char * data,u_int datalen,const char * cuser,const char * chost)1463 monitor_valid_hostbasedblob(struct ssh *ssh, const u_char *data, u_int datalen,
1464     const char *cuser, const char *chost)
1465 {
1466           struct sshbuf *b;
1467           const u_char *p;
1468           char *cp, *userstyle;
1469           size_t len;
1470           int r, fail = 0;
1471           u_char type;
1472 
1473           if ((b = sshbuf_from(data, datalen)) == NULL)
1474                     fatal_f("sshbuf_new");
1475           if ((r = sshbuf_get_string_direct(b, &p, &len)) != 0)
1476                     fatal_fr(r, "parse sessionid");
1477 
1478           if ((session_id2 == NULL) ||
1479               (len != session_id2_len) ||
1480               (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1481                     fail++;
1482 
1483           if ((r = sshbuf_get_u8(b, &type)) != 0)
1484                     fatal_fr(r, "parse type");
1485           if (type != SSH2_MSG_USERAUTH_REQUEST)
1486                     fail++;
1487           if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1488                     fatal_fr(r, "parse userstyle");
1489           xasprintf(&userstyle, "%s%s%s", authctxt->user,
1490               authctxt->style ? ":" : "",
1491               authctxt->style ? authctxt->style : "");
1492           if (strcmp(userstyle, cp) != 0) {
1493                     logit("wrong user name passed to monitor: "
1494                         "expected %s != %.100s", userstyle, cp);
1495                     fail++;
1496           }
1497           free(userstyle);
1498           free(cp);
1499           if ((r = sshbuf_skip_string(b)) != 0 || /* service */
1500               (r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1501                     fatal_fr(r, "parse method");
1502           if (strcmp(cp, "hostbased") != 0)
1503                     fail++;
1504           free(cp);
1505           if ((r = sshbuf_skip_string(b)) != 0 || /* pkalg */
1506               (r = sshbuf_skip_string(b)) != 0)   /* pkblob */
1507                     fatal_fr(r, "parse pk");
1508 
1509           /* verify client host, strip trailing dot if necessary */
1510           if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1511                     fatal_fr(r, "parse host");
1512           if (((len = strlen(cp)) > 0) && cp[len - 1] == '.')
1513                     cp[len - 1] = '\0';
1514           if (strcmp(cp, chost) != 0)
1515                     fail++;
1516           free(cp);
1517 
1518           /* verify client user */
1519           if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1520                     fatal_fr(r, "parse ruser");
1521           if (strcmp(cp, cuser) != 0)
1522                     fail++;
1523           free(cp);
1524 
1525           if (sshbuf_len(b) != 0)
1526                     fail++;
1527           sshbuf_free(b);
1528           return (fail == 0);
1529 }
1530 
1531 int
mm_answer_keyverify(struct ssh * ssh,int sock,struct sshbuf * m)1532 mm_answer_keyverify(struct ssh *ssh, int sock, struct sshbuf *m)
1533 {
1534           struct sshkey *key;
1535           const u_char *signature, *data, *blob;
1536           char *sigalg = NULL, *fp = NULL;
1537           size_t signaturelen, datalen, bloblen;
1538           int r, ret, req_presence = 0, req_verify = 0, valid_data = 0;
1539           int encoded_ret;
1540           struct sshkey_sig_details *sig_details = NULL;
1541 
1542           if ((r = sshbuf_get_string_direct(m, &blob, &bloblen)) != 0 ||
1543               (r = sshbuf_get_string_direct(m, &signature, &signaturelen)) != 0 ||
1544               (r = sshbuf_get_string_direct(m, &data, &datalen)) != 0 ||
1545               (r = sshbuf_get_cstring(m, &sigalg, NULL)) != 0)
1546                     fatal_fr(r, "parse");
1547 
1548           if (hostbased_cuser == NULL || hostbased_chost == NULL ||
1549             !monitor_allowed_key(blob, bloblen))
1550                     fatal_f("bad key, not previously allowed");
1551 
1552           /* Empty signature algorithm means NULL. */
1553           if (*sigalg == '\0') {
1554                     free(sigalg);
1555                     sigalg = NULL;
1556           }
1557 
1558           /* XXX use sshkey_froms here; need to change key_blob, etc. */
1559           if ((r = sshkey_from_blob(blob, bloblen, &key)) != 0)
1560                     fatal_fr(r, "parse key");
1561 
1562           switch (key_blobtype) {
1563           case MM_USERKEY:
1564                     valid_data = monitor_valid_userblob(ssh, data, datalen);
1565                     auth_method = "publickey";
1566                     break;
1567           case MM_HOSTKEY:
1568                     valid_data = monitor_valid_hostbasedblob(ssh, data, datalen,
1569                         hostbased_cuser, hostbased_chost);
1570                     auth_method = "hostbased";
1571                     break;
1572           default:
1573                     valid_data = 0;
1574                     break;
1575           }
1576           if (!valid_data)
1577                     fatal_f("bad %s signature data blob",
1578                         key_blobtype == MM_USERKEY ? "userkey" :
1579                         (key_blobtype == MM_HOSTKEY ? "hostkey" : "unknown"));
1580 
1581           if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
1582               SSH_FP_DEFAULT)) == NULL)
1583                     fatal_f("sshkey_fingerprint failed");
1584 
1585           ret = sshkey_verify(key, signature, signaturelen, data, datalen,
1586               sigalg, ssh->compat, &sig_details);
1587           debug3_f("%s %s signature using %s %s%s%s", auth_method,
1588               sshkey_type(key), sigalg == NULL ? "default" : sigalg,
1589               (ret == 0) ? "verified" : "unverified",
1590               (ret != 0) ? ": " : "", (ret != 0) ? ssh_err(ret) : "");
1591 
1592           if (ret == 0 && key_blobtype == MM_USERKEY && sig_details != NULL) {
1593                     req_presence = (options.pubkey_auth_options &
1594                         PUBKEYAUTH_TOUCH_REQUIRED) ||
1595                         !key_opts->no_require_user_presence;
1596                     if (req_presence &&
1597                         (sig_details->sk_flags & SSH_SK_USER_PRESENCE_REQD) == 0) {
1598                               error("public key %s %s signature for %s%s from %.128s "
1599                                   "port %d rejected: user presence "
1600                                   "(authenticator touch) requirement not met ",
1601                                   sshkey_type(key), fp,
1602                                   authctxt->valid ? "" : "invalid user ",
1603                                   authctxt->user, ssh_remote_ipaddr(ssh),
1604                                   ssh_remote_port(ssh));
1605                               ret = SSH_ERR_SIGNATURE_INVALID;
1606                     }
1607                     req_verify = (options.pubkey_auth_options &
1608                         PUBKEYAUTH_VERIFY_REQUIRED) || key_opts->require_verify;
1609                     if (req_verify &&
1610                         (sig_details->sk_flags & SSH_SK_USER_VERIFICATION_REQD) == 0) {
1611                               error("public key %s %s signature for %s%s from %.128s "
1612                                   "port %d rejected: user verification requirement "
1613                                   "not met ", sshkey_type(key), fp,
1614                                   authctxt->valid ? "" : "invalid user ",
1615                                   authctxt->user, ssh_remote_ipaddr(ssh),
1616                                   ssh_remote_port(ssh));
1617                               ret = SSH_ERR_SIGNATURE_INVALID;
1618                     }
1619           }
1620           auth2_record_key(authctxt, ret == 0, key);
1621 
1622           if (key_blobtype == MM_USERKEY && ret == 0)
1623                     auth_activate_options(ssh, key_opts);
1624           monitor_reset_key_state();
1625 
1626           sshbuf_reset(m);
1627 
1628           /* encode ret != 0 as positive integer, since we're sending u32 */
1629           encoded_ret = (ret != 0);
1630           if ((r = sshbuf_put_u32(m, encoded_ret)) != 0 ||
1631               (r = sshbuf_put_u8(m, sig_details != NULL)) != 0)
1632                     fatal_fr(r, "assemble");
1633           if (sig_details != NULL) {
1634                     if ((r = sshbuf_put_u32(m, sig_details->sk_counter)) != 0 ||
1635                         (r = sshbuf_put_u8(m, sig_details->sk_flags)) != 0)
1636                               fatal_fr(r, "assemble sk");
1637           }
1638           sshkey_sig_details_free(sig_details);
1639           mm_request_send(sock, MONITOR_ANS_KEYVERIFY, m);
1640 
1641           free(sigalg);
1642           free(fp);
1643           sshkey_free(key);
1644 
1645           return ret == 0;
1646 }
1647 
1648 static void
mm_record_login(struct ssh * ssh,Session * s,struct passwd * pw)1649 mm_record_login(struct ssh *ssh, Session *s, struct passwd *pw)
1650 {
1651           socklen_t fromlen;
1652           struct sockaddr_storage from;
1653 
1654           /*
1655            * Get IP address of client. If the connection is not a socket, let
1656            * the address be 0.0.0.0.
1657            */
1658           memset(&from, 0, sizeof(from));
1659           fromlen = sizeof(from);
1660           if (ssh_packet_connection_is_on_socket(ssh)) {
1661                     if (getpeername(ssh_packet_get_connection_in(ssh),
1662                         (struct sockaddr *)&from, &fromlen) == -1) {
1663                               debug("getpeername: %.100s", strerror(errno));
1664                               cleanup_exit(255);
1665                     }
1666           }
1667           /* Record that there was a login on that tty from the remote host. */
1668           record_login(s->pid, s->tty, pw->pw_name, pw->pw_uid,
1669               session_get_remote_name_or_ip(ssh, utmp_len, options.use_dns),
1670               (struct sockaddr *)&from, fromlen);
1671 }
1672 
1673 static void
mm_session_close(Session * s)1674 mm_session_close(Session *s)
1675 {
1676           debug3_f("session %d pid %ld", s->self, (long)s->pid);
1677           if (s->ttyfd != -1) {
1678                     debug3_f("tty %s ptyfd %d", s->tty, s->ptyfd);
1679                     session_pty_cleanup2(s);
1680           }
1681           session_unused(s->self);
1682 }
1683 
1684 int
mm_answer_pty(struct ssh * ssh,int sock,struct sshbuf * m)1685 mm_answer_pty(struct ssh *ssh, int sock, struct sshbuf *m)
1686 {
1687           extern struct monitor *pmonitor;
1688           Session *s;
1689           int r, res, fd0;
1690 
1691           debug3_f("entering");
1692 
1693           sshbuf_reset(m);
1694           s = session_new();
1695           if (s == NULL)
1696                     goto error;
1697           s->authctxt = authctxt;
1698           s->pw = authctxt->pw;
1699           s->pid = pmonitor->m_pid;
1700           res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty));
1701           if (res == 0)
1702                     goto error;
1703           pty_setowner(authctxt->pw, s->tty);
1704 
1705           if ((r = sshbuf_put_u32(m, 1)) != 0 ||
1706               (r = sshbuf_put_cstring(m, s->tty)) != 0)
1707                     fatal_fr(r, "assemble");
1708 
1709           /* We need to trick ttyslot */
1710           if (dup2(s->ttyfd, 0) == -1)
1711                     fatal_f("dup2");
1712 
1713           mm_record_login(ssh, s, authctxt->pw);
1714 
1715           /* Now we can close the file descriptor again */
1716           close(0);
1717 
1718           /* send messages generated by record_login */
1719           if ((r = sshbuf_put_stringb(m, loginmsg)) != 0)
1720                     fatal_fr(r, "assemble loginmsg");
1721           sshbuf_reset(loginmsg);
1722 
1723           mm_request_send(sock, MONITOR_ANS_PTY, m);
1724 
1725           if (mm_send_fd(sock, s->ptyfd) == -1 ||
1726               mm_send_fd(sock, s->ttyfd) == -1)
1727                     fatal_f("send fds failed");
1728 
1729           /* make sure nothing uses fd 0 */
1730           if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1731                     fatal_f("open(/dev/null): %s", strerror(errno));
1732           if (fd0 != 0)
1733                     error_f("fd0 %d != 0", fd0);
1734 
1735           /* slave side of pty is not needed */
1736           close(s->ttyfd);
1737           s->ttyfd = s->ptyfd;
1738           /* no need to dup() because nobody closes ptyfd */
1739           s->ptymaster = s->ptyfd;
1740 
1741           debug3_f("tty %s ptyfd %d", s->tty, s->ttyfd);
1742 
1743           return (0);
1744 
1745  error:
1746           if (s != NULL)
1747                     mm_session_close(s);
1748           if ((r = sshbuf_put_u32(m, 0)) != 0)
1749                     fatal_fr(r, "assemble 0");
1750           mm_request_send(sock, MONITOR_ANS_PTY, m);
1751           return (0);
1752 }
1753 
1754 int
mm_answer_pty_cleanup(struct ssh * ssh,int sock,struct sshbuf * m)1755 mm_answer_pty_cleanup(struct ssh *ssh, int sock, struct sshbuf *m)
1756 {
1757           Session *s;
1758           char *tty;
1759           int r;
1760 
1761           debug3_f("entering");
1762 
1763           if ((r = sshbuf_get_cstring(m, &tty, NULL)) != 0)
1764                     fatal_fr(r, "parse tty");
1765           if ((s = session_by_tty(tty)) != NULL)
1766                     mm_session_close(s);
1767           sshbuf_reset(m);
1768           free(tty);
1769           return (0);
1770 }
1771 
1772 #ifdef KRB5
1773 int
mm_answer_krb5(struct ssh * ssh,int xsocket,struct sshbuf * m)1774 mm_answer_krb5(struct ssh *ssh, int xsocket, struct sshbuf *m)
1775 {
1776           krb5_data tkt, reply;
1777           char *client_user;
1778           unsigned char *data;
1779           size_t len;
1780           int r;
1781           int success;
1782 
1783           /* use temporary var to avoid size issues on 64bit arch */
1784           if ((r = sshbuf_get_string(m, &data, &len)) != 0)
1785                     fatal("%s: buffer error: %s", __func__, ssh_err(r));
1786           tkt.data = data;
1787           tkt.length = len;
1788 
1789           success = options.kerberos_authentication &&
1790               authctxt->valid &&
1791               auth_krb5(ssh, &tkt, &client_user, &reply);
1792 
1793           if (tkt.length)
1794                     free(tkt.data);
1795 
1796           sshbuf_reset(m);
1797           sshbuf_put_u32(m, success);
1798 
1799           if (success) {
1800                     sshbuf_put_cstring(m, client_user);
1801                     sshbuf_put_string(m, reply.data, reply.length);
1802                     if (client_user)
1803                               free(client_user);
1804                     if (reply.length)
1805                               free(reply.data);
1806           }
1807           mm_request_send(xsocket, MONITOR_ANS_KRB5, m);
1808 
1809           auth_method = "kerberos";
1810 
1811           return success;
1812 }
1813 #endif
1814 
1815 int
mm_answer_term(struct ssh * ssh,int sock,struct sshbuf * req)1816 mm_answer_term(struct ssh *ssh, int sock, struct sshbuf *req)
1817 {
1818           extern struct monitor *pmonitor;
1819           int res, status;
1820 
1821           debug3_f("tearing down sessions");
1822 
1823           /* The child is terminating */
1824           session_destroy_all(ssh, &mm_session_close);
1825 
1826 #ifdef USE_PAM
1827           if (options.use_pam)
1828                     sshpam_cleanup();
1829 #endif
1830 
1831           while (waitpid(pmonitor->m_pid, &status, 0) == -1)
1832                     if (errno != EINTR)
1833                               exit(1);
1834 
1835           res = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
1836 
1837           /* Terminate process */
1838           exit(res);
1839 }
1840 
1841 void
monitor_clear_keystate(struct ssh * ssh,struct monitor * pmonitor)1842 monitor_clear_keystate(struct ssh *ssh, struct monitor *pmonitor)
1843 {
1844           ssh_clear_newkeys(ssh, MODE_IN);
1845           ssh_clear_newkeys(ssh, MODE_OUT);
1846           sshbuf_free(child_state);
1847           child_state = NULL;
1848 }
1849 
1850 void
monitor_apply_keystate(struct ssh * ssh,struct monitor * pmonitor)1851 monitor_apply_keystate(struct ssh *ssh, struct monitor *pmonitor)
1852 {
1853           struct kex *kex;
1854           int r;
1855 
1856           debug3_f("packet_set_state");
1857           if ((r = ssh_packet_set_state(ssh, child_state)) != 0)
1858                     fatal_fr(r, "packet_set_state");
1859           sshbuf_free(child_state);
1860           child_state = NULL;
1861           if ((kex = ssh->kex) == NULL)
1862                     fatal_f("internal error: ssh->kex == NULL");
1863           if (session_id2_len != sshbuf_len(ssh->kex->session_id)) {
1864                     fatal_f("incorrect session id length %zu (expected %u)",
1865                         sshbuf_len(ssh->kex->session_id), session_id2_len);
1866           }
1867           if (memcmp(sshbuf_ptr(ssh->kex->session_id), session_id2,
1868               session_id2_len) != 0)
1869                     fatal_f("session ID mismatch");
1870           /* XXX set callbacks */
1871 #ifdef WITH_OPENSSL
1872           kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
1873           kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
1874           kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
1875           kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
1876           kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
1877           kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1878           kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1879           kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
1880 #endif
1881           kex->kex[KEX_C25519_SHA256] = kex_gen_server;
1882           kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
1883           kex->kex[KEX_KEM_MLKEM768X25519_SHA256] = kex_gen_server;
1884           kex->load_host_public_key=&get_hostkey_public_by_type;
1885           kex->load_host_private_key=&get_hostkey_private_by_type;
1886           kex->host_key_index=&get_hostkey_index;
1887           kex->sign = sshd_hostkey_sign;
1888 }
1889 
1890 /* This function requires careful sanity checking */
1891 
1892 void
mm_get_keystate(struct ssh * ssh,struct monitor * pmonitor)1893 mm_get_keystate(struct ssh *ssh, struct monitor *pmonitor)
1894 {
1895           debug3_f("Waiting for new keys");
1896 
1897           if ((child_state = sshbuf_new()) == NULL)
1898                     fatal_f("sshbuf_new failed");
1899           mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT,
1900               child_state);
1901           debug3_f("GOT new keys");
1902 }
1903 
1904 
1905 /* XXX */
1906 
1907 #define FD_CLOSEONEXEC(x) do { \
1908           if (fcntl(x, F_SETFD, FD_CLOEXEC) == -1) \
1909                     fatal("fcntl(%d, F_SETFD)", x); \
1910 } while (0)
1911 
1912 static void
monitor_openfds(struct monitor * mon,int do_logfds)1913 monitor_openfds(struct monitor *mon, int do_logfds)
1914 {
1915           int pair[2];
1916 #ifdef SO_ZEROIZE
1917           int on = 1;
1918 #endif
1919 
1920           if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
1921                     fatal_f("socketpair: %s", strerror(errno));
1922 #ifdef SO_ZEROIZE
1923           if (setsockopt(pair[0], SOL_SOCKET, SO_ZEROIZE, &on, sizeof(on)) == -1)
1924                     error("setsockopt SO_ZEROIZE(0): %.100s", strerror(errno));
1925           if (setsockopt(pair[1], SOL_SOCKET, SO_ZEROIZE, &on, sizeof(on)) == -1)
1926                     error("setsockopt SO_ZEROIZE(1): %.100s", strerror(errno));
1927 #endif
1928           FD_CLOSEONEXEC(pair[0]);
1929           FD_CLOSEONEXEC(pair[1]);
1930           mon->m_recvfd = pair[0];
1931           mon->m_sendfd = pair[1];
1932 
1933           if (do_logfds) {
1934                     if (pipe(pair) == -1)
1935                               fatal_f("pipe: %s", strerror(errno));
1936                     FD_CLOSEONEXEC(pair[0]);
1937                     FD_CLOSEONEXEC(pair[1]);
1938                     mon->m_log_recvfd = pair[0];
1939                     mon->m_log_sendfd = pair[1];
1940           } else
1941                     mon->m_log_recvfd = mon->m_log_sendfd = -1;
1942 }
1943 
1944 struct monitor *
monitor_init(void)1945 monitor_init(void)
1946 {
1947           struct monitor *mon;
1948 
1949           mon = xcalloc(1, sizeof(*mon));
1950           monitor_openfds(mon, 1);
1951 
1952           return mon;
1953 }
1954 
1955 void
monitor_reinit(struct monitor * mon)1956 monitor_reinit(struct monitor *mon)
1957 {
1958           monitor_openfds(mon, 0);
1959 }
1960 
1961 #ifdef GSSAPI
1962 int
mm_answer_gss_setup_ctx(struct ssh * ssh,int sock,struct sshbuf * m)1963 mm_answer_gss_setup_ctx(struct ssh *ssh, int sock, struct sshbuf *m)
1964 {
1965           gss_OID_desc goid;
1966           OM_uint32 major;
1967           size_t len;
1968           u_char *p;
1969           int r;
1970 
1971           if (!options.gss_authentication)
1972                     fatal_f("GSSAPI authentication not enabled");
1973 
1974           if ((r = sshbuf_get_string(m, &p, &len)) != 0)
1975                     fatal_fr(r, "parse");
1976           goid.elements = p;
1977           goid.length = len;
1978 
1979           major = ssh_gssapi_server_ctx(&gsscontext, &goid);
1980 
1981           free(goid.elements);
1982 
1983           sshbuf_reset(m);
1984           if ((r = sshbuf_put_u32(m, major)) != 0)
1985                     fatal_fr(r, "assemble");
1986 
1987           mm_request_send(sock, MONITOR_ANS_GSSSETUP, m);
1988 
1989           /* Now we have a context, enable the step */
1990           monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 1);
1991 
1992           return (0);
1993 }
1994 
1995 int
mm_answer_gss_accept_ctx(struct ssh * ssh,int sock,struct sshbuf * m)1996 mm_answer_gss_accept_ctx(struct ssh *ssh, int sock, struct sshbuf *m)
1997 {
1998           gss_buffer_desc in;
1999           gss_buffer_desc out = GSS_C_EMPTY_BUFFER;
2000           OM_uint32 major, minor;
2001           OM_uint32 flags = 0; /* GSI needs this */
2002           int r;
2003 
2004           if (!options.gss_authentication)
2005                     fatal_f("GSSAPI authentication not enabled");
2006 
2007           if ((r = ssh_gssapi_get_buffer_desc(m, &in)) != 0)
2008                     fatal_fr(r, "ssh_gssapi_get_buffer_desc");
2009           major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags);
2010           free(in.value);
2011 
2012           sshbuf_reset(m);
2013           if ((r = sshbuf_put_u32(m, major)) != 0 ||
2014               (r = sshbuf_put_string(m, out.value, out.length)) != 0 ||
2015               (r = sshbuf_put_u32(m, flags)) != 0)
2016                     fatal_fr(r, "assemble");
2017           mm_request_send(sock, MONITOR_ANS_GSSSTEP, m);
2018 
2019           gss_release_buffer(&minor, &out);
2020 
2021           if (major == GSS_S_COMPLETE) {
2022                     monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
2023                     monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
2024                     monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
2025           }
2026           return (0);
2027 }
2028 
2029 int
mm_answer_gss_checkmic(struct ssh * ssh,int sock,struct sshbuf * m)2030 mm_answer_gss_checkmic(struct ssh *ssh, int sock, struct sshbuf *m)
2031 {
2032           gss_buffer_desc gssbuf, mic;
2033           OM_uint32 ret;
2034           int r;
2035 
2036           if (!options.gss_authentication)
2037                     fatal_f("GSSAPI authentication not enabled");
2038 
2039           if ((r = ssh_gssapi_get_buffer_desc(m, &gssbuf)) != 0 ||
2040               (r = ssh_gssapi_get_buffer_desc(m, &mic)) != 0)
2041                     fatal_fr(r, "ssh_gssapi_get_buffer_desc");
2042 
2043           ret = ssh_gssapi_checkmic(gsscontext, &gssbuf, &mic);
2044 
2045           free(gssbuf.value);
2046           free(mic.value);
2047 
2048           sshbuf_reset(m);
2049           if ((r = sshbuf_put_u32(m, ret)) != 0)
2050                     fatal_fr(r, "assemble");
2051 
2052           mm_request_send(sock, MONITOR_ANS_GSSCHECKMIC, m);
2053 
2054           if (!GSS_ERROR(ret))
2055                     monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
2056 
2057           return (0);
2058 }
2059 
2060 int
mm_answer_gss_userok(struct ssh * ssh,int sock,struct sshbuf * m)2061 mm_answer_gss_userok(struct ssh *ssh, int sock, struct sshbuf *m)
2062 {
2063           int r, authenticated;
2064           const char *displayname;
2065 
2066           if (!options.gss_authentication)
2067                     fatal_f("GSSAPI authentication not enabled");
2068 
2069           authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user);
2070 
2071           sshbuf_reset(m);
2072           if ((r = sshbuf_put_u32(m, authenticated)) != 0)
2073                     fatal_fr(r, "assemble");
2074 
2075           debug3_f("sending result %d", authenticated);
2076           mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m);
2077 
2078           auth_method = "gssapi-with-mic";
2079 
2080           if ((displayname = ssh_gssapi_displayname()) != NULL)
2081                     auth2_record_info(authctxt, "%s", displayname);
2082 
2083           /* Monitor loop will terminate if authenticated */
2084           return (authenticated);
2085 }
2086 #endif /* GSSAPI */
2087 
2088