28 * Packet type contexts, so that ssh2_pkt_type can correctly decode
29 * the ambiguous type numbers back into the correct type strings.
39 SSH2_PKTCTX_PUBLICKEY,
45 static const char *const ssh2_disconnect_reasons[] = {
47 "host not allowed to connect",
49 "key exchange failed",
50 "host authentication failed",
53 "service not available",
54 "protocol version not supported",
55 "host key not verifiable",
58 "too many connections",
59 "auth cancelled by user",
60 "no more auth methods available",
65 * Various remote-bug flags.
67 #define BUG_CHOKES_ON_SSH1_IGNORE 1
68 #define BUG_SSH2_HMAC 2
69 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
70 #define BUG_CHOKES_ON_RSA 8
71 #define BUG_SSH2_RSA_PADDING 16
72 #define BUG_SSH2_DERIVEKEY 32
73 #define BUG_SSH2_REKEY 64
74 #define BUG_SSH2_PK_SESSIONID 128
75 #define BUG_SSH2_MAXPKT 256
76 #define BUG_CHOKES_ON_SSH2_IGNORE 512
77 #define BUG_CHOKES_ON_WINADJ 1024
80 * Codes for terminal modes.
81 * Most of these are the same in SSH-1 and SSH-2.
82 * This list is derived from RFC 4254 and
86 const char* const mode;
88 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
90 /* "V" prefix discarded for special characters relative to SSH specs */
91 { "INTR", 1, TTY_OP_CHAR },
92 { "QUIT", 2, TTY_OP_CHAR },
93 { "ERASE", 3, TTY_OP_CHAR },
94 { "KILL", 4, TTY_OP_CHAR },
95 { "EOF", 5, TTY_OP_CHAR },
96 { "EOL", 6, TTY_OP_CHAR },
97 { "EOL2", 7, TTY_OP_CHAR },
98 { "START", 8, TTY_OP_CHAR },
99 { "STOP", 9, TTY_OP_CHAR },
100 { "SUSP", 10, TTY_OP_CHAR },
101 { "DSUSP", 11, TTY_OP_CHAR },
102 { "REPRINT", 12, TTY_OP_CHAR },
103 { "WERASE", 13, TTY_OP_CHAR },
104 { "LNEXT", 14, TTY_OP_CHAR },
105 { "FLUSH", 15, TTY_OP_CHAR },
106 { "SWTCH", 16, TTY_OP_CHAR },
107 { "STATUS", 17, TTY_OP_CHAR },
108 { "DISCARD", 18, TTY_OP_CHAR },
109 { "IGNPAR", 30, TTY_OP_BOOL },
110 { "PARMRK", 31, TTY_OP_BOOL },
111 { "INPCK", 32, TTY_OP_BOOL },
112 { "ISTRIP", 33, TTY_OP_BOOL },
113 { "INLCR", 34, TTY_OP_BOOL },
114 { "IGNCR", 35, TTY_OP_BOOL },
115 { "ICRNL", 36, TTY_OP_BOOL },
116 { "IUCLC", 37, TTY_OP_BOOL },
117 { "IXON", 38, TTY_OP_BOOL },
118 { "IXANY", 39, TTY_OP_BOOL },
119 { "IXOFF", 40, TTY_OP_BOOL },
120 { "IMAXBEL", 41, TTY_OP_BOOL },
121 { "ISIG", 50, TTY_OP_BOOL },
122 { "ICANON", 51, TTY_OP_BOOL },
123 { "XCASE", 52, TTY_OP_BOOL },
124 { "ECHO", 53, TTY_OP_BOOL },
125 { "ECHOE", 54, TTY_OP_BOOL },
126 { "ECHOK", 55, TTY_OP_BOOL },
127 { "ECHONL", 56, TTY_OP_BOOL },
128 { "NOFLSH", 57, TTY_OP_BOOL },
129 { "TOSTOP", 58, TTY_OP_BOOL },
130 { "IEXTEN", 59, TTY_OP_BOOL },
131 { "ECHOCTL", 60, TTY_OP_BOOL },
132 { "ECHOKE", 61, TTY_OP_BOOL },
133 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
134 { "OPOST", 70, TTY_OP_BOOL },
135 { "OLCUC", 71, TTY_OP_BOOL },
136 { "ONLCR", 72, TTY_OP_BOOL },
137 { "OCRNL", 73, TTY_OP_BOOL },
138 { "ONOCR", 74, TTY_OP_BOOL },
139 { "ONLRET", 75, TTY_OP_BOOL },
140 { "CS7", 90, TTY_OP_BOOL },
141 { "CS8", 91, TTY_OP_BOOL },
142 { "PARENB", 92, TTY_OP_BOOL },
143 { "PARODD", 93, TTY_OP_BOOL }
146 /* Miscellaneous other tty-related constants. */
147 #define SSH_TTY_OP_END 0
148 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
149 #define SSH1_TTY_OP_ISPEED 192
150 #define SSH1_TTY_OP_OSPEED 193
151 #define SSH2_TTY_OP_ISPEED 128
152 #define SSH2_TTY_OP_OSPEED 129
154 /* Helper functions for parsing tty-related config. */
155 static unsigned int ssh_tty_parse_specchar(char *s)
160 ret = ctrlparse(s, &next);
161 if (!next) ret = s[0];
163 ret = 255; /* special value meaning "don't set" */
167 static unsigned int ssh_tty_parse_boolean(char *s)
169 if (stricmp(s, "yes") == 0 ||
170 stricmp(s, "on") == 0 ||
171 stricmp(s, "true") == 0 ||
172 stricmp(s, "+") == 0)
174 else if (stricmp(s, "no") == 0 ||
175 stricmp(s, "off") == 0 ||
176 stricmp(s, "false") == 0 ||
177 stricmp(s, "-") == 0)
178 return 0; /* false */
180 return (atoi(s) != 0);
183 #define translate(x) if (type == x) return #x
184 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
185 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
186 static char *ssh1_pkt_type(int type)
188 translate(SSH1_MSG_DISCONNECT);
189 translate(SSH1_SMSG_PUBLIC_KEY);
190 translate(SSH1_CMSG_SESSION_KEY);
191 translate(SSH1_CMSG_USER);
192 translate(SSH1_CMSG_AUTH_RSA);
193 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
194 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
195 translate(SSH1_CMSG_AUTH_PASSWORD);
196 translate(SSH1_CMSG_REQUEST_PTY);
197 translate(SSH1_CMSG_WINDOW_SIZE);
198 translate(SSH1_CMSG_EXEC_SHELL);
199 translate(SSH1_CMSG_EXEC_CMD);
200 translate(SSH1_SMSG_SUCCESS);
201 translate(SSH1_SMSG_FAILURE);
202 translate(SSH1_CMSG_STDIN_DATA);
203 translate(SSH1_SMSG_STDOUT_DATA);
204 translate(SSH1_SMSG_STDERR_DATA);
205 translate(SSH1_CMSG_EOF);
206 translate(SSH1_SMSG_EXIT_STATUS);
207 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
208 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
209 translate(SSH1_MSG_CHANNEL_DATA);
210 translate(SSH1_MSG_CHANNEL_CLOSE);
211 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
212 translate(SSH1_SMSG_X11_OPEN);
213 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
214 translate(SSH1_MSG_PORT_OPEN);
215 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
216 translate(SSH1_SMSG_AGENT_OPEN);
217 translate(SSH1_MSG_IGNORE);
218 translate(SSH1_CMSG_EXIT_CONFIRMATION);
219 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
220 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
221 translate(SSH1_MSG_DEBUG);
222 translate(SSH1_CMSG_REQUEST_COMPRESSION);
223 translate(SSH1_CMSG_AUTH_TIS);
224 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
225 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
226 translate(SSH1_CMSG_AUTH_CCARD);
227 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
228 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
231 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
233 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
234 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
235 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
236 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
237 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
238 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
239 translate(SSH2_MSG_DISCONNECT);
240 translate(SSH2_MSG_IGNORE);
241 translate(SSH2_MSG_UNIMPLEMENTED);
242 translate(SSH2_MSG_DEBUG);
243 translate(SSH2_MSG_SERVICE_REQUEST);
244 translate(SSH2_MSG_SERVICE_ACCEPT);
245 translate(SSH2_MSG_KEXINIT);
246 translate(SSH2_MSG_NEWKEYS);
247 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
248 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
249 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
250 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
251 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
252 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
253 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
254 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
255 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
256 translate(SSH2_MSG_USERAUTH_REQUEST);
257 translate(SSH2_MSG_USERAUTH_FAILURE);
258 translate(SSH2_MSG_USERAUTH_SUCCESS);
259 translate(SSH2_MSG_USERAUTH_BANNER);
260 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
261 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
262 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
263 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
264 translate(SSH2_MSG_GLOBAL_REQUEST);
265 translate(SSH2_MSG_REQUEST_SUCCESS);
266 translate(SSH2_MSG_REQUEST_FAILURE);
267 translate(SSH2_MSG_CHANNEL_OPEN);
268 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
269 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
270 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
271 translate(SSH2_MSG_CHANNEL_DATA);
272 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
273 translate(SSH2_MSG_CHANNEL_EOF);
274 translate(SSH2_MSG_CHANNEL_CLOSE);
275 translate(SSH2_MSG_CHANNEL_REQUEST);
276 translate(SSH2_MSG_CHANNEL_SUCCESS);
277 translate(SSH2_MSG_CHANNEL_FAILURE);
283 /* Enumeration values for fields in SSH-1 packets */
285 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
289 * Coroutine mechanics for the sillier bits of the code. If these
290 * macros look impenetrable to you, you might find it helpful to
293 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
295 * which explains the theory behind these macros.
297 * In particular, if you are getting `case expression not constant'
298 * errors when building with MS Visual Studio, this is because MS's
299 * Edit and Continue debugging feature causes their compiler to
300 * violate ANSI C. To disable Edit and Continue debugging:
302 * - right-click ssh.c in the FileView
304 * - select the C/C++ tab and the General category
305 * - under `Debug info:', select anything _other_ than `Program
306 * Database for Edit and Continue'.
308 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
309 #define crBeginState crBegin(s->crLine)
310 #define crStateP(t, v) \
312 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
314 #define crState(t) crStateP(t, ssh->t)
315 #define crFinish(z) } *crLine = 0; return (z); }
316 #define crFinishV } *crLine = 0; return; }
317 #define crFinishFree(z) } sfree(s); return (z); }
318 #define crFinishFreeV } sfree(s); return; }
319 #define crReturn(z) \
321 *crLine =__LINE__; return (z); case __LINE__:;\
325 *crLine=__LINE__; return; case __LINE__:;\
327 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
328 #define crStopV do{ *crLine = 0; return; }while(0)
329 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
330 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
332 typedef struct ssh_tag *Ssh;
335 static struct Packet *ssh1_pkt_init(int pkt_type);
336 static struct Packet *ssh2_pkt_init(int pkt_type);
337 static void ssh_pkt_ensure(struct Packet *, int length);
338 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
339 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
340 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
341 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
342 static void ssh_pkt_addstring_start(struct Packet *);
343 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
344 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
345 static void ssh_pkt_addstring(struct Packet *, const char *data);
346 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
347 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
348 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
349 static int ssh2_pkt_construct(Ssh, struct Packet *);
350 static void ssh2_pkt_send(Ssh, struct Packet *);
351 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
352 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
353 struct Packet *pktin);
354 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
355 struct Packet *pktin);
356 static void ssh2_channel_check_close(struct ssh_channel *c);
357 static void ssh_channel_destroy(struct ssh_channel *c);
360 * Buffer management constants. There are several of these for
361 * various different purposes:
363 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
364 * on a local data stream before we throttle the whole SSH
365 * connection (in SSH-1 only). Throttling the whole connection is
366 * pretty drastic so we set this high in the hope it won't
369 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
370 * on the SSH connection itself before we defensively throttle
371 * _all_ local data streams. This is pretty drastic too (though
372 * thankfully unlikely in SSH-2 since the window mechanism should
373 * ensure that the server never has any need to throttle its end
374 * of the connection), so we set this high as well.
376 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
379 * - OUR_V2_BIGWIN is the window size we advertise for the only
380 * channel in a simple connection. It must be <= INT_MAX.
382 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
383 * to the remote side. This actually has nothing to do with the
384 * size of the _packet_, but is instead a limit on the amount
385 * of data we're willing to receive in a single SSH2 channel
388 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
389 * _packet_ we're prepared to cope with. It must be a multiple
390 * of the cipher block size, and must be at least 35000.
393 #define SSH1_BUFFER_LIMIT 32768
394 #define SSH_MAX_BACKLOG 32768
395 #define OUR_V2_WINSIZE 16384
396 #define OUR_V2_BIGWIN 0x7fffffff
397 #define OUR_V2_MAXPKT 0x4000UL
398 #define OUR_V2_PACKETLIMIT 0x9000UL
400 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
402 const static struct ssh_mac *macs[] = {
403 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
405 const static struct ssh_mac *buggymacs[] = {
406 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
409 static void *ssh_comp_none_init(void)
413 static void ssh_comp_none_cleanup(void *handle)
416 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
417 unsigned char **outblock, int *outlen)
421 static int ssh_comp_none_disable(void *handle)
425 const static struct ssh_compress ssh_comp_none = {
427 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
428 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
429 ssh_comp_none_disable, NULL
431 extern const struct ssh_compress ssh_zlib;
432 const static struct ssh_compress *compressions[] = {
433 &ssh_zlib, &ssh_comp_none
436 enum { /* channel types */
441 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
443 * CHAN_ZOMBIE is used to indicate a channel for which we've
444 * already destroyed the local data source: for instance, if a
445 * forwarded port experiences a socket error on the local side, we
446 * immediately destroy its local socket and turn the SSH channel
452 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
453 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
454 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
457 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
460 struct outstanding_channel_request {
461 cchandler_fn_t handler;
463 struct outstanding_channel_request *next;
467 * 2-3-4 tree storing channels.
470 Ssh ssh; /* pointer back to main context */
471 unsigned remoteid, localid;
473 /* True if we opened this channel but server hasn't confirmed. */
476 * In SSH-1, this value contains four bits:
478 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
479 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
480 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
481 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
483 * A channel is completely finished with when all four bits are set.
485 * In SSH-2, the four bits mean:
487 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
488 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
489 * 4 We have received SSH2_MSG_CHANNEL_EOF.
490 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
492 * A channel is completely finished with when we have both sent
493 * and received CLOSE.
495 * The symbolic constants below use the SSH-2 terminology, which
496 * is a bit confusing in SSH-1, but we have to use _something_.
498 #define CLOSES_SENT_EOF 1
499 #define CLOSES_SENT_CLOSE 2
500 #define CLOSES_RCVD_EOF 4
501 #define CLOSES_RCVD_CLOSE 8
505 * This flag indicates that an EOF is pending on the outgoing side
506 * of the channel: that is, wherever we're getting the data for
507 * this channel has sent us some data followed by EOF. We can't
508 * actually send the EOF until we've finished sending the data, so
509 * we set this flag instead to remind us to do so once our buffer
515 * True if this channel is causing the underlying connection to be
520 struct ssh2_data_channel {
522 unsigned remwindow, remmaxpkt;
523 /* locwindow is signed so we can cope with excess data. */
524 int locwindow, locmaxwin;
526 * remlocwin is the amount of local window that we think
527 * the remote end had available to it after it sent the
528 * last data packet or window adjust ack.
532 * These store the list of channel requests that haven't
535 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
536 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
540 struct ssh_agent_channel {
541 unsigned char *message;
542 unsigned char msglen[4];
543 unsigned lensofar, totallen;
544 int outstanding_requests;
546 struct ssh_x11_channel {
547 struct X11Connection *xconn;
549 struct ssh_pfd_channel {
550 struct PortForwarding *pf;
556 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
557 * use this structure in different ways, reflecting SSH-2's
558 * altogether saner approach to port forwarding.
560 * In SSH-1, you arrange a remote forwarding by sending the server
561 * the remote port number, and the local destination host:port.
562 * When a connection comes in, the server sends you back that
563 * host:port pair, and you connect to it. This is a ready-made
564 * security hole if you're not on the ball: a malicious server
565 * could send you back _any_ host:port pair, so if you trustingly
566 * connect to the address it gives you then you've just opened the
567 * entire inside of your corporate network just by connecting
568 * through it to a dodgy SSH server. Hence, we must store a list of
569 * host:port pairs we _are_ trying to forward to, and reject a
570 * connection request from the server if it's not in the list.
572 * In SSH-2, each side of the connection minds its own business and
573 * doesn't send unnecessary information to the other. You arrange a
574 * remote forwarding by sending the server just the remote port
575 * number. When a connection comes in, the server tells you which
576 * of its ports was connected to; and _you_ have to remember what
577 * local host:port pair went with that port number.
579 * Hence, in SSH-1 this structure is indexed by destination
580 * host:port pair, whereas in SSH-2 it is indexed by source port.
582 struct ssh_portfwd; /* forward declaration */
584 struct ssh_rportfwd {
585 unsigned sport, dport;
588 struct ssh_portfwd *pfrec;
591 static void free_rportfwd(struct ssh_rportfwd *pf)
594 sfree(pf->sportdesc);
602 * Separately to the rportfwd tree (which is for looking up port
603 * open requests from the server), a tree of _these_ structures is
604 * used to keep track of all the currently open port forwardings,
605 * so that we can reconfigure in mid-session if the user requests
609 enum { DESTROY, KEEP, CREATE } status;
611 unsigned sport, dport;
614 struct ssh_rportfwd *remote;
616 struct PortListener *local;
618 #define free_portfwd(pf) ( \
619 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
620 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
623 long length; /* length of packet: see below */
624 long forcepad; /* SSH-2: force padding to at least this length */
625 int type; /* only used for incoming packets */
626 unsigned long sequence; /* SSH-2 incoming sequence number */
627 unsigned char *data; /* allocated storage */
628 unsigned char *body; /* offset of payload within `data' */
629 long savedpos; /* dual-purpose saved packet position: see below */
630 long maxlen; /* amount of storage allocated for `data' */
631 long encrypted_len; /* for SSH-2 total-size counting */
634 * A note on the 'length' and 'savedpos' fields above.
636 * Incoming packets are set up so that pkt->length is measured
637 * relative to pkt->body, which itself points to a few bytes after
638 * pkt->data (skipping some uninteresting header fields including
639 * the packet type code). The ssh_pkt_get* functions all expect
640 * this setup, and they also use pkt->savedpos to indicate how far
641 * through the packet being decoded they've got - and that, too,
642 * is an offset from pkt->body rather than pkt->data.
644 * During construction of an outgoing packet, however, pkt->length
645 * is measured relative to the base pointer pkt->data, and
646 * pkt->body is not really used for anything until the packet is
647 * ready for sending. In this mode, pkt->savedpos is reused as a
648 * temporary variable by the addstring functions, which write out
649 * a string length field and then keep going back and updating it
650 * as more data is appended to the subsequent string data field;
651 * pkt->savedpos stores the offset (again relative to pkt->data)
652 * of the start of the string data field.
656 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
657 struct Packet *pktin);
658 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
659 struct Packet *pktin);
660 static void ssh1_protocol_setup(Ssh ssh);
661 static void ssh2_protocol_setup(Ssh ssh);
662 static void ssh_size(void *handle, int width, int height);
663 static void ssh_special(void *handle, Telnet_Special);
664 static int ssh2_try_send(struct ssh_channel *c);
665 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
666 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
667 static void ssh2_set_window(struct ssh_channel *c, int newwin);
668 static int ssh_sendbuffer(void *handle);
669 static int ssh_do_close(Ssh ssh, int notify_exit);
670 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
671 static int ssh2_pkt_getbool(struct Packet *pkt);
672 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
673 static void ssh2_timer(void *ctx, unsigned long now);
674 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
675 struct Packet *pktin);
676 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
678 struct rdpkt1_state_tag {
679 long len, pad, biglen, to_read;
680 unsigned long realcrc, gotcrc;
684 struct Packet *pktin;
687 struct rdpkt2_state_tag {
688 long len, pad, payload, packetlen, maclen;
691 unsigned long incoming_sequence;
692 struct Packet *pktin;
695 struct queued_handler;
696 struct queued_handler {
698 chandler_fn_t handler;
700 struct queued_handler *next;
704 const struct plug_function_table *fn;
705 /* the above field _must_ be first in the structure */
715 unsigned char session_key[32];
717 int v1_remote_protoflags;
718 int v1_local_protoflags;
719 int agentfwd_enabled;
722 const struct ssh_cipher *cipher;
725 const struct ssh2_cipher *cscipher, *sccipher;
726 void *cs_cipher_ctx, *sc_cipher_ctx;
727 const struct ssh_mac *csmac, *scmac;
728 void *cs_mac_ctx, *sc_mac_ctx;
729 const struct ssh_compress *cscomp, *sccomp;
730 void *cs_comp_ctx, *sc_comp_ctx;
731 const struct ssh_kex *kex;
732 const struct ssh_signkey *hostkey;
733 char *hostkey_str; /* string representation, for easy checking in rekeys */
734 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
735 int v2_session_id_len;
741 int echoing, editing;
745 int ospeed, ispeed; /* temporaries */
746 int term_width, term_height;
748 tree234 *channels; /* indexed by local id */
749 struct ssh_channel *mainchan; /* primary session channel */
750 int ncmode; /* is primary channel direct-tcpip? */
755 tree234 *rportfwds, *portfwds;
759 SSH_STATE_BEFORE_SIZE,
765 int size_needed, eof_needed;
766 int sent_console_eof;
767 int got_pty; /* affects EOF behaviour on main channel */
769 struct Packet **queue;
770 int queuelen, queuesize;
772 unsigned char *deferred_send_data;
773 int deferred_len, deferred_size;
776 * Gross hack: pscp will try to start SFTP but fall back to
777 * scp1 if that fails. This variable is the means by which
778 * scp.c can reach into the SSH code and find out which one it
783 bufchain banner; /* accumulates banners during do_ssh2_authconn */
788 struct X11Display *x11disp;
789 struct X11FakeAuth *x11auth;
790 tree234 *x11authtree;
793 int conn_throttle_count;
796 int v1_stdout_throttling;
797 unsigned long v2_outgoing_sequence;
799 int ssh1_rdpkt_crstate;
800 int ssh2_rdpkt_crstate;
801 int ssh_gotdata_crstate;
802 int do_ssh1_connection_crstate;
804 void *do_ssh_init_state;
805 void *do_ssh1_login_state;
806 void *do_ssh2_transport_state;
807 void *do_ssh2_authconn_state;
809 struct rdpkt1_state_tag rdpkt1_state;
810 struct rdpkt2_state_tag rdpkt2_state;
812 /* SSH-1 and SSH-2 use this for different things, but both use it */
813 int protocol_initial_phase_done;
815 void (*protocol) (Ssh ssh, void *vin, int inlen,
817 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
820 * We maintain our own copy of a Conf structure here. That way,
821 * when we're passed a new one for reconfiguration, we can check
822 * the differences and potentially reconfigure port forwardings
823 * etc in mid-session.
828 * Values cached out of conf so as to avoid the tree234 lookup
829 * cost every time they're used.
834 * Dynamically allocated username string created during SSH
835 * login. Stored in here rather than in the coroutine state so
836 * that it'll be reliably freed if we shut down the SSH session
837 * at some unexpected moment.
842 * Used to transfer data back from async callbacks.
844 void *agent_response;
845 int agent_response_len;
849 * The SSH connection can be set as `frozen', meaning we are
850 * not currently accepting incoming data from the network. This
851 * is slightly more serious than setting the _socket_ as
852 * frozen, because we may already have had data passed to us
853 * from the network which we need to delay processing until
854 * after the freeze is lifted, so we also need a bufchain to
858 bufchain queued_incoming_data;
861 * Dispatch table for packet types that we may have to deal
864 handler_fn_t packet_dispatch[256];
867 * Queues of one-off handler functions for success/failure
868 * indications from a request.
870 struct queued_handler *qhead, *qtail;
871 handler_fn_t q_saved_handler1, q_saved_handler2;
874 * This module deals with sending keepalives.
879 * Track incoming and outgoing data sizes and time, for
882 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
883 unsigned long max_data_size;
885 unsigned long next_rekey, last_rekey;
886 char *deferred_rekey_reason; /* points to STATIC string; don't free */
889 * Fully qualified host name, which we need if doing GSSAPI.
895 * GSSAPI libraries for this session.
897 struct ssh_gss_liblist *gsslibs;
901 #define logevent(s) logevent(ssh->frontend, s)
903 /* logevent, only printf-formatted. */
904 static void logeventf(Ssh ssh, const char *fmt, ...)
910 buf = dupvprintf(fmt, ap);
916 static void bomb_out(Ssh ssh, char *text)
918 ssh_do_close(ssh, FALSE);
920 connection_fatal(ssh->frontend, "%s", text);
924 #define bombout(msg) bomb_out(ssh, dupprintf msg)
926 /* Helper function for common bits of parsing ttymodes. */
927 static void parse_ttymodes(Ssh ssh,
928 void (*do_mode)(void *data, char *mode, char *val),
933 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
935 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
937 * val[0] is either 'V', indicating that an explicit value
938 * follows it, or 'A' indicating that we should pass the
939 * value through from the local environment via get_ttymode.
942 val = get_ttymode(ssh->frontend, key);
944 do_mode(data, key, val);
948 do_mode(data, key, val + 1); /* skip the 'V' */
952 static int ssh_channelcmp(void *av, void *bv)
954 struct ssh_channel *a = (struct ssh_channel *) av;
955 struct ssh_channel *b = (struct ssh_channel *) bv;
956 if (a->localid < b->localid)
958 if (a->localid > b->localid)
962 static int ssh_channelfind(void *av, void *bv)
964 unsigned *a = (unsigned *) av;
965 struct ssh_channel *b = (struct ssh_channel *) bv;
973 static int ssh_rportcmp_ssh1(void *av, void *bv)
975 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
976 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
978 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
979 return i < 0 ? -1 : +1;
980 if (a->dport > b->dport)
982 if (a->dport < b->dport)
987 static int ssh_rportcmp_ssh2(void *av, void *bv)
989 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
990 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
992 if ( (i = strcmp(a->shost, b->shost)) != 0)
993 return i < 0 ? -1 : +1;
994 if (a->sport > b->sport)
996 if (a->sport < b->sport)
1002 * Special form of strcmp which can cope with NULL inputs. NULL is
1003 * defined to sort before even the empty string.
1005 static int nullstrcmp(const char *a, const char *b)
1007 if (a == NULL && b == NULL)
1013 return strcmp(a, b);
1016 static int ssh_portcmp(void *av, void *bv)
1018 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1019 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1021 if (a->type > b->type)
1023 if (a->type < b->type)
1025 if (a->addressfamily > b->addressfamily)
1027 if (a->addressfamily < b->addressfamily)
1029 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1030 return i < 0 ? -1 : +1;
1031 if (a->sport > b->sport)
1033 if (a->sport < b->sport)
1035 if (a->type != 'D') {
1036 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1037 return i < 0 ? -1 : +1;
1038 if (a->dport > b->dport)
1040 if (a->dport < b->dport)
1046 static int alloc_channel_id(Ssh ssh)
1048 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1049 unsigned low, high, mid;
1051 struct ssh_channel *c;
1054 * First-fit allocation of channel numbers: always pick the
1055 * lowest unused one. To do this, binary-search using the
1056 * counted B-tree to find the largest channel ID which is in a
1057 * contiguous sequence from the beginning. (Precisely
1058 * everything in that sequence must have ID equal to its tree
1059 * index plus CHANNEL_NUMBER_OFFSET.)
1061 tsize = count234(ssh->channels);
1065 while (high - low > 1) {
1066 mid = (high + low) / 2;
1067 c = index234(ssh->channels, mid);
1068 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1069 low = mid; /* this one is fine */
1071 high = mid; /* this one is past it */
1074 * Now low points to either -1, or the tree index of the
1075 * largest ID in the initial sequence.
1078 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1079 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1081 return low + 1 + CHANNEL_NUMBER_OFFSET;
1084 static void c_write_stderr(int trusted, const char *buf, int len)
1087 for (i = 0; i < len; i++)
1088 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1089 fputc(buf[i], stderr);
1092 static void c_write(Ssh ssh, const char *buf, int len)
1094 if (flags & FLAG_STDERR)
1095 c_write_stderr(1, buf, len);
1097 from_backend(ssh->frontend, 1, buf, len);
1100 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1102 if (flags & FLAG_STDERR)
1103 c_write_stderr(0, buf, len);
1105 from_backend_untrusted(ssh->frontend, buf, len);
1108 static void c_write_str(Ssh ssh, const char *buf)
1110 c_write(ssh, buf, strlen(buf));
1113 static void ssh_free_packet(struct Packet *pkt)
1118 static struct Packet *ssh_new_packet(void)
1120 struct Packet *pkt = snew(struct Packet);
1122 pkt->body = pkt->data = NULL;
1128 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1131 struct logblank_t blanks[4];
1137 if (ssh->logomitdata &&
1138 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1139 pkt->type == SSH1_SMSG_STDERR_DATA ||
1140 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1141 /* "Session data" packets - omit the data string. */
1142 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1143 ssh_pkt_getuint32(pkt); /* skip channel id */
1144 blanks[nblanks].offset = pkt->savedpos + 4;
1145 blanks[nblanks].type = PKTLOG_OMIT;
1146 ssh_pkt_getstring(pkt, &str, &slen);
1148 blanks[nblanks].len = slen;
1152 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1153 ssh1_pkt_type(pkt->type),
1154 pkt->body, pkt->length, nblanks, blanks, NULL);
1157 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1160 struct logblank_t blanks[4];
1165 * For outgoing packets, pkt->length represents the length of the
1166 * whole packet starting at pkt->data (including some header), and
1167 * pkt->body refers to the point within that where the log-worthy
1168 * payload begins. However, incoming packets expect pkt->length to
1169 * represent only the payload length (that is, it's measured from
1170 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1171 * packet to conform to the incoming-packet semantics, so that we
1172 * can analyse it with the ssh_pkt_get functions.
1174 pkt->length -= (pkt->body - pkt->data);
1177 if (ssh->logomitdata &&
1178 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1179 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1180 /* "Session data" packets - omit the data string. */
1181 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1182 ssh_pkt_getuint32(pkt); /* skip channel id */
1183 blanks[nblanks].offset = pkt->savedpos + 4;
1184 blanks[nblanks].type = PKTLOG_OMIT;
1185 ssh_pkt_getstring(pkt, &str, &slen);
1187 blanks[nblanks].len = slen;
1192 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1193 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1194 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1195 conf_get_int(ssh->conf, CONF_logomitpass)) {
1196 /* If this is a password or similar packet, blank the password(s). */
1197 blanks[nblanks].offset = 0;
1198 blanks[nblanks].len = pkt->length;
1199 blanks[nblanks].type = PKTLOG_BLANK;
1201 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1202 conf_get_int(ssh->conf, CONF_logomitpass)) {
1204 * If this is an X forwarding request packet, blank the fake
1207 * Note that while we blank the X authentication data here, we
1208 * don't take any special action to blank the start of an X11
1209 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1210 * an X connection without having session blanking enabled is
1211 * likely to leak your cookie into the log.
1214 ssh_pkt_getstring(pkt, &str, &slen);
1215 blanks[nblanks].offset = pkt->savedpos;
1216 blanks[nblanks].type = PKTLOG_BLANK;
1217 ssh_pkt_getstring(pkt, &str, &slen);
1219 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1224 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1225 ssh1_pkt_type(pkt->data[12]),
1226 pkt->body, pkt->length,
1227 nblanks, blanks, NULL);
1230 * Undo the above adjustment of pkt->length, to put the packet
1231 * back in the state we found it.
1233 pkt->length += (pkt->body - pkt->data);
1237 * Collect incoming data in the incoming packet buffer.
1238 * Decipher and verify the packet when it is completely read.
1239 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1240 * Update the *data and *datalen variables.
1241 * Return a Packet structure when a packet is completed.
1243 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1245 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1247 crBegin(ssh->ssh1_rdpkt_crstate);
1249 st->pktin = ssh_new_packet();
1251 st->pktin->type = 0;
1252 st->pktin->length = 0;
1254 for (st->i = st->len = 0; st->i < 4; st->i++) {
1255 while ((*datalen) == 0)
1257 st->len = (st->len << 8) + **data;
1258 (*data)++, (*datalen)--;
1261 st->pad = 8 - (st->len % 8);
1262 st->biglen = st->len + st->pad;
1263 st->pktin->length = st->len - 5;
1265 if (st->biglen < 0) {
1266 bombout(("Extremely large packet length from server suggests"
1267 " data stream corruption"));
1268 ssh_free_packet(st->pktin);
1272 st->pktin->maxlen = st->biglen;
1273 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1275 st->to_read = st->biglen;
1276 st->p = st->pktin->data;
1277 while (st->to_read > 0) {
1278 st->chunk = st->to_read;
1279 while ((*datalen) == 0)
1281 if (st->chunk > (*datalen))
1282 st->chunk = (*datalen);
1283 memcpy(st->p, *data, st->chunk);
1285 *datalen -= st->chunk;
1287 st->to_read -= st->chunk;
1290 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1291 st->biglen, NULL)) {
1292 bombout(("Network attack (CRC compensation) detected!"));
1293 ssh_free_packet(st->pktin);
1298 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1300 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1301 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1302 if (st->gotcrc != st->realcrc) {
1303 bombout(("Incorrect CRC received on packet"));
1304 ssh_free_packet(st->pktin);
1308 st->pktin->body = st->pktin->data + st->pad + 1;
1310 if (ssh->v1_compressing) {
1311 unsigned char *decompblk;
1313 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1314 st->pktin->body - 1, st->pktin->length + 1,
1315 &decompblk, &decomplen)) {
1316 bombout(("Zlib decompression encountered invalid data"));
1317 ssh_free_packet(st->pktin);
1321 if (st->pktin->maxlen < st->pad + decomplen) {
1322 st->pktin->maxlen = st->pad + decomplen;
1323 st->pktin->data = sresize(st->pktin->data,
1324 st->pktin->maxlen + APIEXTRA,
1326 st->pktin->body = st->pktin->data + st->pad + 1;
1329 memcpy(st->pktin->body - 1, decompblk, decomplen);
1331 st->pktin->length = decomplen - 1;
1334 st->pktin->type = st->pktin->body[-1];
1337 * Now pktin->body and pktin->length identify the semantic content
1338 * of the packet, excluding the initial type byte.
1342 ssh1_log_incoming_packet(ssh, st->pktin);
1344 st->pktin->savedpos = 0;
1346 crFinish(st->pktin);
1349 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1352 struct logblank_t blanks[4];
1358 if (ssh->logomitdata &&
1359 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1360 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1361 /* "Session data" packets - omit the data string. */
1362 ssh_pkt_getuint32(pkt); /* skip channel id */
1363 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1364 ssh_pkt_getuint32(pkt); /* skip extended data type */
1365 blanks[nblanks].offset = pkt->savedpos + 4;
1366 blanks[nblanks].type = PKTLOG_OMIT;
1367 ssh_pkt_getstring(pkt, &str, &slen);
1369 blanks[nblanks].len = slen;
1374 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1375 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1376 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence);
1379 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1382 struct logblank_t blanks[4];
1387 * For outgoing packets, pkt->length represents the length of the
1388 * whole packet starting at pkt->data (including some header), and
1389 * pkt->body refers to the point within that where the log-worthy
1390 * payload begins. However, incoming packets expect pkt->length to
1391 * represent only the payload length (that is, it's measured from
1392 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1393 * packet to conform to the incoming-packet semantics, so that we
1394 * can analyse it with the ssh_pkt_get functions.
1396 pkt->length -= (pkt->body - pkt->data);
1399 if (ssh->logomitdata &&
1400 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1401 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1402 /* "Session data" packets - omit the data string. */
1403 ssh_pkt_getuint32(pkt); /* skip channel id */
1404 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1405 ssh_pkt_getuint32(pkt); /* skip extended data type */
1406 blanks[nblanks].offset = pkt->savedpos + 4;
1407 blanks[nblanks].type = PKTLOG_OMIT;
1408 ssh_pkt_getstring(pkt, &str, &slen);
1410 blanks[nblanks].len = slen;
1415 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1416 conf_get_int(ssh->conf, CONF_logomitpass)) {
1417 /* If this is a password packet, blank the password(s). */
1419 ssh_pkt_getstring(pkt, &str, &slen);
1420 ssh_pkt_getstring(pkt, &str, &slen);
1421 ssh_pkt_getstring(pkt, &str, &slen);
1422 if (slen == 8 && !memcmp(str, "password", 8)) {
1423 ssh2_pkt_getbool(pkt);
1424 /* Blank the password field. */
1425 blanks[nblanks].offset = pkt->savedpos;
1426 blanks[nblanks].type = PKTLOG_BLANK;
1427 ssh_pkt_getstring(pkt, &str, &slen);
1429 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1431 /* If there's another password field beyond it (change of
1432 * password), blank that too. */
1433 ssh_pkt_getstring(pkt, &str, &slen);
1435 blanks[nblanks-1].len =
1436 pkt->savedpos - blanks[nblanks].offset;
1439 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1440 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1441 conf_get_int(ssh->conf, CONF_logomitpass)) {
1442 /* If this is a keyboard-interactive response packet, blank
1445 ssh_pkt_getuint32(pkt);
1446 blanks[nblanks].offset = pkt->savedpos;
1447 blanks[nblanks].type = PKTLOG_BLANK;
1449 ssh_pkt_getstring(pkt, &str, &slen);
1453 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1455 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1456 conf_get_int(ssh->conf, CONF_logomitpass)) {
1458 * If this is an X forwarding request packet, blank the fake
1461 * Note that while we blank the X authentication data here, we
1462 * don't take any special action to blank the start of an X11
1463 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1464 * an X connection without having session blanking enabled is
1465 * likely to leak your cookie into the log.
1468 ssh_pkt_getuint32(pkt);
1469 ssh_pkt_getstring(pkt, &str, &slen);
1470 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1471 ssh2_pkt_getbool(pkt);
1472 ssh2_pkt_getbool(pkt);
1473 ssh_pkt_getstring(pkt, &str, &slen);
1474 blanks[nblanks].offset = pkt->savedpos;
1475 blanks[nblanks].type = PKTLOG_BLANK;
1476 ssh_pkt_getstring(pkt, &str, &slen);
1478 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1484 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1485 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1486 pkt->body, pkt->length, nblanks, blanks,
1487 &ssh->v2_outgoing_sequence);
1490 * Undo the above adjustment of pkt->length, to put the packet
1491 * back in the state we found it.
1493 pkt->length += (pkt->body - pkt->data);
1496 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1498 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1500 crBegin(ssh->ssh2_rdpkt_crstate);
1502 st->pktin = ssh_new_packet();
1504 st->pktin->type = 0;
1505 st->pktin->length = 0;
1507 st->cipherblk = ssh->sccipher->blksize;
1510 if (st->cipherblk < 8)
1512 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1514 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1517 * When dealing with a CBC-mode cipher, we want to avoid the
1518 * possibility of an attacker's tweaking the ciphertext stream
1519 * so as to cause us to feed the same block to the block
1520 * cipher more than once and thus leak information
1521 * (VU#958563). The way we do this is not to take any
1522 * decisions on the basis of anything we've decrypted until
1523 * we've verified it with a MAC. That includes the packet
1524 * length, so we just read data and check the MAC repeatedly,
1525 * and when the MAC passes, see if the length we've got is
1529 /* May as well allocate the whole lot now. */
1530 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1533 /* Read an amount corresponding to the MAC. */
1534 for (st->i = 0; st->i < st->maclen; st->i++) {
1535 while ((*datalen) == 0)
1537 st->pktin->data[st->i] = *(*data)++;
1543 unsigned char seq[4];
1544 ssh->scmac->start(ssh->sc_mac_ctx);
1545 PUT_32BIT(seq, st->incoming_sequence);
1546 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1549 for (;;) { /* Once around this loop per cipher block. */
1550 /* Read another cipher-block's worth, and tack it onto the end. */
1551 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1552 while ((*datalen) == 0)
1554 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1557 /* Decrypt one more block (a little further back in the stream). */
1558 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1559 st->pktin->data + st->packetlen,
1561 /* Feed that block to the MAC. */
1562 ssh->scmac->bytes(ssh->sc_mac_ctx,
1563 st->pktin->data + st->packetlen, st->cipherblk);
1564 st->packetlen += st->cipherblk;
1565 /* See if that gives us a valid packet. */
1566 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1567 st->pktin->data + st->packetlen) &&
1568 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1571 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1572 bombout(("No valid incoming packet found"));
1573 ssh_free_packet(st->pktin);
1577 st->pktin->maxlen = st->packetlen + st->maclen;
1578 st->pktin->data = sresize(st->pktin->data,
1579 st->pktin->maxlen + APIEXTRA,
1582 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1585 * Acquire and decrypt the first block of the packet. This will
1586 * contain the length and padding details.
1588 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1589 while ((*datalen) == 0)
1591 st->pktin->data[st->i] = *(*data)++;
1596 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1597 st->pktin->data, st->cipherblk);
1600 * Now get the length figure.
1602 st->len = toint(GET_32BIT(st->pktin->data));
1605 * _Completely_ silly lengths should be stomped on before they
1606 * do us any more damage.
1608 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1609 (st->len + 4) % st->cipherblk != 0) {
1610 bombout(("Incoming packet was garbled on decryption"));
1611 ssh_free_packet(st->pktin);
1616 * So now we can work out the total packet length.
1618 st->packetlen = st->len + 4;
1621 * Allocate memory for the rest of the packet.
1623 st->pktin->maxlen = st->packetlen + st->maclen;
1624 st->pktin->data = sresize(st->pktin->data,
1625 st->pktin->maxlen + APIEXTRA,
1629 * Read and decrypt the remainder of the packet.
1631 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1633 while ((*datalen) == 0)
1635 st->pktin->data[st->i] = *(*data)++;
1638 /* Decrypt everything _except_ the MAC. */
1640 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1641 st->pktin->data + st->cipherblk,
1642 st->packetlen - st->cipherblk);
1648 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1649 st->len + 4, st->incoming_sequence)) {
1650 bombout(("Incorrect MAC received on packet"));
1651 ssh_free_packet(st->pktin);
1655 /* Get and sanity-check the amount of random padding. */
1656 st->pad = st->pktin->data[4];
1657 if (st->pad < 4 || st->len - st->pad < 1) {
1658 bombout(("Invalid padding length on received packet"));
1659 ssh_free_packet(st->pktin);
1663 * This enables us to deduce the payload length.
1665 st->payload = st->len - st->pad - 1;
1667 st->pktin->length = st->payload + 5;
1668 st->pktin->encrypted_len = st->packetlen;
1670 st->pktin->sequence = st->incoming_sequence++;
1673 * Decompress packet payload.
1676 unsigned char *newpayload;
1679 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1680 st->pktin->data + 5, st->pktin->length - 5,
1681 &newpayload, &newlen)) {
1682 if (st->pktin->maxlen < newlen + 5) {
1683 st->pktin->maxlen = newlen + 5;
1684 st->pktin->data = sresize(st->pktin->data,
1685 st->pktin->maxlen + APIEXTRA,
1688 st->pktin->length = 5 + newlen;
1689 memcpy(st->pktin->data + 5, newpayload, newlen);
1695 * pktin->body and pktin->length should identify the semantic
1696 * content of the packet, excluding the initial type byte.
1698 st->pktin->type = st->pktin->data[5];
1699 st->pktin->body = st->pktin->data + 6;
1700 st->pktin->length = st->packetlen - 6 - st->pad;
1701 assert(st->pktin->length >= 0); /* one last double-check */
1704 ssh2_log_incoming_packet(ssh, st->pktin);
1706 st->pktin->savedpos = 0;
1708 crFinish(st->pktin);
1711 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1713 int pad, biglen, i, pktoffs;
1717 * XXX various versions of SC (including 8.8.4) screw up the
1718 * register allocation in this function and use the same register
1719 * (D6) for len and as a temporary, with predictable results. The
1720 * following sledgehammer prevents this.
1727 ssh1_log_outgoing_packet(ssh, pkt);
1729 if (ssh->v1_compressing) {
1730 unsigned char *compblk;
1732 zlib_compress_block(ssh->cs_comp_ctx,
1733 pkt->data + 12, pkt->length - 12,
1734 &compblk, &complen);
1735 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1736 memcpy(pkt->data + 12, compblk, complen);
1738 pkt->length = complen + 12;
1741 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1743 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1744 pad = 8 - (len % 8);
1746 biglen = len + pad; /* len(padding+type+data+CRC) */
1748 for (i = pktoffs; i < 4+8; i++)
1749 pkt->data[i] = random_byte();
1750 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1751 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1752 PUT_32BIT(pkt->data + pktoffs, len);
1755 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1756 pkt->data + pktoffs + 4, biglen);
1758 if (offset_p) *offset_p = pktoffs;
1759 return biglen + 4; /* len(length+padding+type+data+CRC) */
1762 static int s_write(Ssh ssh, void *data, int len)
1765 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1769 return sk_write(ssh->s, (char *)data, len);
1772 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1774 int len, backlog, offset;
1775 len = s_wrpkt_prepare(ssh, pkt, &offset);
1776 backlog = s_write(ssh, pkt->data + offset, len);
1777 if (backlog > SSH_MAX_BACKLOG)
1778 ssh_throttle_all(ssh, 1, backlog);
1779 ssh_free_packet(pkt);
1782 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1785 len = s_wrpkt_prepare(ssh, pkt, &offset);
1786 if (ssh->deferred_len + len > ssh->deferred_size) {
1787 ssh->deferred_size = ssh->deferred_len + len + 128;
1788 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1792 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1793 pkt->data + offset, len);
1794 ssh->deferred_len += len;
1795 ssh_free_packet(pkt);
1799 * Construct a SSH-1 packet with the specified contents.
1800 * (This all-at-once interface used to be the only one, but now SSH-1
1801 * packets can also be constructed incrementally.)
1803 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1809 pkt = ssh1_pkt_init(pkttype);
1811 while ((argtype = va_arg(ap, int)) != PKT_END) {
1812 unsigned char *argp, argchar;
1814 unsigned long argint;
1817 /* Actual fields in the packet */
1819 argint = va_arg(ap, int);
1820 ssh_pkt_adduint32(pkt, argint);
1823 argchar = (unsigned char) va_arg(ap, int);
1824 ssh_pkt_addbyte(pkt, argchar);
1827 argp = va_arg(ap, unsigned char *);
1828 arglen = va_arg(ap, int);
1829 ssh_pkt_adddata(pkt, argp, arglen);
1832 sargp = va_arg(ap, char *);
1833 ssh_pkt_addstring(pkt, sargp);
1836 bn = va_arg(ap, Bignum);
1837 ssh1_pkt_addmp(pkt, bn);
1845 static void send_packet(Ssh ssh, int pkttype, ...)
1849 va_start(ap, pkttype);
1850 pkt = construct_packet(ssh, pkttype, ap);
1855 static void defer_packet(Ssh ssh, int pkttype, ...)
1859 va_start(ap, pkttype);
1860 pkt = construct_packet(ssh, pkttype, ap);
1862 s_wrpkt_defer(ssh, pkt);
1865 static int ssh_versioncmp(char *a, char *b)
1868 unsigned long av, bv;
1870 av = strtoul(a, &ae, 10);
1871 bv = strtoul(b, &be, 10);
1873 return (av < bv ? -1 : +1);
1878 av = strtoul(ae, &ae, 10);
1879 bv = strtoul(be, &be, 10);
1881 return (av < bv ? -1 : +1);
1886 * Utility routines for putting an SSH-protocol `string' and
1887 * `uint32' into a hash state.
1889 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1891 unsigned char lenblk[4];
1892 PUT_32BIT(lenblk, len);
1893 h->bytes(s, lenblk, 4);
1894 h->bytes(s, str, len);
1897 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1899 unsigned char intblk[4];
1900 PUT_32BIT(intblk, i);
1901 h->bytes(s, intblk, 4);
1905 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1907 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1909 if (pkt->maxlen < length) {
1910 unsigned char *body = pkt->body;
1911 int offset = body ? body - pkt->data : 0;
1912 pkt->maxlen = length + 256;
1913 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1914 if (body) pkt->body = pkt->data + offset;
1917 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
1920 ssh_pkt_ensure(pkt, pkt->length);
1921 memcpy(pkt->data + pkt->length - len, data, len);
1923 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1925 ssh_pkt_adddata(pkt, &byte, 1);
1927 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1929 ssh_pkt_adddata(pkt, &value, 1);
1931 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1934 PUT_32BIT(x, value);
1935 ssh_pkt_adddata(pkt, x, 4);
1937 static void ssh_pkt_addstring_start(struct Packet *pkt)
1939 ssh_pkt_adduint32(pkt, 0);
1940 pkt->savedpos = pkt->length;
1942 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
1944 ssh_pkt_adddata(pkt, data, strlen(data));
1945 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1947 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
1950 ssh_pkt_adddata(pkt, data, len);
1951 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1953 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
1955 ssh_pkt_addstring_start(pkt);
1956 ssh_pkt_addstring_str(pkt, data);
1958 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1960 int len = ssh1_bignum_length(b);
1961 unsigned char *data = snewn(len, unsigned char);
1962 (void) ssh1_write_bignum(data, b);
1963 ssh_pkt_adddata(pkt, data, len);
1966 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1969 int i, n = (bignum_bitcount(b) + 7) / 8;
1970 p = snewn(n + 1, unsigned char);
1972 for (i = 1; i <= n; i++)
1973 p[i] = bignum_byte(b, n - i);
1975 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1977 memmove(p, p + i, n + 1 - i);
1981 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1985 p = ssh2_mpint_fmt(b, &len);
1986 ssh_pkt_addstring_start(pkt);
1987 ssh_pkt_addstring_data(pkt, (char *)p, len);
1991 static struct Packet *ssh1_pkt_init(int pkt_type)
1993 struct Packet *pkt = ssh_new_packet();
1994 pkt->length = 4 + 8; /* space for length + max padding */
1995 ssh_pkt_addbyte(pkt, pkt_type);
1996 pkt->body = pkt->data + pkt->length;
1997 pkt->type = pkt_type;
2001 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2002 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2003 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2004 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2005 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2006 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2007 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2008 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2009 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2011 static struct Packet *ssh2_pkt_init(int pkt_type)
2013 struct Packet *pkt = ssh_new_packet();
2014 pkt->length = 5; /* space for packet length + padding length */
2016 pkt->type = pkt_type;
2017 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2018 pkt->body = pkt->data + pkt->length; /* after packet type */
2023 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2024 * put the MAC on it. Final packet, ready to be sent, is stored in
2025 * pkt->data. Total length is returned.
2027 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2029 int cipherblk, maclen, padding, i;
2032 ssh2_log_outgoing_packet(ssh, pkt);
2035 * Compress packet payload.
2038 unsigned char *newpayload;
2041 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2043 &newpayload, &newlen)) {
2045 ssh2_pkt_adddata(pkt, newpayload, newlen);
2051 * Add padding. At least four bytes, and must also bring total
2052 * length (minus MAC) up to a multiple of the block size.
2053 * If pkt->forcepad is set, make sure the packet is at least that size
2056 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2057 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2059 if (pkt->length + padding < pkt->forcepad)
2060 padding = pkt->forcepad - pkt->length;
2062 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
2063 assert(padding <= 255);
2064 maclen = ssh->csmac ? ssh->csmac->len : 0;
2065 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2066 pkt->data[4] = padding;
2067 for (i = 0; i < padding; i++)
2068 pkt->data[pkt->length + i] = random_byte();
2069 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2071 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2072 pkt->length + padding,
2073 ssh->v2_outgoing_sequence);
2074 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2077 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2078 pkt->data, pkt->length + padding);
2080 pkt->encrypted_len = pkt->length + padding;
2082 /* Ready-to-send packet starts at pkt->data. We return length. */
2083 return pkt->length + padding + maclen;
2087 * Routines called from the main SSH code to send packets. There
2088 * are quite a few of these, because we have two separate
2089 * mechanisms for delaying the sending of packets:
2091 * - In order to send an IGNORE message and a password message in
2092 * a single fixed-length blob, we require the ability to
2093 * concatenate the encrypted forms of those two packets _into_ a
2094 * single blob and then pass it to our <network.h> transport
2095 * layer in one go. Hence, there's a deferment mechanism which
2096 * works after packet encryption.
2098 * - In order to avoid sending any connection-layer messages
2099 * during repeat key exchange, we have to queue up any such
2100 * outgoing messages _before_ they are encrypted (and in
2101 * particular before they're allocated sequence numbers), and
2102 * then send them once we've finished.
2104 * I call these mechanisms `defer' and `queue' respectively, so as
2105 * to distinguish them reasonably easily.
2107 * The functions send_noqueue() and defer_noqueue() free the packet
2108 * structure they are passed. Every outgoing packet goes through
2109 * precisely one of these functions in its life; packets passed to
2110 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2111 * these or get queued, and then when the queue is later emptied
2112 * the packets are all passed to defer_noqueue().
2114 * When using a CBC-mode cipher, it's necessary to ensure that an
2115 * attacker can't provide data to be encrypted using an IV that they
2116 * know. We ensure this by prefixing each packet that might contain
2117 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2118 * mechanism, so in this case send_noqueue() ends up redirecting to
2119 * defer_noqueue(). If you don't like this inefficiency, don't use
2123 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2124 static void ssh_pkt_defersend(Ssh);
2127 * Send an SSH-2 packet immediately, without queuing or deferring.
2129 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2133 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2134 /* We need to send two packets, so use the deferral mechanism. */
2135 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2136 ssh_pkt_defersend(ssh);
2139 len = ssh2_pkt_construct(ssh, pkt);
2140 backlog = s_write(ssh, pkt->data, len);
2141 if (backlog > SSH_MAX_BACKLOG)
2142 ssh_throttle_all(ssh, 1, backlog);
2144 ssh->outgoing_data_size += pkt->encrypted_len;
2145 if (!ssh->kex_in_progress &&
2146 ssh->max_data_size != 0 &&
2147 ssh->outgoing_data_size > ssh->max_data_size)
2148 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2150 ssh_free_packet(pkt);
2154 * Defer an SSH-2 packet.
2156 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2159 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2160 ssh->deferred_len == 0 && !noignore &&
2161 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2163 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2164 * get encrypted with a known IV.
2166 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2167 ssh2_pkt_addstring_start(ipkt);
2168 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2170 len = ssh2_pkt_construct(ssh, pkt);
2171 if (ssh->deferred_len + len > ssh->deferred_size) {
2172 ssh->deferred_size = ssh->deferred_len + len + 128;
2173 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2177 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
2178 ssh->deferred_len += len;
2179 ssh->deferred_data_size += pkt->encrypted_len;
2180 ssh_free_packet(pkt);
2184 * Queue an SSH-2 packet.
2186 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2188 assert(ssh->queueing);
2190 if (ssh->queuelen >= ssh->queuesize) {
2191 ssh->queuesize = ssh->queuelen + 32;
2192 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2195 ssh->queue[ssh->queuelen++] = pkt;
2199 * Either queue or send a packet, depending on whether queueing is
2202 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2205 ssh2_pkt_queue(ssh, pkt);
2207 ssh2_pkt_send_noqueue(ssh, pkt);
2211 * Either queue or defer a packet, depending on whether queueing is
2214 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2217 ssh2_pkt_queue(ssh, pkt);
2219 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2223 * Send the whole deferred data block constructed by
2224 * ssh2_pkt_defer() or SSH-1's defer_packet().
2226 * The expected use of the defer mechanism is that you call
2227 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2228 * not currently queueing, this simply sets up deferred_send_data
2229 * and then sends it. If we _are_ currently queueing, the calls to
2230 * ssh2_pkt_defer() put the deferred packets on to the queue
2231 * instead, and therefore ssh_pkt_defersend() has no deferred data
2232 * to send. Hence, there's no need to make it conditional on
2235 static void ssh_pkt_defersend(Ssh ssh)
2238 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2239 ssh->deferred_len = ssh->deferred_size = 0;
2240 sfree(ssh->deferred_send_data);
2241 ssh->deferred_send_data = NULL;
2242 if (backlog > SSH_MAX_BACKLOG)
2243 ssh_throttle_all(ssh, 1, backlog);
2245 ssh->outgoing_data_size += ssh->deferred_data_size;
2246 if (!ssh->kex_in_progress &&
2247 ssh->max_data_size != 0 &&
2248 ssh->outgoing_data_size > ssh->max_data_size)
2249 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2250 ssh->deferred_data_size = 0;
2254 * Send a packet whose length needs to be disguised (typically
2255 * passwords or keyboard-interactive responses).
2257 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2263 * The simplest way to do this is to adjust the
2264 * variable-length padding field in the outgoing packet.
2266 * Currently compiled out, because some Cisco SSH servers
2267 * don't like excessively padded packets (bah, why's it
2270 pkt->forcepad = padsize;
2271 ssh2_pkt_send(ssh, pkt);
2276 * If we can't do that, however, an alternative approach is
2277 * to use the pkt_defer mechanism to bundle the packet
2278 * tightly together with an SSH_MSG_IGNORE such that their
2279 * combined length is a constant. So first we construct the
2280 * final form of this packet and defer its sending.
2282 ssh2_pkt_defer(ssh, pkt);
2285 * Now construct an SSH_MSG_IGNORE which includes a string
2286 * that's an exact multiple of the cipher block size. (If
2287 * the cipher is NULL so that the block size is
2288 * unavailable, we don't do this trick at all, because we
2289 * gain nothing by it.)
2291 if (ssh->cscipher &&
2292 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2295 stringlen = (256 - ssh->deferred_len);
2296 stringlen += ssh->cscipher->blksize - 1;
2297 stringlen -= (stringlen % ssh->cscipher->blksize);
2300 * Temporarily disable actual compression, so we
2301 * can guarantee to get this string exactly the
2302 * length we want it. The compression-disabling
2303 * routine should return an integer indicating how
2304 * many bytes we should adjust our string length
2308 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2310 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2311 ssh2_pkt_addstring_start(pkt);
2312 for (i = 0; i < stringlen; i++) {
2313 char c = (char) random_byte();
2314 ssh2_pkt_addstring_data(pkt, &c, 1);
2316 ssh2_pkt_defer(ssh, pkt);
2318 ssh_pkt_defersend(ssh);
2323 * Send all queued SSH-2 packets. We send them by means of
2324 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2325 * packets that needed to be lumped together.
2327 static void ssh2_pkt_queuesend(Ssh ssh)
2331 assert(!ssh->queueing);
2333 for (i = 0; i < ssh->queuelen; i++)
2334 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2337 ssh_pkt_defersend(ssh);
2341 void bndebug(char *string, Bignum b)
2345 p = ssh2_mpint_fmt(b, &len);
2346 debug(("%s", string));
2347 for (i = 0; i < len; i++)
2348 debug((" %02x", p[i]));
2354 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2358 p = ssh2_mpint_fmt(b, &len);
2359 hash_string(h, s, p, len);
2364 * Packet decode functions for both SSH-1 and SSH-2.
2366 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2368 unsigned long value;
2369 if (pkt->length - pkt->savedpos < 4)
2370 return 0; /* arrgh, no way to decline (FIXME?) */
2371 value = GET_32BIT(pkt->body + pkt->savedpos);
2375 static int ssh2_pkt_getbool(struct Packet *pkt)
2377 unsigned long value;
2378 if (pkt->length - pkt->savedpos < 1)
2379 return 0; /* arrgh, no way to decline (FIXME?) */
2380 value = pkt->body[pkt->savedpos] != 0;
2384 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2389 if (pkt->length - pkt->savedpos < 4)
2391 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2396 if (pkt->length - pkt->savedpos < *length)
2398 *p = (char *)(pkt->body + pkt->savedpos);
2399 pkt->savedpos += *length;
2401 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2403 if (pkt->length - pkt->savedpos < length)
2405 pkt->savedpos += length;
2406 return pkt->body + (pkt->savedpos - length);
2408 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2409 unsigned char **keystr)
2413 j = makekey(pkt->body + pkt->savedpos,
2414 pkt->length - pkt->savedpos,
2421 assert(pkt->savedpos < pkt->length);
2425 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2430 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2431 pkt->length - pkt->savedpos, &b);
2439 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2445 ssh_pkt_getstring(pkt, &p, &length);
2450 b = bignum_from_bytes((unsigned char *)p, length);
2455 * Helper function to add an SSH-2 signature blob to a packet.
2456 * Expects to be shown the public key blob as well as the signature
2457 * blob. Normally works just like ssh2_pkt_addstring, but will
2458 * fiddle with the signature packet if necessary for
2459 * BUG_SSH2_RSA_PADDING.
2461 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2462 void *pkblob_v, int pkblob_len,
2463 void *sigblob_v, int sigblob_len)
2465 unsigned char *pkblob = (unsigned char *)pkblob_v;
2466 unsigned char *sigblob = (unsigned char *)sigblob_v;
2468 /* dmemdump(pkblob, pkblob_len); */
2469 /* dmemdump(sigblob, sigblob_len); */
2472 * See if this is in fact an ssh-rsa signature and a buggy
2473 * server; otherwise we can just do this the easy way.
2475 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2476 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2477 int pos, len, siglen;
2480 * Find the byte length of the modulus.
2483 pos = 4+7; /* skip over "ssh-rsa" */
2484 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2485 if (len < 0 || len > pkblob_len - pos - 4)
2487 pos += 4 + len; /* skip over exponent */
2488 if (pkblob_len - pos < 4)
2490 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2491 if (len < 0 || len > pkblob_len - pos - 4)
2493 pos += 4; /* find modulus itself */
2494 while (len > 0 && pkblob[pos] == 0)
2496 /* debug(("modulus length is %d\n", len)); */
2499 * Now find the signature integer.
2501 pos = 4+7; /* skip over "ssh-rsa" */
2502 if (sigblob_len < pos+4)
2504 siglen = toint(GET_32BIT(sigblob+pos));
2505 if (siglen != sigblob_len - pos - 4)
2507 /* debug(("signature length is %d\n", siglen)); */
2509 if (len != siglen) {
2510 unsigned char newlen[4];
2511 ssh2_pkt_addstring_start(pkt);
2512 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2513 /* dmemdump(sigblob, pos); */
2514 pos += 4; /* point to start of actual sig */
2515 PUT_32BIT(newlen, len);
2516 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2517 /* dmemdump(newlen, 4); */
2519 while (len-- > siglen) {
2520 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2521 /* dmemdump(newlen, 1); */
2523 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2524 /* dmemdump(sigblob+pos, siglen); */
2528 /* Otherwise fall through and do it the easy way. We also come
2529 * here as a fallback if we discover above that the key blob
2530 * is misformatted in some way. */
2534 ssh2_pkt_addstring_start(pkt);
2535 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2539 * Examine the remote side's version string and compare it against
2540 * a list of known buggy implementations.
2542 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2544 char *imp; /* pointer to implementation part */
2546 imp += strcspn(imp, "-");
2548 imp += strcspn(imp, "-");
2551 ssh->remote_bugs = 0;
2554 * General notes on server version strings:
2555 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2556 * here -- in particular, we've heard of one that's perfectly happy
2557 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2558 * so we can't distinguish them.
2560 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2561 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2562 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2563 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2564 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2565 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2567 * These versions don't support SSH1_MSG_IGNORE, so we have
2568 * to use a different defence against password length
2571 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2572 logevent("We believe remote version has SSH-1 ignore bug");
2575 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2576 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2577 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2579 * These versions need a plain password sent; they can't
2580 * handle having a null and a random length of data after
2583 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2584 logevent("We believe remote version needs a plain SSH-1 password");
2587 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2588 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2589 (!strcmp(imp, "Cisco-1.25")))) {
2591 * These versions apparently have no clue whatever about
2592 * RSA authentication and will panic and die if they see
2593 * an AUTH_RSA message.
2595 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2596 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2599 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2600 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2601 !wc_match("* VShell", imp) &&
2602 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2603 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2604 wc_match("2.1 *", imp)))) {
2606 * These versions have the HMAC bug.
2608 ssh->remote_bugs |= BUG_SSH2_HMAC;
2609 logevent("We believe remote version has SSH-2 HMAC bug");
2612 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2613 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2614 !wc_match("* VShell", imp) &&
2615 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2617 * These versions have the key-derivation bug (failing to
2618 * include the literal shared secret in the hashes that
2619 * generate the keys).
2621 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2622 logevent("We believe remote version has SSH-2 key-derivation bug");
2625 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2626 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2627 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2628 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2630 * These versions have the SSH-2 RSA padding bug.
2632 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2633 logevent("We believe remote version has SSH-2 RSA padding bug");
2636 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2637 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2638 wc_match("OpenSSH_2.[0-2]*", imp))) {
2640 * These versions have the SSH-2 session-ID bug in
2641 * public-key authentication.
2643 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2644 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2647 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2648 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2649 (wc_match("DigiSSH_2.0", imp) ||
2650 wc_match("OpenSSH_2.[0-4]*", imp) ||
2651 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2652 wc_match("Sun_SSH_1.0", imp) ||
2653 wc_match("Sun_SSH_1.0.1", imp) ||
2654 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2655 wc_match("WeOnlyDo-*", imp)))) {
2657 * These versions have the SSH-2 rekey bug.
2659 ssh->remote_bugs |= BUG_SSH2_REKEY;
2660 logevent("We believe remote version has SSH-2 rekey bug");
2663 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2664 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2665 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2666 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2668 * This version ignores our makpkt and needs to be throttled.
2670 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2671 logevent("We believe remote version ignores SSH-2 maximum packet size");
2674 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2676 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2677 * none detected automatically.
2679 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2680 logevent("We believe remote version has SSH-2 ignore bug");
2683 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2685 * Servers that don't support our winadj request for one
2686 * reason or another. Currently, none detected automatically.
2688 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2689 logevent("We believe remote version has winadj bug");
2694 * The `software version' part of an SSH version string is required
2695 * to contain no spaces or minus signs.
2697 static void ssh_fix_verstring(char *str)
2699 /* Eat "SSH-<protoversion>-". */
2700 assert(*str == 'S'); str++;
2701 assert(*str == 'S'); str++;
2702 assert(*str == 'H'); str++;
2703 assert(*str == '-'); str++;
2704 while (*str && *str != '-') str++;
2705 assert(*str == '-'); str++;
2707 /* Convert minus signs and spaces in the remaining string into
2710 if (*str == '-' || *str == ' ')
2717 * Send an appropriate SSH version string.
2719 static void ssh_send_verstring(Ssh ssh, char *svers)
2723 if (ssh->version == 2) {
2725 * Construct a v2 version string.
2727 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2730 * Construct a v1 version string.
2732 verstring = dupprintf("SSH-%s-%s\012",
2733 (ssh_versioncmp(svers, "1.5") <= 0 ?
2738 ssh_fix_verstring(verstring);
2740 if (ssh->version == 2) {
2743 * Record our version string.
2745 len = strcspn(verstring, "\015\012");
2746 ssh->v_c = snewn(len + 1, char);
2747 memcpy(ssh->v_c, verstring, len);
2751 logeventf(ssh, "We claim version: %.*s",
2752 strcspn(verstring, "\015\012"), verstring);
2753 s_write(ssh, verstring, strlen(verstring));
2757 static int do_ssh_init(Ssh ssh, unsigned char c)
2759 struct do_ssh_init_state {
2768 crState(do_ssh_init_state);
2772 /* Search for a line beginning with the string "SSH-" in the input. */
2774 if (c != 'S') goto no;
2776 if (c != 'S') goto no;
2778 if (c != 'H') goto no;
2780 if (c != '-') goto no;
2789 s->vstring = snewn(s->vstrsize, char);
2790 strcpy(s->vstring, "SSH-");
2794 crReturn(1); /* get another char */
2795 if (s->vslen >= s->vstrsize - 1) {
2797 s->vstring = sresize(s->vstring, s->vstrsize, char);
2799 s->vstring[s->vslen++] = c;
2802 s->version[s->i] = '\0';
2804 } else if (s->i < sizeof(s->version) - 1)
2805 s->version[s->i++] = c;
2806 } else if (c == '\012')
2810 ssh->agentfwd_enabled = FALSE;
2811 ssh->rdpkt2_state.incoming_sequence = 0;
2813 s->vstring[s->vslen] = 0;
2814 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2815 logeventf(ssh, "Server version: %s", s->vstring);
2816 ssh_detect_bugs(ssh, s->vstring);
2819 * Decide which SSH protocol version to support.
2822 /* Anything strictly below "2.0" means protocol 1 is supported. */
2823 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2824 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2825 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2827 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2828 bombout(("SSH protocol version 1 required by user but not provided by server"));
2831 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2832 bombout(("SSH protocol version 2 required by user but not provided by server"));
2836 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2841 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2843 /* Send the version string, if we haven't already */
2844 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2845 ssh_send_verstring(ssh, s->version);
2847 if (ssh->version == 2) {
2850 * Record their version string.
2852 len = strcspn(s->vstring, "\015\012");
2853 ssh->v_s = snewn(len + 1, char);
2854 memcpy(ssh->v_s, s->vstring, len);
2858 * Initialise SSH-2 protocol.
2860 ssh->protocol = ssh2_protocol;
2861 ssh2_protocol_setup(ssh);
2862 ssh->s_rdpkt = ssh2_rdpkt;
2865 * Initialise SSH-1 protocol.
2867 ssh->protocol = ssh1_protocol;
2868 ssh1_protocol_setup(ssh);
2869 ssh->s_rdpkt = ssh1_rdpkt;
2871 if (ssh->version == 2)
2872 do_ssh2_transport(ssh, NULL, -1, NULL);
2874 update_specials_menu(ssh->frontend);
2875 ssh->state = SSH_STATE_BEFORE_SIZE;
2876 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
2883 static void ssh_process_incoming_data(Ssh ssh,
2884 unsigned char **data, int *datalen)
2886 struct Packet *pktin;
2888 pktin = ssh->s_rdpkt(ssh, data, datalen);
2890 ssh->protocol(ssh, NULL, 0, pktin);
2891 ssh_free_packet(pktin);
2895 static void ssh_queue_incoming_data(Ssh ssh,
2896 unsigned char **data, int *datalen)
2898 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2903 static void ssh_process_queued_incoming_data(Ssh ssh)
2906 unsigned char *data;
2909 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2910 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2914 while (!ssh->frozen && len > 0)
2915 ssh_process_incoming_data(ssh, &data, &len);
2918 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2922 static void ssh_set_frozen(Ssh ssh, int frozen)
2925 sk_set_frozen(ssh->s, frozen);
2926 ssh->frozen = frozen;
2929 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2931 /* Log raw data, if we're in that mode. */
2933 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2936 crBegin(ssh->ssh_gotdata_crstate);
2939 * To begin with, feed the characters one by one to the
2940 * protocol initialisation / selection function do_ssh_init().
2941 * When that returns 0, we're done with the initial greeting
2942 * exchange and can move on to packet discipline.
2945 int ret; /* need not be kept across crReturn */
2947 crReturnV; /* more data please */
2948 ret = do_ssh_init(ssh, *data);
2956 * We emerge from that loop when the initial negotiation is
2957 * over and we have selected an s_rdpkt function. Now pass
2958 * everything to s_rdpkt, and then pass the resulting packets
2959 * to the proper protocol handler.
2963 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2965 ssh_queue_incoming_data(ssh, &data, &datalen);
2966 /* This uses up all data and cannot cause anything interesting
2967 * to happen; indeed, for anything to happen at all, we must
2968 * return, so break out. */
2970 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2971 /* This uses up some or all data, and may freeze the
2973 ssh_process_queued_incoming_data(ssh);
2975 /* This uses up some or all data, and may freeze the
2977 ssh_process_incoming_data(ssh, &data, &datalen);
2979 /* FIXME this is probably EBW. */
2980 if (ssh->state == SSH_STATE_CLOSED)
2983 /* We're out of data. Go and get some more. */
2989 static int ssh_do_close(Ssh ssh, int notify_exit)
2992 struct ssh_channel *c;
2994 ssh->state = SSH_STATE_CLOSED;
2995 expire_timer_context(ssh);
3000 notify_remote_exit(ssh->frontend);
3005 * Now we must shut down any port- and X-forwarded channels going
3006 * through this connection.
3008 if (ssh->channels) {
3009 while (NULL != (c = index234(ssh->channels, 0))) {
3012 x11_close(c->u.x11.xconn);
3015 case CHAN_SOCKDATA_DORMANT:
3016 pfd_close(c->u.pfd.pf);
3019 del234(ssh->channels, c); /* moving next one to index 0 */
3020 if (ssh->version == 2)
3021 bufchain_clear(&c->v.v2.outbuffer);
3026 * Go through port-forwardings, and close any associated
3027 * listening sockets.
3029 if (ssh->portfwds) {
3030 struct ssh_portfwd *pf;
3031 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3032 /* Dispose of any listening socket. */
3034 pfl_terminate(pf->local);
3035 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3038 freetree234(ssh->portfwds);
3039 ssh->portfwds = NULL;
3045 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
3046 const char *error_msg, int error_code)
3048 Ssh ssh = (Ssh) plug;
3049 char addrbuf[256], *msg;
3051 sk_getaddr(addr, addrbuf, lenof(addrbuf));
3054 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
3056 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
3062 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3065 Ssh ssh = (Ssh) plug;
3066 int need_notify = ssh_do_close(ssh, FALSE);
3069 if (!ssh->close_expected)
3070 error_msg = "Server unexpectedly closed network connection";
3072 error_msg = "Server closed network connection";
3075 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3079 notify_remote_exit(ssh->frontend);
3082 logevent(error_msg);
3083 if (!ssh->close_expected || !ssh->clean_exit)
3084 connection_fatal(ssh->frontend, "%s", error_msg);
3088 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3090 Ssh ssh = (Ssh) plug;
3091 ssh_gotdata(ssh, (unsigned char *)data, len);
3092 if (ssh->state == SSH_STATE_CLOSED) {
3093 ssh_do_close(ssh, TRUE);
3099 static void ssh_sent(Plug plug, int bufsize)
3101 Ssh ssh = (Ssh) plug;
3103 * If the send backlog on the SSH socket itself clears, we
3104 * should unthrottle the whole world if it was throttled.
3106 if (bufsize < SSH_MAX_BACKLOG)
3107 ssh_throttle_all(ssh, 0, bufsize);
3111 * Connect to specified host and port.
3112 * Returns an error message, or NULL on success.
3113 * Also places the canonical host name into `realhost'. It must be
3114 * freed by the caller.
3116 static const char *connect_to_host(Ssh ssh, char *host, int port,
3117 char **realhost, int nodelay, int keepalive)
3119 static const struct plug_function_table fn_table = {
3130 int addressfamily, sshprot;
3132 loghost = conf_get_str(ssh->conf, CONF_loghost);
3136 ssh->savedhost = dupstr(loghost);
3137 ssh->savedport = 22; /* default ssh port */
3140 * A colon suffix on savedhost also lets us affect
3143 * (FIXME: do something about IPv6 address literals here.)
3145 colon = strrchr(ssh->savedhost, ':');
3149 ssh->savedport = atoi(colon);
3152 ssh->savedhost = dupstr(host);
3154 port = 22; /* default ssh port */
3155 ssh->savedport = port;
3161 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3162 logeventf(ssh, "Looking up host \"%s\"%s", host,
3163 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3164 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3165 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3166 if ((err = sk_addr_error(addr)) != NULL) {
3170 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3175 ssh->fn = &fn_table;
3176 ssh->s = new_connection(addr, *realhost, port,
3177 0, 1, nodelay, keepalive, (Plug) ssh, ssh->conf);
3178 if ((err = sk_socket_error(ssh->s)) != NULL) {
3180 notify_remote_exit(ssh->frontend);
3185 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3186 * send the version string too.
3188 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3193 ssh_send_verstring(ssh, NULL);
3197 * loghost, if configured, overrides realhost.
3201 *realhost = dupstr(loghost);
3208 * Throttle or unthrottle the SSH connection.
3210 static void ssh_throttle_conn(Ssh ssh, int adjust)
3212 int old_count = ssh->conn_throttle_count;
3213 ssh->conn_throttle_count += adjust;
3214 assert(ssh->conn_throttle_count >= 0);
3215 if (ssh->conn_throttle_count && !old_count) {
3216 ssh_set_frozen(ssh, 1);
3217 } else if (!ssh->conn_throttle_count && old_count) {
3218 ssh_set_frozen(ssh, 0);
3223 * Throttle or unthrottle _all_ local data streams (for when sends
3224 * on the SSH connection itself back up).
3226 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3229 struct ssh_channel *c;
3231 if (enable == ssh->throttled_all)
3233 ssh->throttled_all = enable;
3234 ssh->overall_bufsize = bufsize;
3237 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3239 case CHAN_MAINSESSION:
3241 * This is treated separately, outside the switch.
3245 x11_override_throttle(c->u.x11.xconn, enable);
3248 /* Agent channels require no buffer management. */
3251 pfd_override_throttle(c->u.pfd.pf, enable);
3257 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3259 Ssh ssh = (Ssh) sshv;
3261 ssh->agent_response = reply;
3262 ssh->agent_response_len = replylen;
3264 if (ssh->version == 1)
3265 do_ssh1_login(ssh, NULL, -1, NULL);
3267 do_ssh2_authconn(ssh, NULL, -1, NULL);
3270 static void ssh_dialog_callback(void *sshv, int ret)
3272 Ssh ssh = (Ssh) sshv;
3274 ssh->user_response = ret;
3276 if (ssh->version == 1)
3277 do_ssh1_login(ssh, NULL, -1, NULL);
3279 do_ssh2_transport(ssh, NULL, -1, NULL);
3282 * This may have unfrozen the SSH connection, so do a
3285 ssh_process_queued_incoming_data(ssh);
3288 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3290 struct ssh_channel *c = (struct ssh_channel *)cv;
3292 void *sentreply = reply;
3294 c->u.a.outstanding_requests--;
3296 /* Fake SSH_AGENT_FAILURE. */
3297 sentreply = "\0\0\0\1\5";
3300 if (ssh->version == 2) {
3301 ssh2_add_channel_data(c, sentreply, replylen);
3304 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3305 PKT_INT, c->remoteid,
3307 PKT_DATA, sentreply, replylen,
3313 * If we've already seen an incoming EOF but haven't sent an
3314 * outgoing one, this may be the moment to send it.
3316 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3317 sshfwd_write_eof(c);
3321 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3322 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3323 * => log `wire_reason'.
3325 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3326 int code, int clean_exit)
3330 client_reason = wire_reason;
3332 error = dupprintf("Disconnected: %s", client_reason);
3334 error = dupstr("Disconnected");
3336 if (ssh->version == 1) {
3337 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3339 } else if (ssh->version == 2) {
3340 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3341 ssh2_pkt_adduint32(pktout, code);
3342 ssh2_pkt_addstring(pktout, wire_reason);
3343 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3344 ssh2_pkt_send_noqueue(ssh, pktout);
3347 ssh->close_expected = TRUE;
3348 ssh->clean_exit = clean_exit;
3349 ssh_closing((Plug)ssh, error, 0, 0);
3354 * Handle the key exchange and user authentication phases.
3356 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3357 struct Packet *pktin)
3360 unsigned char cookie[8], *ptr;
3361 struct MD5Context md5c;
3362 struct do_ssh1_login_state {
3365 unsigned char *rsabuf, *keystr1, *keystr2;
3366 unsigned long supported_ciphers_mask, supported_auths_mask;
3367 int tried_publickey, tried_agent;
3368 int tis_auth_refused, ccard_auth_refused;
3369 unsigned char session_id[16];
3371 void *publickey_blob;
3372 int publickey_bloblen;
3373 char *publickey_comment;
3374 int publickey_encrypted;
3375 prompts_t *cur_prompt;
3378 unsigned char request[5], *response, *p;
3388 struct RSAKey servkey, hostkey;
3390 crState(do_ssh1_login_state);
3397 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3398 bombout(("Public key packet not received"));
3402 logevent("Received public keys");
3404 ptr = ssh_pkt_getdata(pktin, 8);
3406 bombout(("SSH-1 public key packet stopped before random cookie"));
3409 memcpy(cookie, ptr, 8);
3411 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3412 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3413 bombout(("Failed to read SSH-1 public keys from public key packet"));
3418 * Log the host key fingerprint.
3422 logevent("Host key fingerprint is:");
3423 strcpy(logmsg, " ");
3424 s->hostkey.comment = NULL;
3425 rsa_fingerprint(logmsg + strlen(logmsg),
3426 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3430 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3431 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3432 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3433 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3434 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3436 ssh->v1_local_protoflags =
3437 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3438 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3441 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3442 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3443 MD5Update(&md5c, cookie, 8);
3444 MD5Final(s->session_id, &md5c);
3446 for (i = 0; i < 32; i++)
3447 ssh->session_key[i] = random_byte();
3450 * Verify that the `bits' and `bytes' parameters match.
3452 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3453 s->servkey.bits > s->servkey.bytes * 8) {
3454 bombout(("SSH-1 public keys were badly formatted"));
3458 s->len = (s->hostkey.bytes > s->servkey.bytes ?
3459 s->hostkey.bytes : s->servkey.bytes);
3461 s->rsabuf = snewn(s->len, unsigned char);
3464 * Verify the host key.
3468 * First format the key into a string.
3470 int len = rsastr_len(&s->hostkey);
3471 char fingerprint[100];
3472 char *keystr = snewn(len, char);
3473 rsastr_fmt(keystr, &s->hostkey);
3474 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
3476 ssh_set_frozen(ssh, 1);
3477 s->dlgret = verify_ssh_host_key(ssh->frontend,
3478 ssh->savedhost, ssh->savedport,
3479 "rsa", keystr, fingerprint,
3480 ssh_dialog_callback, ssh);
3482 if (s->dlgret < 0) {
3486 bombout(("Unexpected data from server while waiting"
3487 " for user host key response"));
3490 } while (pktin || inlen > 0);
3491 s->dlgret = ssh->user_response;
3493 ssh_set_frozen(ssh, 0);
3495 if (s->dlgret == 0) {
3496 ssh_disconnect(ssh, "User aborted at host key verification",
3502 for (i = 0; i < 32; i++) {
3503 s->rsabuf[i] = ssh->session_key[i];
3505 s->rsabuf[i] ^= s->session_id[i];
3508 if (s->hostkey.bytes > s->servkey.bytes) {
3509 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
3511 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
3513 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
3515 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
3518 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3522 logevent("Encrypted session key");
3525 int cipher_chosen = 0, warn = 0;
3526 char *cipher_string = NULL;
3528 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3529 int next_cipher = conf_get_int_int(ssh->conf,
3530 CONF_ssh_cipherlist, i);
3531 if (next_cipher == CIPHER_WARN) {
3532 /* If/when we choose a cipher, warn about it */
3534 } else if (next_cipher == CIPHER_AES) {
3535 /* XXX Probably don't need to mention this. */
3536 logevent("AES not supported in SSH-1, skipping");
3538 switch (next_cipher) {
3539 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3540 cipher_string = "3DES"; break;
3541 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3542 cipher_string = "Blowfish"; break;
3543 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3544 cipher_string = "single-DES"; break;
3546 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3550 if (!cipher_chosen) {
3551 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3552 bombout(("Server violates SSH-1 protocol by not "
3553 "supporting 3DES encryption"));
3555 /* shouldn't happen */
3556 bombout(("No supported ciphers found"));
3560 /* Warn about chosen cipher if necessary. */
3562 ssh_set_frozen(ssh, 1);
3563 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3564 ssh_dialog_callback, ssh);
3565 if (s->dlgret < 0) {
3569 bombout(("Unexpected data from server while waiting"
3570 " for user response"));
3573 } while (pktin || inlen > 0);
3574 s->dlgret = ssh->user_response;
3576 ssh_set_frozen(ssh, 0);
3577 if (s->dlgret == 0) {
3578 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3585 switch (s->cipher_type) {
3586 case SSH_CIPHER_3DES:
3587 logevent("Using 3DES encryption");
3589 case SSH_CIPHER_DES:
3590 logevent("Using single-DES encryption");
3592 case SSH_CIPHER_BLOWFISH:
3593 logevent("Using Blowfish encryption");
3597 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3598 PKT_CHAR, s->cipher_type,
3599 PKT_DATA, cookie, 8,
3600 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3601 PKT_DATA, s->rsabuf, s->len,
3602 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3604 logevent("Trying to enable encryption...");
3608 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3609 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3611 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3612 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3613 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3615 ssh->crcda_ctx = crcda_make_context();
3616 logevent("Installing CRC compensation attack detector");
3618 if (s->servkey.modulus) {
3619 sfree(s->servkey.modulus);
3620 s->servkey.modulus = NULL;
3622 if (s->servkey.exponent) {
3623 sfree(s->servkey.exponent);
3624 s->servkey.exponent = NULL;
3626 if (s->hostkey.modulus) {
3627 sfree(s->hostkey.modulus);
3628 s->hostkey.modulus = NULL;
3630 if (s->hostkey.exponent) {
3631 sfree(s->hostkey.exponent);
3632 s->hostkey.exponent = NULL;
3636 if (pktin->type != SSH1_SMSG_SUCCESS) {
3637 bombout(("Encryption not successfully enabled"));
3641 logevent("Successfully started encryption");
3643 fflush(stdout); /* FIXME eh? */
3645 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
3646 int ret; /* need not be kept over crReturn */
3647 s->cur_prompt = new_prompts(ssh->frontend);
3648 s->cur_prompt->to_server = TRUE;
3649 s->cur_prompt->name = dupstr("SSH login name");
3650 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
3651 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3654 crWaitUntil(!pktin);
3655 ret = get_userpass_input(s->cur_prompt, in, inlen);
3660 * Failed to get a username. Terminate.
3662 free_prompts(s->cur_prompt);
3663 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3666 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
3667 free_prompts(s->cur_prompt);
3670 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
3672 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
3674 if (flags & FLAG_INTERACTIVE &&
3675 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3676 c_write_str(ssh, userlog);
3677 c_write_str(ssh, "\r\n");
3685 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3686 /* We must not attempt PK auth. Pretend we've already tried it. */
3687 s->tried_publickey = s->tried_agent = 1;
3689 s->tried_publickey = s->tried_agent = 0;
3691 s->tis_auth_refused = s->ccard_auth_refused = 0;
3693 * Load the public half of any configured keyfile for later use.
3695 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3696 if (!filename_is_null(s->keyfile)) {
3698 logeventf(ssh, "Reading private key file \"%.150s\"",
3699 filename_to_str(s->keyfile));
3700 keytype = key_type(s->keyfile);
3701 if (keytype == SSH_KEYTYPE_SSH1) {
3703 if (rsakey_pubblob(s->keyfile,
3704 &s->publickey_blob, &s->publickey_bloblen,
3705 &s->publickey_comment, &error)) {
3706 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
3710 logeventf(ssh, "Unable to load private key (%s)", error);
3711 msgbuf = dupprintf("Unable to load private key file "
3712 "\"%.150s\" (%s)\r\n",
3713 filename_to_str(s->keyfile),
3715 c_write_str(ssh, msgbuf);
3717 s->publickey_blob = NULL;
3721 logeventf(ssh, "Unable to use this key file (%s)",
3722 key_type_to_str(keytype));
3723 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3725 filename_to_str(s->keyfile),
3726 key_type_to_str(keytype));
3727 c_write_str(ssh, msgbuf);
3729 s->publickey_blob = NULL;
3732 s->publickey_blob = NULL;
3734 while (pktin->type == SSH1_SMSG_FAILURE) {
3735 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3737 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
3739 * Attempt RSA authentication using Pageant.
3745 logevent("Pageant is running. Requesting keys.");
3747 /* Request the keys held by the agent. */
3748 PUT_32BIT(s->request, 1);
3749 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3750 if (!agent_query(s->request, 5, &r, &s->responselen,
3751 ssh_agent_callback, ssh)) {
3755 bombout(("Unexpected data from server while waiting"
3756 " for agent response"));
3759 } while (pktin || inlen > 0);
3760 r = ssh->agent_response;
3761 s->responselen = ssh->agent_response_len;
3763 s->response = (unsigned char *) r;
3764 if (s->response && s->responselen >= 5 &&
3765 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3766 s->p = s->response + 5;
3767 s->nkeys = toint(GET_32BIT(s->p));
3769 logeventf(ssh, "Pageant reported negative key count %d",
3774 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3775 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3776 unsigned char *pkblob = s->p;
3780 do { /* do while (0) to make breaking easy */
3781 n = ssh1_read_bignum
3782 (s->p, toint(s->responselen-(s->p-s->response)),
3787 n = ssh1_read_bignum
3788 (s->p, toint(s->responselen-(s->p-s->response)),
3793 if (s->responselen - (s->p-s->response) < 4)
3795 s->commentlen = toint(GET_32BIT(s->p));
3797 if (s->commentlen < 0 ||
3798 toint(s->responselen - (s->p-s->response)) <
3801 s->commentp = (char *)s->p;
3802 s->p += s->commentlen;
3806 logevent("Pageant key list packet was truncated");
3810 if (s->publickey_blob) {
3811 if (!memcmp(pkblob, s->publickey_blob,
3812 s->publickey_bloblen)) {
3813 logeventf(ssh, "Pageant key #%d matches "
3814 "configured key file", s->keyi);
3815 s->tried_publickey = 1;
3817 /* Skip non-configured key */
3820 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3821 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3822 PKT_BIGNUM, s->key.modulus, PKT_END);
3824 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3825 logevent("Key refused");
3828 logevent("Received RSA challenge");
3829 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3830 bombout(("Server's RSA challenge was badly formatted"));
3835 char *agentreq, *q, *ret;
3838 len = 1 + 4; /* message type, bit count */
3839 len += ssh1_bignum_length(s->key.exponent);
3840 len += ssh1_bignum_length(s->key.modulus);
3841 len += ssh1_bignum_length(s->challenge);
3842 len += 16; /* session id */
3843 len += 4; /* response format */
3844 agentreq = snewn(4 + len, char);
3845 PUT_32BIT(agentreq, len);
3847 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3848 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3850 q += ssh1_write_bignum(q, s->key.exponent);
3851 q += ssh1_write_bignum(q, s->key.modulus);
3852 q += ssh1_write_bignum(q, s->challenge);
3853 memcpy(q, s->session_id, 16);
3855 PUT_32BIT(q, 1); /* response format */
3856 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3857 ssh_agent_callback, ssh)) {
3862 bombout(("Unexpected data from server"
3863 " while waiting for agent"
3867 } while (pktin || inlen > 0);
3868 vret = ssh->agent_response;
3869 retlen = ssh->agent_response_len;
3874 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3875 logevent("Sending Pageant's response");
3876 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3877 PKT_DATA, ret + 5, 16,
3881 if (pktin->type == SSH1_SMSG_SUCCESS) {
3883 ("Pageant's response accepted");
3884 if (flags & FLAG_VERBOSE) {
3885 c_write_str(ssh, "Authenticated using"
3887 c_write(ssh, s->commentp,
3889 c_write_str(ssh, "\" from agent\r\n");
3894 ("Pageant's response not accepted");
3897 ("Pageant failed to answer challenge");
3901 logevent("No reply received from Pageant");
3904 freebn(s->key.exponent);
3905 freebn(s->key.modulus);
3906 freebn(s->challenge);
3911 if (s->publickey_blob && !s->tried_publickey)
3912 logevent("Configured key file not in Pageant");
3914 logevent("Failed to get reply from Pageant");
3919 if (s->publickey_blob && !s->tried_publickey) {
3921 * Try public key authentication with the specified
3924 int got_passphrase; /* need not be kept over crReturn */
3925 if (flags & FLAG_VERBOSE)
3926 c_write_str(ssh, "Trying public key authentication.\r\n");
3927 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3928 logeventf(ssh, "Trying public key \"%s\"",
3929 filename_to_str(s->keyfile));
3930 s->tried_publickey = 1;
3931 got_passphrase = FALSE;
3932 while (!got_passphrase) {
3934 * Get a passphrase, if necessary.
3936 char *passphrase = NULL; /* only written after crReturn */
3938 if (!s->publickey_encrypted) {
3939 if (flags & FLAG_VERBOSE)
3940 c_write_str(ssh, "No passphrase required.\r\n");
3943 int ret; /* need not be kept over crReturn */
3944 s->cur_prompt = new_prompts(ssh->frontend);
3945 s->cur_prompt->to_server = FALSE;
3946 s->cur_prompt->name = dupstr("SSH key passphrase");
3947 add_prompt(s->cur_prompt,
3948 dupprintf("Passphrase for key \"%.100s\": ",
3949 s->publickey_comment), FALSE);
3950 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3953 crWaitUntil(!pktin);
3954 ret = get_userpass_input(s->cur_prompt, in, inlen);
3958 /* Failed to get a passphrase. Terminate. */
3959 free_prompts(s->cur_prompt);
3960 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3964 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3965 free_prompts(s->cur_prompt);
3968 * Try decrypting key with passphrase.
3970 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3971 ret = loadrsakey(s->keyfile, &s->key, passphrase,
3974 smemclr(passphrase, strlen(passphrase));
3978 /* Correct passphrase. */
3979 got_passphrase = TRUE;
3980 } else if (ret == 0) {
3981 c_write_str(ssh, "Couldn't load private key from ");
3982 c_write_str(ssh, filename_to_str(s->keyfile));
3983 c_write_str(ssh, " (");
3984 c_write_str(ssh, error);
3985 c_write_str(ssh, ").\r\n");
3986 got_passphrase = FALSE;
3987 break; /* go and try something else */
3988 } else if (ret == -1) {
3989 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3990 got_passphrase = FALSE;
3993 assert(0 && "unexpected return from loadrsakey()");
3994 got_passphrase = FALSE; /* placate optimisers */
3998 if (got_passphrase) {
4001 * Send a public key attempt.
4003 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4004 PKT_BIGNUM, s->key.modulus, PKT_END);
4007 if (pktin->type == SSH1_SMSG_FAILURE) {
4008 c_write_str(ssh, "Server refused our public key.\r\n");
4009 continue; /* go and try something else */
4011 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4012 bombout(("Bizarre response to offer of public key"));
4018 unsigned char buffer[32];
4019 Bignum challenge, response;
4021 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4022 bombout(("Server's RSA challenge was badly formatted"));
4025 response = rsadecrypt(challenge, &s->key);
4026 freebn(s->key.private_exponent);/* burn the evidence */
4028 for (i = 0; i < 32; i++) {
4029 buffer[i] = bignum_byte(response, 31 - i);
4033 MD5Update(&md5c, buffer, 32);
4034 MD5Update(&md5c, s->session_id, 16);
4035 MD5Final(buffer, &md5c);
4037 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4038 PKT_DATA, buffer, 16, PKT_END);
4045 if (pktin->type == SSH1_SMSG_FAILURE) {
4046 if (flags & FLAG_VERBOSE)
4047 c_write_str(ssh, "Failed to authenticate with"
4048 " our public key.\r\n");
4049 continue; /* go and try something else */
4050 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4051 bombout(("Bizarre response to RSA authentication response"));
4055 break; /* we're through! */
4061 * Otherwise, try various forms of password-like authentication.
4063 s->cur_prompt = new_prompts(ssh->frontend);
4065 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4066 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4067 !s->tis_auth_refused) {
4068 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4069 logevent("Requested TIS authentication");
4070 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4072 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4073 logevent("TIS authentication declined");
4074 if (flags & FLAG_INTERACTIVE)
4075 c_write_str(ssh, "TIS authentication refused.\r\n");
4076 s->tis_auth_refused = 1;
4081 char *instr_suf, *prompt;
4083 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4085 bombout(("TIS challenge packet was badly formed"));
4088 logevent("Received TIS challenge");
4089 s->cur_prompt->to_server = TRUE;
4090 s->cur_prompt->name = dupstr("SSH TIS authentication");
4091 /* Prompt heuristic comes from OpenSSH */
4092 if (memchr(challenge, '\n', challengelen)) {
4093 instr_suf = dupstr("");
4094 prompt = dupprintf("%.*s", challengelen, challenge);
4096 instr_suf = dupprintf("%.*s", challengelen, challenge);
4097 prompt = dupstr("Response: ");
4099 s->cur_prompt->instruction =
4100 dupprintf("Using TIS authentication.%s%s",
4101 (*instr_suf) ? "\n" : "",
4103 s->cur_prompt->instr_reqd = TRUE;
4104 add_prompt(s->cur_prompt, prompt, FALSE);
4108 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4109 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4110 !s->ccard_auth_refused) {
4111 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4112 logevent("Requested CryptoCard authentication");
4113 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4115 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4116 logevent("CryptoCard authentication declined");
4117 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4118 s->ccard_auth_refused = 1;
4123 char *instr_suf, *prompt;
4125 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4127 bombout(("CryptoCard challenge packet was badly formed"));
4130 logevent("Received CryptoCard challenge");
4131 s->cur_prompt->to_server = TRUE;
4132 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4133 s->cur_prompt->name_reqd = FALSE;
4134 /* Prompt heuristic comes from OpenSSH */
4135 if (memchr(challenge, '\n', challengelen)) {
4136 instr_suf = dupstr("");
4137 prompt = dupprintf("%.*s", challengelen, challenge);
4139 instr_suf = dupprintf("%.*s", challengelen, challenge);
4140 prompt = dupstr("Response: ");
4142 s->cur_prompt->instruction =
4143 dupprintf("Using CryptoCard authentication.%s%s",
4144 (*instr_suf) ? "\n" : "",
4146 s->cur_prompt->instr_reqd = TRUE;
4147 add_prompt(s->cur_prompt, prompt, FALSE);
4151 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4152 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4153 bombout(("No supported authentication methods available"));
4156 s->cur_prompt->to_server = TRUE;
4157 s->cur_prompt->name = dupstr("SSH password");
4158 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4159 ssh->username, ssh->savedhost),
4164 * Show password prompt, having first obtained it via a TIS
4165 * or CryptoCard exchange if we're doing TIS or CryptoCard
4169 int ret; /* need not be kept over crReturn */
4170 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4173 crWaitUntil(!pktin);
4174 ret = get_userpass_input(s->cur_prompt, in, inlen);
4179 * Failed to get a password (for example
4180 * because one was supplied on the command line
4181 * which has already failed to work). Terminate.
4183 free_prompts(s->cur_prompt);
4184 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4189 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4191 * Defence against traffic analysis: we send a
4192 * whole bunch of packets containing strings of
4193 * different lengths. One of these strings is the
4194 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4195 * The others are all random data in
4196 * SSH1_MSG_IGNORE packets. This way a passive
4197 * listener can't tell which is the password, and
4198 * hence can't deduce the password length.
4200 * Anybody with a password length greater than 16
4201 * bytes is going to have enough entropy in their
4202 * password that a listener won't find it _that_
4203 * much help to know how long it is. So what we'll
4206 * - if password length < 16, we send 15 packets
4207 * containing string lengths 1 through 15
4209 * - otherwise, we let N be the nearest multiple
4210 * of 8 below the password length, and send 8
4211 * packets containing string lengths N through
4212 * N+7. This won't obscure the order of
4213 * magnitude of the password length, but it will
4214 * introduce a bit of extra uncertainty.
4216 * A few servers can't deal with SSH1_MSG_IGNORE, at
4217 * least in this context. For these servers, we need
4218 * an alternative defence. We make use of the fact
4219 * that the password is interpreted as a C string:
4220 * so we can append a NUL, then some random data.
4222 * A few servers can deal with neither SSH1_MSG_IGNORE
4223 * here _nor_ a padded password string.
4224 * For these servers we are left with no defences
4225 * against password length sniffing.
4227 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4228 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4230 * The server can deal with SSH1_MSG_IGNORE, so
4231 * we can use the primary defence.
4233 int bottom, top, pwlen, i;
4236 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4238 bottom = 0; /* zero length passwords are OK! :-) */
4241 bottom = pwlen & ~7;
4245 assert(pwlen >= bottom && pwlen <= top);
4247 randomstr = snewn(top + 1, char);
4249 for (i = bottom; i <= top; i++) {
4251 defer_packet(ssh, s->pwpkt_type,
4252 PKT_STR,s->cur_prompt->prompts[0]->result,
4255 for (j = 0; j < i; j++) {
4257 randomstr[j] = random_byte();
4258 } while (randomstr[j] == '\0');
4260 randomstr[i] = '\0';
4261 defer_packet(ssh, SSH1_MSG_IGNORE,
4262 PKT_STR, randomstr, PKT_END);
4265 logevent("Sending password with camouflage packets");
4266 ssh_pkt_defersend(ssh);
4269 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4271 * The server can't deal with SSH1_MSG_IGNORE
4272 * but can deal with padded passwords, so we
4273 * can use the secondary defence.
4279 len = strlen(s->cur_prompt->prompts[0]->result);
4280 if (len < sizeof(string)) {
4282 strcpy(string, s->cur_prompt->prompts[0]->result);
4283 len++; /* cover the zero byte */
4284 while (len < sizeof(string)) {
4285 string[len++] = (char) random_byte();
4288 ss = s->cur_prompt->prompts[0]->result;
4290 logevent("Sending length-padded password");
4291 send_packet(ssh, s->pwpkt_type,
4292 PKT_INT, len, PKT_DATA, ss, len,
4296 * The server is believed unable to cope with
4297 * any of our password camouflage methods.
4300 len = strlen(s->cur_prompt->prompts[0]->result);
4301 logevent("Sending unpadded password");
4302 send_packet(ssh, s->pwpkt_type,
4304 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4308 send_packet(ssh, s->pwpkt_type,
4309 PKT_STR, s->cur_prompt->prompts[0]->result,
4312 logevent("Sent password");
4313 free_prompts(s->cur_prompt);
4315 if (pktin->type == SSH1_SMSG_FAILURE) {
4316 if (flags & FLAG_VERBOSE)
4317 c_write_str(ssh, "Access denied\r\n");
4318 logevent("Authentication refused");
4319 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4320 bombout(("Strange packet received, type %d", pktin->type));
4326 if (s->publickey_blob) {
4327 sfree(s->publickey_blob);
4328 sfree(s->publickey_comment);
4331 logevent("Authentication successful");
4336 static void ssh_channel_try_eof(struct ssh_channel *c)
4339 assert(c->pending_eof); /* precondition for calling us */
4341 return; /* can't close: not even opened yet */
4342 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4343 return; /* can't send EOF: pending outgoing data */
4345 c->pending_eof = FALSE; /* we're about to send it */
4346 if (ssh->version == 1) {
4347 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4349 c->closes |= CLOSES_SENT_EOF;
4351 struct Packet *pktout;
4352 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4353 ssh2_pkt_adduint32(pktout, c->remoteid);
4354 ssh2_pkt_send(ssh, pktout);
4355 c->closes |= CLOSES_SENT_EOF;
4356 ssh2_channel_check_close(c);
4360 Conf *sshfwd_get_conf(struct ssh_channel *c)
4366 void sshfwd_write_eof(struct ssh_channel *c)
4370 if (ssh->state == SSH_STATE_CLOSED)
4373 if (c->closes & CLOSES_SENT_EOF)
4376 c->pending_eof = TRUE;
4377 ssh_channel_try_eof(c);
4380 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4384 if (ssh->state == SSH_STATE_CLOSED)
4389 x11_close(c->u.x11.xconn);
4390 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4394 case CHAN_SOCKDATA_DORMANT:
4395 pfd_close(c->u.pfd.pf);
4396 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4399 c->type = CHAN_ZOMBIE;
4400 c->pending_eof = FALSE; /* this will confuse a zombie channel */
4402 ssh2_channel_check_close(c);
4405 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4409 if (ssh->state == SSH_STATE_CLOSED)
4412 if (ssh->version == 1) {
4413 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4414 PKT_INT, c->remoteid,
4415 PKT_INT, len, PKT_DATA, buf, len,
4418 * In SSH-1 we can return 0 here - implying that forwarded
4419 * connections are never individually throttled - because
4420 * the only circumstance that can cause throttling will be
4421 * the whole SSH connection backing up, in which case
4422 * _everything_ will be throttled as a whole.
4426 ssh2_add_channel_data(c, buf, len);
4427 return ssh2_try_send(c);
4431 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4436 if (ssh->state == SSH_STATE_CLOSED)
4439 if (ssh->version == 1) {
4440 buflimit = SSH1_BUFFER_LIMIT;
4442 buflimit = c->v.v2.locmaxwin;
4443 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4445 if (c->throttling_conn && bufsize <= buflimit) {
4446 c->throttling_conn = 0;
4447 ssh_throttle_conn(ssh, -1);
4451 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4453 struct queued_handler *qh = ssh->qhead;
4457 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4460 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4461 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4464 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4465 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4469 ssh->qhead = qh->next;
4471 if (ssh->qhead->msg1 > 0) {
4472 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4473 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4475 if (ssh->qhead->msg2 > 0) {
4476 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4477 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4480 ssh->qhead = ssh->qtail = NULL;
4483 qh->handler(ssh, pktin, qh->ctx);
4488 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4489 chandler_fn_t handler, void *ctx)
4491 struct queued_handler *qh;
4493 qh = snew(struct queued_handler);
4496 qh->handler = handler;
4500 if (ssh->qtail == NULL) {
4504 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4505 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4508 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4509 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4512 ssh->qtail->next = qh;
4517 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4519 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4521 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4522 SSH2_MSG_REQUEST_SUCCESS)) {
4523 logeventf(ssh, "Remote port forwarding from %s enabled",
4526 logeventf(ssh, "Remote port forwarding from %s refused",
4529 rpf = del234(ssh->rportfwds, pf);
4531 pf->pfrec->remote = NULL;
4536 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4538 struct ssh_portfwd *epf;
4542 if (!ssh->portfwds) {
4543 ssh->portfwds = newtree234(ssh_portcmp);
4546 * Go through the existing port forwardings and tag them
4547 * with status==DESTROY. Any that we want to keep will be
4548 * re-enabled (status==KEEP) as we go through the
4549 * configuration and find out which bits are the same as
4552 struct ssh_portfwd *epf;
4554 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4555 epf->status = DESTROY;
4558 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4560 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4561 char *kp, *kp2, *vp, *vp2;
4562 char address_family, type;
4563 int sport,dport,sserv,dserv;
4564 char *sports, *dports, *saddr, *host;
4568 address_family = 'A';
4570 if (*kp == 'A' || *kp == '4' || *kp == '6')
4571 address_family = *kp++;
4572 if (*kp == 'L' || *kp == 'R')
4575 if ((kp2 = strchr(kp, ':')) != NULL) {
4577 * There's a colon in the middle of the source port
4578 * string, which means that the part before it is
4579 * actually a source address.
4581 saddr = dupprintf("%.*s", (int)(kp2 - kp), kp);
4587 sport = atoi(sports);
4591 sport = net_service_lookup(sports);
4593 logeventf(ssh, "Service lookup failed for source"
4594 " port \"%s\"", sports);
4598 if (type == 'L' && !strcmp(val, "D")) {
4599 /* dynamic forwarding */
4606 /* ordinary forwarding */
4608 vp2 = vp + strcspn(vp, ":");
4609 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
4613 dport = atoi(dports);
4617 dport = net_service_lookup(dports);
4619 logeventf(ssh, "Service lookup failed for destination"
4620 " port \"%s\"", dports);
4625 if (sport && dport) {
4626 /* Set up a description of the source port. */
4627 struct ssh_portfwd *pfrec, *epfrec;
4629 pfrec = snew(struct ssh_portfwd);
4631 pfrec->saddr = saddr;
4632 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4633 pfrec->sport = sport;
4634 pfrec->daddr = host;
4635 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4636 pfrec->dport = dport;
4637 pfrec->local = NULL;
4638 pfrec->remote = NULL;
4639 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4640 address_family == '6' ? ADDRTYPE_IPV6 :
4643 epfrec = add234(ssh->portfwds, pfrec);
4644 if (epfrec != pfrec) {
4645 if (epfrec->status == DESTROY) {
4647 * We already have a port forwarding up and running
4648 * with precisely these parameters. Hence, no need
4649 * to do anything; simply re-tag the existing one
4652 epfrec->status = KEEP;
4655 * Anything else indicates that there was a duplicate
4656 * in our input, which we'll silently ignore.
4658 free_portfwd(pfrec);
4660 pfrec->status = CREATE;
4669 * Now go through and destroy any port forwardings which were
4672 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4673 if (epf->status == DESTROY) {
4676 message = dupprintf("%s port forwarding from %s%s%d",
4677 epf->type == 'L' ? "local" :
4678 epf->type == 'R' ? "remote" : "dynamic",
4679 epf->saddr ? epf->saddr : "",
4680 epf->saddr ? ":" : "",
4683 if (epf->type != 'D') {
4684 char *msg2 = dupprintf("%s to %s:%d", message,
4685 epf->daddr, epf->dport);
4690 logeventf(ssh, "Cancelling %s", message);
4693 /* epf->remote or epf->local may be NULL if setting up a
4694 * forwarding failed. */
4696 struct ssh_rportfwd *rpf = epf->remote;
4697 struct Packet *pktout;
4700 * Cancel the port forwarding at the server
4703 if (ssh->version == 1) {
4705 * We cannot cancel listening ports on the
4706 * server side in SSH-1! There's no message
4707 * to support it. Instead, we simply remove
4708 * the rportfwd record from the local end
4709 * so that any connections the server tries
4710 * to make on it are rejected.
4713 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4714 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4715 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4717 ssh2_pkt_addstring(pktout, epf->saddr);
4718 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4719 /* XXX: rport_acceptall may not represent
4720 * what was used to open the original connection,
4721 * since it's reconfigurable. */
4722 ssh2_pkt_addstring(pktout, "");
4724 ssh2_pkt_addstring(pktout, "localhost");
4726 ssh2_pkt_adduint32(pktout, epf->sport);
4727 ssh2_pkt_send(ssh, pktout);
4730 del234(ssh->rportfwds, rpf);
4732 } else if (epf->local) {
4733 pfl_terminate(epf->local);
4736 delpos234(ssh->portfwds, i);
4738 i--; /* so we don't skip one in the list */
4742 * And finally, set up any new port forwardings (status==CREATE).
4744 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4745 if (epf->status == CREATE) {
4746 char *sportdesc, *dportdesc;
4747 sportdesc = dupprintf("%s%s%s%s%d%s",
4748 epf->saddr ? epf->saddr : "",
4749 epf->saddr ? ":" : "",
4750 epf->sserv ? epf->sserv : "",
4751 epf->sserv ? "(" : "",
4753 epf->sserv ? ")" : "");
4754 if (epf->type == 'D') {
4757 dportdesc = dupprintf("%s:%s%s%d%s",
4759 epf->dserv ? epf->dserv : "",
4760 epf->dserv ? "(" : "",
4762 epf->dserv ? ")" : "");
4765 if (epf->type == 'L') {
4766 char *err = pfl_listen(epf->daddr, epf->dport,
4767 epf->saddr, epf->sport,
4768 ssh, conf, &epf->local,
4769 epf->addressfamily);
4771 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4772 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4773 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4774 sportdesc, dportdesc,
4775 err ? " failed: " : "", err ? err : "");
4778 } else if (epf->type == 'D') {
4779 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
4780 ssh, conf, &epf->local,
4781 epf->addressfamily);
4783 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4784 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4785 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4787 err ? " failed: " : "", err ? err : "");
4792 struct ssh_rportfwd *pf;
4795 * Ensure the remote port forwardings tree exists.
4797 if (!ssh->rportfwds) {
4798 if (ssh->version == 1)
4799 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4801 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4804 pf = snew(struct ssh_rportfwd);
4805 pf->dhost = dupstr(epf->daddr);
4806 pf->dport = epf->dport;
4808 pf->shost = dupstr(epf->saddr);
4809 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4810 pf->shost = dupstr("");
4812 pf->shost = dupstr("localhost");
4814 pf->sport = epf->sport;
4815 if (add234(ssh->rportfwds, pf) != pf) {
4816 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4817 epf->daddr, epf->dport);
4820 logeventf(ssh, "Requesting remote port %s"
4821 " forward to %s", sportdesc, dportdesc);
4823 pf->sportdesc = sportdesc;
4828 if (ssh->version == 1) {
4829 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4830 PKT_INT, epf->sport,
4831 PKT_STR, epf->daddr,
4832 PKT_INT, epf->dport,
4834 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4836 ssh_rportfwd_succfail, pf);
4838 struct Packet *pktout;
4839 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4840 ssh2_pkt_addstring(pktout, "tcpip-forward");
4841 ssh2_pkt_addbool(pktout, 1);/* want reply */
4842 ssh2_pkt_addstring(pktout, pf->shost);
4843 ssh2_pkt_adduint32(pktout, pf->sport);
4844 ssh2_pkt_send(ssh, pktout);
4846 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4847 SSH2_MSG_REQUEST_FAILURE,
4848 ssh_rportfwd_succfail, pf);
4857 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4860 int stringlen, bufsize;
4862 ssh_pkt_getstring(pktin, &string, &stringlen);
4863 if (string == NULL) {
4864 bombout(("Incoming terminal data packet was badly formed"));
4868 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4870 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4871 ssh->v1_stdout_throttling = 1;
4872 ssh_throttle_conn(ssh, +1);
4876 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4878 /* Remote side is trying to open a channel to talk to our
4879 * X-Server. Give them back a local channel number. */
4880 struct ssh_channel *c;
4881 int remoteid = ssh_pkt_getuint32(pktin);
4883 logevent("Received X11 connect request");
4884 /* Refuse if X11 forwarding is disabled. */
4885 if (!ssh->X11_fwd_enabled) {
4886 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4887 PKT_INT, remoteid, PKT_END);
4888 logevent("Rejected X11 connect request");
4892 c = snew(struct ssh_channel);
4895 if ((err = x11_init(&c->u.x11.xconn, ssh->x11authtree, c,
4896 NULL, -1)) != NULL) {
4897 logeventf(ssh, "Opening X11 forward connection failed: %s", err);
4900 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4901 PKT_INT, remoteid, PKT_END);
4904 ("Opening X11 forward connection succeeded");
4905 c->remoteid = remoteid;
4906 c->halfopen = FALSE;
4907 c->localid = alloc_channel_id(ssh);
4909 c->pending_eof = FALSE;
4910 c->throttling_conn = 0;
4911 c->type = CHAN_X11; /* identify channel type */
4912 add234(ssh->channels, c);
4913 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4914 PKT_INT, c->remoteid, PKT_INT,
4915 c->localid, PKT_END);
4916 logevent("Opened X11 forward channel");
4921 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4923 /* Remote side is trying to open a channel to talk to our
4924 * agent. Give them back a local channel number. */
4925 struct ssh_channel *c;
4926 int remoteid = ssh_pkt_getuint32(pktin);
4928 /* Refuse if agent forwarding is disabled. */
4929 if (!ssh->agentfwd_enabled) {
4930 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4931 PKT_INT, remoteid, PKT_END);
4933 c = snew(struct ssh_channel);
4935 c->remoteid = remoteid;
4936 c->halfopen = FALSE;
4937 c->localid = alloc_channel_id(ssh);
4939 c->pending_eof = FALSE;
4940 c->throttling_conn = 0;
4941 c->type = CHAN_AGENT; /* identify channel type */
4942 c->u.a.lensofar = 0;
4943 c->u.a.message = NULL;
4944 c->u.a.outstanding_requests = 0;
4945 add234(ssh->channels, c);
4946 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4947 PKT_INT, c->remoteid, PKT_INT, c->localid,
4952 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4954 /* Remote side is trying to open a channel to talk to a
4955 * forwarded port. Give them back a local channel number. */
4956 struct ssh_rportfwd pf, *pfp;
4962 remoteid = ssh_pkt_getuint32(pktin);
4963 ssh_pkt_getstring(pktin, &host, &hostsize);
4964 port = ssh_pkt_getuint32(pktin);
4966 pf.dhost = dupprintf(".*s", hostsize, host);
4968 pfp = find234(ssh->rportfwds, &pf, NULL);
4971 logeventf(ssh, "Rejected remote port open request for %s:%d",
4973 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4974 PKT_INT, remoteid, PKT_END);
4976 struct ssh_channel *c = snew(struct ssh_channel);
4979 logeventf(ssh, "Received remote port open request for %s:%d",
4981 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
4982 c, ssh->conf, pfp->pfrec->addressfamily);
4984 logeventf(ssh, "Port open failed: %s", err);
4987 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4988 PKT_INT, remoteid, PKT_END);
4990 c->remoteid = remoteid;
4991 c->halfopen = FALSE;
4992 c->localid = alloc_channel_id(ssh);
4994 c->pending_eof = FALSE;
4995 c->throttling_conn = 0;
4996 c->type = CHAN_SOCKDATA; /* identify channel type */
4997 add234(ssh->channels, c);
4998 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4999 PKT_INT, c->remoteid, PKT_INT,
5000 c->localid, PKT_END);
5001 logevent("Forwarded port opened successfully");
5008 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5010 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5011 unsigned int localid = ssh_pkt_getuint32(pktin);
5012 struct ssh_channel *c;
5014 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5015 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5016 c->remoteid = localid;
5017 c->halfopen = FALSE;
5018 c->type = CHAN_SOCKDATA;
5019 c->throttling_conn = 0;
5020 pfd_confirm(c->u.pfd.pf);
5023 if (c && c->pending_eof) {
5025 * We have a pending close on this channel,
5026 * which we decided on before the server acked
5027 * the channel open. So now we know the
5028 * remoteid, we can close it again.
5030 ssh_channel_try_eof(c);
5034 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5036 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5037 struct ssh_channel *c;
5039 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5040 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5041 logevent("Forwarded connection refused by server");
5042 pfd_close(c->u.pfd.pf);
5043 del234(ssh->channels, c);
5048 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5050 /* Remote side closes a channel. */
5051 unsigned i = ssh_pkt_getuint32(pktin);
5052 struct ssh_channel *c;
5053 c = find234(ssh->channels, &i, ssh_channelfind);
5054 if (c && !c->halfopen) {
5056 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5057 !(c->closes & CLOSES_RCVD_EOF)) {
5059 * Received CHANNEL_CLOSE, which we translate into
5062 int send_close = FALSE;
5064 c->closes |= CLOSES_RCVD_EOF;
5069 x11_send_eof(c->u.x11.xconn);
5075 pfd_send_eof(c->u.pfd.pf);
5084 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5085 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5087 c->closes |= CLOSES_SENT_EOF;
5091 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5092 !(c->closes & CLOSES_RCVD_CLOSE)) {
5094 if (!(c->closes & CLOSES_SENT_EOF)) {
5095 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5096 " for which we never sent CHANNEL_CLOSE\n", i));
5099 c->closes |= CLOSES_RCVD_CLOSE;
5102 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5103 !(c->closes & CLOSES_SENT_CLOSE)) {
5104 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5105 PKT_INT, c->remoteid, PKT_END);
5106 c->closes |= CLOSES_SENT_CLOSE;
5109 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5110 ssh_channel_destroy(c);
5112 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5113 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5114 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5119 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5121 /* Data sent down one of our channels. */
5122 int i = ssh_pkt_getuint32(pktin);
5125 struct ssh_channel *c;
5127 ssh_pkt_getstring(pktin, &p, &len);
5129 c = find234(ssh->channels, &i, ssh_channelfind);
5134 bufsize = x11_send(c->u.x11.xconn, p, len);
5137 bufsize = pfd_send(c->u.pfd.pf, p, len);
5140 /* Data for an agent message. Buffer it. */
5142 if (c->u.a.lensofar < 4) {
5143 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5144 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5148 c->u.a.lensofar += l;
5150 if (c->u.a.lensofar == 4) {
5152 4 + GET_32BIT(c->u.a.msglen);
5153 c->u.a.message = snewn(c->u.a.totallen,
5155 memcpy(c->u.a.message, c->u.a.msglen, 4);
5157 if (c->u.a.lensofar >= 4 && len > 0) {
5159 min(c->u.a.totallen - c->u.a.lensofar,
5161 memcpy(c->u.a.message + c->u.a.lensofar, p,
5165 c->u.a.lensofar += l;
5167 if (c->u.a.lensofar == c->u.a.totallen) {
5170 c->u.a.outstanding_requests++;
5171 if (agent_query(c->u.a.message,
5174 ssh_agentf_callback, c))
5175 ssh_agentf_callback(c, reply, replylen);
5176 sfree(c->u.a.message);
5177 c->u.a.lensofar = 0;
5180 bufsize = 0; /* agent channels never back up */
5183 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5184 c->throttling_conn = 1;
5185 ssh_throttle_conn(ssh, +1);
5190 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5192 ssh->exitcode = ssh_pkt_getuint32(pktin);
5193 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5194 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5196 * In case `helpful' firewalls or proxies tack
5197 * extra human-readable text on the end of the
5198 * session which we might mistake for another
5199 * encrypted packet, we close the session once
5200 * we've sent EXIT_CONFIRMATION.
5202 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5205 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5206 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5208 struct Packet *pktout = (struct Packet *)data;
5210 unsigned int arg = 0;
5211 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5212 if (i == lenof(ssh_ttymodes)) return;
5213 switch (ssh_ttymodes[i].type) {
5215 arg = ssh_tty_parse_specchar(val);
5218 arg = ssh_tty_parse_boolean(val);
5221 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5222 ssh2_pkt_addbyte(pktout, arg);
5226 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5227 struct Packet *pktin)
5229 crBegin(ssh->do_ssh1_connection_crstate);
5231 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5232 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5233 ssh1_smsg_stdout_stderr_data;
5235 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5236 ssh1_msg_channel_open_confirmation;
5237 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5238 ssh1_msg_channel_open_failure;
5239 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5240 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5241 ssh1_msg_channel_close;
5242 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5243 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5245 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
5246 logevent("Requesting agent forwarding");
5247 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5251 if (pktin->type != SSH1_SMSG_SUCCESS
5252 && pktin->type != SSH1_SMSG_FAILURE) {
5253 bombout(("Protocol confusion"));
5255 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5256 logevent("Agent forwarding refused");
5258 logevent("Agent forwarding enabled");
5259 ssh->agentfwd_enabled = TRUE;
5260 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5264 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5266 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5268 if (!ssh->x11disp) {
5269 /* FIXME: return an error message from x11_setup_display */
5270 logevent("X11 forwarding not enabled: unable to"
5271 " initialise X display");
5273 ssh->x11auth = x11_invent_fake_auth
5274 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5275 ssh->x11auth->disp = ssh->x11disp;
5277 logevent("Requesting X11 forwarding");
5278 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5279 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5280 PKT_STR, ssh->x11auth->protoname,
5281 PKT_STR, ssh->x11auth->datastring,
5282 PKT_INT, ssh->x11disp->screennum,
5285 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5286 PKT_STR, ssh->x11auth->protoname,
5287 PKT_STR, ssh->x11auth->datastring,
5293 if (pktin->type != SSH1_SMSG_SUCCESS
5294 && pktin->type != SSH1_SMSG_FAILURE) {
5295 bombout(("Protocol confusion"));
5297 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5298 logevent("X11 forwarding refused");
5300 logevent("X11 forwarding enabled");
5301 ssh->X11_fwd_enabled = TRUE;
5302 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5307 ssh_setup_portfwd(ssh, ssh->conf);
5308 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5310 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5312 /* Unpick the terminal-speed string. */
5313 /* XXX perhaps we should allow no speeds to be sent. */
5314 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5315 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5316 /* Send the pty request. */
5317 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5318 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5319 ssh_pkt_adduint32(pkt, ssh->term_height);
5320 ssh_pkt_adduint32(pkt, ssh->term_width);
5321 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5322 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5323 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5324 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5325 ssh_pkt_adduint32(pkt, ssh->ispeed);
5326 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5327 ssh_pkt_adduint32(pkt, ssh->ospeed);
5328 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5330 ssh->state = SSH_STATE_INTERMED;
5334 if (pktin->type != SSH1_SMSG_SUCCESS
5335 && pktin->type != SSH1_SMSG_FAILURE) {
5336 bombout(("Protocol confusion"));
5338 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5339 c_write_str(ssh, "Server refused to allocate pty\r\n");
5340 ssh->editing = ssh->echoing = 1;
5342 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5343 ssh->ospeed, ssh->ispeed);
5344 ssh->got_pty = TRUE;
5347 ssh->editing = ssh->echoing = 1;
5350 if (conf_get_int(ssh->conf, CONF_compression)) {
5351 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5355 if (pktin->type != SSH1_SMSG_SUCCESS
5356 && pktin->type != SSH1_SMSG_FAILURE) {
5357 bombout(("Protocol confusion"));
5359 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5360 c_write_str(ssh, "Server refused to compress\r\n");
5362 logevent("Started compression");
5363 ssh->v1_compressing = TRUE;
5364 ssh->cs_comp_ctx = zlib_compress_init();
5365 logevent("Initialised zlib (RFC1950) compression");
5366 ssh->sc_comp_ctx = zlib_decompress_init();
5367 logevent("Initialised zlib (RFC1950) decompression");
5371 * Start the shell or command.
5373 * Special case: if the first-choice command is an SSH-2
5374 * subsystem (hence not usable here) and the second choice
5375 * exists, we fall straight back to that.
5378 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5380 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5381 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5382 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5383 ssh->fallback_cmd = TRUE;
5386 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5388 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5389 logevent("Started session");
5392 ssh->state = SSH_STATE_SESSION;
5393 if (ssh->size_needed)
5394 ssh_size(ssh, ssh->term_width, ssh->term_height);
5395 if (ssh->eof_needed)
5396 ssh_special(ssh, TS_EOF);
5399 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5401 ssh->channels = newtree234(ssh_channelcmp);
5405 * By this point, most incoming packets are already being
5406 * handled by the dispatch table, and we need only pay
5407 * attention to the unusual ones.
5412 if (pktin->type == SSH1_SMSG_SUCCESS) {
5413 /* may be from EXEC_SHELL on some servers */
5414 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5415 /* may be from EXEC_SHELL on some servers
5416 * if no pty is available or in other odd cases. Ignore */
5418 bombout(("Strange packet received: type %d", pktin->type));
5423 int len = min(inlen, 512);
5424 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5425 PKT_INT, len, PKT_DATA, in, len,
5437 * Handle the top-level SSH-2 protocol.
5439 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5444 ssh_pkt_getstring(pktin, &msg, &msglen);
5445 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5448 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5450 /* log reason code in disconnect message */
5454 ssh_pkt_getstring(pktin, &msg, &msglen);
5455 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5458 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5460 /* Do nothing, because we're ignoring it! Duhh. */
5463 static void ssh1_protocol_setup(Ssh ssh)
5468 * Most messages are handled by the coroutines.
5470 for (i = 0; i < 256; i++)
5471 ssh->packet_dispatch[i] = NULL;
5474 * These special message types we install handlers for.
5476 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5477 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5478 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5481 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5482 struct Packet *pktin)
5484 unsigned char *in=(unsigned char*)vin;
5485 if (ssh->state == SSH_STATE_CLOSED)
5488 if (pktin && ssh->packet_dispatch[pktin->type]) {
5489 ssh->packet_dispatch[pktin->type](ssh, pktin);
5493 if (!ssh->protocol_initial_phase_done) {
5494 if (do_ssh1_login(ssh, in, inlen, pktin))
5495 ssh->protocol_initial_phase_done = TRUE;
5500 do_ssh1_connection(ssh, in, inlen, pktin);
5504 * Utility routine for decoding comma-separated strings in KEXINIT.
5506 static int in_commasep_string(char *needle, char *haystack, int haylen)
5509 if (!needle || !haystack) /* protect against null pointers */
5511 needlen = strlen(needle);
5514 * Is it at the start of the string?
5516 if (haylen >= needlen && /* haystack is long enough */
5517 !memcmp(needle, haystack, needlen) && /* initial match */
5518 (haylen == needlen || haystack[needlen] == ',')
5519 /* either , or EOS follows */
5523 * If not, search for the next comma and resume after that.
5524 * If no comma found, terminate.
5526 while (haylen > 0 && *haystack != ',')
5527 haylen--, haystack++;
5530 haylen--, haystack++; /* skip over comma itself */
5535 * Similar routine for checking whether we have the first string in a list.
5537 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5540 if (!needle || !haystack) /* protect against null pointers */
5542 needlen = strlen(needle);
5544 * Is it at the start of the string?
5546 if (haylen >= needlen && /* haystack is long enough */
5547 !memcmp(needle, haystack, needlen) && /* initial match */
5548 (haylen == needlen || haystack[needlen] == ',')
5549 /* either , or EOS follows */
5557 * SSH-2 key creation method.
5558 * (Currently assumes 2 lots of any hash are sufficient to generate
5559 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5561 #define SSH2_MKKEY_ITERS (2)
5562 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5563 unsigned char *keyspace)
5565 const struct ssh_hash *h = ssh->kex->hash;
5567 /* First hlen bytes. */
5569 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5570 hash_mpint(h, s, K);
5571 h->bytes(s, H, h->hlen);
5572 h->bytes(s, &chr, 1);
5573 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5574 h->final(s, keyspace);
5575 /* Next hlen bytes. */
5577 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5578 hash_mpint(h, s, K);
5579 h->bytes(s, H, h->hlen);
5580 h->bytes(s, keyspace, h->hlen);
5581 h->final(s, keyspace + h->hlen);
5585 * Handle the SSH-2 transport layer.
5587 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5588 struct Packet *pktin)
5590 unsigned char *in = (unsigned char *)vin;
5591 struct do_ssh2_transport_state {
5593 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5594 Bignum p, g, e, f, K;
5597 int kex_init_value, kex_reply_value;
5598 const struct ssh_mac **maclist;
5600 const struct ssh2_cipher *cscipher_tobe;
5601 const struct ssh2_cipher *sccipher_tobe;
5602 const struct ssh_mac *csmac_tobe;
5603 const struct ssh_mac *scmac_tobe;
5604 const struct ssh_compress *cscomp_tobe;
5605 const struct ssh_compress *sccomp_tobe;
5606 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5607 int hostkeylen, siglen, rsakeylen;
5608 void *hkey; /* actual host key */
5609 void *rsakey; /* for RSA kex */
5610 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5611 int n_preferred_kex;
5612 const struct ssh_kexes *preferred_kex[KEX_MAX];
5613 int n_preferred_ciphers;
5614 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5615 const struct ssh_compress *preferred_comp;
5616 int userauth_succeeded; /* for delayed compression */
5617 int pending_compression;
5618 int got_session_id, activated_authconn;
5619 struct Packet *pktout;
5624 crState(do_ssh2_transport_state);
5628 s->cscipher_tobe = s->sccipher_tobe = NULL;
5629 s->csmac_tobe = s->scmac_tobe = NULL;
5630 s->cscomp_tobe = s->sccomp_tobe = NULL;
5632 s->got_session_id = s->activated_authconn = FALSE;
5633 s->userauth_succeeded = FALSE;
5634 s->pending_compression = FALSE;
5637 * Be prepared to work around the buggy MAC problem.
5639 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5640 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5642 s->maclist = macs, s->nmacs = lenof(macs);
5645 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5647 int i, j, k, commalist_started;
5650 * Set up the preferred key exchange. (NULL => warn below here)
5652 s->n_preferred_kex = 0;
5653 for (i = 0; i < KEX_MAX; i++) {
5654 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
5656 s->preferred_kex[s->n_preferred_kex++] =
5657 &ssh_diffiehellman_gex;
5660 s->preferred_kex[s->n_preferred_kex++] =
5661 &ssh_diffiehellman_group14;
5664 s->preferred_kex[s->n_preferred_kex++] =
5665 &ssh_diffiehellman_group1;
5668 s->preferred_kex[s->n_preferred_kex++] =
5672 /* Flag for later. Don't bother if it's the last in
5674 if (i < KEX_MAX - 1) {
5675 s->preferred_kex[s->n_preferred_kex++] = NULL;
5682 * Set up the preferred ciphers. (NULL => warn below here)
5684 s->n_preferred_ciphers = 0;
5685 for (i = 0; i < CIPHER_MAX; i++) {
5686 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
5687 case CIPHER_BLOWFISH:
5688 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5691 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
5692 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5696 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5699 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5701 case CIPHER_ARCFOUR:
5702 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5705 /* Flag for later. Don't bother if it's the last in
5707 if (i < CIPHER_MAX - 1) {
5708 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5715 * Set up preferred compression.
5717 if (conf_get_int(ssh->conf, CONF_compression))
5718 s->preferred_comp = &ssh_zlib;
5720 s->preferred_comp = &ssh_comp_none;
5723 * Enable queueing of outgoing auth- or connection-layer
5724 * packets while we are in the middle of a key exchange.
5726 ssh->queueing = TRUE;
5729 * Flag that KEX is in progress.
5731 ssh->kex_in_progress = TRUE;
5734 * Construct and send our key exchange packet.
5736 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5737 for (i = 0; i < 16; i++)
5738 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5739 /* List key exchange algorithms. */
5740 ssh2_pkt_addstring_start(s->pktout);
5741 commalist_started = 0;
5742 for (i = 0; i < s->n_preferred_kex; i++) {
5743 const struct ssh_kexes *k = s->preferred_kex[i];
5744 if (!k) continue; /* warning flag */
5745 for (j = 0; j < k->nkexes; j++) {
5746 if (commalist_started)
5747 ssh2_pkt_addstring_str(s->pktout, ",");
5748 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5749 commalist_started = 1;
5752 /* List server host key algorithms. */
5753 if (!s->got_session_id) {
5755 * In the first key exchange, we list all the algorithms
5756 * we're prepared to cope with.
5758 ssh2_pkt_addstring_start(s->pktout);
5759 for (i = 0; i < lenof(hostkey_algs); i++) {
5760 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5761 if (i < lenof(hostkey_algs) - 1)
5762 ssh2_pkt_addstring_str(s->pktout, ",");
5766 * In subsequent key exchanges, we list only the kex
5767 * algorithm that was selected in the first key exchange,
5768 * so that we keep getting the same host key and hence
5769 * don't have to interrupt the user's session to ask for
5773 ssh2_pkt_addstring(s->pktout, ssh->hostkey->name);
5775 /* List encryption algorithms (client->server then server->client). */
5776 for (k = 0; k < 2; k++) {
5777 ssh2_pkt_addstring_start(s->pktout);
5778 commalist_started = 0;
5779 for (i = 0; i < s->n_preferred_ciphers; i++) {
5780 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5781 if (!c) continue; /* warning flag */
5782 for (j = 0; j < c->nciphers; j++) {
5783 if (commalist_started)
5784 ssh2_pkt_addstring_str(s->pktout, ",");
5785 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5786 commalist_started = 1;
5790 /* List MAC algorithms (client->server then server->client). */
5791 for (j = 0; j < 2; j++) {
5792 ssh2_pkt_addstring_start(s->pktout);
5793 for (i = 0; i < s->nmacs; i++) {
5794 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5795 if (i < s->nmacs - 1)
5796 ssh2_pkt_addstring_str(s->pktout, ",");
5799 /* List client->server compression algorithms,
5800 * then server->client compression algorithms. (We use the
5801 * same set twice.) */
5802 for (j = 0; j < 2; j++) {
5803 ssh2_pkt_addstring_start(s->pktout);
5804 assert(lenof(compressions) > 1);
5805 /* Prefer non-delayed versions */
5806 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5807 /* We don't even list delayed versions of algorithms until
5808 * they're allowed to be used, to avoid a race. See the end of
5810 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
5811 ssh2_pkt_addstring_str(s->pktout, ",");
5812 ssh2_pkt_addstring_str(s->pktout,
5813 s->preferred_comp->delayed_name);
5815 for (i = 0; i < lenof(compressions); i++) {
5816 const struct ssh_compress *c = compressions[i];
5817 if (c != s->preferred_comp) {
5818 ssh2_pkt_addstring_str(s->pktout, ",");
5819 ssh2_pkt_addstring_str(s->pktout, c->name);
5820 if (s->userauth_succeeded && c->delayed_name) {
5821 ssh2_pkt_addstring_str(s->pktout, ",");
5822 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
5827 /* List client->server languages. Empty list. */
5828 ssh2_pkt_addstring_start(s->pktout);
5829 /* List server->client languages. Empty list. */
5830 ssh2_pkt_addstring_start(s->pktout);
5831 /* First KEX packet does _not_ follow, because we're not that brave. */
5832 ssh2_pkt_addbool(s->pktout, FALSE);
5834 ssh2_pkt_adduint32(s->pktout, 0);
5837 s->our_kexinitlen = s->pktout->length - 5;
5838 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5839 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5841 ssh2_pkt_send_noqueue(ssh, s->pktout);
5844 crWaitUntilV(pktin);
5847 * Now examine the other side's KEXINIT to see what we're up
5851 char *str, *preferred;
5854 if (pktin->type != SSH2_MSG_KEXINIT) {
5855 bombout(("expected key exchange packet from server"));
5859 ssh->hostkey = NULL;
5860 s->cscipher_tobe = NULL;
5861 s->sccipher_tobe = NULL;
5862 s->csmac_tobe = NULL;
5863 s->scmac_tobe = NULL;
5864 s->cscomp_tobe = NULL;
5865 s->sccomp_tobe = NULL;
5866 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5868 pktin->savedpos += 16; /* skip garbage cookie */
5869 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5872 for (i = 0; i < s->n_preferred_kex; i++) {
5873 const struct ssh_kexes *k = s->preferred_kex[i];
5877 for (j = 0; j < k->nkexes; j++) {
5878 if (!preferred) preferred = k->list[j]->name;
5879 if (in_commasep_string(k->list[j]->name, str, len)) {
5880 ssh->kex = k->list[j];
5889 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5890 str ? str : "(null)"));
5894 * Note that the server's guess is considered wrong if it doesn't match
5895 * the first algorithm in our list, even if it's still the algorithm
5898 s->guessok = first_in_commasep_string(preferred, str, len);
5899 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5900 for (i = 0; i < lenof(hostkey_algs); i++) {
5901 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5902 ssh->hostkey = hostkey_algs[i];
5906 if (!ssh->hostkey) {
5907 bombout(("Couldn't agree a host key algorithm (available: %s)",
5908 str ? str : "(null)"));
5912 s->guessok = s->guessok &&
5913 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5914 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5915 for (i = 0; i < s->n_preferred_ciphers; i++) {
5916 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5918 s->warn_cscipher = TRUE;
5920 for (j = 0; j < c->nciphers; j++) {
5921 if (in_commasep_string(c->list[j]->name, str, len)) {
5922 s->cscipher_tobe = c->list[j];
5927 if (s->cscipher_tobe)
5930 if (!s->cscipher_tobe) {
5931 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5932 str ? str : "(null)"));
5936 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5937 for (i = 0; i < s->n_preferred_ciphers; i++) {
5938 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5940 s->warn_sccipher = TRUE;
5942 for (j = 0; j < c->nciphers; j++) {
5943 if (in_commasep_string(c->list[j]->name, str, len)) {
5944 s->sccipher_tobe = c->list[j];
5949 if (s->sccipher_tobe)
5952 if (!s->sccipher_tobe) {
5953 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5954 str ? str : "(null)"));
5958 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5959 for (i = 0; i < s->nmacs; i++) {
5960 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5961 s->csmac_tobe = s->maclist[i];
5965 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5966 for (i = 0; i < s->nmacs; i++) {
5967 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5968 s->scmac_tobe = s->maclist[i];
5972 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5973 for (i = 0; i < lenof(compressions) + 1; i++) {
5974 const struct ssh_compress *c =
5975 i == 0 ? s->preferred_comp : compressions[i - 1];
5976 if (in_commasep_string(c->name, str, len)) {
5979 } else if (in_commasep_string(c->delayed_name, str, len)) {
5980 if (s->userauth_succeeded) {
5984 s->pending_compression = TRUE; /* try this later */
5988 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5989 for (i = 0; i < lenof(compressions) + 1; i++) {
5990 const struct ssh_compress *c =
5991 i == 0 ? s->preferred_comp : compressions[i - 1];
5992 if (in_commasep_string(c->name, str, len)) {
5995 } else if (in_commasep_string(c->delayed_name, str, len)) {
5996 if (s->userauth_succeeded) {
6000 s->pending_compression = TRUE; /* try this later */
6004 if (s->pending_compression) {
6005 logevent("Server supports delayed compression; "
6006 "will try this later");
6008 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6009 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6010 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6012 ssh->exhash = ssh->kex->hash->init();
6013 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6014 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6015 hash_string(ssh->kex->hash, ssh->exhash,
6016 s->our_kexinit, s->our_kexinitlen);
6017 sfree(s->our_kexinit);
6018 /* Include the type byte in the hash of server's KEXINIT */
6019 hash_string(ssh->kex->hash, ssh->exhash,
6020 pktin->body - 1, pktin->length + 1);
6023 ssh_set_frozen(ssh, 1);
6024 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6026 ssh_dialog_callback, ssh);
6027 if (s->dlgret < 0) {
6031 bombout(("Unexpected data from server while"
6032 " waiting for user response"));
6035 } while (pktin || inlen > 0);
6036 s->dlgret = ssh->user_response;
6038 ssh_set_frozen(ssh, 0);
6039 if (s->dlgret == 0) {
6040 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6046 if (s->warn_cscipher) {
6047 ssh_set_frozen(ssh, 1);
6048 s->dlgret = askalg(ssh->frontend,
6049 "client-to-server cipher",
6050 s->cscipher_tobe->name,
6051 ssh_dialog_callback, ssh);
6052 if (s->dlgret < 0) {
6056 bombout(("Unexpected data from server while"
6057 " waiting for user response"));
6060 } while (pktin || inlen > 0);
6061 s->dlgret = ssh->user_response;
6063 ssh_set_frozen(ssh, 0);
6064 if (s->dlgret == 0) {
6065 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6071 if (s->warn_sccipher) {
6072 ssh_set_frozen(ssh, 1);
6073 s->dlgret = askalg(ssh->frontend,
6074 "server-to-client cipher",
6075 s->sccipher_tobe->name,
6076 ssh_dialog_callback, ssh);
6077 if (s->dlgret < 0) {
6081 bombout(("Unexpected data from server while"
6082 " waiting for user response"));
6085 } while (pktin || inlen > 0);
6086 s->dlgret = ssh->user_response;
6088 ssh_set_frozen(ssh, 0);
6089 if (s->dlgret == 0) {
6090 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6096 if (s->ignorepkt) /* first_kex_packet_follows */
6097 crWaitUntilV(pktin); /* Ignore packet */
6100 if (ssh->kex->main_type == KEXTYPE_DH) {
6102 * Work out the number of bits of key we will need from the
6103 * key exchange. We start with the maximum key length of
6109 csbits = s->cscipher_tobe->keylen;
6110 scbits = s->sccipher_tobe->keylen;
6111 s->nbits = (csbits > scbits ? csbits : scbits);
6113 /* The keys only have hlen-bit entropy, since they're based on
6114 * a hash. So cap the key size at hlen bits. */
6115 if (s->nbits > ssh->kex->hash->hlen * 8)
6116 s->nbits = ssh->kex->hash->hlen * 8;
6119 * If we're doing Diffie-Hellman group exchange, start by
6120 * requesting a group.
6122 if (!ssh->kex->pdata) {
6123 logevent("Doing Diffie-Hellman group exchange");
6124 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6126 * Work out how big a DH group we will need to allow that
6129 s->pbits = 512 << ((s->nbits - 1) / 64);
6130 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6131 ssh2_pkt_adduint32(s->pktout, s->pbits);
6132 ssh2_pkt_send_noqueue(ssh, s->pktout);
6134 crWaitUntilV(pktin);
6135 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6136 bombout(("expected key exchange group packet from server"));
6139 s->p = ssh2_pkt_getmp(pktin);
6140 s->g = ssh2_pkt_getmp(pktin);
6141 if (!s->p || !s->g) {
6142 bombout(("unable to read mp-ints from incoming group packet"));
6145 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6146 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6147 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6149 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6150 ssh->kex_ctx = dh_setup_group(ssh->kex);
6151 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6152 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6153 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6154 ssh->kex->groupname);
6157 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6158 ssh->kex->hash->text_name);
6160 * Now generate and send e for Diffie-Hellman.
6162 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6163 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6164 s->pktout = ssh2_pkt_init(s->kex_init_value);
6165 ssh2_pkt_addmp(s->pktout, s->e);
6166 ssh2_pkt_send_noqueue(ssh, s->pktout);
6168 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6169 crWaitUntilV(pktin);
6170 if (pktin->type != s->kex_reply_value) {
6171 bombout(("expected key exchange reply packet from server"));
6174 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6175 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6176 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6177 s->f = ssh2_pkt_getmp(pktin);
6179 bombout(("unable to parse key exchange reply packet"));
6182 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6184 s->K = dh_find_K(ssh->kex_ctx, s->f);
6186 /* We assume everything from now on will be quick, and it might
6187 * involve user interaction. */
6188 set_busy_status(ssh->frontend, BUSY_NOT);
6190 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6191 if (!ssh->kex->pdata) {
6192 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6193 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6194 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6196 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6197 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6199 dh_cleanup(ssh->kex_ctx);
6201 if (!ssh->kex->pdata) {
6206 logeventf(ssh, "Doing RSA key exchange with hash %s",
6207 ssh->kex->hash->text_name);
6208 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6210 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6213 crWaitUntilV(pktin);
6214 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6215 bombout(("expected RSA public key packet from server"));
6219 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6220 hash_string(ssh->kex->hash, ssh->exhash,
6221 s->hostkeydata, s->hostkeylen);
6222 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6226 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6227 s->rsakeydata = snewn(s->rsakeylen, char);
6228 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6231 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6233 sfree(s->rsakeydata);
6234 bombout(("unable to parse RSA public key from server"));
6238 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6241 * Next, set up a shared secret K, of precisely KLEN -
6242 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6243 * RSA key modulus and HLEN is the bit length of the hash
6247 int klen = ssh_rsakex_klen(s->rsakey);
6248 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6250 unsigned char *kstr1, *kstr2, *outstr;
6251 int kstr1len, kstr2len, outstrlen;
6253 s->K = bn_power_2(nbits - 1);
6255 for (i = 0; i < nbits; i++) {
6257 byte = random_byte();
6259 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6263 * Encode this as an mpint.
6265 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6266 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6267 PUT_32BIT(kstr2, kstr1len);
6268 memcpy(kstr2 + 4, kstr1, kstr1len);
6271 * Encrypt it with the given RSA key.
6273 outstrlen = (klen + 7) / 8;
6274 outstr = snewn(outstrlen, unsigned char);
6275 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6276 outstr, outstrlen, s->rsakey);
6279 * And send it off in a return packet.
6281 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6282 ssh2_pkt_addstring_start(s->pktout);
6283 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6284 ssh2_pkt_send_noqueue(ssh, s->pktout);
6286 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6293 ssh_rsakex_freekey(s->rsakey);
6295 crWaitUntilV(pktin);
6296 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6297 sfree(s->rsakeydata);
6298 bombout(("expected signature packet from server"));
6302 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6304 sfree(s->rsakeydata);
6307 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6308 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6309 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6311 ssh->kex_ctx = NULL;
6314 debug(("Exchange hash is:\n"));
6315 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6319 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6320 (char *)s->exchange_hash,
6321 ssh->kex->hash->hlen)) {
6322 bombout(("Server's host key did not match the signature supplied"));
6326 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6327 if (!s->got_session_id) {
6329 * Authenticate remote host: verify host key. (We've already
6330 * checked the signature of the exchange hash.)
6332 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6333 ssh_set_frozen(ssh, 1);
6334 s->dlgret = verify_ssh_host_key(ssh->frontend,
6335 ssh->savedhost, ssh->savedport,
6336 ssh->hostkey->keytype, s->keystr,
6338 ssh_dialog_callback, ssh);
6339 if (s->dlgret < 0) {
6343 bombout(("Unexpected data from server while waiting"
6344 " for user host key response"));
6347 } while (pktin || inlen > 0);
6348 s->dlgret = ssh->user_response;
6350 ssh_set_frozen(ssh, 0);
6351 if (s->dlgret == 0) {
6352 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6356 logevent("Host key fingerprint is:");
6357 logevent(s->fingerprint);
6358 sfree(s->fingerprint);
6360 * Save this host key, to check against the one presented in
6361 * subsequent rekeys.
6363 ssh->hostkey_str = s->keystr;
6366 * In a rekey, we never present an interactive host key
6367 * verification request to the user. Instead, we simply
6368 * enforce that the key we're seeing this time is identical to
6369 * the one we saw before.
6371 if (strcmp(ssh->hostkey_str, s->keystr)) {
6372 bombout(("Host key was different in repeat key exchange"));
6377 ssh->hostkey->freekey(s->hkey);
6380 * The exchange hash from the very first key exchange is also
6381 * the session id, used in session key construction and
6384 if (!s->got_session_id) {
6385 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6386 memcpy(ssh->v2_session_id, s->exchange_hash,
6387 sizeof(s->exchange_hash));
6388 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6389 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6390 s->got_session_id = TRUE;
6394 * Send SSH2_MSG_NEWKEYS.
6396 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6397 ssh2_pkt_send_noqueue(ssh, s->pktout);
6398 ssh->outgoing_data_size = 0; /* start counting from here */
6401 * We've sent client NEWKEYS, so create and initialise
6402 * client-to-server session keys.
6404 if (ssh->cs_cipher_ctx)
6405 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6406 ssh->cscipher = s->cscipher_tobe;
6407 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6409 if (ssh->cs_mac_ctx)
6410 ssh->csmac->free_context(ssh->cs_mac_ctx);
6411 ssh->csmac = s->csmac_tobe;
6412 ssh->cs_mac_ctx = ssh->csmac->make_context();
6414 if (ssh->cs_comp_ctx)
6415 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6416 ssh->cscomp = s->cscomp_tobe;
6417 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6420 * Set IVs on client-to-server keys. Here we use the exchange
6421 * hash from the _first_ key exchange.
6424 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6425 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6426 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6427 assert((ssh->cscipher->keylen+7) / 8 <=
6428 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6429 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6430 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6431 assert(ssh->cscipher->blksize <=
6432 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6433 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6434 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6435 assert(ssh->csmac->len <=
6436 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6437 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6438 smemclr(keyspace, sizeof(keyspace));
6441 logeventf(ssh, "Initialised %.200s client->server encryption",
6442 ssh->cscipher->text_name);
6443 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6444 ssh->csmac->text_name);
6445 if (ssh->cscomp->text_name)
6446 logeventf(ssh, "Initialised %s compression",
6447 ssh->cscomp->text_name);
6450 * Now our end of the key exchange is complete, we can send all
6451 * our queued higher-layer packets.
6453 ssh->queueing = FALSE;
6454 ssh2_pkt_queuesend(ssh);
6457 * Expect SSH2_MSG_NEWKEYS from server.
6459 crWaitUntilV(pktin);
6460 if (pktin->type != SSH2_MSG_NEWKEYS) {
6461 bombout(("expected new-keys packet from server"));
6464 ssh->incoming_data_size = 0; /* start counting from here */
6467 * We've seen server NEWKEYS, so create and initialise
6468 * server-to-client session keys.
6470 if (ssh->sc_cipher_ctx)
6471 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6472 ssh->sccipher = s->sccipher_tobe;
6473 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6475 if (ssh->sc_mac_ctx)
6476 ssh->scmac->free_context(ssh->sc_mac_ctx);
6477 ssh->scmac = s->scmac_tobe;
6478 ssh->sc_mac_ctx = ssh->scmac->make_context();
6480 if (ssh->sc_comp_ctx)
6481 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6482 ssh->sccomp = s->sccomp_tobe;
6483 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6486 * Set IVs on server-to-client keys. Here we use the exchange
6487 * hash from the _first_ key exchange.
6490 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6491 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6492 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6493 assert((ssh->sccipher->keylen+7) / 8 <=
6494 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6495 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6496 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6497 assert(ssh->sccipher->blksize <=
6498 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6499 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6500 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6501 assert(ssh->scmac->len <=
6502 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6503 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6504 smemclr(keyspace, sizeof(keyspace));
6506 logeventf(ssh, "Initialised %.200s server->client encryption",
6507 ssh->sccipher->text_name);
6508 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6509 ssh->scmac->text_name);
6510 if (ssh->sccomp->text_name)
6511 logeventf(ssh, "Initialised %s decompression",
6512 ssh->sccomp->text_name);
6515 * Free shared secret.
6520 * Key exchange is over. Loop straight back round if we have a
6521 * deferred rekey reason.
6523 if (ssh->deferred_rekey_reason) {
6524 logevent(ssh->deferred_rekey_reason);
6526 ssh->deferred_rekey_reason = NULL;
6527 goto begin_key_exchange;
6531 * Otherwise, schedule a timer for our next rekey.
6533 ssh->kex_in_progress = FALSE;
6534 ssh->last_rekey = GETTICKCOUNT();
6535 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6536 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6540 * Now we're encrypting. Begin returning 1 to the protocol main
6541 * function so that other things can run on top of the
6542 * transport. If we ever see a KEXINIT, we must go back to the
6545 * We _also_ go back to the start if we see pktin==NULL and
6546 * inlen negative, because this is a special signal meaning
6547 * `initiate client-driven rekey', and `in' contains a message
6548 * giving the reason for the rekey.
6550 * inlen==-1 means always initiate a rekey;
6551 * inlen==-2 means that userauth has completed successfully and
6552 * we should consider rekeying (for delayed compression).
6554 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6555 (!pktin && inlen < 0))) {
6557 if (!ssh->protocol_initial_phase_done) {
6558 ssh->protocol_initial_phase_done = TRUE;
6560 * Allow authconn to initialise itself.
6562 do_ssh2_authconn(ssh, NULL, 0, NULL);
6567 logevent("Server initiated key re-exchange");
6571 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6572 * delayed compression, if it's available.
6574 * draft-miller-secsh-compression-delayed-00 says that you
6575 * negotiate delayed compression in the first key exchange, and
6576 * both sides start compressing when the server has sent
6577 * USERAUTH_SUCCESS. This has a race condition -- the server
6578 * can't know when the client has seen it, and thus which incoming
6579 * packets it should treat as compressed.
6581 * Instead, we do the initial key exchange without offering the
6582 * delayed methods, but note if the server offers them; when we
6583 * get here, if a delayed method was available that was higher
6584 * on our list than what we got, we initiate a rekey in which we
6585 * _do_ list the delayed methods (and hopefully get it as a
6586 * result). Subsequent rekeys will do the same.
6588 assert(!s->userauth_succeeded); /* should only happen once */
6589 s->userauth_succeeded = TRUE;
6590 if (!s->pending_compression)
6591 /* Can't see any point rekeying. */
6592 goto wait_for_rekey; /* this is utterly horrid */
6593 /* else fall through to rekey... */
6594 s->pending_compression = FALSE;
6597 * Now we've decided to rekey.
6599 * Special case: if the server bug is set that doesn't
6600 * allow rekeying, we give a different log message and
6601 * continue waiting. (If such a server _initiates_ a rekey,
6602 * we process it anyway!)
6604 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6605 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6607 /* Reset the counters, so that at least this message doesn't
6608 * hit the event log _too_ often. */
6609 ssh->outgoing_data_size = 0;
6610 ssh->incoming_data_size = 0;
6611 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
6613 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6616 goto wait_for_rekey; /* this is still utterly horrid */
6618 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6621 goto begin_key_exchange;
6627 * Add data to an SSH-2 channel output buffer.
6629 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6632 bufchain_add(&c->v.v2.outbuffer, buf, len);
6636 * Attempt to send data on an SSH-2 channel.
6638 static int ssh2_try_send(struct ssh_channel *c)
6641 struct Packet *pktout;
6644 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6647 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6648 if ((unsigned)len > c->v.v2.remwindow)
6649 len = c->v.v2.remwindow;
6650 if ((unsigned)len > c->v.v2.remmaxpkt)
6651 len = c->v.v2.remmaxpkt;
6652 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6653 ssh2_pkt_adduint32(pktout, c->remoteid);
6654 ssh2_pkt_addstring_start(pktout);
6655 ssh2_pkt_addstring_data(pktout, data, len);
6656 ssh2_pkt_send(ssh, pktout);
6657 bufchain_consume(&c->v.v2.outbuffer, len);
6658 c->v.v2.remwindow -= len;
6662 * After having sent as much data as we can, return the amount
6665 ret = bufchain_size(&c->v.v2.outbuffer);
6668 * And if there's no data pending but we need to send an EOF, send
6671 if (!ret && c->pending_eof)
6672 ssh_channel_try_eof(c);
6677 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
6680 if (c->closes & CLOSES_SENT_EOF)
6681 return; /* don't send on channels we've EOFed */
6682 bufsize = ssh2_try_send(c);
6685 case CHAN_MAINSESSION:
6686 /* stdin need not receive an unthrottle
6687 * notification since it will be polled */
6690 x11_unthrottle(c->u.x11.xconn);
6693 /* agent sockets are request/response and need no
6694 * buffer management */
6697 pfd_unthrottle(c->u.pfd.pf);
6704 * Set up most of a new ssh_channel for SSH-2.
6706 static void ssh2_channel_init(struct ssh_channel *c)
6709 c->localid = alloc_channel_id(ssh);
6711 c->pending_eof = FALSE;
6712 c->throttling_conn = FALSE;
6713 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6714 conf_get_int(ssh->conf, CONF_ssh_simple) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6715 c->v.v2.chanreq_head = NULL;
6716 c->v.v2.throttle_state = UNTHROTTLED;
6717 bufchain_init(&c->v.v2.outbuffer);
6721 * Construct the common parts of a CHANNEL_OPEN.
6723 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c, char *type)
6725 struct Packet *pktout;
6727 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
6728 ssh2_pkt_addstring(pktout, type);
6729 ssh2_pkt_adduint32(pktout, c->localid);
6730 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
6731 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
6736 * CHANNEL_FAILURE doesn't come with any indication of what message
6737 * caused it, so we have to keep track of the outstanding
6738 * CHANNEL_REQUESTs ourselves.
6740 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
6741 cchandler_fn_t handler, void *ctx)
6743 struct outstanding_channel_request *ocr =
6744 snew(struct outstanding_channel_request);
6746 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
6747 ocr->handler = handler;
6750 if (!c->v.v2.chanreq_head)
6751 c->v.v2.chanreq_head = ocr;
6753 c->v.v2.chanreq_tail->next = ocr;
6754 c->v.v2.chanreq_tail = ocr;
6758 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
6759 * NULL then a reply will be requested and the handler will be called
6760 * when it arrives. The returned packet is ready to have any
6761 * request-specific data added and be sent. Note that if a handler is
6762 * provided, it's essential that the request actually be sent.
6764 * The handler will usually be passed the response packet in pktin.
6765 * If pktin is NULL, this means that no reply will ever be forthcoming
6766 * (e.g. because the entire connection is being destroyed) and the
6767 * handler should free any storage it's holding.
6769 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c, char *type,
6770 cchandler_fn_t handler, void *ctx)
6772 struct Packet *pktout;
6774 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
6775 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6776 ssh2_pkt_adduint32(pktout, c->remoteid);
6777 ssh2_pkt_addstring(pktout, type);
6778 ssh2_pkt_addbool(pktout, handler != NULL);
6779 if (handler != NULL)
6780 ssh2_queue_chanreq_handler(c, handler, ctx);
6785 * Potentially enlarge the window on an SSH-2 channel.
6787 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
6789 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6794 * Never send WINDOW_ADJUST for a channel that the remote side has
6795 * already sent EOF on; there's no point, since it won't be
6796 * sending any more data anyway. Ditto if _we've_ already sent
6799 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6803 * If the remote end has a habit of ignoring maxpkt, limit the
6804 * window so that it has no choice (assuming it doesn't ignore the
6807 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6808 newwin = OUR_V2_MAXPKT;
6811 * Only send a WINDOW_ADJUST if there's significantly more window
6812 * available than the other end thinks there is. This saves us
6813 * sending a WINDOW_ADJUST for every character in a shell session.
6815 * "Significant" is arbitrarily defined as half the window size.
6817 if (newwin / 2 >= c->v.v2.locwindow) {
6818 struct Packet *pktout;
6822 * In order to keep track of how much window the client
6823 * actually has available, we'd like it to acknowledge each
6824 * WINDOW_ADJUST. We can't do that directly, so we accompany
6825 * it with a CHANNEL_REQUEST that has to be acknowledged.
6827 * This is only necessary if we're opening the window wide.
6828 * If we're not, then throughput is being constrained by
6829 * something other than the maximum window size anyway.
6831 if (newwin == c->v.v2.locmaxwin &&
6832 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
6833 up = snew(unsigned);
6834 *up = newwin - c->v.v2.locwindow;
6835 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
6836 ssh2_handle_winadj_response, up);
6837 ssh2_pkt_send(ssh, pktout);
6839 if (c->v.v2.throttle_state != UNTHROTTLED)
6840 c->v.v2.throttle_state = UNTHROTTLING;
6842 /* Pretend the WINDOW_ADJUST was acked immediately. */
6843 c->v.v2.remlocwin = newwin;
6844 c->v.v2.throttle_state = THROTTLED;
6846 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6847 ssh2_pkt_adduint32(pktout, c->remoteid);
6848 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6849 ssh2_pkt_send(ssh, pktout);
6850 c->v.v2.locwindow = newwin;
6855 * Find the channel associated with a message. If there's no channel,
6856 * or it's not properly open, make a noise about it and return NULL.
6858 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6860 unsigned localid = ssh_pkt_getuint32(pktin);
6861 struct ssh_channel *c;
6863 c = find234(ssh->channels, &localid, ssh_channelfind);
6865 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6866 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6867 char *buf = dupprintf("Received %s for %s channel %u",
6868 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6870 c ? "half-open" : "nonexistent", localid);
6871 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6878 static void ssh2_handle_winadj_response(struct ssh_channel *c,
6879 struct Packet *pktin, void *ctx)
6881 unsigned *sizep = ctx;
6884 * Winadj responses should always be failures. However, at least
6885 * one server ("boks_sshd") is known to return SUCCESS for channel
6886 * requests it's never heard of, such as "winadj@putty". Raised
6887 * with foxt.com as bug 090916-090424, but for the sake of a quiet
6888 * life, we don't worry about what kind of response we got.
6891 c->v.v2.remlocwin += *sizep;
6894 * winadj messages are only sent when the window is fully open, so
6895 * if we get an ack of one, we know any pending unthrottle is
6898 if (c->v.v2.throttle_state == UNTHROTTLING)
6899 c->v.v2.throttle_state = UNTHROTTLED;
6902 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
6904 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
6905 struct outstanding_channel_request *ocr;
6908 ocr = c->v.v2.chanreq_head;
6910 ssh2_msg_unexpected(ssh, pktin);
6913 ocr->handler(c, pktin, ocr->ctx);
6914 c->v.v2.chanreq_head = ocr->next;
6917 * We may now initiate channel-closing procedures, if that
6918 * CHANNEL_REQUEST was the last thing outstanding before we send
6921 ssh2_channel_check_close(c);
6924 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6926 struct ssh_channel *c;
6927 c = ssh2_channel_msg(ssh, pktin);
6930 if (!(c->closes & CLOSES_SENT_EOF)) {
6931 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6932 ssh2_try_send_and_unthrottle(ssh, c);
6936 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6940 struct ssh_channel *c;
6941 c = ssh2_channel_msg(ssh, pktin);
6944 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6945 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6946 return; /* extended but not stderr */
6947 ssh_pkt_getstring(pktin, &data, &length);
6950 c->v.v2.locwindow -= length;
6951 c->v.v2.remlocwin -= length;
6953 case CHAN_MAINSESSION:
6955 from_backend(ssh->frontend, pktin->type ==
6956 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6960 bufsize = x11_send(c->u.x11.xconn, data, length);
6963 bufsize = pfd_send(c->u.pfd.pf, data, length);
6966 while (length > 0) {
6967 if (c->u.a.lensofar < 4) {
6968 unsigned int l = min(4 - c->u.a.lensofar,
6970 memcpy(c->u.a.msglen + c->u.a.lensofar,
6974 c->u.a.lensofar += l;
6976 if (c->u.a.lensofar == 4) {
6978 4 + GET_32BIT(c->u.a.msglen);
6979 c->u.a.message = snewn(c->u.a.totallen,
6981 memcpy(c->u.a.message, c->u.a.msglen, 4);
6983 if (c->u.a.lensofar >= 4 && length > 0) {
6985 min(c->u.a.totallen - c->u.a.lensofar,
6987 memcpy(c->u.a.message + c->u.a.lensofar,
6991 c->u.a.lensofar += l;
6993 if (c->u.a.lensofar == c->u.a.totallen) {
6996 c->u.a.outstanding_requests++;
6997 if (agent_query(c->u.a.message,
7000 ssh_agentf_callback, c))
7001 ssh_agentf_callback(c, reply, replylen);
7002 sfree(c->u.a.message);
7003 c->u.a.message = NULL;
7004 c->u.a.lensofar = 0;
7011 * If it looks like the remote end hit the end of its window,
7012 * and we didn't want it to do that, think about using a
7015 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
7016 c->v.v2.locmaxwin < 0x40000000)
7017 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
7019 * If we are not buffering too much data,
7020 * enlarge the window again at the remote side.
7021 * If we are buffering too much, we may still
7022 * need to adjust the window if the server's
7025 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7026 c->v.v2.locmaxwin - bufsize : 0);
7028 * If we're either buffering way too much data, or if we're
7029 * buffering anything at all and we're in "simple" mode,
7030 * throttle the whole channel.
7032 if ((bufsize > c->v.v2.locmaxwin ||
7033 (conf_get_int(ssh->conf, CONF_ssh_simple) && bufsize > 0)) &&
7034 !c->throttling_conn) {
7035 c->throttling_conn = 1;
7036 ssh_throttle_conn(ssh, +1);
7041 static void ssh_channel_destroy(struct ssh_channel *c)
7046 case CHAN_MAINSESSION:
7047 ssh->mainchan = NULL;
7048 update_specials_menu(ssh->frontend);
7051 if (c->u.x11.xconn != NULL)
7052 x11_close(c->u.x11.xconn);
7053 logevent("Forwarded X11 connection terminated");
7056 sfree(c->u.a.message);
7059 if (c->u.pfd.pf != NULL)
7060 pfd_close(c->u.pfd.pf);
7061 logevent("Forwarded port closed");
7065 del234(ssh->channels, c);
7066 if (ssh->version == 2) {
7067 bufchain_clear(&c->v.v2.outbuffer);
7068 assert(c->v.v2.chanreq_head == NULL);
7073 * See if that was the last channel left open.
7074 * (This is only our termination condition if we're
7075 * not running in -N mode.)
7077 if (ssh->version == 2 &&
7078 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7079 count234(ssh->channels) == 0) {
7081 * We used to send SSH_MSG_DISCONNECT here,
7082 * because I'd believed that _every_ conforming
7083 * SSH-2 connection had to end with a disconnect
7084 * being sent by at least one side; apparently
7085 * I was wrong and it's perfectly OK to
7086 * unceremoniously slam the connection shut
7087 * when you're done, and indeed OpenSSH feels
7088 * this is more polite than sending a
7089 * DISCONNECT. So now we don't.
7091 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7095 static void ssh2_channel_check_close(struct ssh_channel *c)
7098 struct Packet *pktout;
7102 * If we've sent out our own CHANNEL_OPEN but not yet seen
7103 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
7104 * it's too early to be sending close messages of any kind.
7109 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
7110 c->type == CHAN_ZOMBIE) &&
7111 !c->v.v2.chanreq_head &&
7112 !(c->closes & CLOSES_SENT_CLOSE)) {
7114 * We have both sent and received EOF (or the channel is a
7115 * zombie), and we have no outstanding channel requests, which
7116 * means the channel is in final wind-up. But we haven't sent
7117 * CLOSE, so let's do so now.
7119 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
7120 ssh2_pkt_adduint32(pktout, c->remoteid);
7121 ssh2_pkt_send(ssh, pktout);
7122 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
7125 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
7126 assert(c->v.v2.chanreq_head == NULL);
7128 * We have both sent and received CLOSE, which means we're
7129 * completely done with the channel.
7131 ssh_channel_destroy(c);
7135 static void ssh2_channel_got_eof(struct ssh_channel *c)
7137 if (c->closes & CLOSES_RCVD_EOF)
7138 return; /* already seen EOF */
7139 c->closes |= CLOSES_RCVD_EOF;
7141 if (c->type == CHAN_X11) {
7142 x11_send_eof(c->u.x11.xconn);
7143 } else if (c->type == CHAN_AGENT) {
7144 if (c->u.a.outstanding_requests == 0) {
7145 /* Manufacture an outgoing EOF in response to the incoming one. */
7146 sshfwd_write_eof(c);
7148 } else if (c->type == CHAN_SOCKDATA) {
7149 pfd_send_eof(c->u.pfd.pf);
7150 } else if (c->type == CHAN_MAINSESSION) {
7153 if (!ssh->sent_console_eof &&
7154 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
7156 * Either from_backend_eof told us that the front end
7157 * wants us to close the outgoing side of the connection
7158 * as soon as we see EOF from the far end, or else we've
7159 * unilaterally decided to do that because we've allocated
7160 * a remote pty and hence EOF isn't a particularly
7161 * meaningful concept.
7163 sshfwd_write_eof(c);
7165 ssh->sent_console_eof = TRUE;
7168 ssh2_channel_check_close(c);
7171 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
7173 struct ssh_channel *c;
7175 c = ssh2_channel_msg(ssh, pktin);
7178 ssh2_channel_got_eof(c);
7181 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7183 struct ssh_channel *c;
7185 c = ssh2_channel_msg(ssh, pktin);
7190 * When we receive CLOSE on a channel, we assume it comes with an
7191 * implied EOF if we haven't seen EOF yet.
7193 ssh2_channel_got_eof(c);
7196 * And we also send an outgoing EOF, if we haven't already, on the
7197 * assumption that CLOSE is a pretty forceful announcement that
7198 * the remote side is doing away with the entire channel. (If it
7199 * had wanted to send us EOF and continue receiving data from us,
7200 * it would have just sent CHANNEL_EOF.)
7202 if (!(c->closes & CLOSES_SENT_EOF)) {
7204 * Make sure we don't read any more from whatever our local
7205 * data source is for this channel.
7208 case CHAN_MAINSESSION:
7209 ssh->send_ok = 0; /* stop trying to read from stdin */
7212 x11_override_throttle(c->u.x11.xconn, 1);
7215 pfd_override_throttle(c->u.pfd.pf, 1);
7220 * Abandon any buffered data we still wanted to send to this
7221 * channel. Receiving a CHANNEL_CLOSE is an indication that
7222 * the server really wants to get on and _destroy_ this
7223 * channel, and it isn't going to send us any further
7224 * WINDOW_ADJUSTs to permit us to send pending stuff.
7226 bufchain_clear(&c->v.v2.outbuffer);
7229 * Send outgoing EOF.
7231 sshfwd_write_eof(c);
7235 * Now process the actual close.
7237 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7238 c->closes |= CLOSES_RCVD_CLOSE;
7239 ssh2_channel_check_close(c);
7243 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7245 struct ssh_channel *c;
7247 c = ssh2_channel_msg(ssh, pktin);
7250 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7251 c->remoteid = ssh_pkt_getuint32(pktin);
7252 c->halfopen = FALSE;
7253 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7254 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7256 if (c->type == CHAN_SOCKDATA_DORMANT) {
7257 c->type = CHAN_SOCKDATA;
7259 pfd_confirm(c->u.pfd.pf);
7260 } else if (c->type == CHAN_ZOMBIE) {
7262 * This case can occur if a local socket error occurred
7263 * between us sending out CHANNEL_OPEN and receiving
7264 * OPEN_CONFIRMATION. In this case, all we can do is
7265 * immediately initiate close proceedings now that we know the
7266 * server's id to put in the close message.
7268 ssh2_channel_check_close(c);
7271 * We never expect to receive OPEN_CONFIRMATION for any
7272 * *other* channel type (since only local-to-remote port
7273 * forwardings cause us to send CHANNEL_OPEN after the main
7274 * channel is live - all other auxiliary channel types are
7275 * initiated from the server end). It's safe to enforce this
7276 * by assertion rather than by ssh_disconnect, because the
7277 * real point is that we never constructed a half-open channel
7278 * structure in the first place with any type other than the
7281 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
7285 ssh_channel_try_eof(c); /* in case we had a pending EOF */
7288 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7290 static const char *const reasons[] = {
7291 "<unknown reason code>",
7292 "Administratively prohibited",
7294 "Unknown channel type",
7295 "Resource shortage",
7297 unsigned reason_code;
7298 char *reason_string;
7300 struct ssh_channel *c;
7302 c = ssh2_channel_msg(ssh, pktin);
7305 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7307 if (c->type == CHAN_SOCKDATA_DORMANT) {
7308 reason_code = ssh_pkt_getuint32(pktin);
7309 if (reason_code >= lenof(reasons))
7310 reason_code = 0; /* ensure reasons[reason_code] in range */
7311 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7312 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7313 reasons[reason_code], reason_length, reason_string);
7315 pfd_close(c->u.pfd.pf);
7316 } else if (c->type == CHAN_ZOMBIE) {
7318 * This case can occur if a local socket error occurred
7319 * between us sending out CHANNEL_OPEN and receiving
7320 * OPEN_FAILURE. In this case, we need do nothing except allow
7321 * the code below to throw the half-open channel away.
7325 * We never expect to receive OPEN_FAILURE for any *other*
7326 * channel type (since only local-to-remote port forwardings
7327 * cause us to send CHANNEL_OPEN after the main channel is
7328 * live - all other auxiliary channel types are initiated from
7329 * the server end). It's safe to enforce this by assertion
7330 * rather than by ssh_disconnect, because the real point is
7331 * that we never constructed a half-open channel structure in
7332 * the first place with any type other than the above.
7334 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
7337 del234(ssh->channels, c);
7341 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7344 int typelen, want_reply;
7345 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7346 struct ssh_channel *c;
7347 struct Packet *pktout;
7349 c = ssh2_channel_msg(ssh, pktin);
7352 ssh_pkt_getstring(pktin, &type, &typelen);
7353 want_reply = ssh2_pkt_getbool(pktin);
7356 * Having got the channel number, we now look at
7357 * the request type string to see if it's something
7360 if (c == ssh->mainchan) {
7362 * We recognise "exit-status" and "exit-signal" on
7363 * the primary channel.
7365 if (typelen == 11 &&
7366 !memcmp(type, "exit-status", 11)) {
7368 ssh->exitcode = ssh_pkt_getuint32(pktin);
7369 logeventf(ssh, "Server sent command exit status %d",
7371 reply = SSH2_MSG_CHANNEL_SUCCESS;
7373 } else if (typelen == 11 &&
7374 !memcmp(type, "exit-signal", 11)) {
7376 int is_plausible = TRUE, is_int = FALSE;
7377 char *fmt_sig = "", *fmt_msg = "";
7379 int msglen = 0, core = FALSE;
7380 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7381 * provide an `int' for the signal, despite its
7382 * having been a `string' in the drafts of RFC 4254 since at
7383 * least 2001. (Fixed in session.c 1.147.) Try to
7384 * infer which we can safely parse it as. */
7386 unsigned char *p = pktin->body +
7388 long len = pktin->length - pktin->savedpos;
7389 unsigned long num = GET_32BIT(p); /* what is it? */
7390 /* If it's 0, it hardly matters; assume string */
7394 int maybe_int = FALSE, maybe_str = FALSE;
7395 #define CHECK_HYPOTHESIS(offset, result) \
7398 int q = toint(offset); \
7399 if (q >= 0 && q+4 <= len) { \
7400 q = toint(q + 4 + GET_32BIT(p+q)); \
7401 if (q >= 0 && q+4 <= len && \
7402 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
7407 CHECK_HYPOTHESIS(4+1, maybe_int);
7408 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7409 #undef CHECK_HYPOTHESIS
7410 if (maybe_int && !maybe_str)
7412 else if (!maybe_int && maybe_str)
7415 /* Crikey. Either or neither. Panic. */
7416 is_plausible = FALSE;
7419 ssh->exitcode = 128; /* means `unknown signal' */
7422 /* Old non-standard OpenSSH. */
7423 int signum = ssh_pkt_getuint32(pktin);
7424 fmt_sig = dupprintf(" %d", signum);
7425 ssh->exitcode = 128 + signum;
7427 /* As per RFC 4254. */
7430 ssh_pkt_getstring(pktin, &sig, &siglen);
7431 /* Signal name isn't supposed to be blank, but
7432 * let's cope gracefully if it is. */
7434 fmt_sig = dupprintf(" \"%.*s\"",
7439 * Really hideous method of translating the
7440 * signal description back into a locally
7441 * meaningful number.
7446 #define TRANSLATE_SIGNAL(s) \
7447 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7448 ssh->exitcode = 128 + SIG ## s
7450 TRANSLATE_SIGNAL(ABRT);
7453 TRANSLATE_SIGNAL(ALRM);
7456 TRANSLATE_SIGNAL(FPE);
7459 TRANSLATE_SIGNAL(HUP);
7462 TRANSLATE_SIGNAL(ILL);
7465 TRANSLATE_SIGNAL(INT);
7468 TRANSLATE_SIGNAL(KILL);
7471 TRANSLATE_SIGNAL(PIPE);
7474 TRANSLATE_SIGNAL(QUIT);
7477 TRANSLATE_SIGNAL(SEGV);
7480 TRANSLATE_SIGNAL(TERM);
7483 TRANSLATE_SIGNAL(USR1);
7486 TRANSLATE_SIGNAL(USR2);
7488 #undef TRANSLATE_SIGNAL
7490 ssh->exitcode = 128;
7492 core = ssh2_pkt_getbool(pktin);
7493 ssh_pkt_getstring(pktin, &msg, &msglen);
7495 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7497 /* ignore lang tag */
7498 } /* else don't attempt to parse */
7499 logeventf(ssh, "Server exited on signal%s%s%s",
7500 fmt_sig, core ? " (core dumped)" : "",
7502 if (*fmt_sig) sfree(fmt_sig);
7503 if (*fmt_msg) sfree(fmt_msg);
7504 reply = SSH2_MSG_CHANNEL_SUCCESS;
7509 * This is a channel request we don't know
7510 * about, so we now either ignore the request
7511 * or respond with CHANNEL_FAILURE, depending
7514 reply = SSH2_MSG_CHANNEL_FAILURE;
7517 pktout = ssh2_pkt_init(reply);
7518 ssh2_pkt_adduint32(pktout, c->remoteid);
7519 ssh2_pkt_send(ssh, pktout);
7523 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7526 int typelen, want_reply;
7527 struct Packet *pktout;
7529 ssh_pkt_getstring(pktin, &type, &typelen);
7530 want_reply = ssh2_pkt_getbool(pktin);
7533 * We currently don't support any global requests
7534 * at all, so we either ignore the request or
7535 * respond with REQUEST_FAILURE, depending on
7539 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7540 ssh2_pkt_send(ssh, pktout);
7544 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7552 struct ssh_channel *c;
7553 unsigned remid, winsize, pktsize;
7554 struct Packet *pktout;
7556 ssh_pkt_getstring(pktin, &type, &typelen);
7557 c = snew(struct ssh_channel);
7560 remid = ssh_pkt_getuint32(pktin);
7561 winsize = ssh_pkt_getuint32(pktin);
7562 pktsize = ssh_pkt_getuint32(pktin);
7564 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7568 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7569 addrstr = snewn(peeraddrlen+1, char);
7570 memcpy(addrstr, peeraddr, peeraddrlen);
7571 addrstr[peeraddrlen] = '\0';
7572 peerport = ssh_pkt_getuint32(pktin);
7574 logeventf(ssh, "Received X11 connect request from %s:%d",
7577 if (!ssh->X11_fwd_enabled)
7578 error = "X11 forwarding is not enabled";
7579 else if ((x11err = x11_init(&c->u.x11.xconn, ssh->x11authtree, c,
7580 addrstr, peerport)) != NULL) {
7581 logeventf(ssh, "Local X11 connection failed: %s", x11err);
7583 error = "Unable to open an X11 connection";
7585 logevent("Opening X11 forward connection succeeded");
7590 } else if (typelen == 15 &&
7591 !memcmp(type, "forwarded-tcpip", 15)) {
7592 struct ssh_rportfwd pf, *realpf;
7595 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
7596 pf.shost = dupprintf("%.*s", shostlen, shost);
7597 pf.sport = ssh_pkt_getuint32(pktin);
7598 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7599 peerport = ssh_pkt_getuint32(pktin);
7600 realpf = find234(ssh->rportfwds, &pf, NULL);
7601 logeventf(ssh, "Received remote port %s:%d open request "
7602 "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
7605 if (realpf == NULL) {
7606 error = "Remote port is not recognised";
7608 char *err = pfd_connect(&c->u.pfd.pf,
7612 realpf->pfrec->addressfamily);
7613 logeventf(ssh, "Attempting to forward remote port to "
7614 "%s:%d", realpf->dhost, realpf->dport);
7616 logeventf(ssh, "Port open failed: %s", err);
7618 error = "Port open failed";
7620 logevent("Forwarded port opened successfully");
7621 c->type = CHAN_SOCKDATA;
7624 } else if (typelen == 22 &&
7625 !memcmp(type, "auth-agent@openssh.com", 22)) {
7626 if (!ssh->agentfwd_enabled)
7627 error = "Agent forwarding is not enabled";
7629 c->type = CHAN_AGENT; /* identify channel type */
7630 c->u.a.lensofar = 0;
7631 c->u.a.message = NULL;
7632 c->u.a.outstanding_requests = 0;
7635 error = "Unsupported channel type requested";
7638 c->remoteid = remid;
7639 c->halfopen = FALSE;
7641 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7642 ssh2_pkt_adduint32(pktout, c->remoteid);
7643 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7644 ssh2_pkt_addstring(pktout, error);
7645 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7646 ssh2_pkt_send(ssh, pktout);
7647 logeventf(ssh, "Rejected channel open: %s", error);
7650 ssh2_channel_init(c);
7651 c->v.v2.remwindow = winsize;
7652 c->v.v2.remmaxpkt = pktsize;
7653 add234(ssh->channels, c);
7654 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7655 ssh2_pkt_adduint32(pktout, c->remoteid);
7656 ssh2_pkt_adduint32(pktout, c->localid);
7657 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7658 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7659 ssh2_pkt_send(ssh, pktout);
7664 * Buffer banner messages for later display at some convenient point,
7665 * if we're going to display them.
7667 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7669 /* Arbitrary limit to prevent unbounded inflation of buffer */
7670 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
7671 bufchain_size(&ssh->banner) <= 131072) {
7672 char *banner = NULL;
7674 ssh_pkt_getstring(pktin, &banner, &size);
7676 bufchain_add(&ssh->banner, banner, size);
7680 /* Helper function to deal with sending tty modes for "pty-req" */
7681 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7683 struct Packet *pktout = (struct Packet *)data;
7685 unsigned int arg = 0;
7686 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7687 if (i == lenof(ssh_ttymodes)) return;
7688 switch (ssh_ttymodes[i].type) {
7690 arg = ssh_tty_parse_specchar(val);
7693 arg = ssh_tty_parse_boolean(val);
7696 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7697 ssh2_pkt_adduint32(pktout, arg);
7700 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
7703 struct ssh2_setup_x11_state {
7707 struct Packet *pktout;
7708 crStateP(ssh2_setup_x11_state, ctx);
7712 logevent("Requesting X11 forwarding");
7713 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
7715 ssh2_pkt_addbool(pktout, 0); /* many connections */
7716 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
7717 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
7718 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
7719 ssh2_pkt_send(ssh, pktout);
7721 /* Wait to be called back with either a response packet, or NULL
7722 * meaning clean up and free our data */
7726 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7727 logevent("X11 forwarding enabled");
7728 ssh->X11_fwd_enabled = TRUE;
7730 logevent("X11 forwarding refused");
7736 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
7739 struct ssh2_setup_agent_state {
7743 struct Packet *pktout;
7744 crStateP(ssh2_setup_agent_state, ctx);
7748 logevent("Requesting OpenSSH-style agent forwarding");
7749 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
7750 ssh2_setup_agent, s);
7751 ssh2_pkt_send(ssh, pktout);
7753 /* Wait to be called back with either a response packet, or NULL
7754 * meaning clean up and free our data */
7758 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7759 logevent("Agent forwarding enabled");
7760 ssh->agentfwd_enabled = TRUE;
7762 logevent("Agent forwarding refused");
7768 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
7771 struct ssh2_setup_pty_state {
7775 struct Packet *pktout;
7776 crStateP(ssh2_setup_pty_state, ctx);
7780 /* Unpick the terminal-speed string. */
7781 /* XXX perhaps we should allow no speeds to be sent. */
7782 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
7783 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
7784 /* Build the pty request. */
7785 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
7787 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
7788 ssh2_pkt_adduint32(pktout, ssh->term_width);
7789 ssh2_pkt_adduint32(pktout, ssh->term_height);
7790 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
7791 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
7792 ssh2_pkt_addstring_start(pktout);
7793 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
7794 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
7795 ssh2_pkt_adduint32(pktout, ssh->ispeed);
7796 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
7797 ssh2_pkt_adduint32(pktout, ssh->ospeed);
7798 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
7799 ssh2_pkt_send(ssh, pktout);
7800 ssh->state = SSH_STATE_INTERMED;
7802 /* Wait to be called back with either a response packet, or NULL
7803 * meaning clean up and free our data */
7807 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7808 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
7809 ssh->ospeed, ssh->ispeed);
7810 ssh->got_pty = TRUE;
7812 c_write_str(ssh, "Server refused to allocate pty\r\n");
7813 ssh->editing = ssh->echoing = 1;
7820 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
7823 struct ssh2_setup_env_state {
7825 int num_env, env_left, env_ok;
7828 struct Packet *pktout;
7829 crStateP(ssh2_setup_env_state, ctx);
7834 * Send environment variables.
7836 * Simplest thing here is to send all the requests at once, and
7837 * then wait for a whole bunch of successes or failures.
7843 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
7845 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
7846 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
7847 ssh2_pkt_addstring(pktout, key);
7848 ssh2_pkt_addstring(pktout, val);
7849 ssh2_pkt_send(ssh, pktout);
7854 logeventf(ssh, "Sent %d environment variables", s->num_env);
7859 s->env_left = s->num_env;
7861 while (s->env_left > 0) {
7862 /* Wait to be called back with either a response packet,
7863 * or NULL meaning clean up and free our data */
7865 if (!pktin) goto out;
7866 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
7871 if (s->env_ok == s->num_env) {
7872 logevent("All environment variables successfully set");
7873 } else if (s->env_ok == 0) {
7874 logevent("All environment variables refused");
7875 c_write_str(ssh, "Server refused to set environment variables\r\n");
7877 logeventf(ssh, "%d environment variables refused",
7878 s->num_env - s->env_ok);
7879 c_write_str(ssh, "Server refused to set all environment variables\r\n");
7887 * Handle the SSH-2 userauth and connection layers.
7889 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
7891 do_ssh2_authconn(ssh, NULL, 0, pktin);
7894 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
7897 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
7900 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7901 struct Packet *pktin)
7903 struct do_ssh2_authconn_state {
7907 AUTH_TYPE_PUBLICKEY,
7908 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7909 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7911 AUTH_TYPE_GSSAPI, /* always QUIET */
7912 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7913 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7915 int done_service_req;
7916 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7917 int tried_pubkey_config, done_agent;
7922 int kbd_inter_refused;
7923 int we_are_in, userauth_success;
7924 prompts_t *cur_prompt;
7929 void *publickey_blob;
7930 int publickey_bloblen;
7931 int publickey_encrypted;
7932 char *publickey_algorithm;
7933 char *publickey_comment;
7934 unsigned char agent_request[5], *agent_response, *agentp;
7935 int agent_responselen;
7936 unsigned char *pkblob_in_agent;
7938 char *pkblob, *alg, *commentp;
7939 int pklen, alglen, commentlen;
7940 int siglen, retlen, len;
7941 char *q, *agentreq, *ret;
7943 struct Packet *pktout;
7946 struct ssh_gss_library *gsslib;
7947 Ssh_gss_ctx gss_ctx;
7948 Ssh_gss_buf gss_buf;
7949 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7950 Ssh_gss_name gss_srv_name;
7951 Ssh_gss_stat gss_stat;
7954 crState(do_ssh2_authconn_state);
7958 /* Register as a handler for all the messages this coroutine handles. */
7959 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
7960 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
7961 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
7962 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
7963 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
7964 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
7965 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
7966 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
7967 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
7968 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
7969 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
7970 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
7971 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
7972 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
7973 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
7974 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
7975 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
7976 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
7977 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
7978 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
7980 s->done_service_req = FALSE;
7981 s->we_are_in = s->userauth_success = FALSE;
7983 s->tried_gssapi = FALSE;
7986 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
7988 * Request userauth protocol, and await a response to it.
7990 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7991 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7992 ssh2_pkt_send(ssh, s->pktout);
7993 crWaitUntilV(pktin);
7994 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7995 s->done_service_req = TRUE;
7997 if (!s->done_service_req) {
7999 * Request connection protocol directly, without authentication.
8001 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8002 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8003 ssh2_pkt_send(ssh, s->pktout);
8004 crWaitUntilV(pktin);
8005 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
8006 s->we_are_in = TRUE; /* no auth required */
8008 bombout(("Server refused service request"));
8013 /* Arrange to be able to deal with any BANNERs that come in.
8014 * (We do this now as packets may come in during the next bit.) */
8015 bufchain_init(&ssh->banner);
8016 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
8017 ssh2_msg_userauth_banner;
8020 * Misc one-time setup for authentication.
8022 s->publickey_blob = NULL;
8023 if (!s->we_are_in) {
8026 * Load the public half of any configured public key file
8029 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8030 if (!filename_is_null(s->keyfile)) {
8032 logeventf(ssh, "Reading private key file \"%.150s\"",
8033 filename_to_str(s->keyfile));
8034 keytype = key_type(s->keyfile);
8035 if (keytype == SSH_KEYTYPE_SSH2) {
8038 ssh2_userkey_loadpub(s->keyfile,
8039 &s->publickey_algorithm,
8040 &s->publickey_bloblen,
8041 &s->publickey_comment, &error);
8042 if (s->publickey_blob) {
8043 s->publickey_encrypted =
8044 ssh2_userkey_encrypted(s->keyfile, NULL);
8047 logeventf(ssh, "Unable to load private key (%s)",
8049 msgbuf = dupprintf("Unable to load private key file "
8050 "\"%.150s\" (%s)\r\n",
8051 filename_to_str(s->keyfile),
8053 c_write_str(ssh, msgbuf);
8058 logeventf(ssh, "Unable to use this key file (%s)",
8059 key_type_to_str(keytype));
8060 msgbuf = dupprintf("Unable to use key file \"%.150s\""
8062 filename_to_str(s->keyfile),
8063 key_type_to_str(keytype));
8064 c_write_str(ssh, msgbuf);
8066 s->publickey_blob = NULL;
8071 * Find out about any keys Pageant has (but if there's a
8072 * public key configured, filter out all others).
8075 s->agent_response = NULL;
8076 s->pkblob_in_agent = NULL;
8077 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
8081 logevent("Pageant is running. Requesting keys.");
8083 /* Request the keys held by the agent. */
8084 PUT_32BIT(s->agent_request, 1);
8085 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
8086 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
8087 ssh_agent_callback, ssh)) {
8091 bombout(("Unexpected data from server while"
8092 " waiting for agent response"));
8095 } while (pktin || inlen > 0);
8096 r = ssh->agent_response;
8097 s->agent_responselen = ssh->agent_response_len;
8099 s->agent_response = (unsigned char *) r;
8100 if (s->agent_response && s->agent_responselen >= 5 &&
8101 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
8104 p = s->agent_response + 5;
8105 s->nkeys = toint(GET_32BIT(p));
8108 * Vet the Pageant response to ensure that the key
8109 * count and blob lengths make sense.
8112 logeventf(ssh, "Pageant response contained a negative"
8113 " key count %d", s->nkeys);
8115 goto done_agent_query;
8117 unsigned char *q = p + 4;
8118 int lenleft = s->agent_responselen - 5 - 4;
8120 for (keyi = 0; keyi < s->nkeys; keyi++) {
8121 int bloblen, commentlen;
8123 logeventf(ssh, "Pageant response was truncated");
8125 goto done_agent_query;
8127 bloblen = toint(GET_32BIT(q));
8128 if (bloblen < 0 || bloblen > lenleft) {
8129 logeventf(ssh, "Pageant response was truncated");
8131 goto done_agent_query;
8133 lenleft -= 4 + bloblen;
8135 commentlen = toint(GET_32BIT(q));
8136 if (commentlen < 0 || commentlen > lenleft) {
8137 logeventf(ssh, "Pageant response was truncated");
8139 goto done_agent_query;
8141 lenleft -= 4 + commentlen;
8142 q += 4 + commentlen;
8147 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
8148 if (s->publickey_blob) {
8149 /* See if configured key is in agent. */
8150 for (keyi = 0; keyi < s->nkeys; keyi++) {
8151 s->pklen = toint(GET_32BIT(p));
8152 if (s->pklen == s->publickey_bloblen &&
8153 !memcmp(p+4, s->publickey_blob,
8154 s->publickey_bloblen)) {
8155 logeventf(ssh, "Pageant key #%d matches "
8156 "configured key file", keyi);
8158 s->pkblob_in_agent = p;
8162 p += toint(GET_32BIT(p)) + 4; /* comment */
8164 if (!s->pkblob_in_agent) {
8165 logevent("Configured key file not in Pageant");
8170 logevent("Failed to get reply from Pageant");
8178 * We repeat this whole loop, including the username prompt,
8179 * until we manage a successful authentication. If the user
8180 * types the wrong _password_, they can be sent back to the
8181 * beginning to try another username, if this is configured on.
8182 * (If they specify a username in the config, they are never
8183 * asked, even if they do give a wrong password.)
8185 * I think this best serves the needs of
8187 * - the people who have no configuration, no keys, and just
8188 * want to try repeated (username,password) pairs until they
8189 * type both correctly
8191 * - people who have keys and configuration but occasionally
8192 * need to fall back to passwords
8194 * - people with a key held in Pageant, who might not have
8195 * logged in to a particular machine before; so they want to
8196 * type a username, and then _either_ their key will be
8197 * accepted, _or_ they will type a password. If they mistype
8198 * the username they will want to be able to get back and
8201 s->got_username = FALSE;
8202 while (!s->we_are_in) {
8206 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
8208 * We got a username last time round this loop, and
8209 * with change_username turned off we don't try to get
8212 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
8213 int ret; /* need not be kept over crReturn */
8214 s->cur_prompt = new_prompts(ssh->frontend);
8215 s->cur_prompt->to_server = TRUE;
8216 s->cur_prompt->name = dupstr("SSH login name");
8217 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
8218 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8221 crWaitUntilV(!pktin);
8222 ret = get_userpass_input(s->cur_prompt, in, inlen);
8227 * get_userpass_input() failed to get a username.
8230 free_prompts(s->cur_prompt);
8231 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
8234 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
8235 free_prompts(s->cur_prompt);
8238 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
8239 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
8240 c_write_str(ssh, stuff);
8244 s->got_username = TRUE;
8247 * Send an authentication request using method "none": (a)
8248 * just in case it succeeds, and (b) so that we know what
8249 * authentication methods we can usefully try next.
8251 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8253 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8254 ssh2_pkt_addstring(s->pktout, ssh->username);
8255 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
8256 ssh2_pkt_addstring(s->pktout, "none"); /* method */
8257 ssh2_pkt_send(ssh, s->pktout);
8258 s->type = AUTH_TYPE_NONE;
8260 s->we_are_in = FALSE;
8262 s->tried_pubkey_config = FALSE;
8263 s->kbd_inter_refused = FALSE;
8265 /* Reset agent request state. */
8266 s->done_agent = FALSE;
8267 if (s->agent_response) {
8268 if (s->pkblob_in_agent) {
8269 s->agentp = s->pkblob_in_agent;
8271 s->agentp = s->agent_response + 5 + 4;
8277 char *methods = NULL;
8281 * Wait for the result of the last authentication request.
8284 crWaitUntilV(pktin);
8286 * Now is a convenient point to spew any banner material
8287 * that we've accumulated. (This should ensure that when
8288 * we exit the auth loop, we haven't any left to deal
8292 int size = bufchain_size(&ssh->banner);
8294 * Don't show the banner if we're operating in
8295 * non-verbose non-interactive mode. (It's probably
8296 * a script, which means nobody will read the
8297 * banner _anyway_, and moreover the printing of
8298 * the banner will screw up processing on the
8299 * output of (say) plink.)
8301 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
8302 char *banner = snewn(size, char);
8303 bufchain_fetch(&ssh->banner, banner, size);
8304 c_write_untrusted(ssh, banner, size);
8307 bufchain_clear(&ssh->banner);
8309 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
8310 logevent("Access granted");
8311 s->we_are_in = s->userauth_success = TRUE;
8315 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
8316 bombout(("Strange packet received during authentication: "
8317 "type %d", pktin->type));
8324 * OK, we're now sitting on a USERAUTH_FAILURE message, so
8325 * we can look at the string in it and know what we can
8326 * helpfully try next.
8328 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
8329 ssh_pkt_getstring(pktin, &methods, &methlen);
8330 if (!ssh2_pkt_getbool(pktin)) {
8332 * We have received an unequivocal Access
8333 * Denied. This can translate to a variety of
8334 * messages, or no message at all.
8336 * For forms of authentication which are attempted
8337 * implicitly, by which I mean without printing
8338 * anything in the window indicating that we're
8339 * trying them, we should never print 'Access
8342 * If we do print a message saying that we're
8343 * attempting some kind of authentication, it's OK
8344 * to print a followup message saying it failed -
8345 * but the message may sometimes be more specific
8346 * than simply 'Access denied'.
8348 * Additionally, if we'd just tried password
8349 * authentication, we should break out of this
8350 * whole loop so as to go back to the username
8351 * prompt (iff we're configured to allow
8352 * username change attempts).
8354 if (s->type == AUTH_TYPE_NONE) {
8356 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
8357 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
8358 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
8359 c_write_str(ssh, "Server refused our key\r\n");
8360 logevent("Server refused our key");
8361 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
8362 /* This _shouldn't_ happen except by a
8363 * protocol bug causing client and server to
8364 * disagree on what is a correct signature. */
8365 c_write_str(ssh, "Server refused public-key signature"
8366 " despite accepting key!\r\n");
8367 logevent("Server refused public-key signature"
8368 " despite accepting key!");
8369 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
8370 /* quiet, so no c_write */
8371 logevent("Server refused keyboard-interactive authentication");
8372 } else if (s->type==AUTH_TYPE_GSSAPI) {
8373 /* always quiet, so no c_write */
8374 /* also, the code down in the GSSAPI block has
8375 * already logged this in the Event Log */
8376 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
8377 logevent("Keyboard-interactive authentication failed");
8378 c_write_str(ssh, "Access denied\r\n");
8380 assert(s->type == AUTH_TYPE_PASSWORD);
8381 logevent("Password authentication failed");
8382 c_write_str(ssh, "Access denied\r\n");
8384 if (conf_get_int(ssh->conf, CONF_change_username)) {
8385 /* XXX perhaps we should allow
8386 * keyboard-interactive to do this too? */
8387 s->we_are_in = FALSE;
8392 c_write_str(ssh, "Further authentication required\r\n");
8393 logevent("Further authentication required");
8397 in_commasep_string("publickey", methods, methlen);
8399 in_commasep_string("password", methods, methlen);
8400 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
8401 in_commasep_string("keyboard-interactive", methods, methlen);
8404 ssh->gsslibs = ssh_gss_setup(ssh->conf);
8405 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
8406 in_commasep_string("gssapi-with-mic", methods, methlen) &&
8407 ssh->gsslibs->nlibraries > 0;
8411 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8413 if (s->can_pubkey && !s->done_agent && s->nkeys) {
8416 * Attempt public-key authentication using a key from Pageant.
8419 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8421 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
8423 /* Unpack key from agent response */
8424 s->pklen = toint(GET_32BIT(s->agentp));
8426 s->pkblob = (char *)s->agentp;
8427 s->agentp += s->pklen;
8428 s->alglen = toint(GET_32BIT(s->pkblob));
8429 s->alg = s->pkblob + 4;
8430 s->commentlen = toint(GET_32BIT(s->agentp));
8432 s->commentp = (char *)s->agentp;
8433 s->agentp += s->commentlen;
8434 /* s->agentp now points at next key, if any */
8436 /* See if server will accept it */
8437 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8438 ssh2_pkt_addstring(s->pktout, ssh->username);
8439 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8440 /* service requested */
8441 ssh2_pkt_addstring(s->pktout, "publickey");
8443 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
8444 ssh2_pkt_addstring_start(s->pktout);
8445 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
8446 ssh2_pkt_addstring_start(s->pktout);
8447 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
8448 ssh2_pkt_send(ssh, s->pktout);
8449 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
8451 crWaitUntilV(pktin);
8452 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8454 /* Offer of key refused. */
8461 if (flags & FLAG_VERBOSE) {
8462 c_write_str(ssh, "Authenticating with "
8464 c_write(ssh, s->commentp, s->commentlen);
8465 c_write_str(ssh, "\" from agent\r\n");
8469 * Server is willing to accept the key.
8470 * Construct a SIGN_REQUEST.
8472 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8473 ssh2_pkt_addstring(s->pktout, ssh->username);
8474 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8475 /* service requested */
8476 ssh2_pkt_addstring(s->pktout, "publickey");
8478 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
8479 ssh2_pkt_addstring_start(s->pktout);
8480 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
8481 ssh2_pkt_addstring_start(s->pktout);
8482 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
8484 /* Ask agent for signature. */
8485 s->siglen = s->pktout->length - 5 + 4 +
8486 ssh->v2_session_id_len;
8487 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8489 s->len = 1; /* message type */
8490 s->len += 4 + s->pklen; /* key blob */
8491 s->len += 4 + s->siglen; /* data to sign */
8492 s->len += 4; /* flags */
8493 s->agentreq = snewn(4 + s->len, char);
8494 PUT_32BIT(s->agentreq, s->len);
8495 s->q = s->agentreq + 4;
8496 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
8497 PUT_32BIT(s->q, s->pklen);
8499 memcpy(s->q, s->pkblob, s->pklen);
8501 PUT_32BIT(s->q, s->siglen);
8503 /* Now the data to be signed... */
8504 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8505 PUT_32BIT(s->q, ssh->v2_session_id_len);
8508 memcpy(s->q, ssh->v2_session_id,
8509 ssh->v2_session_id_len);
8510 s->q += ssh->v2_session_id_len;
8511 memcpy(s->q, s->pktout->data + 5,
8512 s->pktout->length - 5);
8513 s->q += s->pktout->length - 5;
8514 /* And finally the (zero) flags word. */
8516 if (!agent_query(s->agentreq, s->len + 4,
8518 ssh_agent_callback, ssh)) {
8522 bombout(("Unexpected data from server"
8523 " while waiting for agent"
8527 } while (pktin || inlen > 0);
8528 vret = ssh->agent_response;
8529 s->retlen = ssh->agent_response_len;
8534 if (s->retlen >= 9 &&
8535 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
8536 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
8537 logevent("Sending Pageant's response");
8538 ssh2_add_sigblob(ssh, s->pktout,
8539 s->pkblob, s->pklen,
8541 GET_32BIT(s->ret + 5));
8542 ssh2_pkt_send(ssh, s->pktout);
8543 s->type = AUTH_TYPE_PUBLICKEY;
8545 /* FIXME: less drastic response */
8546 bombout(("Pageant failed to answer challenge"));
8552 /* Do we have any keys left to try? */
8553 if (s->pkblob_in_agent) {
8554 s->done_agent = TRUE;
8555 s->tried_pubkey_config = TRUE;
8558 if (s->keyi >= s->nkeys)
8559 s->done_agent = TRUE;
8562 } else if (s->can_pubkey && s->publickey_blob &&
8563 !s->tried_pubkey_config) {
8565 struct ssh2_userkey *key; /* not live over crReturn */
8566 char *passphrase; /* not live over crReturn */
8568 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8570 s->tried_pubkey_config = TRUE;
8573 * Try the public key supplied in the configuration.
8575 * First, offer the public blob to see if the server is
8576 * willing to accept it.
8578 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8579 ssh2_pkt_addstring(s->pktout, ssh->username);
8580 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8581 /* service requested */
8582 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
8583 ssh2_pkt_addbool(s->pktout, FALSE);
8584 /* no signature included */
8585 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
8586 ssh2_pkt_addstring_start(s->pktout);
8587 ssh2_pkt_addstring_data(s->pktout,
8588 (char *)s->publickey_blob,
8589 s->publickey_bloblen);
8590 ssh2_pkt_send(ssh, s->pktout);
8591 logevent("Offered public key");
8593 crWaitUntilV(pktin);
8594 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8595 /* Key refused. Give up. */
8596 s->gotit = TRUE; /* reconsider message next loop */
8597 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
8598 continue; /* process this new message */
8600 logevent("Offer of public key accepted");
8603 * Actually attempt a serious authentication using
8606 if (flags & FLAG_VERBOSE) {
8607 c_write_str(ssh, "Authenticating with public key \"");
8608 c_write_str(ssh, s->publickey_comment);
8609 c_write_str(ssh, "\"\r\n");
8613 const char *error; /* not live over crReturn */
8614 if (s->publickey_encrypted) {
8616 * Get a passphrase from the user.
8618 int ret; /* need not be kept over crReturn */
8619 s->cur_prompt = new_prompts(ssh->frontend);
8620 s->cur_prompt->to_server = FALSE;
8621 s->cur_prompt->name = dupstr("SSH key passphrase");
8622 add_prompt(s->cur_prompt,
8623 dupprintf("Passphrase for key \"%.100s\": ",
8624 s->publickey_comment),
8626 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8629 crWaitUntilV(!pktin);
8630 ret = get_userpass_input(s->cur_prompt,
8635 /* Failed to get a passphrase. Terminate. */
8636 free_prompts(s->cur_prompt);
8637 ssh_disconnect(ssh, NULL,
8638 "Unable to authenticate",
8639 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8644 dupstr(s->cur_prompt->prompts[0]->result);
8645 free_prompts(s->cur_prompt);
8647 passphrase = NULL; /* no passphrase needed */
8651 * Try decrypting the key.
8653 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8654 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
8656 /* burn the evidence */
8657 smemclr(passphrase, strlen(passphrase));
8660 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
8662 (key == SSH2_WRONG_PASSPHRASE)) {
8663 c_write_str(ssh, "Wrong passphrase\r\n");
8665 /* and loop again */
8667 c_write_str(ssh, "Unable to load private key (");
8668 c_write_str(ssh, error);
8669 c_write_str(ssh, ")\r\n");
8671 break; /* try something else */
8677 unsigned char *pkblob, *sigblob, *sigdata;
8678 int pkblob_len, sigblob_len, sigdata_len;
8682 * We have loaded the private key and the server
8683 * has announced that it's willing to accept it.
8684 * Hallelujah. Generate a signature and send it.
8686 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8687 ssh2_pkt_addstring(s->pktout, ssh->username);
8688 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8689 /* service requested */
8690 ssh2_pkt_addstring(s->pktout, "publickey");
8692 ssh2_pkt_addbool(s->pktout, TRUE);
8693 /* signature follows */
8694 ssh2_pkt_addstring(s->pktout, key->alg->name);
8695 pkblob = key->alg->public_blob(key->data,
8697 ssh2_pkt_addstring_start(s->pktout);
8698 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
8702 * The data to be signed is:
8706 * followed by everything so far placed in the
8709 sigdata_len = s->pktout->length - 5 + 4 +
8710 ssh->v2_session_id_len;
8711 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8713 sigdata = snewn(sigdata_len, unsigned char);
8715 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8716 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
8719 memcpy(sigdata+p, ssh->v2_session_id,
8720 ssh->v2_session_id_len);
8721 p += ssh->v2_session_id_len;
8722 memcpy(sigdata+p, s->pktout->data + 5,
8723 s->pktout->length - 5);
8724 p += s->pktout->length - 5;
8725 assert(p == sigdata_len);
8726 sigblob = key->alg->sign(key->data, (char *)sigdata,
8727 sigdata_len, &sigblob_len);
8728 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
8729 sigblob, sigblob_len);
8734 ssh2_pkt_send(ssh, s->pktout);
8735 logevent("Sent public key signature");
8736 s->type = AUTH_TYPE_PUBLICKEY;
8737 key->alg->freekey(key->data);
8741 } else if (s->can_gssapi && !s->tried_gssapi) {
8743 /* GSSAPI Authentication */
8748 s->type = AUTH_TYPE_GSSAPI;
8749 s->tried_gssapi = TRUE;
8751 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
8754 * Pick the highest GSS library on the preference
8760 for (i = 0; i < ngsslibs; i++) {
8761 int want_id = conf_get_int_int(ssh->conf,
8762 CONF_ssh_gsslist, i);
8763 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
8764 if (ssh->gsslibs->libraries[j].id == want_id) {
8765 s->gsslib = &ssh->gsslibs->libraries[j];
8766 goto got_gsslib; /* double break */
8771 * We always expect to have found something in
8772 * the above loop: we only came here if there
8773 * was at least one viable GSS library, and the
8774 * preference list should always mention
8775 * everything and only change the order.
8780 if (s->gsslib->gsslogmsg)
8781 logevent(s->gsslib->gsslogmsg);
8783 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8784 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8785 ssh2_pkt_addstring(s->pktout, ssh->username);
8786 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8787 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
8788 logevent("Attempting GSSAPI authentication");
8790 /* add mechanism info */
8791 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
8793 /* number of GSSAPI mechanisms */
8794 ssh2_pkt_adduint32(s->pktout,1);
8796 /* length of OID + 2 */
8797 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
8798 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
8801 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
8803 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
8805 ssh2_pkt_send(ssh, s->pktout);
8806 crWaitUntilV(pktin);
8807 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
8808 logevent("GSSAPI authentication request refused");
8812 /* check returned packet ... */
8814 ssh_pkt_getstring(pktin, &data, &len);
8815 s->gss_rcvtok.value = data;
8816 s->gss_rcvtok.length = len;
8817 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
8818 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
8819 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8820 memcmp((char *)s->gss_rcvtok.value + 2,
8821 s->gss_buf.value,s->gss_buf.length) ) {
8822 logevent("GSSAPI authentication - wrong response from server");
8826 /* now start running */
8827 s->gss_stat = s->gsslib->import_name(s->gsslib,
8830 if (s->gss_stat != SSH_GSS_OK) {
8831 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8832 logevent("GSSAPI import name failed - Bad service name");
8834 logevent("GSSAPI import name failed");
8838 /* fetch TGT into GSS engine */
8839 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
8841 if (s->gss_stat != SSH_GSS_OK) {
8842 logevent("GSSAPI authentication failed to get credentials");
8843 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8847 /* initial tokens are empty */
8848 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
8849 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
8851 /* now enter the loop */
8853 s->gss_stat = s->gsslib->init_sec_context
8857 conf_get_int(ssh->conf, CONF_gssapifwd),
8861 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8862 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8863 logevent("GSSAPI authentication initialisation failed");
8865 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8866 &s->gss_buf) == SSH_GSS_OK) {
8867 logevent(s->gss_buf.value);
8868 sfree(s->gss_buf.value);
8873 logevent("GSSAPI authentication initialised");
8875 /* Client and server now exchange tokens until GSSAPI
8876 * no longer says CONTINUE_NEEDED */
8878 if (s->gss_sndtok.length != 0) {
8879 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8880 ssh_pkt_addstring_start(s->pktout);
8881 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8882 ssh2_pkt_send(ssh, s->pktout);
8883 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
8886 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8887 crWaitUntilV(pktin);
8888 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8889 logevent("GSSAPI authentication - bad server response");
8890 s->gss_stat = SSH_GSS_FAILURE;
8893 ssh_pkt_getstring(pktin, &data, &len);
8894 s->gss_rcvtok.value = data;
8895 s->gss_rcvtok.length = len;
8897 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8899 if (s->gss_stat != SSH_GSS_OK) {
8900 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8901 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8904 logevent("GSSAPI authentication loop finished OK");
8906 /* Now send the MIC */
8908 s->pktout = ssh2_pkt_init(0);
8909 micoffset = s->pktout->length;
8910 ssh_pkt_addstring_start(s->pktout);
8911 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8912 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8913 ssh_pkt_addstring(s->pktout, ssh->username);
8914 ssh_pkt_addstring(s->pktout, "ssh-connection");
8915 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8917 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8918 s->gss_buf.length = s->pktout->length - micoffset;
8920 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
8921 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8922 ssh_pkt_addstring_start(s->pktout);
8923 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8924 ssh2_pkt_send(ssh, s->pktout);
8925 s->gsslib->free_mic(s->gsslib, &mic);
8929 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8930 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8933 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8936 * Keyboard-interactive authentication.
8939 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8941 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8943 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8944 ssh2_pkt_addstring(s->pktout, ssh->username);
8945 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8946 /* service requested */
8947 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8949 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8950 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8951 ssh2_pkt_send(ssh, s->pktout);
8953 logevent("Attempting keyboard-interactive authentication");
8955 crWaitUntilV(pktin);
8956 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8957 /* Server is not willing to do keyboard-interactive
8958 * at all (or, bizarrely but legally, accepts the
8959 * user without actually issuing any prompts).
8960 * Give up on it entirely. */
8962 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8963 s->kbd_inter_refused = TRUE; /* don't try it again */
8968 * Loop while the server continues to send INFO_REQUESTs.
8970 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8972 char *name, *inst, *lang;
8973 int name_len, inst_len, lang_len;
8977 * We've got a fresh USERAUTH_INFO_REQUEST.
8978 * Get the preamble and start building a prompt.
8980 ssh_pkt_getstring(pktin, &name, &name_len);
8981 ssh_pkt_getstring(pktin, &inst, &inst_len);
8982 ssh_pkt_getstring(pktin, &lang, &lang_len);
8983 s->cur_prompt = new_prompts(ssh->frontend);
8984 s->cur_prompt->to_server = TRUE;
8987 * Get any prompt(s) from the packet.
8989 s->num_prompts = ssh_pkt_getuint32(pktin);
8990 for (i = 0; i < s->num_prompts; i++) {
8994 static char noprompt[] =
8995 "<server failed to send prompt>: ";
8997 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8998 echo = ssh2_pkt_getbool(pktin);
9001 prompt_len = lenof(noprompt)-1;
9003 add_prompt(s->cur_prompt,
9004 dupprintf("%.*s", prompt_len, prompt),
9009 /* FIXME: better prefix to distinguish from
9011 s->cur_prompt->name =
9012 dupprintf("SSH server: %.*s", name_len, name);
9013 s->cur_prompt->name_reqd = TRUE;
9015 s->cur_prompt->name =
9016 dupstr("SSH server authentication");
9017 s->cur_prompt->name_reqd = FALSE;
9019 /* We add a prefix to try to make it clear that a prompt
9020 * has come from the server.
9021 * FIXME: ugly to print "Using..." in prompt _every_
9022 * time round. Can this be done more subtly? */
9023 /* Special case: for reasons best known to themselves,
9024 * some servers send k-i requests with no prompts and
9025 * nothing to display. Keep quiet in this case. */
9026 if (s->num_prompts || name_len || inst_len) {
9027 s->cur_prompt->instruction =
9028 dupprintf("Using keyboard-interactive authentication.%s%.*s",
9029 inst_len ? "\n" : "", inst_len, inst);
9030 s->cur_prompt->instr_reqd = TRUE;
9032 s->cur_prompt->instr_reqd = FALSE;
9036 * Display any instructions, and get the user's
9040 int ret; /* not live over crReturn */
9041 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9044 crWaitUntilV(!pktin);
9045 ret = get_userpass_input(s->cur_prompt, in, inlen);
9050 * Failed to get responses. Terminate.
9052 free_prompts(s->cur_prompt);
9053 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9054 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9061 * Send the response(s) to the server.
9063 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
9064 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
9065 for (i=0; i < s->num_prompts; i++) {
9066 ssh2_pkt_addstring(s->pktout,
9067 s->cur_prompt->prompts[i]->result);
9069 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9072 * Free the prompts structure from this iteration.
9073 * If there's another, a new one will be allocated
9074 * when we return to the top of this while loop.
9076 free_prompts(s->cur_prompt);
9079 * Get the next packet in case it's another
9082 crWaitUntilV(pktin);
9087 * We should have SUCCESS or FAILURE now.
9091 } else if (s->can_passwd) {
9094 * Plain old password authentication.
9096 int ret; /* not live over crReturn */
9097 int changereq_first_time; /* not live over crReturn */
9099 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
9101 s->cur_prompt = new_prompts(ssh->frontend);
9102 s->cur_prompt->to_server = TRUE;
9103 s->cur_prompt->name = dupstr("SSH password");
9104 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
9109 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9112 crWaitUntilV(!pktin);
9113 ret = get_userpass_input(s->cur_prompt, in, inlen);
9118 * Failed to get responses. Terminate.
9120 free_prompts(s->cur_prompt);
9121 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9122 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9127 * Squirrel away the password. (We may need it later if
9128 * asked to change it.)
9130 s->password = dupstr(s->cur_prompt->prompts[0]->result);
9131 free_prompts(s->cur_prompt);
9134 * Send the password packet.
9136 * We pad out the password packet to 256 bytes to make
9137 * it harder for an attacker to find the length of the
9140 * Anyone using a password longer than 256 bytes
9141 * probably doesn't have much to worry about from
9142 * people who find out how long their password is!
9144 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9145 ssh2_pkt_addstring(s->pktout, ssh->username);
9146 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9147 /* service requested */
9148 ssh2_pkt_addstring(s->pktout, "password");
9149 ssh2_pkt_addbool(s->pktout, FALSE);
9150 ssh2_pkt_addstring(s->pktout, s->password);
9151 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9152 logevent("Sent password");
9153 s->type = AUTH_TYPE_PASSWORD;
9156 * Wait for next packet, in case it's a password change
9159 crWaitUntilV(pktin);
9160 changereq_first_time = TRUE;
9162 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
9165 * We're being asked for a new password
9166 * (perhaps not for the first time).
9167 * Loop until the server accepts it.
9170 int got_new = FALSE; /* not live over crReturn */
9171 char *prompt; /* not live over crReturn */
9172 int prompt_len; /* not live over crReturn */
9176 if (changereq_first_time)
9177 msg = "Server requested password change";
9179 msg = "Server rejected new password";
9181 c_write_str(ssh, msg);
9182 c_write_str(ssh, "\r\n");
9185 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9187 s->cur_prompt = new_prompts(ssh->frontend);
9188 s->cur_prompt->to_server = TRUE;
9189 s->cur_prompt->name = dupstr("New SSH password");
9190 s->cur_prompt->instruction =
9191 dupprintf("%.*s", prompt_len, prompt);
9192 s->cur_prompt->instr_reqd = TRUE;
9194 * There's no explicit requirement in the protocol
9195 * for the "old" passwords in the original and
9196 * password-change messages to be the same, and
9197 * apparently some Cisco kit supports password change
9198 * by the user entering a blank password originally
9199 * and the real password subsequently, so,
9200 * reluctantly, we prompt for the old password again.
9202 * (On the other hand, some servers don't even bother
9203 * to check this field.)
9205 add_prompt(s->cur_prompt,
9206 dupstr("Current password (blank for previously entered password): "),
9208 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
9210 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
9214 * Loop until the user manages to enter the same
9219 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9222 crWaitUntilV(!pktin);
9223 ret = get_userpass_input(s->cur_prompt, in, inlen);
9228 * Failed to get responses. Terminate.
9230 /* burn the evidence */
9231 free_prompts(s->cur_prompt);
9232 smemclr(s->password, strlen(s->password));
9234 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9235 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9241 * If the user specified a new original password
9242 * (IYSWIM), overwrite any previously specified
9244 * (A side effect is that the user doesn't have to
9245 * re-enter it if they louse up the new password.)
9247 if (s->cur_prompt->prompts[0]->result[0]) {
9248 smemclr(s->password, strlen(s->password));
9249 /* burn the evidence */
9252 dupstr(s->cur_prompt->prompts[0]->result);
9256 * Check the two new passwords match.
9258 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
9259 s->cur_prompt->prompts[2]->result)
9262 /* They don't. Silly user. */
9263 c_write_str(ssh, "Passwords do not match\r\n");
9268 * Send the new password (along with the old one).
9269 * (see above for padding rationale)
9271 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9272 ssh2_pkt_addstring(s->pktout, ssh->username);
9273 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9274 /* service requested */
9275 ssh2_pkt_addstring(s->pktout, "password");
9276 ssh2_pkt_addbool(s->pktout, TRUE);
9277 ssh2_pkt_addstring(s->pktout, s->password);
9278 ssh2_pkt_addstring(s->pktout,
9279 s->cur_prompt->prompts[1]->result);
9280 free_prompts(s->cur_prompt);
9281 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9282 logevent("Sent new password");
9285 * Now see what the server has to say about it.
9286 * (If it's CHANGEREQ again, it's not happy with the
9289 crWaitUntilV(pktin);
9290 changereq_first_time = FALSE;
9295 * We need to reexamine the current pktin at the top
9296 * of the loop. Either:
9297 * - we weren't asked to change password at all, in
9298 * which case it's a SUCCESS or FAILURE with the
9300 * - we sent a new password, and the server was
9301 * either OK with it (SUCCESS or FAILURE w/partial
9302 * success) or unhappy with the _old_ password
9303 * (FAILURE w/o partial success)
9304 * In any of these cases, we go back to the top of
9305 * the loop and start again.
9310 * We don't need the old password any more, in any
9311 * case. Burn the evidence.
9313 smemclr(s->password, strlen(s->password));
9317 char *str = dupprintf("No supported authentication methods available"
9318 " (server sent: %.*s)",
9321 ssh_disconnect(ssh, str,
9322 "No supported authentication methods available",
9323 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
9333 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9335 /* Clear up various bits and pieces from authentication. */
9336 if (s->publickey_blob) {
9337 sfree(s->publickey_blob);
9338 sfree(s->publickey_comment);
9340 if (s->agent_response)
9341 sfree(s->agent_response);
9343 if (s->userauth_success) {
9345 * We've just received USERAUTH_SUCCESS, and we haven't sent any
9346 * packets since. Signal the transport layer to consider enacting
9347 * delayed compression.
9349 * (Relying on we_are_in is not sufficient, as
9350 * draft-miller-secsh-compression-delayed is quite clear that it
9351 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
9352 * become set for other reasons.)
9354 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
9358 * Now the connection protocol has started, one way or another.
9361 ssh->channels = newtree234(ssh_channelcmp);
9364 * Set up handlers for some connection protocol messages, so we
9365 * don't have to handle them repeatedly in this coroutine.
9367 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
9368 ssh2_msg_channel_window_adjust;
9369 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
9370 ssh2_msg_global_request;
9373 * Create the main session channel.
9375 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
9376 ssh->mainchan = NULL;
9378 ssh->mainchan = snew(struct ssh_channel);
9379 ssh->mainchan->ssh = ssh;
9380 ssh2_channel_init(ssh->mainchan);
9382 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
9384 * Just start a direct-tcpip channel and use it as the main
9387 ssh_send_port_open(ssh->mainchan,
9388 conf_get_str(ssh->conf, CONF_ssh_nc_host),
9389 conf_get_int(ssh->conf, CONF_ssh_nc_port),
9393 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
9394 logevent("Opening session as main channel");
9395 ssh2_pkt_send(ssh, s->pktout);
9396 ssh->ncmode = FALSE;
9398 crWaitUntilV(pktin);
9399 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
9400 bombout(("Server refused to open channel"));
9402 /* FIXME: error data comes back in FAILURE packet */
9404 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
9405 bombout(("Server's channel confirmation cited wrong channel"));
9408 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
9409 ssh->mainchan->halfopen = FALSE;
9410 ssh->mainchan->type = CHAN_MAINSESSION;
9411 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
9412 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
9413 add234(ssh->channels, ssh->mainchan);
9414 update_specials_menu(ssh->frontend);
9415 logevent("Opened main channel");
9419 * Now we have a channel, make dispatch table entries for
9420 * general channel-based messages.
9422 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
9423 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
9424 ssh2_msg_channel_data;
9425 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
9426 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
9427 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
9428 ssh2_msg_channel_open_confirmation;
9429 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
9430 ssh2_msg_channel_open_failure;
9431 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
9432 ssh2_msg_channel_request;
9433 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
9434 ssh2_msg_channel_open;
9435 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
9436 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
9439 if (ssh->mainchan && conf_get_int(ssh->conf, CONF_ssh_simple)) {
9441 * This message indicates to the server that we promise
9442 * not to try to run any other channel in parallel with
9443 * this one, so it's safe for it to advertise a very large
9444 * window and leave the flow control to TCP.
9446 s->pktout = ssh2_chanreq_init(ssh->mainchan,
9447 "simple@putty.projects.tartarus.org",
9449 ssh2_pkt_send(ssh, s->pktout);
9453 * Enable port forwardings.
9455 ssh_setup_portfwd(ssh, ssh->conf);
9457 if (ssh->mainchan && !ssh->ncmode) {
9459 * Send the CHANNEL_REQUESTS for the main session channel.
9460 * Each one is handled by its own little asynchronous
9464 /* Potentially enable X11 forwarding. */
9465 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
9467 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
9469 if (!ssh->x11disp) {
9470 /* FIXME: return an error message from x11_setup_display */
9471 logevent("X11 forwarding not enabled: unable to"
9472 " initialise X display");
9474 ssh->x11auth = x11_invent_fake_auth
9475 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
9476 ssh->x11auth->disp = ssh->x11disp;
9478 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
9482 /* Potentially enable agent forwarding. */
9483 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists())
9484 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
9486 /* Now allocate a pty for the session. */
9487 if (!conf_get_int(ssh->conf, CONF_nopty))
9488 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
9490 /* Send environment variables. */
9491 ssh2_setup_env(ssh->mainchan, NULL, NULL);
9494 * Start a shell or a remote command. We may have to attempt
9495 * this twice if the config data has provided a second choice
9502 if (ssh->fallback_cmd) {
9503 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
9504 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
9506 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
9507 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
9511 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
9512 ssh2_response_authconn, NULL);
9513 ssh2_pkt_addstring(s->pktout, cmd);
9515 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
9516 ssh2_response_authconn, NULL);
9517 ssh2_pkt_addstring(s->pktout, cmd);
9519 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
9520 ssh2_response_authconn, NULL);
9522 ssh2_pkt_send(ssh, s->pktout);
9524 crWaitUntilV(pktin);
9526 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9527 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9528 bombout(("Unexpected response to shell/command request:"
9529 " packet type %d", pktin->type));
9533 * We failed to start the command. If this is the
9534 * fallback command, we really are finished; if it's
9535 * not, and if the fallback command exists, try falling
9536 * back to it before complaining.
9538 if (!ssh->fallback_cmd &&
9539 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
9540 logevent("Primary command failed; attempting fallback");
9541 ssh->fallback_cmd = TRUE;
9544 bombout(("Server refused to start a shell/command"));
9547 logevent("Started a shell/command");
9552 ssh->editing = ssh->echoing = TRUE;
9555 ssh->state = SSH_STATE_SESSION;
9556 if (ssh->size_needed)
9557 ssh_size(ssh, ssh->term_width, ssh->term_height);
9558 if (ssh->eof_needed)
9559 ssh_special(ssh, TS_EOF);
9565 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
9570 s->try_send = FALSE;
9574 * _All_ the connection-layer packets we expect to
9575 * receive are now handled by the dispatch table.
9576 * Anything that reaches here must be bogus.
9579 bombout(("Strange packet received: type %d", pktin->type));
9581 } else if (ssh->mainchan) {
9583 * We have spare data. Add it to the channel buffer.
9585 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
9590 struct ssh_channel *c;
9592 * Try to send data on all channels if we can.
9594 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
9595 ssh2_try_send_and_unthrottle(ssh, c);
9603 * Handlers for SSH-2 messages that might arrive at any moment.
9605 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
9607 /* log reason code in disconnect message */
9611 reason = ssh_pkt_getuint32(pktin);
9612 ssh_pkt_getstring(pktin, &msg, &msglen);
9614 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
9615 buf = dupprintf("Received disconnect message (%s)",
9616 ssh2_disconnect_reasons[reason]);
9618 buf = dupprintf("Received disconnect message (unknown"
9619 " type %d)", reason);
9623 buf = dupprintf("Disconnection message text: %.*s",
9626 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9628 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
9629 ssh2_disconnect_reasons[reason] : "unknown",
9634 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
9636 /* log the debug message */
9640 /* XXX maybe we should actually take notice of the return value */
9641 ssh2_pkt_getbool(pktin);
9642 ssh_pkt_getstring(pktin, &msg, &msglen);
9644 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
9647 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
9649 do_ssh2_transport(ssh, NULL, 0, pktin);
9653 * Called if we receive a packet that isn't allowed by the protocol.
9654 * This only applies to packets whose meaning PuTTY understands.
9655 * Entirely unknown packets are handled below.
9657 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
9659 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
9660 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
9662 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
9666 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
9668 struct Packet *pktout;
9669 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
9670 ssh2_pkt_adduint32(pktout, pktin->sequence);
9672 * UNIMPLEMENTED messages MUST appear in the same order as the
9673 * messages they respond to. Hence, never queue them.
9675 ssh2_pkt_send_noqueue(ssh, pktout);
9679 * Handle the top-level SSH-2 protocol.
9681 static void ssh2_protocol_setup(Ssh ssh)
9686 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9688 for (i = 0; i < 256; i++)
9689 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9692 * Initially, we only accept transport messages (and a few generic
9693 * ones). do_ssh2_authconn will add more when it starts.
9694 * Messages that are understood but not currently acceptable go to
9695 * ssh2_msg_unexpected.
9697 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
9698 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
9699 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
9700 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
9701 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
9702 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
9703 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
9704 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
9705 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
9706 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
9707 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
9708 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
9709 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
9710 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
9711 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
9712 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
9713 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
9714 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
9715 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
9716 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
9717 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
9718 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
9719 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
9720 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
9721 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
9722 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
9723 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
9724 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
9725 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
9726 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
9727 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
9728 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
9729 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
9732 * These messages have a special handler from the start.
9734 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9735 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9736 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9739 static void ssh2_timer(void *ctx, unsigned long now)
9743 if (ssh->state == SSH_STATE_CLOSED)
9746 if (!ssh->kex_in_progress && conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
9747 now == ssh->next_rekey) {
9748 do_ssh2_transport(ssh, "timeout", -1, NULL);
9752 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9753 struct Packet *pktin)
9755 unsigned char *in = (unsigned char *)vin;
9756 if (ssh->state == SSH_STATE_CLOSED)
9760 ssh->incoming_data_size += pktin->encrypted_len;
9761 if (!ssh->kex_in_progress &&
9762 ssh->max_data_size != 0 &&
9763 ssh->incoming_data_size > ssh->max_data_size)
9764 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9768 ssh->packet_dispatch[pktin->type](ssh, pktin);
9769 else if (!ssh->protocol_initial_phase_done)
9770 do_ssh2_transport(ssh, in, inlen, pktin);
9772 do_ssh2_authconn(ssh, in, inlen, pktin);
9775 static void ssh_cache_conf_values(Ssh ssh)
9777 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
9781 * Called to set up the connection.
9783 * Returns an error message, or NULL on success.
9785 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9786 Conf *conf, char *host, int port, char **realhost,
9787 int nodelay, int keepalive)
9792 ssh = snew(struct ssh_tag);
9793 ssh->conf = conf_copy(conf);
9794 ssh_cache_conf_values(ssh);
9795 ssh->version = 0; /* when not ready yet */
9798 ssh->v1_cipher_ctx = NULL;
9799 ssh->crcda_ctx = NULL;
9800 ssh->cscipher = NULL;
9801 ssh->cs_cipher_ctx = NULL;
9802 ssh->sccipher = NULL;
9803 ssh->sc_cipher_ctx = NULL;
9805 ssh->cs_mac_ctx = NULL;
9807 ssh->sc_mac_ctx = NULL;
9809 ssh->cs_comp_ctx = NULL;
9811 ssh->sc_comp_ctx = NULL;
9813 ssh->kex_ctx = NULL;
9814 ssh->hostkey = NULL;
9815 ssh->hostkey_str = NULL;
9817 ssh->close_expected = FALSE;
9818 ssh->clean_exit = FALSE;
9819 ssh->state = SSH_STATE_PREPACKET;
9820 ssh->size_needed = FALSE;
9821 ssh->eof_needed = FALSE;
9824 ssh->deferred_send_data = NULL;
9825 ssh->deferred_len = 0;
9826 ssh->deferred_size = 0;
9827 ssh->fallback_cmd = 0;
9828 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9829 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9830 ssh->x11disp = NULL;
9831 ssh->x11auth = NULL;
9832 ssh->x11authtree = newtree234(x11_authcmp);
9833 ssh->v1_compressing = FALSE;
9834 ssh->v2_outgoing_sequence = 0;
9835 ssh->ssh1_rdpkt_crstate = 0;
9836 ssh->ssh2_rdpkt_crstate = 0;
9837 ssh->ssh_gotdata_crstate = 0;
9838 ssh->do_ssh1_connection_crstate = 0;
9839 ssh->do_ssh_init_state = NULL;
9840 ssh->do_ssh1_login_state = NULL;
9841 ssh->do_ssh2_transport_state = NULL;
9842 ssh->do_ssh2_authconn_state = NULL;
9845 ssh->mainchan = NULL;
9846 ssh->throttled_all = 0;
9847 ssh->v1_stdout_throttling = 0;
9849 ssh->queuelen = ssh->queuesize = 0;
9850 ssh->queueing = FALSE;
9851 ssh->qhead = ssh->qtail = NULL;
9852 ssh->deferred_rekey_reason = NULL;
9853 bufchain_init(&ssh->queued_incoming_data);
9854 ssh->frozen = FALSE;
9855 ssh->username = NULL;
9856 ssh->sent_console_eof = FALSE;
9857 ssh->got_pty = FALSE;
9859 *backend_handle = ssh;
9862 if (crypto_startup() == 0)
9863 return "Microsoft high encryption pack not installed!";
9866 ssh->frontend = frontend_handle;
9867 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
9868 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
9870 ssh->channels = NULL;
9871 ssh->rportfwds = NULL;
9872 ssh->portfwds = NULL;
9877 ssh->conn_throttle_count = 0;
9878 ssh->overall_bufsize = 0;
9879 ssh->fallback_cmd = 0;
9881 ssh->protocol = NULL;
9883 ssh->protocol_initial_phase_done = FALSE;
9887 ssh->incoming_data_size = ssh->outgoing_data_size =
9888 ssh->deferred_data_size = 0L;
9889 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9890 CONF_ssh_rekey_data));
9891 ssh->kex_in_progress = FALSE;
9894 ssh->gsslibs = NULL;
9897 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9906 static void ssh_free(void *handle)
9908 Ssh ssh = (Ssh) handle;
9909 struct ssh_channel *c;
9910 struct ssh_rportfwd *pf;
9911 struct X11FakeAuth *auth;
9913 if (ssh->v1_cipher_ctx)
9914 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9915 if (ssh->cs_cipher_ctx)
9916 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9917 if (ssh->sc_cipher_ctx)
9918 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9919 if (ssh->cs_mac_ctx)
9920 ssh->csmac->free_context(ssh->cs_mac_ctx);
9921 if (ssh->sc_mac_ctx)
9922 ssh->scmac->free_context(ssh->sc_mac_ctx);
9923 if (ssh->cs_comp_ctx) {
9925 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9927 zlib_compress_cleanup(ssh->cs_comp_ctx);
9929 if (ssh->sc_comp_ctx) {
9931 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9933 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9936 dh_cleanup(ssh->kex_ctx);
9937 sfree(ssh->savedhost);
9939 while (ssh->queuelen-- > 0)
9940 ssh_free_packet(ssh->queue[ssh->queuelen]);
9943 while (ssh->qhead) {
9944 struct queued_handler *qh = ssh->qhead;
9945 ssh->qhead = qh->next;
9948 ssh->qhead = ssh->qtail = NULL;
9950 if (ssh->channels) {
9951 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9954 if (c->u.x11.xconn != NULL)
9955 x11_close(c->u.x11.xconn);
9958 case CHAN_SOCKDATA_DORMANT:
9959 if (c->u.pfd.pf != NULL)
9960 pfd_close(c->u.pfd.pf);
9963 if (ssh->version == 2) {
9964 struct outstanding_channel_request *ocr, *nocr;
9965 ocr = c->v.v2.chanreq_head;
9967 ocr->handler(c, NULL, ocr->ctx);
9972 bufchain_clear(&c->v.v2.outbuffer);
9976 freetree234(ssh->channels);
9977 ssh->channels = NULL;
9980 if (ssh->rportfwds) {
9981 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9983 freetree234(ssh->rportfwds);
9984 ssh->rportfwds = NULL;
9986 sfree(ssh->deferred_send_data);
9988 x11_free_display(ssh->x11disp);
9989 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
9990 x11_free_fake_auth(auth);
9991 freetree234(ssh->x11authtree);
9992 sfree(ssh->do_ssh_init_state);
9993 sfree(ssh->do_ssh1_login_state);
9994 sfree(ssh->do_ssh2_transport_state);
9995 sfree(ssh->do_ssh2_authconn_state);
9998 sfree(ssh->fullhostname);
9999 sfree(ssh->hostkey_str);
10000 if (ssh->crcda_ctx) {
10001 crcda_free_context(ssh->crcda_ctx);
10002 ssh->crcda_ctx = NULL;
10005 ssh_do_close(ssh, TRUE);
10006 expire_timer_context(ssh);
10008 pinger_free(ssh->pinger);
10009 bufchain_clear(&ssh->queued_incoming_data);
10010 sfree(ssh->username);
10011 conf_free(ssh->conf);
10014 ssh_gss_cleanup(ssh->gsslibs);
10022 * Reconfigure the SSH backend.
10024 static void ssh_reconfig(void *handle, Conf *conf)
10026 Ssh ssh = (Ssh) handle;
10027 char *rekeying = NULL, rekey_mandatory = FALSE;
10028 unsigned long old_max_data_size;
10031 pinger_reconfig(ssh->pinger, ssh->conf, conf);
10033 ssh_setup_portfwd(ssh, conf);
10035 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
10036 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
10038 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
10039 unsigned long now = GETTICKCOUNT();
10041 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
10042 rekeying = "timeout shortened";
10044 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
10048 old_max_data_size = ssh->max_data_size;
10049 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10050 CONF_ssh_rekey_data));
10051 if (old_max_data_size != ssh->max_data_size &&
10052 ssh->max_data_size != 0) {
10053 if (ssh->outgoing_data_size > ssh->max_data_size ||
10054 ssh->incoming_data_size > ssh->max_data_size)
10055 rekeying = "data limit lowered";
10058 if (conf_get_int(ssh->conf, CONF_compression) !=
10059 conf_get_int(conf, CONF_compression)) {
10060 rekeying = "compression setting changed";
10061 rekey_mandatory = TRUE;
10064 for (i = 0; i < CIPHER_MAX; i++)
10065 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
10066 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
10067 rekeying = "cipher settings changed";
10068 rekey_mandatory = TRUE;
10070 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
10071 conf_get_int(conf, CONF_ssh2_des_cbc)) {
10072 rekeying = "cipher settings changed";
10073 rekey_mandatory = TRUE;
10076 conf_free(ssh->conf);
10077 ssh->conf = conf_copy(conf);
10078 ssh_cache_conf_values(ssh);
10081 if (!ssh->kex_in_progress) {
10082 do_ssh2_transport(ssh, rekeying, -1, NULL);
10083 } else if (rekey_mandatory) {
10084 ssh->deferred_rekey_reason = rekeying;
10090 * Called to send data down the SSH connection.
10092 static int ssh_send(void *handle, char *buf, int len)
10094 Ssh ssh = (Ssh) handle;
10096 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10099 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
10101 return ssh_sendbuffer(ssh);
10105 * Called to query the current amount of buffered stdin data.
10107 static int ssh_sendbuffer(void *handle)
10109 Ssh ssh = (Ssh) handle;
10110 int override_value;
10112 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10116 * If the SSH socket itself has backed up, add the total backup
10117 * size on that to any individual buffer on the stdin channel.
10119 override_value = 0;
10120 if (ssh->throttled_all)
10121 override_value = ssh->overall_bufsize;
10123 if (ssh->version == 1) {
10124 return override_value;
10125 } else if (ssh->version == 2) {
10126 if (!ssh->mainchan)
10127 return override_value;
10129 return (override_value +
10130 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
10137 * Called to set the size of the window from SSH's POV.
10139 static void ssh_size(void *handle, int width, int height)
10141 Ssh ssh = (Ssh) handle;
10142 struct Packet *pktout;
10144 ssh->term_width = width;
10145 ssh->term_height = height;
10147 switch (ssh->state) {
10148 case SSH_STATE_BEFORE_SIZE:
10149 case SSH_STATE_PREPACKET:
10150 case SSH_STATE_CLOSED:
10151 break; /* do nothing */
10152 case SSH_STATE_INTERMED:
10153 ssh->size_needed = TRUE; /* buffer for later */
10155 case SSH_STATE_SESSION:
10156 if (!conf_get_int(ssh->conf, CONF_nopty)) {
10157 if (ssh->version == 1) {
10158 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
10159 PKT_INT, ssh->term_height,
10160 PKT_INT, ssh->term_width,
10161 PKT_INT, 0, PKT_INT, 0, PKT_END);
10162 } else if (ssh->mainchan) {
10163 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
10165 ssh2_pkt_adduint32(pktout, ssh->term_width);
10166 ssh2_pkt_adduint32(pktout, ssh->term_height);
10167 ssh2_pkt_adduint32(pktout, 0);
10168 ssh2_pkt_adduint32(pktout, 0);
10169 ssh2_pkt_send(ssh, pktout);
10177 * Return a list of the special codes that make sense in this
10180 static const struct telnet_special *ssh_get_specials(void *handle)
10182 static const struct telnet_special ssh1_ignore_special[] = {
10183 {"IGNORE message", TS_NOP}
10185 static const struct telnet_special ssh2_ignore_special[] = {
10186 {"IGNORE message", TS_NOP},
10188 static const struct telnet_special ssh2_rekey_special[] = {
10189 {"Repeat key exchange", TS_REKEY},
10191 static const struct telnet_special ssh2_session_specials[] = {
10194 /* These are the signal names defined by RFC 4254.
10195 * They include all the ISO C signals, but are a subset of the POSIX
10196 * required signals. */
10197 {"SIGINT (Interrupt)", TS_SIGINT},
10198 {"SIGTERM (Terminate)", TS_SIGTERM},
10199 {"SIGKILL (Kill)", TS_SIGKILL},
10200 {"SIGQUIT (Quit)", TS_SIGQUIT},
10201 {"SIGHUP (Hangup)", TS_SIGHUP},
10202 {"More signals", TS_SUBMENU},
10203 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
10204 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
10205 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
10206 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
10207 {NULL, TS_EXITMENU}
10209 static const struct telnet_special specials_end[] = {
10210 {NULL, TS_EXITMENU}
10212 /* XXX review this length for any changes: */
10213 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
10214 lenof(ssh2_rekey_special) +
10215 lenof(ssh2_session_specials) +
10216 lenof(specials_end)];
10217 Ssh ssh = (Ssh) handle;
10219 #define ADD_SPECIALS(name) \
10221 assert((i + lenof(name)) <= lenof(ssh_specials)); \
10222 memcpy(&ssh_specials[i], name, sizeof name); \
10223 i += lenof(name); \
10226 if (ssh->version == 1) {
10227 /* Don't bother offering IGNORE if we've decided the remote
10228 * won't cope with it, since we wouldn't bother sending it if
10230 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10231 ADD_SPECIALS(ssh1_ignore_special);
10232 } else if (ssh->version == 2) {
10233 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
10234 ADD_SPECIALS(ssh2_ignore_special);
10235 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
10236 ADD_SPECIALS(ssh2_rekey_special);
10238 ADD_SPECIALS(ssh2_session_specials);
10239 } /* else we're not ready yet */
10242 ADD_SPECIALS(specials_end);
10243 return ssh_specials;
10247 #undef ADD_SPECIALS
10251 * Send special codes. TS_EOF is useful for `plink', so you
10252 * can send an EOF and collect resulting output (e.g. `plink
10255 static void ssh_special(void *handle, Telnet_Special code)
10257 Ssh ssh = (Ssh) handle;
10258 struct Packet *pktout;
10260 if (code == TS_EOF) {
10261 if (ssh->state != SSH_STATE_SESSION) {
10263 * Buffer the EOF in case we are pre-SESSION, so we can
10264 * send it as soon as we reach SESSION.
10266 if (code == TS_EOF)
10267 ssh->eof_needed = TRUE;
10270 if (ssh->version == 1) {
10271 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
10272 } else if (ssh->mainchan) {
10273 sshfwd_write_eof(ssh->mainchan);
10274 ssh->send_ok = 0; /* now stop trying to read from stdin */
10276 logevent("Sent EOF message");
10277 } else if (code == TS_PING || code == TS_NOP) {
10278 if (ssh->state == SSH_STATE_CLOSED
10279 || ssh->state == SSH_STATE_PREPACKET) return;
10280 if (ssh->version == 1) {
10281 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10282 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
10284 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
10285 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
10286 ssh2_pkt_addstring_start(pktout);
10287 ssh2_pkt_send_noqueue(ssh, pktout);
10290 } else if (code == TS_REKEY) {
10291 if (!ssh->kex_in_progress && ssh->version == 2) {
10292 do_ssh2_transport(ssh, "at user request", -1, NULL);
10294 } else if (code == TS_BRK) {
10295 if (ssh->state == SSH_STATE_CLOSED
10296 || ssh->state == SSH_STATE_PREPACKET) return;
10297 if (ssh->version == 1) {
10298 logevent("Unable to send BREAK signal in SSH-1");
10299 } else if (ssh->mainchan) {
10300 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
10301 ssh2_pkt_adduint32(pktout, 0); /* default break length */
10302 ssh2_pkt_send(ssh, pktout);
10305 /* Is is a POSIX signal? */
10306 char *signame = NULL;
10307 if (code == TS_SIGABRT) signame = "ABRT";
10308 if (code == TS_SIGALRM) signame = "ALRM";
10309 if (code == TS_SIGFPE) signame = "FPE";
10310 if (code == TS_SIGHUP) signame = "HUP";
10311 if (code == TS_SIGILL) signame = "ILL";
10312 if (code == TS_SIGINT) signame = "INT";
10313 if (code == TS_SIGKILL) signame = "KILL";
10314 if (code == TS_SIGPIPE) signame = "PIPE";
10315 if (code == TS_SIGQUIT) signame = "QUIT";
10316 if (code == TS_SIGSEGV) signame = "SEGV";
10317 if (code == TS_SIGTERM) signame = "TERM";
10318 if (code == TS_SIGUSR1) signame = "USR1";
10319 if (code == TS_SIGUSR2) signame = "USR2";
10320 /* The SSH-2 protocol does in principle support arbitrary named
10321 * signals, including signame@domain, but we don't support those. */
10323 /* It's a signal. */
10324 if (ssh->version == 2 && ssh->mainchan) {
10325 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
10326 ssh2_pkt_addstring(pktout, signame);
10327 ssh2_pkt_send(ssh, pktout);
10328 logeventf(ssh, "Sent signal SIG%s", signame);
10331 /* Never heard of it. Do nothing */
10336 void *new_sock_channel(void *handle, struct PortForwarding *pf)
10338 Ssh ssh = (Ssh) handle;
10339 struct ssh_channel *c;
10340 c = snew(struct ssh_channel);
10343 ssh2_channel_init(c);
10344 c->halfopen = TRUE;
10345 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
10347 add234(ssh->channels, c);
10352 * This is called when stdout/stderr (the entity to which
10353 * from_backend sends data) manages to clear some backlog.
10355 static void ssh_unthrottle(void *handle, int bufsize)
10357 Ssh ssh = (Ssh) handle;
10360 if (ssh->version == 1) {
10361 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
10362 ssh->v1_stdout_throttling = 0;
10363 ssh_throttle_conn(ssh, -1);
10366 if (ssh->mainchan) {
10367 ssh2_set_window(ssh->mainchan,
10368 bufsize < ssh->mainchan->v.v2.locmaxwin ?
10369 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
10370 if (conf_get_int(ssh->conf, CONF_ssh_simple))
10373 buflimit = ssh->mainchan->v.v2.locmaxwin;
10374 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
10375 ssh->mainchan->throttling_conn = 0;
10376 ssh_throttle_conn(ssh, -1);
10382 * Now process any SSH connection data that was stashed in our
10383 * queue while we were frozen.
10385 ssh_process_queued_incoming_data(ssh);
10388 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
10390 struct ssh_channel *c = (struct ssh_channel *)channel;
10392 struct Packet *pktout;
10394 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
10396 if (ssh->version == 1) {
10397 send_packet(ssh, SSH1_MSG_PORT_OPEN,
10398 PKT_INT, c->localid,
10401 /* PKT_STR, <org:orgport>, */
10404 pktout = ssh2_chanopen_init(c, "direct-tcpip");
10405 ssh2_pkt_addstring(pktout, hostname);
10406 ssh2_pkt_adduint32(pktout, port);
10408 * We make up values for the originator data; partly it's
10409 * too much hassle to keep track, and partly I'm not
10410 * convinced the server should be told details like that
10411 * about my local network configuration.
10412 * The "originator IP address" is syntactically a numeric
10413 * IP address, and some servers (e.g., Tectia) get upset
10414 * if it doesn't match this syntax.
10416 ssh2_pkt_addstring(pktout, "0.0.0.0");
10417 ssh2_pkt_adduint32(pktout, 0);
10418 ssh2_pkt_send(ssh, pktout);
10422 static int ssh_connected(void *handle)
10424 Ssh ssh = (Ssh) handle;
10425 return ssh->s != NULL;
10428 static int ssh_sendok(void *handle)
10430 Ssh ssh = (Ssh) handle;
10431 return ssh->send_ok;
10434 static int ssh_ldisc(void *handle, int option)
10436 Ssh ssh = (Ssh) handle;
10437 if (option == LD_ECHO)
10438 return ssh->echoing;
10439 if (option == LD_EDIT)
10440 return ssh->editing;
10444 static void ssh_provide_ldisc(void *handle, void *ldisc)
10446 Ssh ssh = (Ssh) handle;
10447 ssh->ldisc = ldisc;
10450 static void ssh_provide_logctx(void *handle, void *logctx)
10452 Ssh ssh = (Ssh) handle;
10453 ssh->logctx = logctx;
10456 static int ssh_return_exitcode(void *handle)
10458 Ssh ssh = (Ssh) handle;
10459 if (ssh->s != NULL)
10462 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
10466 * cfg_info for SSH is the currently running version of the
10467 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
10469 static int ssh_cfg_info(void *handle)
10471 Ssh ssh = (Ssh) handle;
10472 return ssh->version;
10476 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
10477 * that fails. This variable is the means by which scp.c can reach
10478 * into the SSH code and find out which one it got.
10480 extern int ssh_fallback_cmd(void *handle)
10482 Ssh ssh = (Ssh) handle;
10483 return ssh->fallback_cmd;
10486 Backend ssh_backend = {
10496 ssh_return_exitcode,
10500 ssh_provide_logctx,