1 /*
2  * SSH backend.
3  */
4 
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdarg.h>
8 #include <assert.h>
9 #include <limits.h>
10 #include <signal.h>
11 
12 #include "putty.h"
13 #include "pageant.h" /* for AGENT_MAX_MSGLEN */
14 #include "tree234.h"
15 #include "storage.h"
16 #include "marshal.h"
17 #include "ssh.h"
18 #include "sshcr.h"
19 #include "sshbpp.h"
20 #include "sshppl.h"
21 #include "sshchan.h"
22 #ifndef NO_GSSAPI
23 #include "sshgssc.h"
24 #include "sshgss.h"
25 #define MIN_CTXT_LIFETIME 5     /* Avoid rekey with short lifetime (seconds) */
26 #define GSS_KEX_CAPABLE (1<<0)  /* Can do GSS KEX */
27 #define GSS_CRED_UPDATED (1<<1) /* Cred updated since previous delegation */
28 #define GSS_CTXT_EXPIRES (1<<2) /* Context expires before next timer */
29 #define GSS_CTXT_MAYFAIL (1<<3) /* Context may expire during handshake */
30 #endif
31 
32 struct Ssh {
33     Socket *s;
34     Seat *seat;
35     Conf *conf;
36 
37     struct ssh_version_receiver version_receiver;
38     int remote_bugs;
39 
40     Plug plug;
41     Backend backend;
42 
43     Ldisc *ldisc;
44     LogContext *logctx;
45 
46     /* The last list returned from get_specials. */
47     SessionSpecial *specials;
48 
49     bool bare_connection;
50     ssh_sharing_state *connshare;
51     bool attempting_connshare;
52 
53 #ifndef NO_GSSAPI
54     struct ssh_connection_shared_gss_state gss_state;
55 #endif
56 
57     char *savedhost;
58     int savedport;
59     char *fullhostname;
60 
61     bool fallback_cmd;
62     int exitcode;
63 
64     int version;
65     int conn_throttle_count;
66     size_t overall_bufsize;
67     bool throttled_all;
68 
69     /*
70      * logically_frozen is true if we're not currently _processing_
71      * data from the SSH socket (e.g. because a higher layer has asked
72      * us not to due to ssh_throttle_conn). socket_frozen is true if
73      * we're not even _reading_ data from the socket (i.e. it should
74      * always match the value we last passed to sk_set_frozen).
75      *
76      * The two differ in that socket_frozen can also become
77      * temporarily true because of a large backlog in the in_raw
78      * bufchain, to force no further plug_receive events until the BPP
79      * input function has had a chance to run. (Some front ends, like
80      * GTK, can persistently call the network and never get round to
81      * the toplevel callbacks.) If we've stopped reading from the
82      * socket for that reason, we absolutely _do_ want to carry on
83      * processing our input bufchain, because that's the only way
84      * it'll ever get cleared!
85      *
86      * ssh_check_frozen() resets socket_frozen, and should be called
87      * whenever either of logically_frozen and the bufchain size
88      * changes.
89      */
90     bool logically_frozen, socket_frozen;
91 
92     /* in case we find these out before we have a ConnectionLayer to tell */
93     int term_width, term_height;
94 
95     bufchain in_raw, out_raw, user_input;
96     bool pending_close;
97     IdempotentCallback ic_out_raw;
98 
99     PacketLogSettings pls;
100     struct DataTransferStats stats;
101 
102     BinaryPacketProtocol *bpp;
103 
104     /*
105      * base_layer identifies the bottommost packet protocol layer, the
106      * one connected directly to the BPP's packet queues. Any
107      * operation that needs to talk to all layers (e.g. free, or
108      * get_specials) will do it by talking to this, which will
109      * recursively propagate it if necessary.
110      */
111     PacketProtocolLayer *base_layer;
112 
113     /*
114      * The ConnectionLayer vtable from our connection layer.
115      */
116     ConnectionLayer *cl;
117 
118     /*
119      * A dummy ConnectionLayer that can be used for logging sharing
120      * downstreams that connect before the real one is ready.
121      */
122     ConnectionLayer cl_dummy;
123 
124     /*
125      * session_started is false until we initialise the main protocol
126      * layers. So it distinguishes between base_layer==NULL meaning
127      * that the SSH protocol hasn't been set up _yet_, and
128      * base_layer==NULL meaning the SSH protocol has run and finished.
129      * It's also used to mark the point where we stop counting proxy
130      * command diagnostics as pre-session-startup.
131      */
132     bool session_started;
133 
134     Pinger *pinger;
135 
136     char *deferred_abort_message;
137 
138     bool need_random_unref;
139 };
140 
141 
ssh_get_socket(Ssh * ssh)142 Socket* ssh_get_socket(Ssh *ssh)
143 {
144     return ssh ? ssh->s : 0;
145 }
146 
147 #define ssh_logevent(params) ( \
148         logevent_and_free((ssh)->logctx, dupprintf params))
149 
150 static void ssh_shutdown(Ssh *ssh);
151 static void ssh_throttle_all(Ssh *ssh, bool enable, size_t bufsize);
152 static void ssh_bpp_output_raw_data_callback(void *vctx);
153 
ssh_get_logctx(Ssh * ssh)154 LogContext *ssh_get_logctx(Ssh *ssh)
155 {
156     return ssh->logctx;
157 }
158 
ssh_connect_bpp(Ssh * ssh)159 static void ssh_connect_bpp(Ssh *ssh)
160 {
161     ssh->bpp->ssh = ssh;
162     ssh->bpp->in_raw = &ssh->in_raw;
163     ssh->bpp->out_raw = &ssh->out_raw;
164     bufchain_set_callback(ssh->bpp->out_raw, &ssh->ic_out_raw);
165     ssh->bpp->pls = &ssh->pls;
166     ssh->bpp->logctx = ssh->logctx;
167     ssh->bpp->remote_bugs = ssh->remote_bugs;
168 }
169 
ssh_connect_ppl(Ssh * ssh,PacketProtocolLayer * ppl)170 static void ssh_connect_ppl(Ssh *ssh, PacketProtocolLayer *ppl)
171 {
172     ppl->bpp = ssh->bpp;
173     ppl->user_input = &ssh->user_input;
174     ppl->seat = ssh->seat;
175     ppl->ssh = ssh;
176     ppl->logctx = ssh->logctx;
177     ppl->remote_bugs = ssh->remote_bugs;
178 }
179 
ssh_got_ssh_version(struct ssh_version_receiver * rcv,int major_version)180 static void ssh_got_ssh_version(struct ssh_version_receiver *rcv,
181                                 int major_version)
182 {
183     Ssh *ssh = container_of(rcv, Ssh, version_receiver);
184     BinaryPacketProtocol *old_bpp;
185     PacketProtocolLayer *connection_layer;
186 
187     ssh->session_started = true;
188 
189     /*
190      * We don't support choosing a major protocol version dynamically,
191      * so this should always be the same value we set up in
192      * connect_to_host().
193      */
194     assert(ssh->version == major_version);
195 
196     old_bpp = ssh->bpp;
197     ssh->remote_bugs = ssh_verstring_get_bugs(old_bpp);
198 
199     if (!ssh->bare_connection) {
200         if (ssh->version == 2) {
201             PacketProtocolLayer *userauth_layer, *transport_child_layer;
202 
203             /*
204              * We use the 'simple' variant of the SSH protocol if
205              * we're asked to, except not if we're also doing
206              * connection-sharing (either tunnelling our packets over
207              * an upstream or expecting to be tunnelled over
208              * ourselves), since then the assumption that we have only
209              * one channel to worry about is not true after all.
210              */
211             bool is_simple =
212                 (conf_get_bool(ssh->conf, CONF_ssh_simple) && !ssh->connshare);
213 
214             ssh->bpp = ssh2_bpp_new(ssh->logctx, &ssh->stats, false);
215             ssh_connect_bpp(ssh);
216 
217 #ifndef NO_GSSAPI
218             /* Load and pick the highest GSS library on the preference
219              * list. */
220             if (!ssh->gss_state.libs)
221                 ssh->gss_state.libs = ssh_gss_setup(ssh->conf);
222             ssh->gss_state.lib = NULL;
223             if (ssh->gss_state.libs->nlibraries > 0) {
224                 int i, j;
225                 for (i = 0; i < ngsslibs; i++) {
226                     int want_id = conf_get_int_int(ssh->conf,
227                                                    CONF_ssh_gsslist, i);
228                     for (j = 0; j < ssh->gss_state.libs->nlibraries; j++)
229                         if (ssh->gss_state.libs->libraries[j].id == want_id) {
230                             ssh->gss_state.lib =
231                                 &ssh->gss_state.libs->libraries[j];
232                             goto got_gsslib;   /* double break */
233                         }
234                 }
235               got_gsslib:
236                 /*
237                  * We always expect to have found something in
238                  * the above loop: we only came here if there
239                  * was at least one viable GSS library, and the
240                  * preference list should always mention
241                  * everything and only change the order.
242                  */
243                 assert(ssh->gss_state.lib);
244             }
245 #endif
246 
247             connection_layer = ssh2_connection_new(
248                 ssh, ssh->connshare, is_simple, ssh->conf,
249                 ssh_verstring_get_remote(old_bpp), &ssh->cl);
250             ssh_connect_ppl(ssh, connection_layer);
251 
252             if (conf_get_bool(ssh->conf, CONF_ssh_no_userauth)) {
253                 userauth_layer = NULL;
254                 transport_child_layer = connection_layer;
255             } else {
256                 char *username = get_remote_username(ssh->conf);
257 
258                 userauth_layer = ssh2_userauth_new(
259                     connection_layer, ssh->savedhost, ssh->fullhostname,
260                     conf_get_filename(ssh->conf, CONF_keyfile),
261                     conf_get_bool(ssh->conf, CONF_ssh_show_banner),
262                     conf_get_bool(ssh->conf, CONF_tryagent),
263                     conf_get_bool(ssh->conf, CONF_ssh_no_trivial_userauth),
264                     username,
265                     conf_get_bool(ssh->conf, CONF_change_username),
266                     conf_get_bool(ssh->conf, CONF_try_ki_auth),
267 #ifndef NO_GSSAPI
268                     conf_get_bool(ssh->conf, CONF_try_gssapi_auth),
269                     conf_get_bool(ssh->conf, CONF_try_gssapi_kex),
270                     conf_get_bool(ssh->conf, CONF_gssapifwd),
271                     &ssh->gss_state
272 #else
273                     false,
274                     false,
275                     false,
276                     NULL,
277 #endif
278 					ssh->conf
279                     );
280                 ssh_connect_ppl(ssh, userauth_layer);
281                 transport_child_layer = userauth_layer;
282 
283                 sfree(username);
284             }
285 
286             ssh->base_layer = ssh2_transport_new(
287                 ssh->conf, ssh->savedhost, ssh->savedport,
288                 ssh->fullhostname,
289                 ssh_verstring_get_local(old_bpp),
290                 ssh_verstring_get_remote(old_bpp),
291 #ifndef NO_GSSAPI
292                 &ssh->gss_state,
293 #else
294                 NULL,
295 #endif
296                 &ssh->stats, transport_child_layer, NULL);
297             ssh_connect_ppl(ssh, ssh->base_layer);
298 
299             if (userauth_layer)
300                 ssh2_userauth_set_transport_layer(userauth_layer,
301                                                   ssh->base_layer);
302 
303 /*        } else {
304 
305             ssh->bpp = ssh1_bpp_new(ssh->logctx);
306             ssh_connect_bpp(ssh);
307 
308             connection_layer = ssh1_connection_new(ssh, ssh->conf, &ssh->cl);
309             ssh_connect_ppl(ssh, connection_layer);
310 
311             ssh->base_layer = ssh1_login_new(
312                 ssh->conf, ssh->savedhost, ssh->savedport, connection_layer);
313             ssh_connect_ppl(ssh, ssh->base_layer);
314 */
315         }
316 
317 /*    } else {
318         ssh->bpp = ssh2_bare_bpp_new(ssh->logctx);
319         ssh_connect_bpp(ssh);
320 
321         connection_layer = ssh2_connection_new(
322             ssh, ssh->connshare, false, ssh->conf,
323             ssh_verstring_get_remote(old_bpp), &ssh->cl);
324         ssh_connect_ppl(ssh, connection_layer);
325         ssh->base_layer = connection_layer;
326 */
327     }
328 
329     /* Connect the base layer - whichever it is - to the BPP, and set
330      * up its selfptr. */
331     ssh->base_layer->selfptr = &ssh->base_layer;
332     ssh_ppl_setup_queues(ssh->base_layer, &ssh->bpp->in_pq, &ssh->bpp->out_pq);
333 
334     seat_update_specials_menu(ssh->seat);
335     ssh->pinger = pinger_new(ssh->conf, &ssh->backend);
336 
337     queue_idempotent_callback(&ssh->bpp->ic_in_raw);
338     ssh_ppl_process_queue(ssh->base_layer);
339 
340     /* Pass in the initial terminal size, if we knew it already. */
341     ssh_terminal_size(ssh->cl, ssh->term_width, ssh->term_height);
342 
343     ssh_bpp_free(old_bpp);
344 }
345 
ssh_check_frozen(Ssh * ssh)346 void ssh_check_frozen(Ssh *ssh)
347 {
348     if (!ssh->s)
349         return;
350 
351     bool prev_frozen = ssh->socket_frozen;
352     ssh->socket_frozen = (ssh->logically_frozen ||
353                           bufchain_size(&ssh->in_raw) > SSH_MAX_BACKLOG);
354     sk_set_frozen(ssh->s, ssh->socket_frozen);
355     if (prev_frozen && !ssh->socket_frozen && ssh->bpp) {
356         /*
357          * If we've just unfrozen, process any SSH connection data
358          * that was stashed in our queue while we were frozen.
359          */
360         queue_idempotent_callback(&ssh->bpp->ic_in_raw);
361     }
362 }
363 
ssh_conn_processed_data(Ssh * ssh)364 void ssh_conn_processed_data(Ssh *ssh)
365 {
366     ssh_check_frozen(ssh);
367 }
368 
ssh_bpp_output_raw_data_callback(void * vctx)369 static void ssh_bpp_output_raw_data_callback(void *vctx)
370 {
371     Ssh *ssh = (Ssh *)vctx;
372 
373     if (!ssh->s)
374         return;
375 
376     while (bufchain_size(&ssh->out_raw) > 0) {
377         size_t backlog;
378 
379         ptrlen data = bufchain_prefix(&ssh->out_raw);
380 
381         if (ssh->logctx)
382             log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data.ptr, data.len,
383                        0, NULL, NULL, 0, NULL);
384         backlog = sk_write(ssh->s, data.ptr, data.len);
385 
386         bufchain_consume(&ssh->out_raw, data.len);
387 
388         if (backlog > SSH_MAX_BACKLOG) {
389             ssh_throttle_all(ssh, true, backlog);
390             return;
391         }
392     }
393 
394     ssh_check_frozen(ssh);
395 
396     if (ssh->pending_close) {
397         sk_close(ssh->s);
398         ssh->s = NULL;
399     }
400 }
401 
ssh_shutdown_internal(Ssh * ssh)402 static void ssh_shutdown_internal(Ssh *ssh)
403 {
404     expire_timer_context(ssh);
405 
406     if (ssh->connshare) {
407         sharestate_free(ssh->connshare);
408         ssh->connshare = NULL;
409     }
410 
411     if (ssh->pinger) {
412         pinger_free(ssh->pinger);
413         ssh->pinger = NULL;
414     }
415 
416     /*
417      * We only need to free the base PPL, which will free the others
418      * (if any) transitively.
419      */
420     if (ssh->base_layer) {
421         ssh_ppl_free(ssh->base_layer);
422         ssh->base_layer = NULL;
423     }
424 
425     ssh->cl = NULL;
426 }
427 
ssh_shutdown(Ssh * ssh)428 static void ssh_shutdown(Ssh *ssh)
429 {
430     ssh_shutdown_internal(ssh);
431 
432     if (ssh->bpp) {
433         ssh_bpp_free(ssh->bpp);
434         ssh->bpp = NULL;
435     }
436 
437     if (ssh->s) {
438         sk_close(ssh->s);
439         ssh->s = NULL;
440     }
441 
442     bufchain_clear(&ssh->in_raw);
443     bufchain_clear(&ssh->out_raw);
444     bufchain_clear(&ssh->user_input);
445 }
446 
ssh_initiate_connection_close(Ssh * ssh)447 static void ssh_initiate_connection_close(Ssh *ssh)
448 {
449     /* Wind up everything above the BPP. */
450     ssh_shutdown_internal(ssh);
451 
452     /* Force any remaining queued SSH packets through the BPP, and
453      * schedule closing the network socket after they go out. */
454     ssh_bpp_handle_output(ssh->bpp);
455     ssh->pending_close = true;
456     queue_idempotent_callback(&ssh->ic_out_raw);
457 
458     /* Now we expect the other end to close the connection too in
459      * response, so arrange that we'll receive notification of that
460      * via ssh_remote_eof. */
461     ssh->bpp->expect_close = true;
462 }
463 
464 #define GET_FORMATTED_MSG                       \
465     char *msg;                                  \
466     va_list ap;                                 \
467     va_start(ap, fmt);                          \
468     msg = dupvprintf(fmt, ap);                  \
469     va_end(ap);                                 \
470     ((void)0) /* eat trailing semicolon */
471 
ssh_remote_error(Ssh * ssh,const char * fmt,...)472 void ssh_remote_error(Ssh *ssh, const char *fmt, ...)
473 {
474     if (ssh->base_layer || !ssh->session_started) {
475         GET_FORMATTED_MSG;
476 
477         /* Error messages sent by the remote don't count as clean exits */
478         ssh->exitcode = 128;
479 
480         /* Close the socket immediately, since the server has already
481          * closed its end (or is about to). */
482         ssh_shutdown(ssh);
483 
484         logevent(ssh->logctx, msg);
485         seat_connection_fatal(ssh->seat, "%s", msg);
486         sfree(msg);
487     }
488 }
489 
ssh_remote_eof(Ssh * ssh,const char * fmt,...)490 void ssh_remote_eof(Ssh *ssh, const char *fmt, ...)
491 {
492     if (ssh->base_layer || !ssh->session_started) {
493         GET_FORMATTED_MSG;
494 
495         /* EOF from the remote, if we were expecting it, does count as
496          * a clean exit */
497         ssh->exitcode = 0;
498 
499         /* Close the socket immediately, since the server has already
500          * closed its end. */
501         ssh_shutdown(ssh);
502 
503         logevent(ssh->logctx, msg);
504         sfree(msg);
505         seat_notify_remote_exit(ssh->seat);
506     } else {
507         /* This is responding to EOF after we've already seen some
508          * other reason for terminating the session. */
509         ssh_shutdown(ssh);
510     }
511 }
512 
ssh_proto_error(Ssh * ssh,const char * fmt,...)513 void ssh_proto_error(Ssh *ssh, const char *fmt, ...)
514 {
515     if (ssh->base_layer || !ssh->session_started) {
516         GET_FORMATTED_MSG;
517 
518         ssh->exitcode = 128;
519 
520         ssh_bpp_queue_disconnect(ssh->bpp, msg,
521                                  SSH2_DISCONNECT_PROTOCOL_ERROR);
522         ssh_initiate_connection_close(ssh);
523 
524         logevent(ssh->logctx, msg);
525         seat_connection_fatal(ssh->seat, "%s", msg);
526         sfree(msg);
527     }
528 }
529 
ssh_sw_abort(Ssh * ssh,const char * fmt,...)530 void ssh_sw_abort(Ssh *ssh, const char *fmt, ...)
531 {
532     if (ssh->base_layer || !ssh->session_started) {
533         GET_FORMATTED_MSG;
534 
535         ssh->exitcode = 128;
536 
537         ssh_initiate_connection_close(ssh);
538 
539         logevent(ssh->logctx, msg);
540         seat_connection_fatal(ssh->seat, "%s", msg);
541         sfree(msg);
542 
543         seat_notify_remote_exit(ssh->seat);
544     }
545 }
546 
ssh_user_close(Ssh * ssh,const char * fmt,...)547 void ssh_user_close(Ssh *ssh, const char *fmt, ...)
548 {
549     if (ssh->base_layer || !ssh->session_started) {
550         GET_FORMATTED_MSG;
551 
552         /* Closing the connection due to user action, even if the
553          * action is the user aborting during authentication prompts,
554          * does count as a clean exit - except that this is also how
555          * we signal ordinary session termination, in which case we
556          * should use the exit status already sent from the main
557          * session (if any). */
558         if (ssh->exitcode < 0)
559             ssh->exitcode = 0;
560 
561         ssh_initiate_connection_close(ssh);
562 
563         logevent(ssh->logctx, msg);
564         sfree(msg);
565 
566         seat_notify_remote_exit(ssh->seat);
567     }
568 }
569 
ssh_deferred_abort_callback(void * vctx)570 static void ssh_deferred_abort_callback(void *vctx)
571 {
572     Ssh *ssh = (Ssh *)vctx;
573     char *msg = ssh->deferred_abort_message;
574     ssh->deferred_abort_message = NULL;
575     ssh_sw_abort(ssh, "%s", msg);
576     sfree(msg);
577 }
578 
ssh_sw_abort_deferred(Ssh * ssh,const char * fmt,...)579 void ssh_sw_abort_deferred(Ssh *ssh, const char *fmt, ...)
580 {
581     if (!ssh->deferred_abort_message) {
582         GET_FORMATTED_MSG;
583         ssh->deferred_abort_message = msg;
584         queue_toplevel_callback(ssh_deferred_abort_callback, ssh);
585     }
586 }
587 
ssh_socket_log(Plug * plug,PlugLogType type,SockAddr * addr,int port,const char * error_msg,int error_code)588 static void ssh_socket_log(Plug *plug, PlugLogType type, SockAddr *addr,
589                            int port, const char *error_msg, int error_code)
590 {
591     Ssh *ssh = container_of(plug, Ssh, plug);
592 
593     /*
594      * While we're attempting connection sharing, don't loudly log
595      * everything that happens. Real TCP connections need to be logged
596      * when we _start_ trying to connect, because it might be ages
597      * before they respond if something goes wrong; but connection
598      * sharing is local and quick to respond, and it's sufficient to
599      * simply wait and see whether it worked afterwards.
600      */
601 
602     if (!ssh->attempting_connshare)
603         backend_socket_log(ssh->seat, ssh->logctx, type, addr, port,
604                            error_msg, error_code, ssh->conf,
605                            ssh->session_started);
606 }
607 
ssh_closing(Plug * plug,const char * error_msg,int error_code,bool calling_back)608 static void ssh_closing(Plug *plug, const char *error_msg, int error_code,
609                         bool calling_back)
610 {
611     Ssh *ssh = container_of(plug, Ssh, plug);
612     if (error_msg) {
613         ssh_remote_error(ssh, "%s", error_msg);
614     } else if (ssh->bpp) {
615         ssh->bpp->input_eof = true;
616         queue_idempotent_callback(&ssh->bpp->ic_in_raw);
617     }
618 }
619 
ssh_receive(Plug * plug,int urgent,const char * data,size_t len)620 static void ssh_receive(Plug *plug, int urgent, const char *data, size_t len)
621 {
622     Ssh *ssh = container_of(plug, Ssh, plug);
623 
624     /* Log raw data, if we're in that mode. */
625     if (ssh->logctx)
626         log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, len,
627                    0, NULL, NULL, 0, NULL);
628 
629     bufchain_add(&ssh->in_raw, data, len);
630     if (!ssh->logically_frozen && ssh->bpp)
631         queue_idempotent_callback(&ssh->bpp->ic_in_raw);
632 
633     ssh_check_frozen(ssh);
634 }
635 
ssh_sent(Plug * plug,size_t bufsize)636 static void ssh_sent(Plug *plug, size_t bufsize)
637 {
638     Ssh *ssh = container_of(plug, Ssh, plug);
639     /*
640      * If the send backlog on the SSH socket itself clears, we should
641      * unthrottle the whole world if it was throttled. Also trigger an
642      * extra call to the consumer of the BPP's output, to try to send
643      * some more data off its bufchain.
644      */
645     if (bufsize < SSH_MAX_BACKLOG) {
646         ssh_throttle_all(ssh, false, bufsize);
647         queue_idempotent_callback(&ssh->ic_out_raw);
648     }
649 }
650 
ssh_hostport_setup(const char * host,int port,Conf * conf,char ** savedhost,int * savedport,char ** loghost_ret)651 static void ssh_hostport_setup(const char *host, int port, Conf *conf,
652                                char **savedhost, int *savedport,
653                                char **loghost_ret)
654 {
655     char *loghost = conf_get_str(conf, CONF_loghost);
656     if (loghost_ret)
657         *loghost_ret = loghost;
658 
659     if (*loghost) {
660         char *tmphost;
661         char *colon;
662 
663         tmphost = dupstr(loghost);
664         *savedport = 22;               /* default ssh port */
665 
666         /*
667          * A colon suffix on the hostname string also lets us affect
668          * savedport. (Unless there are multiple colons, in which case
669          * we assume this is an unbracketed IPv6 literal.)
670          */
671         colon = host_strrchr(tmphost, ':');
672         if (colon && colon == host_strchr(tmphost, ':')) {
673             *colon++ = '\0';
674             if (*colon)
675                 *savedport = atoi(colon);
676         }
677 
678         *savedhost = host_strduptrim(tmphost);
679         sfree(tmphost);
680     } else {
681         *savedhost = host_strduptrim(host);
682         if (port < 0)
683             port = 22;                 /* default ssh port */
684         *savedport = port;
685     }
686 }
687 
ssh_test_for_upstream(const char * host,int port,Conf * conf)688 static bool ssh_test_for_upstream(const char *host, int port, Conf *conf)
689 {
690     char *savedhost;
691     int savedport;
692     bool ret;
693 
694     random_ref(); /* platform may need this to determine share socket name */
695     ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
696     ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
697     sfree(savedhost);
698     random_unref();
699 
700     return ret;
701 }
702 
ssh_close_warn_text(Backend * be)703 static char *ssh_close_warn_text(Backend *be)
704 {
705     Ssh *ssh = container_of(be, Ssh, backend);
706     if (!ssh->connshare)
707         return NULL;
708     int ndowns = share_ndownstreams(ssh->connshare);
709     if (ndowns == 0)
710         return NULL;
711     char *msg = dupprintf("This will also close %d downstream connection%s.",
712                           ndowns, ndowns==1 ? "" : "s");
713     return msg;
714 }
715 
716 static const PlugVtable Ssh_plugvt = {
717     .log = ssh_socket_log,
718     .closing = ssh_closing,
719     .receive = ssh_receive,
720     .sent = ssh_sent,
721 };
722 
723 /*
724  * Connect to specified host and port.
725  * Returns an error message, or NULL on success.
726  * Also places the canonical host name into `realhost'. It must be
727  * freed by the caller.
728  */
connect_to_host(Ssh * ssh,const char * host,int port,char ** realhost,bool nodelay,bool keepalive)729 static char *connect_to_host(
730     Ssh *ssh, const char *host, int port, char **realhost,
731     bool nodelay, bool keepalive)
732 {
733     SockAddr *addr;
734     const char *err;
735     char *loghost;
736     int addressfamily, sshprot;
737 
738     ssh_hostport_setup(host, port, ssh->conf,
739                        &ssh->savedhost, &ssh->savedport, &loghost);
740 
741     ssh->plug.vt = &Ssh_plugvt;
742 
743     /*
744      * Try connection-sharing, in case that means we don't open a
745      * socket after all. ssh_connection_sharing_init will connect to a
746      * previously established upstream if it can, and failing that,
747      * establish a listening socket for _us_ to be the upstream. In
748      * the latter case it will return NULL just as if it had done
749      * nothing, because here we only need to care if we're a
750      * downstream and need to do our connection setup differently.
751      */
752     ssh->connshare = NULL;
753     ssh->attempting_connshare = true;  /* affects socket logging behaviour */
754     ssh->s = ssh_connection_sharing_init(
755         ssh->savedhost, ssh->savedport, ssh->conf, ssh->logctx,
756         &ssh->plug, &ssh->connshare);
757     if (ssh->connshare)
758         ssh_connshare_provide_connlayer(ssh->connshare, &ssh->cl_dummy);
759     ssh->attempting_connshare = false;
760     if (ssh->s != NULL) {
761         /*
762          * We are a downstream.
763          */
764         ssh->bare_connection = true;
765         ssh->fullhostname = NULL;
766         *realhost = dupstr(host);      /* best we can do */
767 
768         if (seat_verbose(ssh->seat) || seat_interactive(ssh->seat)) {
769             /* In an interactive session, or in verbose mode, announce
770              * in the console window that we're a sharing downstream,
771              * to avoid confusing users as to why this session doesn't
772              * behave in quite the usual way. */
773             const char *msg =
774                 "Reusing a shared connection to this server.\r\n";
775             seat_stderr_pl(ssh->seat, ptrlen_from_asciz(msg));
776         }
777     } else {
778         /*
779          * We're not a downstream, so open a normal socket.
780          */
781 
782         /*
783          * Try to find host.
784          */
785         addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
786         addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
787                            ssh->logctx, "SSH connection");
788         if ((err = sk_addr_error(addr)) != NULL) {
789             sk_addr_free(addr);
790             return dupstr(err);
791         }
792         ssh->fullhostname = dupstr(*realhost);   /* save in case of GSSAPI */
793 
794         ssh->s = new_connection(addr, *realhost, port,
795                                 false, true, nodelay, keepalive,
796                                 &ssh->plug, ssh->conf);
797         if ((err = sk_socket_error(ssh->s)) != NULL) {
798             ssh->s = NULL;
799             seat_notify_remote_exit(ssh->seat);
800             return dupstr(err);
801         }
802     }
803 
804     /*
805      * The SSH version number is always fixed (since we no longer support
806      * fallback between versions), so set it now.
807      */
808     sshprot = conf_get_int(ssh->conf, CONF_sshprot);
809     assert(sshprot == 0 || sshprot == 3);
810     if (sshprot == 0)
811         /* SSH-1 only */
812         ssh->version = 1;
813     if (sshprot == 3 || ssh->bare_connection) {
814         /* SSH-2 only */
815         ssh->version = 2;
816     }
817 
818     /*
819      * Set up the initial BPP that will do the version string
820      * exchange, and get it started so that it can send the outgoing
821      * version string early if it wants to.
822      */
823     ssh->version_receiver.got_ssh_version = ssh_got_ssh_version;
824     ssh->bpp = ssh_verstring_new(
825         ssh->conf, ssh->logctx, ssh->bare_connection,
826         ssh->version == 1 ? "1.5" : "2.0", &ssh->version_receiver,
827         false, "FileZilla");
828     ssh_connect_bpp(ssh);
829     queue_idempotent_callback(&ssh->bpp->ic_in_raw);
830 
831     /*
832      * loghost, if configured, overrides realhost.
833      */
834     if (*loghost) {
835         sfree(*realhost);
836         *realhost = dupstr(loghost);
837     }
838 
839     return NULL;
840 }
841 
842 /*
843  * Throttle or unthrottle the SSH connection.
844  */
ssh_throttle_conn(Ssh * ssh,int adjust)845 void ssh_throttle_conn(Ssh *ssh, int adjust)
846 {
847     int old_count = ssh->conn_throttle_count;
848     bool frozen;
849 
850     ssh->conn_throttle_count += adjust;
851     assert(ssh->conn_throttle_count >= 0);
852 
853     if (ssh->conn_throttle_count && !old_count) {
854         frozen = true;
855     } else if (!ssh->conn_throttle_count && old_count) {
856         frozen = false;
857     } else {
858         return;                /* don't change current frozen state */
859     }
860 
861     ssh->logically_frozen = frozen;
862     ssh_check_frozen(ssh);
863 }
864 
865 /*
866  * Throttle or unthrottle _all_ local data streams (for when sends
867  * on the SSH connection itself back up).
868  */
ssh_throttle_all(Ssh * ssh,bool enable,size_t bufsize)869 static void ssh_throttle_all(Ssh *ssh, bool enable, size_t bufsize)
870 {
871     if (enable == ssh->throttled_all)
872         return;
873     ssh->throttled_all = enable;
874     ssh->overall_bufsize = bufsize;
875 
876     ssh_throttle_all_channels(ssh->cl, enable);
877 }
878 
ssh_cache_conf_values(Ssh * ssh)879 static void ssh_cache_conf_values(Ssh *ssh)
880 {
881     ssh->pls.omit_passwords = conf_get_bool(ssh->conf, CONF_logomitpass);
882     ssh->pls.omit_data = conf_get_bool(ssh->conf, CONF_logomitdata);
883 }
884 
ssh_is_bare(Ssh * ssh)885 bool ssh_is_bare(Ssh *ssh)
886 {
887     return ssh->backend.vt->protocol == PROT_SSHCONN;
888 }
889 
890 /* Dummy connlayer must provide ssh_sharing_no_more_downstreams,
891  * because it might be called early due to plink -shareexists */
dummy_sharing_no_more_downstreams(ConnectionLayer * cl)892 static void dummy_sharing_no_more_downstreams(ConnectionLayer *cl) {}
893 static const ConnectionLayerVtable dummy_connlayer_vtable = {
894     .sharing_no_more_downstreams = dummy_sharing_no_more_downstreams,
895 };
896 
897 /*
898  * Called to set up the connection.
899  *
900  * Returns an error message, or NULL on success.
901  */
ssh_init(const BackendVtable * vt,Seat * seat,Backend ** backend_handle,LogContext * logctx,Conf * conf,const char * host,int port,char ** realhost,bool nodelay,bool keepalive)902 static char *ssh_init(const BackendVtable *vt, Seat *seat,
903                       Backend **backend_handle, LogContext *logctx,
904                       Conf *conf, const char *host, int port,
905                       char **realhost, bool nodelay, bool keepalive)
906 {
907     Ssh *ssh;
908 
909     ssh = snew(Ssh);
910     memset(ssh, 0, sizeof(Ssh));
911 
912     ssh->conf = conf_copy(conf);
913     ssh_cache_conf_values(ssh);
914     ssh->exitcode = -1;
915     ssh->pls.kctx = SSH2_PKTCTX_NOKEX;
916     ssh->pls.actx = SSH2_PKTCTX_NOAUTH;
917     bufchain_init(&ssh->in_raw);
918     bufchain_init(&ssh->out_raw);
919     bufchain_init(&ssh->user_input);
920     ssh->ic_out_raw.fn = ssh_bpp_output_raw_data_callback;
921     ssh->ic_out_raw.ctx = ssh;
922 
923     ssh->term_width = conf_get_int(ssh->conf, CONF_width);
924     ssh->term_height = conf_get_int(ssh->conf, CONF_height);
925 
926     ssh->backend.vt = vt;
927     *backend_handle = &ssh->backend;
928 
929     ssh->bare_connection = (vt->protocol == PROT_SSHCONN);
930 
931     ssh->seat = seat;
932     ssh->cl_dummy.vt = &dummy_connlayer_vtable;
933     ssh->cl_dummy.logctx = ssh->logctx = logctx;
934 
935     random_ref(); /* do this now - may be needed by sharing setup code */
936     ssh->need_random_unref = true;
937 
938     char *conn_err = connect_to_host(
939         ssh, host, port, realhost, nodelay, keepalive);
940     if (conn_err) {
941         /* Call random_unref now instead of waiting until the caller
942          * frees this useless Ssh object, in case the caller is
943          * impatient and just exits without bothering, in which case
944          * the random seed won't be re-saved. */
945         ssh->need_random_unref = false;
946         random_unref();
947         return conn_err;
948     }
949 
950     return NULL;
951 }
952 
ssh_free(Backend * be)953 static void ssh_free(Backend *be)
954 {
955     Ssh *ssh = container_of(be, Ssh, backend);
956     bool need_random_unref;
957 
958     ssh_shutdown(ssh);
959 
960     conf_free(ssh->conf);
961     if (ssh->connshare)
962         sharestate_free(ssh->connshare);
963     sfree(ssh->savedhost);
964     sfree(ssh->fullhostname);
965     sfree(ssh->specials);
966 
967 #ifndef NO_GSSAPI
968     if (ssh->gss_state.srv_name)
969         ssh->gss_state.lib->release_name(
970             ssh->gss_state.lib, &ssh->gss_state.srv_name);
971     if (ssh->gss_state.ctx != NULL)
972         ssh->gss_state.lib->release_cred(
973             ssh->gss_state.lib, &ssh->gss_state.ctx);
974     if (ssh->gss_state.libs)
975         ssh_gss_cleanup(ssh->gss_state.libs);
976 #endif
977 
978     sfree(ssh->deferred_abort_message);
979 
980     delete_callbacks_for_context(ssh); /* likely to catch ic_out_raw */
981 
982     need_random_unref = ssh->need_random_unref;
983     sfree(ssh);
984 
985     if (need_random_unref)
986         random_unref();
987 }
988 
989 /*
990  * Reconfigure the SSH backend.
991  */
ssh_reconfig(Backend * be,Conf * conf)992 static void ssh_reconfig(Backend *be, Conf *conf)
993 {
994     Ssh *ssh = container_of(be, Ssh, backend);
995 
996     if (ssh->pinger)
997         pinger_reconfig(ssh->pinger, ssh->conf, conf);
998 
999     ssh_ppl_reconfigure(ssh->base_layer, conf);
1000 
1001     conf_free(ssh->conf);
1002     ssh->conf = conf_copy(conf);
1003     ssh_cache_conf_values(ssh);
1004 }
1005 
1006 /*
1007  * Called to send data down the SSH connection.
1008  */
ssh_send(Backend * be,const char * buf,size_t len)1009 static size_t ssh_send(Backend *be, const char *buf, size_t len)
1010 {
1011     Ssh *ssh = container_of(be, Ssh, backend);
1012 
1013     if (ssh == NULL || ssh->s == NULL)
1014         return 0;
1015 
1016     bufchain_add(&ssh->user_input, buf, len);
1017     if (ssh->base_layer)
1018         ssh_ppl_got_user_input(ssh->base_layer);
1019 
1020     return backend_sendbuffer(&ssh->backend);
1021 }
1022 
1023 /*
1024  * Called to query the current amount of buffered stdin data.
1025  */
ssh_sendbuffer(Backend * be)1026 static size_t ssh_sendbuffer(Backend *be)
1027 {
1028     Ssh *ssh = container_of(be, Ssh, backend);
1029     size_t backlog;
1030 
1031     if (!ssh || !ssh->s || !ssh->cl)
1032         return 0;
1033 
1034     backlog = ssh_stdin_backlog(ssh->cl);
1035 
1036     if (ssh->base_layer)
1037         backlog += ssh_ppl_queued_data_size(ssh->base_layer);
1038 
1039     /*
1040      * If the SSH socket itself has backed up, add the total backup
1041      * size on that to any individual buffer on the stdin channel.
1042      */
1043     if (ssh->throttled_all)
1044         backlog += ssh->overall_bufsize;
1045 
1046     return backlog;
1047 }
1048 
1049 /*
1050  * Called to set the size of the window from SSH's POV.
1051  */
ssh_size(Backend * be,int width,int height)1052 static void ssh_size(Backend *be, int width, int height)
1053 {
1054     Ssh *ssh = container_of(be, Ssh, backend);
1055 
1056     ssh->term_width = width;
1057     ssh->term_height = height;
1058     if (ssh->cl)
1059         ssh_terminal_size(ssh->cl, ssh->term_width, ssh->term_height);
1060 }
1061 
1062 struct ssh_add_special_ctx {
1063     SessionSpecial *specials;
1064     size_t nspecials, specials_size;
1065 };
1066 
ssh_add_special(void * vctx,const char * text,SessionSpecialCode code,int arg)1067 static void ssh_add_special(void *vctx, const char *text,
1068                             SessionSpecialCode code, int arg)
1069 {
1070     struct ssh_add_special_ctx *ctx = (struct ssh_add_special_ctx *)vctx;
1071     SessionSpecial *spec;
1072 
1073     sgrowarray(ctx->specials, ctx->specials_size, ctx->nspecials);
1074     spec = &ctx->specials[ctx->nspecials++];
1075     spec->name = text;
1076     spec->code = code;
1077     spec->arg = arg;
1078 }
1079 
1080 /*
1081  * Return a list of the special codes that make sense in this
1082  * protocol.
1083  */
ssh_get_specials(Backend * be)1084 static const SessionSpecial *ssh_get_specials(Backend *be)
1085 {
1086     Ssh *ssh = container_of(be, Ssh, backend);
1087 
1088     /*
1089      * Ask all our active protocol layers what specials they've got,
1090      * and amalgamate the list into one combined one.
1091      */
1092 
1093     struct ssh_add_special_ctx ctx[1];
1094 
1095     ctx->specials = NULL;
1096     ctx->nspecials = ctx->specials_size = 0;
1097 
1098     if (ssh->base_layer)
1099         ssh_ppl_get_specials(ssh->base_layer, ssh_add_special, ctx);
1100 
1101     if (ctx->specials) {
1102         /* If the list is non-empty, terminate it with a SS_EXITMENU. */
1103         ssh_add_special(ctx, NULL, SS_EXITMENU, 0);
1104     }
1105 
1106     sfree(ssh->specials);
1107     ssh->specials = ctx->specials;
1108     return ssh->specials;
1109 }
1110 
1111 /*
1112  * Send special codes.
1113  */
ssh_special(Backend * be,SessionSpecialCode code,int arg)1114 static void ssh_special(Backend *be, SessionSpecialCode code, int arg)
1115 {
1116     Ssh *ssh = container_of(be, Ssh, backend);
1117 
1118     if (ssh->base_layer)
1119         ssh_ppl_special_cmd(ssh->base_layer, code, arg);
1120 }
1121 
1122 /*
1123  * This is called when the seat's output channel manages to clear some
1124  * backlog.
1125  */
ssh_unthrottle(Backend * be,size_t bufsize)1126 static void ssh_unthrottle(Backend *be, size_t bufsize)
1127 {
1128     Ssh *ssh = container_of(be, Ssh, backend);
1129 
1130     if (ssh->cl)
1131         ssh_stdout_unthrottle(ssh->cl, bufsize);
1132 }
1133 
ssh_connected(Backend * be)1134 static bool ssh_connected(Backend *be)
1135 {
1136     Ssh *ssh = container_of(be, Ssh, backend);
1137     return ssh->s != NULL;
1138 }
1139 
ssh_sendok(Backend * be)1140 static bool ssh_sendok(Backend *be)
1141 {
1142     Ssh *ssh = container_of(be, Ssh, backend);
1143     return ssh->base_layer && ssh_ppl_want_user_input(ssh->base_layer);
1144 }
1145 
ssh_ldisc_update(Ssh * ssh)1146 void ssh_ldisc_update(Ssh *ssh)
1147 {
1148     /* Called when the connection layer wants to propagate an update
1149      * to the line discipline options */
1150     if (ssh->ldisc)
1151         ldisc_echoedit_update(ssh->ldisc);
1152 }
1153 
ssh_ldisc(Backend * be,int option)1154 static bool ssh_ldisc(Backend *be, int option)
1155 {
1156     Ssh *ssh = container_of(be, Ssh, backend);
1157     return ssh->cl ? ssh_ldisc_option(ssh->cl, option) : false;
1158 }
1159 
ssh_provide_ldisc(Backend * be,Ldisc * ldisc)1160 static void ssh_provide_ldisc(Backend *be, Ldisc *ldisc)
1161 {
1162     Ssh *ssh = container_of(be, Ssh, backend);
1163     ssh->ldisc = ldisc;
1164 }
1165 
ssh_got_exitcode(Ssh * ssh,int exitcode)1166 void ssh_got_exitcode(Ssh *ssh, int exitcode)
1167 {
1168     ssh->exitcode = exitcode;
1169 }
1170 
ssh_return_exitcode(Backend * be)1171 static int ssh_return_exitcode(Backend *be)
1172 {
1173     Ssh *ssh = container_of(be, Ssh, backend);
1174     if (ssh->s && (!ssh->session_started || ssh->base_layer))
1175         return -1;
1176     else
1177         return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
1178 }
1179 
1180 /*
1181  * cfg_info for SSH is the protocol running in this session.
1182  * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
1183  * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
1184  */
ssh_cfg_info(Backend * be)1185 static int ssh_cfg_info(Backend *be)
1186 {
1187     Ssh *ssh = container_of(be, Ssh, backend);
1188     if (ssh->version == 0)
1189         return 0; /* don't know yet */
1190     else if (ssh->bare_connection)
1191         return -1;
1192     else
1193         return ssh->version;
1194 }
1195 
1196 /*
1197  * Gross hack: pscp will try to start SFTP but fall back to scp1 if
1198  * that fails. This variable is the means by which scp.c can reach
1199  * into the SSH code and find out which one it got.
1200  */
ssh_fallback_cmd(Backend * be)1201 extern bool ssh_fallback_cmd(Backend *be)
1202 {
1203     Ssh *ssh = container_of(be, Ssh, backend);
1204     return ssh->fallback_cmd;
1205 }
1206 
ssh_got_fallback_cmd(Ssh * ssh)1207 void ssh_got_fallback_cmd(Ssh *ssh)
1208 {
1209     ssh->fallback_cmd = true;
1210 }
1211 
1212 const BackendVtable ssh_backend = {
1213     .init = ssh_init,
1214     .free = ssh_free,
1215     .reconfig = ssh_reconfig,
1216     .send = ssh_send,
1217     .sendbuffer = ssh_sendbuffer,
1218     .size = ssh_size,
1219     .special = ssh_special,
1220     .get_specials = ssh_get_specials,
1221     .connected = ssh_connected,
1222     .exitcode = ssh_return_exitcode,
1223     .sendok = ssh_sendok,
1224     .ldisc_option_state = ssh_ldisc,
1225     .provide_ldisc = ssh_provide_ldisc,
1226     .unthrottle = ssh_unthrottle,
1227     .cfg_info = ssh_cfg_info,
1228     .test_for_upstream = ssh_test_for_upstream,
1229     .close_warn_text = ssh_close_warn_text,
1230     .id = "ssh",
1231     .displayname = "SSH",
1232     .protocol = PROT_SSH,
1233     .default_port = 22,
1234 };
1235 
1236 const BackendVtable sshconn_backend = {
1237     .init = ssh_init,
1238     .free = ssh_free,
1239     .reconfig = ssh_reconfig,
1240     .send = ssh_send,
1241     .sendbuffer = ssh_sendbuffer,
1242     .size = ssh_size,
1243     .special = ssh_special,
1244     .get_specials = ssh_get_specials,
1245     .connected = ssh_connected,
1246     .exitcode = ssh_return_exitcode,
1247     .sendok = ssh_sendok,
1248     .ldisc_option_state = ssh_ldisc,
1249     .provide_ldisc = ssh_provide_ldisc,
1250     .unthrottle = ssh_unthrottle,
1251     .cfg_info = ssh_cfg_info,
1252     .test_for_upstream = ssh_test_for_upstream,
1253     .close_warn_text = ssh_close_warn_text,
1254     .id = "ssh-connection",
1255     .displayname = "Bare ssh-connection",
1256     .protocol = PROT_SSHCONN,
1257 };
1258 
ssh_pending_receive(Backend * be)1259 size_t ssh_pending_receive(Backend *be)
1260 {
1261     Ssh *ssh = container_of(be, Ssh, backend);
1262     if (!ssh || !ssh->s) {
1263         return 0;
1264     }
1265 
1266     char tmp[64];
1267     int r = recv_peek(ssh->s, tmp, 64);
1268     return r > 0 ? r : 0;
1269 }
1270