1 /*
2 * Packet protocol layer for the SSH-2 connection protocol (RFC 4254).
3 */
4
5 #include <assert.h>
6
7 #include "putty.h"
8 #include "ssh.h"
9 #include "sshbpp.h"
10 #include "sshppl.h"
11 #include "sshchan.h"
12 #include "sshcr.h"
13 #include "ssh2connection.h"
14
15 static void ssh2_connection_free(PacketProtocolLayer *);
16 static void ssh2_connection_process_queue(PacketProtocolLayer *);
17 static bool ssh2_connection_get_specials(
18 PacketProtocolLayer *ppl, add_special_fn_t add_special, void *ctx);
19 static void ssh2_connection_special_cmd(PacketProtocolLayer *ppl,
20 SessionSpecialCode code, int arg);
21 static bool ssh2_connection_want_user_input(PacketProtocolLayer *ppl);
22 static void ssh2_connection_got_user_input(PacketProtocolLayer *ppl);
23 static void ssh2_connection_reconfigure(PacketProtocolLayer *ppl, Conf *conf);
24
25 static const PacketProtocolLayerVtable ssh2_connection_vtable = {
26 .free = ssh2_connection_free,
27 .process_queue = ssh2_connection_process_queue,
28 .get_specials = ssh2_connection_get_specials,
29 .special_cmd = ssh2_connection_special_cmd,
30 .want_user_input = ssh2_connection_want_user_input,
31 .got_user_input = ssh2_connection_got_user_input,
32 .reconfigure = ssh2_connection_reconfigure,
33 .queued_data_size = ssh_ppl_default_queued_data_size,
34 .name = "ssh-connection",
35 };
36
37 static SshChannel *ssh2_lportfwd_open(
38 ConnectionLayer *cl, const char *hostname, int port,
39 const char *description, const SocketPeerInfo *pi, Channel *chan);
40 static struct X11FakeAuth *ssh2_add_x11_display(
41 ConnectionLayer *cl, int authtype, struct X11Display *x11disp);
42 static struct X11FakeAuth *ssh2_add_sharing_x11_display(
43 ConnectionLayer *cl, int authtype, ssh_sharing_connstate *share_cs,
44 share_channel *share_chan);
45 static void ssh2_remove_sharing_x11_display(ConnectionLayer *cl,
46 struct X11FakeAuth *auth);
47 static void ssh2_send_packet_from_downstream(
48 ConnectionLayer *cl, unsigned id, int type,
49 const void *pkt, int pktlen, const char *additional_log_text);
50 static unsigned ssh2_alloc_sharing_channel(
51 ConnectionLayer *cl, ssh_sharing_connstate *connstate);
52 static void ssh2_delete_sharing_channel(
53 ConnectionLayer *cl, unsigned localid);
54 static void ssh2_sharing_queue_global_request(
55 ConnectionLayer *cl, ssh_sharing_connstate *share_ctx);
56 static void ssh2_sharing_no_more_downstreams(ConnectionLayer *cl);
57 static bool ssh2_agent_forwarding_permitted(ConnectionLayer *cl);
58 static void ssh2_terminal_size(ConnectionLayer *cl, int width, int height);
59 static void ssh2_stdout_unthrottle(ConnectionLayer *cl, size_t bufsize);
60 static size_t ssh2_stdin_backlog(ConnectionLayer *cl);
61 static void ssh2_throttle_all_channels(ConnectionLayer *cl, bool throttled);
62 static bool ssh2_ldisc_option(ConnectionLayer *cl, int option);
63 static void ssh2_set_ldisc_option(ConnectionLayer *cl, int option, bool value);
64 static void ssh2_enable_x_fwd(ConnectionLayer *cl);
65 static void ssh2_set_wants_user_input(ConnectionLayer *cl, bool wanted);
66
67 static const ConnectionLayerVtable ssh2_connlayer_vtable = {
68 .rportfwd_alloc = ssh2_rportfwd_alloc,
69 .rportfwd_remove = ssh2_rportfwd_remove,
70 .lportfwd_open = ssh2_lportfwd_open,
71 .session_open = ssh2_session_open,
72 .serverside_x11_open = ssh2_serverside_x11_open,
73 .serverside_agent_open = ssh2_serverside_agent_open,
74 .add_x11_display = ssh2_add_x11_display,
75 .add_sharing_x11_display = ssh2_add_sharing_x11_display,
76 .remove_sharing_x11_display = ssh2_remove_sharing_x11_display,
77 .send_packet_from_downstream = ssh2_send_packet_from_downstream,
78 .alloc_sharing_channel = ssh2_alloc_sharing_channel,
79 .delete_sharing_channel = ssh2_delete_sharing_channel,
80 .sharing_queue_global_request = ssh2_sharing_queue_global_request,
81 .sharing_no_more_downstreams = ssh2_sharing_no_more_downstreams,
82 .agent_forwarding_permitted = ssh2_agent_forwarding_permitted,
83 .terminal_size = ssh2_terminal_size,
84 .stdout_unthrottle = ssh2_stdout_unthrottle,
85 .stdin_backlog = ssh2_stdin_backlog,
86 .throttle_all_channels = ssh2_throttle_all_channels,
87 .ldisc_option = ssh2_ldisc_option,
88 .set_ldisc_option = ssh2_set_ldisc_option,
89 .enable_x_fwd = ssh2_enable_x_fwd,
90 .set_wants_user_input = ssh2_set_wants_user_input,
91 };
92
ssh2_channel_open_failure_error_text(PktIn * pktin)93 static char *ssh2_channel_open_failure_error_text(PktIn *pktin)
94 {
95 static const char *const reasons[] = {
96 NULL,
97 "Administratively prohibited",
98 "Connect failed",
99 "Unknown channel type",
100 "Resource shortage",
101 };
102 unsigned reason_code;
103 const char *reason_code_string;
104 char reason_code_buf[256];
105 ptrlen reason;
106
107 reason_code = get_uint32(pktin);
108 if (reason_code < lenof(reasons) && reasons[reason_code]) {
109 reason_code_string = reasons[reason_code];
110 } else {
111 reason_code_string = reason_code_buf;
112 sprintf(reason_code_buf, "unknown reason code %#x", reason_code);
113 }
114
115 reason = get_string(pktin);
116
117 return dupprintf("%s [%.*s]", reason_code_string, PTRLEN_PRINTF(reason));
118 }
119
120 static size_t ssh2channel_write(
121 SshChannel *c, bool is_stderr, const void *buf, size_t len);
122 static void ssh2channel_write_eof(SshChannel *c);
123 static void ssh2channel_initiate_close(SshChannel *c, const char *err);
124 static void ssh2channel_unthrottle(SshChannel *c, size_t bufsize);
125 static Conf *ssh2channel_get_conf(SshChannel *c);
126 static void ssh2channel_window_override_removed(SshChannel *c);
127 static void ssh2channel_x11_sharing_handover(
128 SshChannel *c, ssh_sharing_connstate *share_cs, share_channel *share_chan,
129 const char *peer_addr, int peer_port, int endian,
130 int protomajor, int protominor, const void *initial_data, int initial_len);
131 static void ssh2channel_hint_channel_is_simple(SshChannel *c);
132
133 static const SshChannelVtable ssh2channel_vtable = {
134 .write = ssh2channel_write,
135 .write_eof = ssh2channel_write_eof,
136 .initiate_close = ssh2channel_initiate_close,
137 .unthrottle = ssh2channel_unthrottle,
138 .get_conf = ssh2channel_get_conf,
139 .window_override_removed = ssh2channel_window_override_removed,
140 .x11_sharing_handover = ssh2channel_x11_sharing_handover,
141 .send_exit_status = ssh2channel_send_exit_status,
142 .send_exit_signal = ssh2channel_send_exit_signal,
143 .send_exit_signal_numeric = ssh2channel_send_exit_signal_numeric,
144 .request_x11_forwarding = ssh2channel_request_x11_forwarding,
145 .request_agent_forwarding = ssh2channel_request_agent_forwarding,
146 .request_pty = ssh2channel_request_pty,
147 .send_env_var = ssh2channel_send_env_var,
148 .start_shell = ssh2channel_start_shell,
149 .start_command = ssh2channel_start_command,
150 .start_subsystem = ssh2channel_start_subsystem,
151 .send_serial_break = ssh2channel_send_serial_break,
152 .send_signal = ssh2channel_send_signal,
153 .send_terminal_size_change = ssh2channel_send_terminal_size_change,
154 .hint_channel_is_simple = ssh2channel_hint_channel_is_simple,
155 };
156
157 static void ssh2_channel_check_close(struct ssh2_channel *c);
158 static void ssh2_channel_try_eof(struct ssh2_channel *c);
159 static void ssh2_set_window(struct ssh2_channel *c, int newwin);
160 static size_t ssh2_try_send(struct ssh2_channel *c);
161 static void ssh2_try_send_and_unthrottle(struct ssh2_channel *c);
162 static void ssh2_channel_check_throttle(struct ssh2_channel *c);
163 static void ssh2_channel_close_local(struct ssh2_channel *c,
164 const char *reason);
165 static void ssh2_channel_destroy(struct ssh2_channel *c);
166
167 static void ssh2_check_termination(struct ssh2_connection_state *s);
168
169 struct outstanding_global_request {
170 gr_handler_fn_t handler;
171 void *ctx;
172 struct outstanding_global_request *next;
173 };
ssh2_queue_global_request_handler(struct ssh2_connection_state * s,gr_handler_fn_t handler,void * ctx)174 void ssh2_queue_global_request_handler(
175 struct ssh2_connection_state *s, gr_handler_fn_t handler, void *ctx)
176 {
177 struct outstanding_global_request *ogr =
178 snew(struct outstanding_global_request);
179 ogr->handler = handler;
180 ogr->ctx = ctx;
181 if (s->globreq_tail)
182 s->globreq_tail->next = ogr;
183 else
184 s->globreq_head = ogr;
185 s->globreq_tail = ogr;
186 }
187
ssh2_channelcmp(void * av,void * bv)188 static int ssh2_channelcmp(void *av, void *bv)
189 {
190 const struct ssh2_channel *a = (const struct ssh2_channel *) av;
191 const struct ssh2_channel *b = (const struct ssh2_channel *) bv;
192 if (a->localid < b->localid)
193 return -1;
194 if (a->localid > b->localid)
195 return +1;
196 return 0;
197 }
198
ssh2_channelfind(void * av,void * bv)199 static int ssh2_channelfind(void *av, void *bv)
200 {
201 const unsigned *a = (const unsigned *) av;
202 const struct ssh2_channel *b = (const struct ssh2_channel *) bv;
203 if (*a < b->localid)
204 return -1;
205 if (*a > b->localid)
206 return +1;
207 return 0;
208 }
209
210 /*
211 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
212 * handlers.
213 */
214 struct outstanding_channel_request {
215 cr_handler_fn_t handler;
216 void *ctx;
217 struct outstanding_channel_request *next;
218 };
219
ssh2_channel_free(struct ssh2_channel * c)220 static void ssh2_channel_free(struct ssh2_channel *c)
221 {
222 bufchain_clear(&c->outbuffer);
223 bufchain_clear(&c->errbuffer);
224 while (c->chanreq_head) {
225 struct outstanding_channel_request *chanreq = c->chanreq_head;
226 c->chanreq_head = c->chanreq_head->next;
227 sfree(chanreq);
228 }
229 if (c->chan) {
230 struct ssh2_connection_state *s = c->connlayer;
231 if (s->mainchan_sc == &c->sc) {
232 s->mainchan = NULL;
233 s->mainchan_sc = NULL;
234 }
235 chan_free(c->chan);
236 }
237 sfree(c);
238 }
239
ssh2_connection_new(Ssh * ssh,ssh_sharing_state * connshare,bool is_simple,Conf * conf,const char * peer_verstring,ConnectionLayer ** cl_out)240 PacketProtocolLayer *ssh2_connection_new(
241 Ssh *ssh, ssh_sharing_state *connshare, bool is_simple,
242 Conf *conf, const char *peer_verstring, ConnectionLayer **cl_out)
243 {
244 struct ssh2_connection_state *s = snew(struct ssh2_connection_state);
245 memset(s, 0, sizeof(*s));
246 s->ppl.vt = &ssh2_connection_vtable;
247
248 s->conf = conf_copy(conf);
249
250 s->ssh_is_simple = is_simple;
251
252 /*
253 * If the ssh_no_shell option is enabled, we disable the usual
254 * termination check, so that we persist even in the absence of
255 * any at all channels (because our purpose is probably to be a
256 * background port forwarder).
257 */
258 s->persistent = conf_get_bool(s->conf, CONF_ssh_no_shell);
259
260 s->connshare = connshare;
261 s->peer_verstring = dupstr(peer_verstring);
262
263 s->channels = newtree234(ssh2_channelcmp);
264
265 s->x11authtree = newtree234(x11_authcmp);
266
267 /* Need to get the log context for s->cl now, because we won't be
268 * helpfully notified when a copy is written into s->ppl by our
269 * owner. */
270 s->cl.vt = &ssh2_connlayer_vtable;
271 s->cl.logctx = ssh_get_logctx(ssh);
272
273 s->portfwdmgr = portfwdmgr_new(&s->cl);
274
275 *cl_out = &s->cl;
276 if (s->connshare)
277 ssh_connshare_provide_connlayer(s->connshare, &s->cl);
278
279 return &s->ppl;
280 }
281
ssh2_connection_free(PacketProtocolLayer * ppl)282 static void ssh2_connection_free(PacketProtocolLayer *ppl)
283 {
284 struct ssh2_connection_state *s =
285 container_of(ppl, struct ssh2_connection_state, ppl);
286 struct X11FakeAuth *auth;
287 struct ssh2_channel *c;
288 struct ssh_rportfwd *rpf;
289
290 sfree(s->peer_verstring);
291
292 conf_free(s->conf);
293
294 while ((c = delpos234(s->channels, 0)) != NULL)
295 ssh2_channel_free(c);
296 freetree234(s->channels);
297
298 while ((auth = delpos234(s->x11authtree, 0)) != NULL) {
299 if (auth->disp)
300 x11_free_display(auth->disp);
301 x11_free_fake_auth(auth);
302 }
303 freetree234(s->x11authtree);
304
305 if (s->rportfwds) {
306 while ((rpf = delpos234(s->rportfwds, 0)) != NULL)
307 free_rportfwd(rpf);
308 freetree234(s->rportfwds);
309 }
310 portfwdmgr_free(s->portfwdmgr);
311
312 if (s->antispoof_prompt)
313 free_prompts(s->antispoof_prompt);
314
315 delete_callbacks_for_context(s);
316
317 sfree(s);
318 }
319
ssh2_connection_filter_queue(struct ssh2_connection_state * s)320 static bool ssh2_connection_filter_queue(struct ssh2_connection_state *s)
321 {
322 PktIn *pktin;
323 PktOut *pktout;
324 ptrlen type, data;
325 struct ssh2_channel *c;
326 struct outstanding_channel_request *ocr;
327 unsigned localid, remid, winsize, pktsize, ext_type;
328 bool want_reply, reply_success, expect_halfopen;
329 ChanopenResult chanopen_result;
330 PacketProtocolLayer *ppl = &s->ppl; /* for ppl_logevent */
331
332 while (1) {
333 if (ssh2_common_filter_queue(&s->ppl))
334 return true;
335 if ((pktin = pq_peek(s->ppl.in_pq)) == NULL)
336 return false;
337
338 switch (pktin->type) {
339 case SSH2_MSG_GLOBAL_REQUEST:
340 type = get_string(pktin);
341 want_reply = get_bool(pktin);
342
343 reply_success = ssh2_connection_parse_global_request(
344 s, type, pktin);
345
346 if (want_reply) {
347 int type = (reply_success ? SSH2_MSG_REQUEST_SUCCESS :
348 SSH2_MSG_REQUEST_FAILURE);
349 pktout = ssh_bpp_new_pktout(s->ppl.bpp, type);
350 pq_push(s->ppl.out_pq, pktout);
351 }
352 pq_pop(s->ppl.in_pq);
353 break;
354
355 case SSH2_MSG_REQUEST_SUCCESS:
356 case SSH2_MSG_REQUEST_FAILURE:
357 if (!s->globreq_head) {
358 ssh_proto_error(
359 s->ppl.ssh,
360 "Received %s with no outstanding global request",
361 ssh2_pkt_type(s->ppl.bpp->pls->kctx, s->ppl.bpp->pls->actx,
362 pktin->type));
363 return true;
364 }
365
366 s->globreq_head->handler(s, pktin, s->globreq_head->ctx);
367 {
368 struct outstanding_global_request *tmp = s->globreq_head;
369 s->globreq_head = s->globreq_head->next;
370 sfree(tmp);
371 }
372
373 pq_pop(s->ppl.in_pq);
374 break;
375
376 case SSH2_MSG_CHANNEL_OPEN:
377 type = get_string(pktin);
378 c = snew(struct ssh2_channel);
379 c->connlayer = s;
380 c->chan = NULL;
381
382 remid = get_uint32(pktin);
383 winsize = get_uint32(pktin);
384 pktsize = get_uint32(pktin);
385
386 chanopen_result = ssh2_connection_parse_channel_open(
387 s, type, pktin, &c->sc);
388
389 if (chanopen_result.outcome == CHANOPEN_RESULT_DOWNSTREAM) {
390 /*
391 * This channel-open request needs to go to a
392 * connection-sharing downstream, so abandon our own
393 * channel-open procedure and just pass the message on
394 * to sshshare.c.
395 */
396 share_got_pkt_from_server(
397 chanopen_result.u.downstream.share_ctx, pktin->type,
398 BinarySource_UPCAST(pktin)->data,
399 BinarySource_UPCAST(pktin)->len);
400 sfree(c);
401 break;
402 }
403
404 c->remoteid = remid;
405 c->halfopen = false;
406 if (chanopen_result.outcome == CHANOPEN_RESULT_FAILURE) {
407 pktout = ssh_bpp_new_pktout(
408 s->ppl.bpp, SSH2_MSG_CHANNEL_OPEN_FAILURE);
409 put_uint32(pktout, c->remoteid);
410 put_uint32(pktout, chanopen_result.u.failure.reason_code);
411 put_stringz(pktout, chanopen_result.u.failure.wire_message);
412 put_stringz(pktout, "en"); /* language tag */
413 pq_push(s->ppl.out_pq, pktout);
414 ppl_logevent("Rejected channel open: %s",
415 chanopen_result.u.failure.wire_message);
416 sfree(chanopen_result.u.failure.wire_message);
417 sfree(c);
418 } else {
419 c->chan = chanopen_result.u.success.channel;
420 ssh2_channel_init(c);
421 c->remwindow = winsize;
422 c->remmaxpkt = pktsize;
423 if (c->remmaxpkt > s->ppl.bpp->vt->packet_size_limit)
424 c->remmaxpkt = s->ppl.bpp->vt->packet_size_limit;
425 if (c->chan->initial_fixed_window_size) {
426 c->locwindow = c->locmaxwin = c->remlocwin =
427 c->chan->initial_fixed_window_size;
428 }
429 pktout = ssh_bpp_new_pktout(
430 s->ppl.bpp, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
431 put_uint32(pktout, c->remoteid);
432 put_uint32(pktout, c->localid);
433 put_uint32(pktout, c->locwindow);
434 put_uint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
435 pq_push(s->ppl.out_pq, pktout);
436 }
437
438 pq_pop(s->ppl.in_pq);
439 break;
440
441 case SSH2_MSG_CHANNEL_DATA:
442 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
443 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
444 case SSH2_MSG_CHANNEL_REQUEST:
445 case SSH2_MSG_CHANNEL_EOF:
446 case SSH2_MSG_CHANNEL_CLOSE:
447 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
448 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
449 case SSH2_MSG_CHANNEL_SUCCESS:
450 case SSH2_MSG_CHANNEL_FAILURE:
451 /*
452 * Common preliminary code for all the messages from the
453 * server that cite one of our channel ids: look up that
454 * channel id, check it exists, and if it's for a sharing
455 * downstream, pass it on.
456 */
457 localid = get_uint32(pktin);
458 c = find234(s->channels, &localid, ssh2_channelfind);
459
460 if (c && c->sharectx) {
461 share_got_pkt_from_server(c->sharectx, pktin->type,
462 BinarySource_UPCAST(pktin)->data,
463 BinarySource_UPCAST(pktin)->len);
464 pq_pop(s->ppl.in_pq);
465 break;
466 }
467
468 expect_halfopen = (
469 pktin->type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION ||
470 pktin->type == SSH2_MSG_CHANNEL_OPEN_FAILURE);
471
472 if (!c || c->halfopen != expect_halfopen) {
473 ssh_proto_error(s->ppl.ssh,
474 "Received %s for %s channel %u",
475 ssh2_pkt_type(s->ppl.bpp->pls->kctx,
476 s->ppl.bpp->pls->actx,
477 pktin->type),
478 (!c ? "nonexistent" :
479 c->halfopen ? "half-open" : "open"),
480 localid);
481 return true;
482 }
483
484 switch (pktin->type) {
485 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
486 assert(c->halfopen);
487 c->remoteid = get_uint32(pktin);
488 c->halfopen = false;
489 c->remwindow = get_uint32(pktin);
490 c->remmaxpkt = get_uint32(pktin);
491 if (c->remmaxpkt > s->ppl.bpp->vt->packet_size_limit)
492 c->remmaxpkt = s->ppl.bpp->vt->packet_size_limit;
493
494 chan_open_confirmation(c->chan);
495
496 /*
497 * Now that the channel is fully open, it's possible
498 * in principle to immediately close it. Check whether
499 * it wants us to!
500 *
501 * This can occur if a local socket error occurred
502 * between us sending out CHANNEL_OPEN and receiving
503 * OPEN_CONFIRMATION. If that happens, all we can do
504 * is immediately initiate close proceedings now that
505 * we know the server's id to put in the close
506 * message. We'll have handled that in this code by
507 * having already turned c->chan into a zombie, so its
508 * want_close method (which ssh2_channel_check_close
509 * will consult) will already be returning true.
510 */
511 ssh2_channel_check_close(c);
512
513 if (c->pending_eof)
514 ssh2_channel_try_eof(c); /* in case we had a pending EOF */
515 break;
516
517 case SSH2_MSG_CHANNEL_OPEN_FAILURE: {
518 assert(c->halfopen);
519
520 char *err = ssh2_channel_open_failure_error_text(pktin);
521 chan_open_failed(c->chan, err);
522 sfree(err);
523
524 del234(s->channels, c);
525 ssh2_channel_free(c);
526
527 break;
528 }
529
530 case SSH2_MSG_CHANNEL_DATA:
531 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
532 ext_type = (pktin->type == SSH2_MSG_CHANNEL_DATA ? 0 :
533 get_uint32(pktin));
534 data = get_string(pktin);
535 if (!get_err(pktin)) {
536 int bufsize;
537 c->locwindow -= data.len;
538 c->remlocwin -= data.len;
539 if (ext_type != 0 && ext_type != SSH2_EXTENDED_DATA_STDERR)
540 data.len = 0; /* ignore unknown extended data */
541 bufsize = chan_send(
542 c->chan, ext_type == SSH2_EXTENDED_DATA_STDERR,
543 data.ptr, data.len);
544
545 /*
546 * The channel may have turned into a connection-
547 * shared one as a result of that chan_send, e.g.
548 * if the data we just provided completed the X11
549 * auth phase and caused a callback to
550 * x11_sharing_handover. If so, do nothing
551 * further.
552 */
553 if (c->sharectx)
554 break;
555
556 /*
557 * If it looks like the remote end hit the end of
558 * its window, and we didn't want it to do that,
559 * think about using a larger window.
560 */
561 if (c->remlocwin <= 0 &&
562 c->throttle_state == UNTHROTTLED &&
563 c->locmaxwin < 0x40000000)
564 c->locmaxwin += OUR_V2_WINSIZE;
565
566 /*
567 * If we are not buffering too much data, enlarge
568 * the window again at the remote side. If we are
569 * buffering too much, we may still need to adjust
570 * the window if the server's sent excess data.
571 */
572 if (bufsize < c->locmaxwin)
573 ssh2_set_window(c, c->locmaxwin - bufsize);
574
575 /*
576 * If we're either buffering way too much data, or
577 * if we're buffering anything at all and we're in
578 * "simple" mode, throttle the whole channel.
579 */
580 if ((bufsize > c->locmaxwin ||
581 (s->ssh_is_simple && bufsize>0)) &&
582 !c->throttling_conn) {
583 c->throttling_conn = true;
584 ssh_throttle_conn(s->ppl.ssh, +1);
585 }
586 }
587 break;
588
589 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
590 if (!(c->closes & CLOSES_SENT_EOF)) {
591 c->remwindow += get_uint32(pktin);
592 ssh2_try_send_and_unthrottle(c);
593 }
594 break;
595
596 case SSH2_MSG_CHANNEL_REQUEST:
597 type = get_string(pktin);
598 want_reply = get_bool(pktin);
599
600 reply_success = false;
601
602 if (c->closes & CLOSES_SENT_CLOSE) {
603 /*
604 * We don't reply to channel requests after we've
605 * sent CHANNEL_CLOSE for the channel, because our
606 * reply might cross in the network with the other
607 * side's CHANNEL_CLOSE and arrive after they have
608 * wound the channel up completely.
609 */
610 want_reply = false;
611 }
612
613 /*
614 * Try every channel request name we recognise, no
615 * matter what the channel, and see if the Channel
616 * instance will accept it.
617 */
618 if (ptrlen_eq_string(type, "exit-status")) {
619 int exitcode = toint(get_uint32(pktin));
620 reply_success = chan_rcvd_exit_status(c->chan, exitcode);
621 } else if (ptrlen_eq_string(type, "exit-signal")) {
622 ptrlen signame;
623 int signum;
624 bool core = false;
625 ptrlen errmsg;
626 int format;
627
628 /*
629 * ICK: older versions of OpenSSH (e.g. 3.4p1)
630 * provide an `int' for the signal, despite its
631 * having been a `string' in the drafts of RFC
632 * 4254 since at least 2001. (Fixed in session.c
633 * 1.147.) Try to infer which we can safely parse
634 * it as.
635 */
636
637 size_t startpos = BinarySource_UPCAST(pktin)->pos;
638
639 for (format = 0; format < 2; format++) {
640 BinarySource_UPCAST(pktin)->pos = startpos;
641 BinarySource_UPCAST(pktin)->err = BSE_NO_ERROR;
642
643 /* placate compiler warnings about unin */
644 signame = make_ptrlen(NULL, 0);
645 signum = 0;
646
647 if (format == 0) /* standard string-based format */
648 signame = get_string(pktin);
649 else /* nonstandard integer format */
650 signum = toint(get_uint32(pktin));
651
652 core = get_bool(pktin);
653 errmsg = get_string(pktin); /* error message */
654 get_string(pktin); /* language tag */
655
656 if (!get_err(pktin) && get_avail(pktin) == 0)
657 break; /* successful parse */
658 }
659
660 switch (format) {
661 case 0:
662 reply_success = chan_rcvd_exit_signal(
663 c->chan, signame, core, errmsg);
664 break;
665 case 1:
666 reply_success = chan_rcvd_exit_signal_numeric(
667 c->chan, signum, core, errmsg);
668 break;
669 default:
670 /* Couldn't parse this message in either format */
671 reply_success = false;
672 break;
673 }
674 } else if (ptrlen_eq_string(type, "shell")) {
675 reply_success = chan_run_shell(c->chan);
676 } else if (ptrlen_eq_string(type, "exec")) {
677 ptrlen command = get_string(pktin);
678 reply_success = chan_run_command(c->chan, command);
679 } else if (ptrlen_eq_string(type, "subsystem")) {
680 ptrlen subsys = get_string(pktin);
681 reply_success = chan_run_subsystem(c->chan, subsys);
682 } else if (ptrlen_eq_string(type, "x11-req")) {
683 bool oneshot = get_bool(pktin);
684 ptrlen authproto = get_string(pktin);
685 ptrlen authdata = get_string(pktin);
686 unsigned screen_number = get_uint32(pktin);
687 reply_success = chan_enable_x11_forwarding(
688 c->chan, oneshot, authproto, authdata, screen_number);
689 } else if (ptrlen_eq_string(type,
690 "auth-agent-req@openssh.com")) {
691 reply_success = chan_enable_agent_forwarding(c->chan);
692 } else if (ptrlen_eq_string(type, "pty-req")) {
693 ptrlen termtype = get_string(pktin);
694 unsigned width = get_uint32(pktin);
695 unsigned height = get_uint32(pktin);
696 unsigned pixwidth = get_uint32(pktin);
697 unsigned pixheight = get_uint32(pktin);
698 ptrlen encoded_modes = get_string(pktin);
699 BinarySource bs_modes[1];
700 struct ssh_ttymodes modes;
701
702 BinarySource_BARE_INIT_PL(bs_modes, encoded_modes);
703 modes = read_ttymodes_from_packet(bs_modes, 2);
704 if (get_err(bs_modes) || get_avail(bs_modes) > 0) {
705 ppl_logevent("Unable to decode terminal mode string");
706 reply_success = false;
707 } else {
708 reply_success = chan_allocate_pty(
709 c->chan, termtype, width, height,
710 pixwidth, pixheight, modes);
711 }
712 } else if (ptrlen_eq_string(type, "env")) {
713 ptrlen var = get_string(pktin);
714 ptrlen value = get_string(pktin);
715
716 reply_success = chan_set_env(c->chan, var, value);
717 } else if (ptrlen_eq_string(type, "break")) {
718 unsigned length = get_uint32(pktin);
719
720 reply_success = chan_send_break(c->chan, length);
721 } else if (ptrlen_eq_string(type, "signal")) {
722 ptrlen signame = get_string(pktin);
723
724 reply_success = chan_send_signal(c->chan, signame);
725 } else if (ptrlen_eq_string(type, "window-change")) {
726 unsigned width = get_uint32(pktin);
727 unsigned height = get_uint32(pktin);
728 unsigned pixwidth = get_uint32(pktin);
729 unsigned pixheight = get_uint32(pktin);
730 reply_success = chan_change_window_size(
731 c->chan, width, height, pixwidth, pixheight);
732 }
733 if (want_reply) {
734 int type = (reply_success ? SSH2_MSG_CHANNEL_SUCCESS :
735 SSH2_MSG_CHANNEL_FAILURE);
736 pktout = ssh_bpp_new_pktout(s->ppl.bpp, type);
737 put_uint32(pktout, c->remoteid);
738 pq_push(s->ppl.out_pq, pktout);
739 }
740 break;
741
742 case SSH2_MSG_CHANNEL_SUCCESS:
743 case SSH2_MSG_CHANNEL_FAILURE:
744 ocr = c->chanreq_head;
745 if (!ocr) {
746 ssh_proto_error(
747 s->ppl.ssh,
748 "Received %s for channel %d with no outstanding "
749 "channel request",
750 ssh2_pkt_type(s->ppl.bpp->pls->kctx,
751 s->ppl.bpp->pls->actx, pktin->type),
752 c->localid);
753 return true;
754 }
755 ocr->handler(c, pktin, ocr->ctx);
756 c->chanreq_head = ocr->next;
757 sfree(ocr);
758 /*
759 * We may now initiate channel-closing procedures, if
760 * that CHANNEL_REQUEST was the last thing outstanding
761 * before we send CHANNEL_CLOSE.
762 */
763 ssh2_channel_check_close(c);
764 break;
765
766 case SSH2_MSG_CHANNEL_EOF:
767 if (!(c->closes & CLOSES_RCVD_EOF)) {
768 c->closes |= CLOSES_RCVD_EOF;
769 chan_send_eof(c->chan);
770 ssh2_channel_check_close(c);
771 }
772 break;
773
774 case SSH2_MSG_CHANNEL_CLOSE:
775 /*
776 * When we receive CLOSE on a channel, we assume it
777 * comes with an implied EOF if we haven't seen EOF
778 * yet.
779 */
780 if (!(c->closes & CLOSES_RCVD_EOF)) {
781 c->closes |= CLOSES_RCVD_EOF;
782 chan_send_eof(c->chan);
783 }
784
785 if (!(s->ppl.remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
786 /*
787 * It also means we stop expecting to see replies
788 * to any outstanding channel requests, so clean
789 * those up too. (ssh_chanreq_init will enforce by
790 * assertion that we don't subsequently put
791 * anything back on this list.)
792 */
793 while (c->chanreq_head) {
794 struct outstanding_channel_request *ocr =
795 c->chanreq_head;
796 ocr->handler(c, NULL, ocr->ctx);
797 c->chanreq_head = ocr->next;
798 sfree(ocr);
799 }
800 }
801
802 /*
803 * And we also send an outgoing EOF, if we haven't
804 * already, on the assumption that CLOSE is a pretty
805 * forceful announcement that the remote side is doing
806 * away with the entire channel. (If it had wanted to
807 * send us EOF and continue receiving data from us, it
808 * would have just sent CHANNEL_EOF.)
809 */
810 if (!(c->closes & CLOSES_SENT_EOF)) {
811 /*
812 * Abandon any buffered data we still wanted to
813 * send to this channel. Receiving a CHANNEL_CLOSE
814 * is an indication that the server really wants
815 * to get on and _destroy_ this channel, and it
816 * isn't going to send us any further
817 * WINDOW_ADJUSTs to permit us to send pending
818 * stuff.
819 */
820 bufchain_clear(&c->outbuffer);
821 bufchain_clear(&c->errbuffer);
822
823 /*
824 * Send outgoing EOF.
825 */
826 sshfwd_write_eof(&c->sc);
827
828 /*
829 * Make sure we don't read any more from whatever
830 * our local data source is for this channel.
831 * (This will pick up on the changes made by
832 * sshfwd_write_eof.)
833 */
834 ssh2_channel_check_throttle(c);
835 }
836
837 /*
838 * Now process the actual close.
839 */
840 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
841 c->closes |= CLOSES_RCVD_CLOSE;
842 ssh2_channel_check_close(c);
843 }
844
845 break;
846 }
847
848 pq_pop(s->ppl.in_pq);
849 break;
850
851 default:
852 return false;
853 }
854 }
855 }
856
ssh2_handle_winadj_response(struct ssh2_channel * c,PktIn * pktin,void * ctx)857 static void ssh2_handle_winadj_response(struct ssh2_channel *c,
858 PktIn *pktin, void *ctx)
859 {
860 unsigned *sizep = ctx;
861
862 /*
863 * Winadj responses should always be failures. However, at least
864 * one server ("boks_sshd") is known to return SUCCESS for channel
865 * requests it's never heard of, such as "winadj@putty". Raised
866 * with foxt.com as bug 090916-090424, but for the sake of a quiet
867 * life, we don't worry about what kind of response we got.
868 */
869
870 c->remlocwin += *sizep;
871 sfree(sizep);
872 /*
873 * winadj messages are only sent when the window is fully open, so
874 * if we get an ack of one, we know any pending unthrottle is
875 * complete.
876 */
877 if (c->throttle_state == UNTHROTTLING)
878 c->throttle_state = UNTHROTTLED;
879 }
880
ssh2_set_window(struct ssh2_channel * c,int newwin)881 static void ssh2_set_window(struct ssh2_channel *c, int newwin)
882 {
883 struct ssh2_connection_state *s = c->connlayer;
884
885 /*
886 * Never send WINDOW_ADJUST for a channel that the remote side has
887 * already sent EOF on; there's no point, since it won't be
888 * sending any more data anyway. Ditto if _we've_ already sent
889 * CLOSE.
890 */
891 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
892 return;
893
894 /*
895 * If the client-side Channel is in an initial setup phase with a
896 * fixed window size, e.g. for an X11 channel when we're still
897 * waiting to see its initial auth and may yet hand it off to a
898 * downstream, don't send any WINDOW_ADJUST either.
899 */
900 if (c->chan->initial_fixed_window_size)
901 return;
902
903 /*
904 * If the remote end has a habit of ignoring maxpkt, limit the
905 * window so that it has no choice (assuming it doesn't ignore the
906 * window as well).
907 */
908 if ((s->ppl.remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
909 newwin = OUR_V2_MAXPKT;
910
911 /*
912 * Only send a WINDOW_ADJUST if there's significantly more window
913 * available than the other end thinks there is. This saves us
914 * sending a WINDOW_ADJUST for every character in a shell session.
915 *
916 * "Significant" is arbitrarily defined as half the window size.
917 */
918 if (newwin / 2 >= c->locwindow) {
919 PktOut *pktout;
920 unsigned *up;
921
922 /*
923 * In order to keep track of how much window the client
924 * actually has available, we'd like it to acknowledge each
925 * WINDOW_ADJUST. We can't do that directly, so we accompany
926 * it with a CHANNEL_REQUEST that has to be acknowledged.
927 *
928 * This is only necessary if we're opening the window wide.
929 * If we're not, then throughput is being constrained by
930 * something other than the maximum window size anyway.
931 */
932 if (newwin == c->locmaxwin &&
933 !(s->ppl.remote_bugs & BUG_CHOKES_ON_WINADJ)) {
934 up = snew(unsigned);
935 *up = newwin - c->locwindow;
936 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
937 ssh2_handle_winadj_response, up);
938 pq_push(s->ppl.out_pq, pktout);
939
940 if (c->throttle_state != UNTHROTTLED)
941 c->throttle_state = UNTHROTTLING;
942 } else {
943 /* Pretend the WINDOW_ADJUST was acked immediately. */
944 c->remlocwin = newwin;
945 c->throttle_state = THROTTLED;
946 }
947 pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_CHANNEL_WINDOW_ADJUST);
948 put_uint32(pktout, c->remoteid);
949 put_uint32(pktout, newwin - c->locwindow);
950 pq_push(s->ppl.out_pq, pktout);
951 c->locwindow = newwin;
952 }
953 }
954
ssh2_connection_pop(struct ssh2_connection_state * s)955 static PktIn *ssh2_connection_pop(struct ssh2_connection_state *s)
956 {
957 ssh2_connection_filter_queue(s);
958 return pq_pop(s->ppl.in_pq);
959 }
960
ssh2_connection_process_queue(PacketProtocolLayer * ppl)961 static void ssh2_connection_process_queue(PacketProtocolLayer *ppl)
962 {
963 struct ssh2_connection_state *s =
964 container_of(ppl, struct ssh2_connection_state, ppl);
965 PktIn *pktin;
966
967 if (ssh2_connection_filter_queue(s)) /* no matter why we were called */
968 return;
969
970 crBegin(s->crState);
971
972 if (s->connshare)
973 share_activate(s->connshare, s->peer_verstring);
974
975 /*
976 * Signal the seat that authentication is done, so that it can
977 * deploy spoofing defences. If it doesn't have any, deploy our
978 * own fallback one.
979 *
980 * We do this here rather than at the end of userauth, because we
981 * might not have gone through userauth at all (if we're a
982 * connection-sharing downstream).
983 */
984 if (ssh2_connection_need_antispoof_prompt(s)) {
985 s->antispoof_prompt = new_prompts();
986 s->antispoof_prompt->to_server = true;
987 s->antispoof_prompt->from_server = false;
988 s->antispoof_prompt->name = dupstr("Authentication successful");
989 add_prompt(
990 s->antispoof_prompt,
991 dupstr("Access granted. Press Return to begin session. "), false);
992 s->antispoof_ret = seat_get_userpass_input(
993 s->ppl.seat, s->antispoof_prompt, NULL);
994 while (1) {
995 while (s->antispoof_ret < 0 &&
996 bufchain_size(s->ppl.user_input) > 0)
997 s->antispoof_ret = seat_get_userpass_input(
998 s->ppl.seat, s->antispoof_prompt, s->ppl.user_input);
999
1000 if (s->antispoof_ret >= 0)
1001 break;
1002
1003 s->want_user_input = true;
1004 crReturnV;
1005 s->want_user_input = false;
1006 }
1007 free_prompts(s->antispoof_prompt);
1008 s->antispoof_prompt = NULL;
1009 }
1010
1011 /*
1012 * Enable port forwardings.
1013 */
1014 portfwdmgr_config(s->portfwdmgr, s->conf);
1015 s->portfwdmgr_configured = true;
1016
1017 /*
1018 * Create the main session channel, if any.
1019 */
1020 s->mainchan = mainchan_new(
1021 &s->ppl, &s->cl, s->conf, s->term_width, s->term_height,
1022 s->ssh_is_simple, &s->mainchan_sc);
1023 s->started = true;
1024
1025 /*
1026 * Transfer data!
1027 */
1028
1029 while (1) {
1030 if ((pktin = ssh2_connection_pop(s)) != NULL) {
1031
1032 /*
1033 * _All_ the connection-layer packets we expect to
1034 * receive are now handled by the dispatch table.
1035 * Anything that reaches here must be bogus.
1036 */
1037
1038 ssh_proto_error(s->ppl.ssh, "Received unexpected connection-layer "
1039 "packet, type %d (%s)", pktin->type,
1040 ssh2_pkt_type(s->ppl.bpp->pls->kctx,
1041 s->ppl.bpp->pls->actx,
1042 pktin->type));
1043 return;
1044 }
1045 crReturnV;
1046 }
1047
1048 crFinishV;
1049 }
1050
ssh2_channel_check_close(struct ssh2_channel * c)1051 static void ssh2_channel_check_close(struct ssh2_channel *c)
1052 {
1053 struct ssh2_connection_state *s = c->connlayer;
1054 PktOut *pktout;
1055
1056 if (c->halfopen) {
1057 /*
1058 * If we've sent out our own CHANNEL_OPEN but not yet seen
1059 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
1060 * it's too early to be sending close messages of any kind.
1061 */
1062 return;
1063 }
1064
1065 if (chan_want_close(c->chan, (c->closes & CLOSES_SENT_EOF),
1066 (c->closes & CLOSES_RCVD_EOF)) &&
1067 !c->chanreq_head &&
1068 !(c->closes & CLOSES_SENT_CLOSE)) {
1069 /*
1070 * We have both sent and received EOF (or the channel is a
1071 * zombie), and we have no outstanding channel requests, which
1072 * means the channel is in final wind-up. But we haven't sent
1073 * CLOSE, so let's do so now.
1074 */
1075 pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_CHANNEL_CLOSE);
1076 put_uint32(pktout, c->remoteid);
1077 pq_push(s->ppl.out_pq, pktout);
1078 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
1079 }
1080
1081 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
1082 assert(c->chanreq_head == NULL);
1083 /*
1084 * We have both sent and received CLOSE, which means we're
1085 * completely done with the channel.
1086 */
1087 ssh2_channel_destroy(c);
1088 }
1089 }
1090
ssh2_channel_try_eof(struct ssh2_channel * c)1091 static void ssh2_channel_try_eof(struct ssh2_channel *c)
1092 {
1093 struct ssh2_connection_state *s = c->connlayer;
1094 PktOut *pktout;
1095 assert(c->pending_eof); /* precondition for calling us */
1096 if (c->halfopen)
1097 return; /* can't close: not even opened yet */
1098 if (bufchain_size(&c->outbuffer) > 0 || bufchain_size(&c->errbuffer) > 0)
1099 return; /* can't send EOF: pending outgoing data */
1100
1101 c->pending_eof = false; /* we're about to send it */
1102
1103 pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_CHANNEL_EOF);
1104 put_uint32(pktout, c->remoteid);
1105 pq_push(s->ppl.out_pq, pktout);
1106 c->closes |= CLOSES_SENT_EOF;
1107 ssh2_channel_check_close(c);
1108 }
1109
1110 /*
1111 * Attempt to send data on an SSH-2 channel.
1112 */
ssh2_try_send(struct ssh2_channel * c)1113 static size_t ssh2_try_send(struct ssh2_channel *c)
1114 {
1115 struct ssh2_connection_state *s = c->connlayer;
1116 PktOut *pktout;
1117 size_t bufsize;
1118
1119 if (!c->halfopen) {
1120 while (c->remwindow > 0 &&
1121 (bufchain_size(&c->outbuffer) > 0 ||
1122 bufchain_size(&c->errbuffer) > 0)) {
1123 bufchain *buf = (bufchain_size(&c->errbuffer) > 0 ?
1124 &c->errbuffer : &c->outbuffer);
1125
1126 ptrlen data = bufchain_prefix(buf);
1127 if (data.len > c->remwindow)
1128 data.len = c->remwindow;
1129 if (data.len > c->remmaxpkt)
1130 data.len = c->remmaxpkt;
1131 if (buf == &c->errbuffer) {
1132 pktout = ssh_bpp_new_pktout(
1133 s->ppl.bpp, SSH2_MSG_CHANNEL_EXTENDED_DATA);
1134 put_uint32(pktout, c->remoteid);
1135 put_uint32(pktout, SSH2_EXTENDED_DATA_STDERR);
1136 } else {
1137 pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_CHANNEL_DATA);
1138 put_uint32(pktout, c->remoteid);
1139 }
1140 put_stringpl(pktout, data);
1141 pq_push(s->ppl.out_pq, pktout);
1142 bufchain_consume(buf, data.len);
1143 c->remwindow -= data.len;
1144 }
1145 }
1146
1147 /*
1148 * After having sent as much data as we can, return the amount
1149 * still buffered.
1150 */
1151 bufsize = bufchain_size(&c->outbuffer) + bufchain_size(&c->errbuffer);
1152
1153 /*
1154 * And if there's no data pending but we need to send an EOF, send
1155 * it.
1156 */
1157 if (!bufsize && c->pending_eof)
1158 ssh2_channel_try_eof(c);
1159
1160 return bufsize;
1161 }
1162
ssh2_try_send_and_unthrottle(struct ssh2_channel * c)1163 static void ssh2_try_send_and_unthrottle(struct ssh2_channel *c)
1164 {
1165 int bufsize;
1166 if (c->closes & CLOSES_SENT_EOF)
1167 return; /* don't send on channels we've EOFed */
1168 bufsize = ssh2_try_send(c);
1169 if (bufsize == 0) {
1170 c->throttled_by_backlog = false;
1171 ssh2_channel_check_throttle(c);
1172 }
1173 }
1174
ssh2_channel_check_throttle(struct ssh2_channel * c)1175 static void ssh2_channel_check_throttle(struct ssh2_channel *c)
1176 {
1177 /*
1178 * We don't want this channel to read further input if this
1179 * particular channel has a backed-up SSH window, or if the
1180 * outgoing side of the whole SSH connection is currently
1181 * throttled, or if this channel already has an outgoing EOF
1182 * either sent or pending.
1183 */
1184 chan_set_input_wanted(c->chan,
1185 !c->throttled_by_backlog &&
1186 !c->connlayer->all_channels_throttled &&
1187 !c->pending_eof &&
1188 !(c->closes & CLOSES_SENT_EOF));
1189 }
1190
1191 /*
1192 * Close any local socket and free any local resources associated with
1193 * a channel. This converts the channel into a zombie.
1194 */
ssh2_channel_close_local(struct ssh2_channel * c,const char * reason)1195 static void ssh2_channel_close_local(struct ssh2_channel *c,
1196 const char *reason)
1197 {
1198 struct ssh2_connection_state *s = c->connlayer;
1199 PacketProtocolLayer *ppl = &s->ppl; /* for ppl_logevent */
1200 char *msg = NULL;
1201
1202 if (c->sharectx)
1203 return;
1204
1205 msg = chan_log_close_msg(c->chan);
1206
1207 if (msg)
1208 ppl_logevent("%s%s%s", msg, reason ? " " : "", reason ? reason : "");
1209
1210 sfree(msg);
1211
1212 chan_free(c->chan);
1213 c->chan = zombiechan_new();
1214 }
1215
ssh2_check_termination_callback(void * vctx)1216 static void ssh2_check_termination_callback(void *vctx)
1217 {
1218 struct ssh2_connection_state *s = (struct ssh2_connection_state *)vctx;
1219 ssh2_check_termination(s);
1220 }
1221
ssh2_channel_destroy(struct ssh2_channel * c)1222 static void ssh2_channel_destroy(struct ssh2_channel *c)
1223 {
1224 struct ssh2_connection_state *s = c->connlayer;
1225
1226 assert(c->chanreq_head == NULL);
1227
1228 ssh2_channel_close_local(c, NULL);
1229 del234(s->channels, c);
1230 ssh2_channel_free(c);
1231
1232 /*
1233 * If that was the last channel left open, we might need to
1234 * terminate. But we'll be a bit cautious, by doing that in a
1235 * toplevel callback, just in case anything on the current call
1236 * stack objects to this entire PPL being freed.
1237 */
1238 queue_toplevel_callback(ssh2_check_termination_callback, s);
1239 }
1240
ssh2_check_termination(struct ssh2_connection_state * s)1241 static void ssh2_check_termination(struct ssh2_connection_state *s)
1242 {
1243 /*
1244 * Decide whether we should terminate the SSH connection now.
1245 * Called after a channel or a downstream goes away. The general
1246 * policy is that we terminate when none of either is left.
1247 */
1248
1249 if (s->persistent)
1250 return; /* persistent mode: never proactively terminate */
1251
1252 if (!s->started) {
1253 /* At startup, we don't have any channels open because we
1254 * haven't got round to opening the main one yet. In that
1255 * situation, we don't want to terminate, even if a sharing
1256 * connection opens and closes and causes a call to this
1257 * function. */
1258 return;
1259 }
1260
1261 if (count234(s->channels) == 0 &&
1262 !(s->connshare && share_ndownstreams(s->connshare) > 0)) {
1263 /*
1264 * We used to send SSH_MSG_DISCONNECT here, because I'd
1265 * believed that _every_ conforming SSH-2 connection had to
1266 * end with a disconnect being sent by at least one side;
1267 * apparently I was wrong and it's perfectly OK to
1268 * unceremoniously slam the connection shut when you're done,
1269 * and indeed OpenSSH feels this is more polite than sending a
1270 * DISCONNECT. So now we don't.
1271 */
1272 ssh_user_close(s->ppl.ssh, "All channels closed");
1273 return;
1274 }
1275 }
1276
1277 /*
1278 * Set up most of a new ssh2_channel. Nulls out sharectx, but leaves
1279 * chan untouched (since it will sometimes have been filled in before
1280 * calling this).
1281 */
ssh2_channel_init(struct ssh2_channel * c)1282 void ssh2_channel_init(struct ssh2_channel *c)
1283 {
1284 struct ssh2_connection_state *s = c->connlayer;
1285 c->closes = 0;
1286 c->pending_eof = false;
1287 c->throttling_conn = false;
1288 c->throttled_by_backlog = false;
1289 c->sharectx = NULL;
1290 c->locwindow = c->locmaxwin = c->remlocwin =
1291 s->ssh_is_simple ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
1292 c->chanreq_head = NULL;
1293 c->throttle_state = UNTHROTTLED;
1294 bufchain_init(&c->outbuffer);
1295 bufchain_init(&c->errbuffer);
1296 c->sc.vt = &ssh2channel_vtable;
1297 c->sc.cl = &s->cl;
1298 c->localid = alloc_channel_id(s->channels, struct ssh2_channel);
1299 add234(s->channels, c);
1300 }
1301
1302 /*
1303 * Construct the common parts of a CHANNEL_OPEN.
1304 */
ssh2_chanopen_init(struct ssh2_channel * c,const char * type)1305 PktOut *ssh2_chanopen_init(struct ssh2_channel *c, const char *type)
1306 {
1307 struct ssh2_connection_state *s = c->connlayer;
1308 PktOut *pktout;
1309
1310 pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_CHANNEL_OPEN);
1311 put_stringz(pktout, type);
1312 put_uint32(pktout, c->localid);
1313 put_uint32(pktout, c->locwindow); /* our window size */
1314 put_uint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
1315 return pktout;
1316 }
1317
1318 /*
1319 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
1320 * NULL then a reply will be requested and the handler will be called
1321 * when it arrives. The returned packet is ready to have any
1322 * request-specific data added and be sent. Note that if a handler is
1323 * provided, it's essential that the request actually be sent.
1324 *
1325 * The handler will usually be passed the response packet in pktin. If
1326 * pktin is NULL, this means that no reply will ever be forthcoming
1327 * (e.g. because the entire connection is being destroyed, or because
1328 * the server initiated channel closure before we saw the response)
1329 * and the handler should free any storage it's holding.
1330 */
ssh2_chanreq_init(struct ssh2_channel * c,const char * type,cr_handler_fn_t handler,void * ctx)1331 PktOut *ssh2_chanreq_init(struct ssh2_channel *c, const char *type,
1332 cr_handler_fn_t handler, void *ctx)
1333 {
1334 struct ssh2_connection_state *s = c->connlayer;
1335 PktOut *pktout;
1336
1337 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
1338 pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_CHANNEL_REQUEST);
1339 put_uint32(pktout, c->remoteid);
1340 put_stringz(pktout, type);
1341 put_bool(pktout, handler != NULL);
1342 if (handler != NULL) {
1343 struct outstanding_channel_request *ocr =
1344 snew(struct outstanding_channel_request);
1345
1346 ocr->handler = handler;
1347 ocr->ctx = ctx;
1348 ocr->next = NULL;
1349 if (!c->chanreq_head)
1350 c->chanreq_head = ocr;
1351 else
1352 c->chanreq_tail->next = ocr;
1353 c->chanreq_tail = ocr;
1354 }
1355 return pktout;
1356 }
1357
ssh2channel_get_conf(SshChannel * sc)1358 static Conf *ssh2channel_get_conf(SshChannel *sc)
1359 {
1360 struct ssh2_channel *c = container_of(sc, struct ssh2_channel, sc);
1361 struct ssh2_connection_state *s = c->connlayer;
1362 return s->conf;
1363 }
1364
ssh2channel_write_eof(SshChannel * sc)1365 static void ssh2channel_write_eof(SshChannel *sc)
1366 {
1367 struct ssh2_channel *c = container_of(sc, struct ssh2_channel, sc);
1368
1369 if (c->closes & CLOSES_SENT_EOF)
1370 return;
1371
1372 c->pending_eof = true;
1373 ssh2_channel_try_eof(c);
1374 }
1375
ssh2channel_initiate_close(SshChannel * sc,const char * err)1376 static void ssh2channel_initiate_close(SshChannel *sc, const char *err)
1377 {
1378 struct ssh2_channel *c = container_of(sc, struct ssh2_channel, sc);
1379 char *reason;
1380
1381 reason = err ? dupprintf("due to local error: %s", err) : NULL;
1382 ssh2_channel_close_local(c, reason);
1383 sfree(reason);
1384 c->pending_eof = false; /* this will confuse a zombie channel */
1385
1386 ssh2_channel_check_close(c);
1387 }
1388
ssh2channel_unthrottle(SshChannel * sc,size_t bufsize)1389 static void ssh2channel_unthrottle(SshChannel *sc, size_t bufsize)
1390 {
1391 struct ssh2_channel *c = container_of(sc, struct ssh2_channel, sc);
1392 struct ssh2_connection_state *s = c->connlayer;
1393 size_t buflimit;
1394
1395 buflimit = s->ssh_is_simple ? 0 : c->locmaxwin;
1396 if (bufsize < buflimit)
1397 ssh2_set_window(c, buflimit - bufsize);
1398
1399 if (c->throttling_conn && bufsize <= buflimit) {
1400 c->throttling_conn = false;
1401 ssh_throttle_conn(s->ppl.ssh, -1);
1402 }
1403 }
1404
ssh2channel_write(SshChannel * sc,bool is_stderr,const void * buf,size_t len)1405 static size_t ssh2channel_write(
1406 SshChannel *sc, bool is_stderr, const void *buf, size_t len)
1407 {
1408 struct ssh2_channel *c = container_of(sc, struct ssh2_channel, sc);
1409 assert(!(c->closes & CLOSES_SENT_EOF));
1410 bufchain_add(is_stderr ? &c->errbuffer : &c->outbuffer, buf, len);
1411 return ssh2_try_send(c);
1412 }
1413
ssh2channel_x11_sharing_handover(SshChannel * sc,ssh_sharing_connstate * share_cs,share_channel * share_chan,const char * peer_addr,int peer_port,int endian,int protomajor,int protominor,const void * initial_data,int initial_len)1414 static void ssh2channel_x11_sharing_handover(
1415 SshChannel *sc, ssh_sharing_connstate *share_cs, share_channel *share_chan,
1416 const char *peer_addr, int peer_port, int endian,
1417 int protomajor, int protominor, const void *initial_data, int initial_len)
1418 {
1419 struct ssh2_channel *c = container_of(sc, struct ssh2_channel, sc);
1420 /*
1421 * This function is called when we've just discovered that an X
1422 * forwarding channel on which we'd been handling the initial auth
1423 * ourselves turns out to be destined for a connection-sharing
1424 * downstream. So we turn the channel into a sharing one, meaning
1425 * that we completely stop tracking windows and buffering data and
1426 * just pass more or less unmodified SSH messages back and forth.
1427 */
1428 c->sharectx = share_cs;
1429 share_setup_x11_channel(share_cs, share_chan,
1430 c->localid, c->remoteid, c->remwindow,
1431 c->remmaxpkt, c->locwindow,
1432 peer_addr, peer_port, endian,
1433 protomajor, protominor,
1434 initial_data, initial_len);
1435 chan_free(c->chan);
1436 c->chan = NULL;
1437 }
1438
ssh2channel_window_override_removed(SshChannel * sc)1439 static void ssh2channel_window_override_removed(SshChannel *sc)
1440 {
1441 struct ssh2_channel *c = container_of(sc, struct ssh2_channel, sc);
1442 struct ssh2_connection_state *s = c->connlayer;
1443
1444 /*
1445 * This function is called when a client-side Channel has just
1446 * stopped requiring an initial fixed-size window.
1447 */
1448 assert(!c->chan->initial_fixed_window_size);
1449 ssh2_set_window(c, s->ssh_is_simple ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
1450 }
1451
ssh2channel_hint_channel_is_simple(SshChannel * sc)1452 static void ssh2channel_hint_channel_is_simple(SshChannel *sc)
1453 {
1454 struct ssh2_channel *c = container_of(sc, struct ssh2_channel, sc);
1455 struct ssh2_connection_state *s = c->connlayer;
1456
1457 PktOut *pktout = ssh2_chanreq_init(
1458 c, "simple@putty.projects.tartarus.org", NULL, NULL);
1459 pq_push(s->ppl.out_pq, pktout);
1460 }
1461
ssh2_lportfwd_open(ConnectionLayer * cl,const char * hostname,int port,const char * description,const SocketPeerInfo * pi,Channel * chan)1462 static SshChannel *ssh2_lportfwd_open(
1463 ConnectionLayer *cl, const char *hostname, int port,
1464 const char *description, const SocketPeerInfo *pi, Channel *chan)
1465 {
1466 struct ssh2_connection_state *s =
1467 container_of(cl, struct ssh2_connection_state, cl);
1468 struct ssh2_channel *c = snew(struct ssh2_channel);
1469 PktOut *pktout;
1470
1471 c->connlayer = s;
1472 ssh2_channel_init(c);
1473 c->halfopen = true;
1474 c->chan = chan;
1475
1476 pktout = ssh2_portfwd_chanopen(s, c, hostname, port, description, pi);
1477 pq_push(s->ppl.out_pq, pktout);
1478
1479 return &c->sc;
1480 }
1481
ssh2_sharing_globreq_response(struct ssh2_connection_state * s,PktIn * pktin,void * ctx)1482 static void ssh2_sharing_globreq_response(
1483 struct ssh2_connection_state *s, PktIn *pktin, void *ctx)
1484 {
1485 ssh_sharing_connstate *cs = (ssh_sharing_connstate *)ctx;
1486 share_got_pkt_from_server(cs, pktin->type,
1487 BinarySource_UPCAST(pktin)->data,
1488 BinarySource_UPCAST(pktin)->len);
1489 }
1490
ssh2_sharing_queue_global_request(ConnectionLayer * cl,ssh_sharing_connstate * cs)1491 static void ssh2_sharing_queue_global_request(
1492 ConnectionLayer *cl, ssh_sharing_connstate *cs)
1493 {
1494 struct ssh2_connection_state *s =
1495 container_of(cl, struct ssh2_connection_state, cl);
1496 ssh2_queue_global_request_handler(s, ssh2_sharing_globreq_response, cs);
1497 }
1498
ssh2_sharing_no_more_downstreams(ConnectionLayer * cl)1499 static void ssh2_sharing_no_more_downstreams(ConnectionLayer *cl)
1500 {
1501 struct ssh2_connection_state *s =
1502 container_of(cl, struct ssh2_connection_state, cl);
1503 queue_toplevel_callback(ssh2_check_termination_callback, s);
1504 }
1505
ssh2_add_x11_display(ConnectionLayer * cl,int authtype,struct X11Display * disp)1506 static struct X11FakeAuth *ssh2_add_x11_display(
1507 ConnectionLayer *cl, int authtype, struct X11Display *disp)
1508 {
1509 struct ssh2_connection_state *s =
1510 container_of(cl, struct ssh2_connection_state, cl);
1511 struct X11FakeAuth *auth = x11_invent_fake_auth(s->x11authtree, authtype);
1512 auth->disp = disp;
1513 return auth;
1514 }
1515
ssh2_add_sharing_x11_display(ConnectionLayer * cl,int authtype,ssh_sharing_connstate * share_cs,share_channel * share_chan)1516 static struct X11FakeAuth *ssh2_add_sharing_x11_display(
1517 ConnectionLayer *cl, int authtype, ssh_sharing_connstate *share_cs,
1518 share_channel *share_chan)
1519 {
1520 struct ssh2_connection_state *s =
1521 container_of(cl, struct ssh2_connection_state, cl);
1522 struct X11FakeAuth *auth;
1523
1524 /*
1525 * Make up a new set of fake X11 auth data, and add it to the tree
1526 * of currently valid ones with an indication of the sharing
1527 * context that it's relevant to.
1528 */
1529 auth = x11_invent_fake_auth(s->x11authtree, authtype);
1530 auth->share_cs = share_cs;
1531 auth->share_chan = share_chan;
1532
1533 return auth;
1534 }
1535
ssh2_remove_sharing_x11_display(ConnectionLayer * cl,struct X11FakeAuth * auth)1536 static void ssh2_remove_sharing_x11_display(
1537 ConnectionLayer *cl, struct X11FakeAuth *auth)
1538 {
1539 struct ssh2_connection_state *s =
1540 container_of(cl, struct ssh2_connection_state, cl);
1541 del234(s->x11authtree, auth);
1542 x11_free_fake_auth(auth);
1543 }
1544
ssh2_alloc_sharing_channel(ConnectionLayer * cl,ssh_sharing_connstate * connstate)1545 static unsigned ssh2_alloc_sharing_channel(
1546 ConnectionLayer *cl, ssh_sharing_connstate *connstate)
1547 {
1548 struct ssh2_connection_state *s =
1549 container_of(cl, struct ssh2_connection_state, cl);
1550 struct ssh2_channel *c = snew(struct ssh2_channel);
1551
1552 c->connlayer = s;
1553 ssh2_channel_init(c);
1554 c->chan = NULL;
1555 c->sharectx = connstate;
1556 return c->localid;
1557 }
1558
ssh2_delete_sharing_channel(ConnectionLayer * cl,unsigned localid)1559 static void ssh2_delete_sharing_channel(ConnectionLayer *cl, unsigned localid)
1560 {
1561 struct ssh2_connection_state *s =
1562 container_of(cl, struct ssh2_connection_state, cl);
1563 struct ssh2_channel *c = find234(s->channels, &localid, ssh2_channelfind);
1564 if (c)
1565 ssh2_channel_destroy(c);
1566 }
1567
ssh2_send_packet_from_downstream(ConnectionLayer * cl,unsigned id,int type,const void * data,int datalen,const char * additional_log_text)1568 static void ssh2_send_packet_from_downstream(
1569 ConnectionLayer *cl, unsigned id, int type,
1570 const void *data, int datalen, const char *additional_log_text)
1571 {
1572 struct ssh2_connection_state *s =
1573 container_of(cl, struct ssh2_connection_state, cl);
1574 PktOut *pkt = ssh_bpp_new_pktout(s->ppl.bpp, type);
1575 pkt->downstream_id = id;
1576 pkt->additional_log_text = additional_log_text;
1577 put_data(pkt, data, datalen);
1578 pq_push(s->ppl.out_pq, pkt);
1579 }
1580
ssh2_agent_forwarding_permitted(ConnectionLayer * cl)1581 static bool ssh2_agent_forwarding_permitted(ConnectionLayer *cl)
1582 {
1583 struct ssh2_connection_state *s =
1584 container_of(cl, struct ssh2_connection_state, cl);
1585 return conf_get_bool(s->conf, CONF_agentfwd) && agent_exists();
1586 }
1587
ssh2_connection_get_specials(PacketProtocolLayer * ppl,add_special_fn_t add_special,void * ctx)1588 static bool ssh2_connection_get_specials(
1589 PacketProtocolLayer *ppl, add_special_fn_t add_special, void *ctx)
1590 {
1591 struct ssh2_connection_state *s =
1592 container_of(ppl, struct ssh2_connection_state, ppl);
1593 bool toret = false;
1594
1595 if (s->mainchan) {
1596 mainchan_get_specials(s->mainchan, add_special, ctx);
1597 toret = true;
1598 }
1599
1600 /*
1601 * Don't bother offering IGNORE if we've decided the remote
1602 * won't cope with it, since we wouldn't bother sending it if
1603 * asked anyway.
1604 */
1605 if (!(s->ppl.remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
1606 if (toret)
1607 add_special(ctx, NULL, SS_SEP, 0);
1608
1609 add_special(ctx, "IGNORE message", SS_NOP, 0);
1610 toret = true;
1611 }
1612
1613 return toret;
1614 }
1615
ssh2_connection_special_cmd(PacketProtocolLayer * ppl,SessionSpecialCode code,int arg)1616 static void ssh2_connection_special_cmd(PacketProtocolLayer *ppl,
1617 SessionSpecialCode code, int arg)
1618 {
1619 struct ssh2_connection_state *s =
1620 container_of(ppl, struct ssh2_connection_state, ppl);
1621 PktOut *pktout;
1622
1623 if (code == SS_PING || code == SS_NOP) {
1624 if (!(s->ppl.remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
1625 pktout = ssh_bpp_new_pktout(s->ppl.bpp, SSH2_MSG_IGNORE);
1626 put_stringz(pktout, "");
1627 pq_push(s->ppl.out_pq, pktout);
1628 }
1629 } else if (s->mainchan) {
1630 mainchan_special_cmd(s->mainchan, code, arg);
1631 }
1632 }
1633
ssh2_terminal_size(ConnectionLayer * cl,int width,int height)1634 static void ssh2_terminal_size(ConnectionLayer *cl, int width, int height)
1635 {
1636 struct ssh2_connection_state *s =
1637 container_of(cl, struct ssh2_connection_state, cl);
1638
1639 s->term_width = width;
1640 s->term_height = height;
1641 if (s->mainchan)
1642 mainchan_terminal_size(s->mainchan, width, height);
1643 }
1644
ssh2_stdout_unthrottle(ConnectionLayer * cl,size_t bufsize)1645 static void ssh2_stdout_unthrottle(ConnectionLayer *cl, size_t bufsize)
1646 {
1647 struct ssh2_connection_state *s =
1648 container_of(cl, struct ssh2_connection_state, cl);
1649
1650 if (s->mainchan)
1651 sshfwd_unthrottle(s->mainchan_sc, bufsize);
1652 }
1653
ssh2_stdin_backlog(ConnectionLayer * cl)1654 static size_t ssh2_stdin_backlog(ConnectionLayer *cl)
1655 {
1656 struct ssh2_connection_state *s =
1657 container_of(cl, struct ssh2_connection_state, cl);
1658 struct ssh2_channel *c;
1659
1660 if (!s->mainchan)
1661 return 0;
1662 c = container_of(s->mainchan_sc, struct ssh2_channel, sc);
1663 return s->mainchan ?
1664 bufchain_size(&c->outbuffer) + bufchain_size(&c->errbuffer) : 0;
1665 }
1666
ssh2_throttle_all_channels(ConnectionLayer * cl,bool throttled)1667 static void ssh2_throttle_all_channels(ConnectionLayer *cl, bool throttled)
1668 {
1669 struct ssh2_connection_state *s =
1670 container_of(cl, struct ssh2_connection_state, cl);
1671 struct ssh2_channel *c;
1672 int i;
1673
1674 s->all_channels_throttled = throttled;
1675
1676 for (i = 0; NULL != (c = index234(s->channels, i)); i++)
1677 if (!c->sharectx)
1678 ssh2_channel_check_throttle(c);
1679 }
1680
ssh2_ldisc_option(ConnectionLayer * cl,int option)1681 static bool ssh2_ldisc_option(ConnectionLayer *cl, int option)
1682 {
1683 struct ssh2_connection_state *s =
1684 container_of(cl, struct ssh2_connection_state, cl);
1685
1686 return s->ldisc_opts[option];
1687 }
1688
ssh2_set_ldisc_option(ConnectionLayer * cl,int option,bool value)1689 static void ssh2_set_ldisc_option(ConnectionLayer *cl, int option, bool value)
1690 {
1691 struct ssh2_connection_state *s =
1692 container_of(cl, struct ssh2_connection_state, cl);
1693
1694 s->ldisc_opts[option] = value;
1695 }
1696
ssh2_enable_x_fwd(ConnectionLayer * cl)1697 static void ssh2_enable_x_fwd(ConnectionLayer *cl)
1698 {
1699 struct ssh2_connection_state *s =
1700 container_of(cl, struct ssh2_connection_state, cl);
1701
1702 s->X11_fwd_enabled = true;
1703 }
1704
ssh2_set_wants_user_input(ConnectionLayer * cl,bool wanted)1705 static void ssh2_set_wants_user_input(ConnectionLayer *cl, bool wanted)
1706 {
1707 struct ssh2_connection_state *s =
1708 container_of(cl, struct ssh2_connection_state, cl);
1709
1710 s->want_user_input = wanted;
1711 }
1712
ssh2_connection_want_user_input(PacketProtocolLayer * ppl)1713 static bool ssh2_connection_want_user_input(PacketProtocolLayer *ppl)
1714 {
1715 struct ssh2_connection_state *s =
1716 container_of(ppl, struct ssh2_connection_state, ppl);
1717 return s->want_user_input;
1718 }
1719
ssh2_connection_got_user_input(PacketProtocolLayer * ppl)1720 static void ssh2_connection_got_user_input(PacketProtocolLayer *ppl)
1721 {
1722 struct ssh2_connection_state *s =
1723 container_of(ppl, struct ssh2_connection_state, ppl);
1724
1725 while (s->mainchan && bufchain_size(s->ppl.user_input) > 0) {
1726 /*
1727 * Add user input to the main channel's buffer.
1728 */
1729 ptrlen data = bufchain_prefix(s->ppl.user_input);
1730 sshfwd_write(s->mainchan_sc, data.ptr, data.len);
1731 bufchain_consume(s->ppl.user_input, data.len);
1732 }
1733 }
1734
ssh2_connection_reconfigure(PacketProtocolLayer * ppl,Conf * conf)1735 static void ssh2_connection_reconfigure(PacketProtocolLayer *ppl, Conf *conf)
1736 {
1737 struct ssh2_connection_state *s =
1738 container_of(ppl, struct ssh2_connection_state, ppl);
1739
1740 conf_free(s->conf);
1741 s->conf = conf_copy(conf);
1742
1743 if (s->portfwdmgr_configured)
1744 portfwdmgr_config(s->portfwdmgr, s->conf);
1745 }
1746