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");
4890 c = snew(struct ssh_channel);
4893 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
4894 c->remoteid = remoteid;
4895 c->halfopen = FALSE;
4896 c->localid = alloc_channel_id(ssh);
4898 c->pending_eof = FALSE;
4899 c->throttling_conn = 0;
4900 c->type = CHAN_X11; /* identify channel type */
4901 add234(ssh->channels, c);
4902 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4903 PKT_INT, c->remoteid, PKT_INT,
4904 c->localid, PKT_END);
4905 logevent("Opened X11 forward channel");
4909 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4911 /* Remote side is trying to open a channel to talk to our
4912 * agent. Give them back a local channel number. */
4913 struct ssh_channel *c;
4914 int remoteid = ssh_pkt_getuint32(pktin);
4916 /* Refuse if agent forwarding is disabled. */
4917 if (!ssh->agentfwd_enabled) {
4918 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4919 PKT_INT, remoteid, PKT_END);
4921 c = snew(struct ssh_channel);
4923 c->remoteid = remoteid;
4924 c->halfopen = FALSE;
4925 c->localid = alloc_channel_id(ssh);
4927 c->pending_eof = FALSE;
4928 c->throttling_conn = 0;
4929 c->type = CHAN_AGENT; /* identify channel type */
4930 c->u.a.lensofar = 0;
4931 c->u.a.message = NULL;
4932 c->u.a.outstanding_requests = 0;
4933 add234(ssh->channels, c);
4934 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4935 PKT_INT, c->remoteid, PKT_INT, c->localid,
4940 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4942 /* Remote side is trying to open a channel to talk to a
4943 * forwarded port. Give them back a local channel number. */
4944 struct ssh_rportfwd pf, *pfp;
4950 remoteid = ssh_pkt_getuint32(pktin);
4951 ssh_pkt_getstring(pktin, &host, &hostsize);
4952 port = ssh_pkt_getuint32(pktin);
4954 pf.dhost = dupprintf(".*s", hostsize, host);
4956 pfp = find234(ssh->rportfwds, &pf, NULL);
4959 logeventf(ssh, "Rejected remote port open request for %s:%d",
4961 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4962 PKT_INT, remoteid, PKT_END);
4964 struct ssh_channel *c = snew(struct ssh_channel);
4967 logeventf(ssh, "Received remote port open request for %s:%d",
4969 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
4970 c, ssh->conf, pfp->pfrec->addressfamily);
4972 logeventf(ssh, "Port open failed: %s", err);
4975 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4976 PKT_INT, remoteid, PKT_END);
4978 c->remoteid = remoteid;
4979 c->halfopen = FALSE;
4980 c->localid = alloc_channel_id(ssh);
4982 c->pending_eof = FALSE;
4983 c->throttling_conn = 0;
4984 c->type = CHAN_SOCKDATA; /* identify channel type */
4985 add234(ssh->channels, c);
4986 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4987 PKT_INT, c->remoteid, PKT_INT,
4988 c->localid, PKT_END);
4989 logevent("Forwarded port opened successfully");
4996 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4998 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4999 unsigned int localid = ssh_pkt_getuint32(pktin);
5000 struct ssh_channel *c;
5002 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5003 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5004 c->remoteid = localid;
5005 c->halfopen = FALSE;
5006 c->type = CHAN_SOCKDATA;
5007 c->throttling_conn = 0;
5008 pfd_confirm(c->u.pfd.pf);
5011 if (c && c->pending_eof) {
5013 * We have a pending close on this channel,
5014 * which we decided on before the server acked
5015 * the channel open. So now we know the
5016 * remoteid, we can close it again.
5018 ssh_channel_try_eof(c);
5022 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5024 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5025 struct ssh_channel *c;
5027 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5028 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5029 logevent("Forwarded connection refused by server");
5030 pfd_close(c->u.pfd.pf);
5031 del234(ssh->channels, c);
5036 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5038 /* Remote side closes a channel. */
5039 unsigned i = ssh_pkt_getuint32(pktin);
5040 struct ssh_channel *c;
5041 c = find234(ssh->channels, &i, ssh_channelfind);
5042 if (c && !c->halfopen) {
5044 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5045 !(c->closes & CLOSES_RCVD_EOF)) {
5047 * Received CHANNEL_CLOSE, which we translate into
5050 int send_close = FALSE;
5052 c->closes |= CLOSES_RCVD_EOF;
5057 x11_send_eof(c->u.x11.xconn);
5063 pfd_send_eof(c->u.pfd.pf);
5072 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5073 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5075 c->closes |= CLOSES_SENT_EOF;
5079 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5080 !(c->closes & CLOSES_RCVD_CLOSE)) {
5082 if (!(c->closes & CLOSES_SENT_EOF)) {
5083 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5084 " for which we never sent CHANNEL_CLOSE\n", i));
5087 c->closes |= CLOSES_RCVD_CLOSE;
5090 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5091 !(c->closes & CLOSES_SENT_CLOSE)) {
5092 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5093 PKT_INT, c->remoteid, PKT_END);
5094 c->closes |= CLOSES_SENT_CLOSE;
5097 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5098 ssh_channel_destroy(c);
5100 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5101 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5102 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5107 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5109 /* Data sent down one of our channels. */
5110 int i = ssh_pkt_getuint32(pktin);
5113 struct ssh_channel *c;
5115 ssh_pkt_getstring(pktin, &p, &len);
5117 c = find234(ssh->channels, &i, ssh_channelfind);
5122 bufsize = x11_send(c->u.x11.xconn, p, len);
5125 bufsize = pfd_send(c->u.pfd.pf, p, len);
5128 /* Data for an agent message. Buffer it. */
5130 if (c->u.a.lensofar < 4) {
5131 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5132 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5136 c->u.a.lensofar += l;
5138 if (c->u.a.lensofar == 4) {
5140 4 + GET_32BIT(c->u.a.msglen);
5141 c->u.a.message = snewn(c->u.a.totallen,
5143 memcpy(c->u.a.message, c->u.a.msglen, 4);
5145 if (c->u.a.lensofar >= 4 && len > 0) {
5147 min(c->u.a.totallen - c->u.a.lensofar,
5149 memcpy(c->u.a.message + c->u.a.lensofar, p,
5153 c->u.a.lensofar += l;
5155 if (c->u.a.lensofar == c->u.a.totallen) {
5158 c->u.a.outstanding_requests++;
5159 if (agent_query(c->u.a.message,
5162 ssh_agentf_callback, c))
5163 ssh_agentf_callback(c, reply, replylen);
5164 sfree(c->u.a.message);
5165 c->u.a.lensofar = 0;
5168 bufsize = 0; /* agent channels never back up */
5171 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5172 c->throttling_conn = 1;
5173 ssh_throttle_conn(ssh, +1);
5178 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5180 ssh->exitcode = ssh_pkt_getuint32(pktin);
5181 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5182 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5184 * In case `helpful' firewalls or proxies tack
5185 * extra human-readable text on the end of the
5186 * session which we might mistake for another
5187 * encrypted packet, we close the session once
5188 * we've sent EXIT_CONFIRMATION.
5190 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5193 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5194 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5196 struct Packet *pktout = (struct Packet *)data;
5198 unsigned int arg = 0;
5199 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5200 if (i == lenof(ssh_ttymodes)) return;
5201 switch (ssh_ttymodes[i].type) {
5203 arg = ssh_tty_parse_specchar(val);
5206 arg = ssh_tty_parse_boolean(val);
5209 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5210 ssh2_pkt_addbyte(pktout, arg);
5214 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5215 struct Packet *pktin)
5217 crBegin(ssh->do_ssh1_connection_crstate);
5219 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5220 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5221 ssh1_smsg_stdout_stderr_data;
5223 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5224 ssh1_msg_channel_open_confirmation;
5225 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5226 ssh1_msg_channel_open_failure;
5227 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5228 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5229 ssh1_msg_channel_close;
5230 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5231 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5233 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
5234 logevent("Requesting agent forwarding");
5235 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5239 if (pktin->type != SSH1_SMSG_SUCCESS
5240 && pktin->type != SSH1_SMSG_FAILURE) {
5241 bombout(("Protocol confusion"));
5243 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5244 logevent("Agent forwarding refused");
5246 logevent("Agent forwarding enabled");
5247 ssh->agentfwd_enabled = TRUE;
5248 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5252 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5254 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5256 if (!ssh->x11disp) {
5257 /* FIXME: return an error message from x11_setup_display */
5258 logevent("X11 forwarding not enabled: unable to"
5259 " initialise X display");
5261 ssh->x11auth = x11_invent_fake_auth
5262 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5263 ssh->x11auth->disp = ssh->x11disp;
5265 logevent("Requesting X11 forwarding");
5266 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5267 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5268 PKT_STR, ssh->x11auth->protoname,
5269 PKT_STR, ssh->x11auth->datastring,
5270 PKT_INT, ssh->x11disp->screennum,
5273 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5274 PKT_STR, ssh->x11auth->protoname,
5275 PKT_STR, ssh->x11auth->datastring,
5281 if (pktin->type != SSH1_SMSG_SUCCESS
5282 && pktin->type != SSH1_SMSG_FAILURE) {
5283 bombout(("Protocol confusion"));
5285 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5286 logevent("X11 forwarding refused");
5288 logevent("X11 forwarding enabled");
5289 ssh->X11_fwd_enabled = TRUE;
5290 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5295 ssh_setup_portfwd(ssh, ssh->conf);
5296 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5298 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5300 /* Unpick the terminal-speed string. */
5301 /* XXX perhaps we should allow no speeds to be sent. */
5302 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5303 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5304 /* Send the pty request. */
5305 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5306 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5307 ssh_pkt_adduint32(pkt, ssh->term_height);
5308 ssh_pkt_adduint32(pkt, ssh->term_width);
5309 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5310 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5311 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5312 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5313 ssh_pkt_adduint32(pkt, ssh->ispeed);
5314 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5315 ssh_pkt_adduint32(pkt, ssh->ospeed);
5316 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5318 ssh->state = SSH_STATE_INTERMED;
5322 if (pktin->type != SSH1_SMSG_SUCCESS
5323 && pktin->type != SSH1_SMSG_FAILURE) {
5324 bombout(("Protocol confusion"));
5326 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5327 c_write_str(ssh, "Server refused to allocate pty\r\n");
5328 ssh->editing = ssh->echoing = 1;
5330 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5331 ssh->ospeed, ssh->ispeed);
5332 ssh->got_pty = TRUE;
5335 ssh->editing = ssh->echoing = 1;
5338 if (conf_get_int(ssh->conf, CONF_compression)) {
5339 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5343 if (pktin->type != SSH1_SMSG_SUCCESS
5344 && pktin->type != SSH1_SMSG_FAILURE) {
5345 bombout(("Protocol confusion"));
5347 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5348 c_write_str(ssh, "Server refused to compress\r\n");
5350 logevent("Started compression");
5351 ssh->v1_compressing = TRUE;
5352 ssh->cs_comp_ctx = zlib_compress_init();
5353 logevent("Initialised zlib (RFC1950) compression");
5354 ssh->sc_comp_ctx = zlib_decompress_init();
5355 logevent("Initialised zlib (RFC1950) decompression");
5359 * Start the shell or command.
5361 * Special case: if the first-choice command is an SSH-2
5362 * subsystem (hence not usable here) and the second choice
5363 * exists, we fall straight back to that.
5366 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5368 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5369 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5370 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5371 ssh->fallback_cmd = TRUE;
5374 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5376 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5377 logevent("Started session");
5380 ssh->state = SSH_STATE_SESSION;
5381 if (ssh->size_needed)
5382 ssh_size(ssh, ssh->term_width, ssh->term_height);
5383 if (ssh->eof_needed)
5384 ssh_special(ssh, TS_EOF);
5387 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5389 ssh->channels = newtree234(ssh_channelcmp);
5393 * By this point, most incoming packets are already being
5394 * handled by the dispatch table, and we need only pay
5395 * attention to the unusual ones.
5400 if (pktin->type == SSH1_SMSG_SUCCESS) {
5401 /* may be from EXEC_SHELL on some servers */
5402 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5403 /* may be from EXEC_SHELL on some servers
5404 * if no pty is available or in other odd cases. Ignore */
5406 bombout(("Strange packet received: type %d", pktin->type));
5411 int len = min(inlen, 512);
5412 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5413 PKT_INT, len, PKT_DATA, in, len,
5425 * Handle the top-level SSH-2 protocol.
5427 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5432 ssh_pkt_getstring(pktin, &msg, &msglen);
5433 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5436 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5438 /* log reason code in disconnect message */
5442 ssh_pkt_getstring(pktin, &msg, &msglen);
5443 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5446 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5448 /* Do nothing, because we're ignoring it! Duhh. */
5451 static void ssh1_protocol_setup(Ssh ssh)
5456 * Most messages are handled by the coroutines.
5458 for (i = 0; i < 256; i++)
5459 ssh->packet_dispatch[i] = NULL;
5462 * These special message types we install handlers for.
5464 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5465 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5466 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5469 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5470 struct Packet *pktin)
5472 unsigned char *in=(unsigned char*)vin;
5473 if (ssh->state == SSH_STATE_CLOSED)
5476 if (pktin && ssh->packet_dispatch[pktin->type]) {
5477 ssh->packet_dispatch[pktin->type](ssh, pktin);
5481 if (!ssh->protocol_initial_phase_done) {
5482 if (do_ssh1_login(ssh, in, inlen, pktin))
5483 ssh->protocol_initial_phase_done = TRUE;
5488 do_ssh1_connection(ssh, in, inlen, pktin);
5492 * Utility routine for decoding comma-separated strings in KEXINIT.
5494 static int in_commasep_string(char *needle, char *haystack, int haylen)
5497 if (!needle || !haystack) /* protect against null pointers */
5499 needlen = strlen(needle);
5502 * Is it at the start of the string?
5504 if (haylen >= needlen && /* haystack is long enough */
5505 !memcmp(needle, haystack, needlen) && /* initial match */
5506 (haylen == needlen || haystack[needlen] == ',')
5507 /* either , or EOS follows */
5511 * If not, search for the next comma and resume after that.
5512 * If no comma found, terminate.
5514 while (haylen > 0 && *haystack != ',')
5515 haylen--, haystack++;
5518 haylen--, haystack++; /* skip over comma itself */
5523 * Similar routine for checking whether we have the first string in a list.
5525 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5528 if (!needle || !haystack) /* protect against null pointers */
5530 needlen = strlen(needle);
5532 * Is it at the start of the string?
5534 if (haylen >= needlen && /* haystack is long enough */
5535 !memcmp(needle, haystack, needlen) && /* initial match */
5536 (haylen == needlen || haystack[needlen] == ',')
5537 /* either , or EOS follows */
5545 * SSH-2 key creation method.
5546 * (Currently assumes 2 lots of any hash are sufficient to generate
5547 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5549 #define SSH2_MKKEY_ITERS (2)
5550 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5551 unsigned char *keyspace)
5553 const struct ssh_hash *h = ssh->kex->hash;
5555 /* First hlen bytes. */
5557 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5558 hash_mpint(h, s, K);
5559 h->bytes(s, H, h->hlen);
5560 h->bytes(s, &chr, 1);
5561 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5562 h->final(s, keyspace);
5563 /* Next hlen bytes. */
5565 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5566 hash_mpint(h, s, K);
5567 h->bytes(s, H, h->hlen);
5568 h->bytes(s, keyspace, h->hlen);
5569 h->final(s, keyspace + h->hlen);
5573 * Handle the SSH-2 transport layer.
5575 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5576 struct Packet *pktin)
5578 unsigned char *in = (unsigned char *)vin;
5579 struct do_ssh2_transport_state {
5581 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5582 Bignum p, g, e, f, K;
5585 int kex_init_value, kex_reply_value;
5586 const struct ssh_mac **maclist;
5588 const struct ssh2_cipher *cscipher_tobe;
5589 const struct ssh2_cipher *sccipher_tobe;
5590 const struct ssh_mac *csmac_tobe;
5591 const struct ssh_mac *scmac_tobe;
5592 const struct ssh_compress *cscomp_tobe;
5593 const struct ssh_compress *sccomp_tobe;
5594 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5595 int hostkeylen, siglen, rsakeylen;
5596 void *hkey; /* actual host key */
5597 void *rsakey; /* for RSA kex */
5598 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5599 int n_preferred_kex;
5600 const struct ssh_kexes *preferred_kex[KEX_MAX];
5601 int n_preferred_ciphers;
5602 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5603 const struct ssh_compress *preferred_comp;
5604 int userauth_succeeded; /* for delayed compression */
5605 int pending_compression;
5606 int got_session_id, activated_authconn;
5607 struct Packet *pktout;
5612 crState(do_ssh2_transport_state);
5616 s->cscipher_tobe = s->sccipher_tobe = NULL;
5617 s->csmac_tobe = s->scmac_tobe = NULL;
5618 s->cscomp_tobe = s->sccomp_tobe = NULL;
5620 s->got_session_id = s->activated_authconn = FALSE;
5621 s->userauth_succeeded = FALSE;
5622 s->pending_compression = FALSE;
5625 * Be prepared to work around the buggy MAC problem.
5627 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5628 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5630 s->maclist = macs, s->nmacs = lenof(macs);
5633 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5635 int i, j, k, commalist_started;
5638 * Set up the preferred key exchange. (NULL => warn below here)
5640 s->n_preferred_kex = 0;
5641 for (i = 0; i < KEX_MAX; i++) {
5642 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
5644 s->preferred_kex[s->n_preferred_kex++] =
5645 &ssh_diffiehellman_gex;
5648 s->preferred_kex[s->n_preferred_kex++] =
5649 &ssh_diffiehellman_group14;
5652 s->preferred_kex[s->n_preferred_kex++] =
5653 &ssh_diffiehellman_group1;
5656 s->preferred_kex[s->n_preferred_kex++] =
5660 /* Flag for later. Don't bother if it's the last in
5662 if (i < KEX_MAX - 1) {
5663 s->preferred_kex[s->n_preferred_kex++] = NULL;
5670 * Set up the preferred ciphers. (NULL => warn below here)
5672 s->n_preferred_ciphers = 0;
5673 for (i = 0; i < CIPHER_MAX; i++) {
5674 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
5675 case CIPHER_BLOWFISH:
5676 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5679 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
5680 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5684 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5687 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5689 case CIPHER_ARCFOUR:
5690 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5693 /* Flag for later. Don't bother if it's the last in
5695 if (i < CIPHER_MAX - 1) {
5696 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5703 * Set up preferred compression.
5705 if (conf_get_int(ssh->conf, CONF_compression))
5706 s->preferred_comp = &ssh_zlib;
5708 s->preferred_comp = &ssh_comp_none;
5711 * Enable queueing of outgoing auth- or connection-layer
5712 * packets while we are in the middle of a key exchange.
5714 ssh->queueing = TRUE;
5717 * Flag that KEX is in progress.
5719 ssh->kex_in_progress = TRUE;
5722 * Construct and send our key exchange packet.
5724 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5725 for (i = 0; i < 16; i++)
5726 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5727 /* List key exchange algorithms. */
5728 ssh2_pkt_addstring_start(s->pktout);
5729 commalist_started = 0;
5730 for (i = 0; i < s->n_preferred_kex; i++) {
5731 const struct ssh_kexes *k = s->preferred_kex[i];
5732 if (!k) continue; /* warning flag */
5733 for (j = 0; j < k->nkexes; j++) {
5734 if (commalist_started)
5735 ssh2_pkt_addstring_str(s->pktout, ",");
5736 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5737 commalist_started = 1;
5740 /* List server host key algorithms. */
5741 if (!s->got_session_id) {
5743 * In the first key exchange, we list all the algorithms
5744 * we're prepared to cope with.
5746 ssh2_pkt_addstring_start(s->pktout);
5747 for (i = 0; i < lenof(hostkey_algs); i++) {
5748 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5749 if (i < lenof(hostkey_algs) - 1)
5750 ssh2_pkt_addstring_str(s->pktout, ",");
5754 * In subsequent key exchanges, we list only the kex
5755 * algorithm that was selected in the first key exchange,
5756 * so that we keep getting the same host key and hence
5757 * don't have to interrupt the user's session to ask for
5761 ssh2_pkt_addstring(s->pktout, ssh->hostkey->name);
5763 /* List encryption algorithms (client->server then server->client). */
5764 for (k = 0; k < 2; k++) {
5765 ssh2_pkt_addstring_start(s->pktout);
5766 commalist_started = 0;
5767 for (i = 0; i < s->n_preferred_ciphers; i++) {
5768 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5769 if (!c) continue; /* warning flag */
5770 for (j = 0; j < c->nciphers; j++) {
5771 if (commalist_started)
5772 ssh2_pkt_addstring_str(s->pktout, ",");
5773 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5774 commalist_started = 1;
5778 /* List MAC algorithms (client->server then server->client). */
5779 for (j = 0; j < 2; j++) {
5780 ssh2_pkt_addstring_start(s->pktout);
5781 for (i = 0; i < s->nmacs; i++) {
5782 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5783 if (i < s->nmacs - 1)
5784 ssh2_pkt_addstring_str(s->pktout, ",");
5787 /* List client->server compression algorithms,
5788 * then server->client compression algorithms. (We use the
5789 * same set twice.) */
5790 for (j = 0; j < 2; j++) {
5791 ssh2_pkt_addstring_start(s->pktout);
5792 assert(lenof(compressions) > 1);
5793 /* Prefer non-delayed versions */
5794 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5795 /* We don't even list delayed versions of algorithms until
5796 * they're allowed to be used, to avoid a race. See the end of
5798 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
5799 ssh2_pkt_addstring_str(s->pktout, ",");
5800 ssh2_pkt_addstring_str(s->pktout,
5801 s->preferred_comp->delayed_name);
5803 for (i = 0; i < lenof(compressions); i++) {
5804 const struct ssh_compress *c = compressions[i];
5805 if (c != s->preferred_comp) {
5806 ssh2_pkt_addstring_str(s->pktout, ",");
5807 ssh2_pkt_addstring_str(s->pktout, c->name);
5808 if (s->userauth_succeeded && c->delayed_name) {
5809 ssh2_pkt_addstring_str(s->pktout, ",");
5810 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
5815 /* List client->server languages. Empty list. */
5816 ssh2_pkt_addstring_start(s->pktout);
5817 /* List server->client languages. Empty list. */
5818 ssh2_pkt_addstring_start(s->pktout);
5819 /* First KEX packet does _not_ follow, because we're not that brave. */
5820 ssh2_pkt_addbool(s->pktout, FALSE);
5822 ssh2_pkt_adduint32(s->pktout, 0);
5825 s->our_kexinitlen = s->pktout->length - 5;
5826 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5827 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5829 ssh2_pkt_send_noqueue(ssh, s->pktout);
5832 crWaitUntilV(pktin);
5835 * Now examine the other side's KEXINIT to see what we're up
5839 char *str, *preferred;
5842 if (pktin->type != SSH2_MSG_KEXINIT) {
5843 bombout(("expected key exchange packet from server"));
5847 ssh->hostkey = NULL;
5848 s->cscipher_tobe = NULL;
5849 s->sccipher_tobe = NULL;
5850 s->csmac_tobe = NULL;
5851 s->scmac_tobe = NULL;
5852 s->cscomp_tobe = NULL;
5853 s->sccomp_tobe = NULL;
5854 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5856 pktin->savedpos += 16; /* skip garbage cookie */
5857 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5860 for (i = 0; i < s->n_preferred_kex; i++) {
5861 const struct ssh_kexes *k = s->preferred_kex[i];
5865 for (j = 0; j < k->nkexes; j++) {
5866 if (!preferred) preferred = k->list[j]->name;
5867 if (in_commasep_string(k->list[j]->name, str, len)) {
5868 ssh->kex = k->list[j];
5877 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5878 str ? str : "(null)"));
5882 * Note that the server's guess is considered wrong if it doesn't match
5883 * the first algorithm in our list, even if it's still the algorithm
5886 s->guessok = first_in_commasep_string(preferred, str, len);
5887 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5888 for (i = 0; i < lenof(hostkey_algs); i++) {
5889 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5890 ssh->hostkey = hostkey_algs[i];
5894 if (!ssh->hostkey) {
5895 bombout(("Couldn't agree a host key algorithm (available: %s)",
5896 str ? str : "(null)"));
5900 s->guessok = s->guessok &&
5901 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5902 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5903 for (i = 0; i < s->n_preferred_ciphers; i++) {
5904 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5906 s->warn_cscipher = TRUE;
5908 for (j = 0; j < c->nciphers; j++) {
5909 if (in_commasep_string(c->list[j]->name, str, len)) {
5910 s->cscipher_tobe = c->list[j];
5915 if (s->cscipher_tobe)
5918 if (!s->cscipher_tobe) {
5919 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5920 str ? str : "(null)"));
5924 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5925 for (i = 0; i < s->n_preferred_ciphers; i++) {
5926 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5928 s->warn_sccipher = TRUE;
5930 for (j = 0; j < c->nciphers; j++) {
5931 if (in_commasep_string(c->list[j]->name, str, len)) {
5932 s->sccipher_tobe = c->list[j];
5937 if (s->sccipher_tobe)
5940 if (!s->sccipher_tobe) {
5941 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5942 str ? str : "(null)"));
5946 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5947 for (i = 0; i < s->nmacs; i++) {
5948 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5949 s->csmac_tobe = s->maclist[i];
5953 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5954 for (i = 0; i < s->nmacs; i++) {
5955 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5956 s->scmac_tobe = s->maclist[i];
5960 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5961 for (i = 0; i < lenof(compressions) + 1; i++) {
5962 const struct ssh_compress *c =
5963 i == 0 ? s->preferred_comp : compressions[i - 1];
5964 if (in_commasep_string(c->name, str, len)) {
5967 } else if (in_commasep_string(c->delayed_name, str, len)) {
5968 if (s->userauth_succeeded) {
5972 s->pending_compression = TRUE; /* try this later */
5976 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5977 for (i = 0; i < lenof(compressions) + 1; i++) {
5978 const struct ssh_compress *c =
5979 i == 0 ? s->preferred_comp : compressions[i - 1];
5980 if (in_commasep_string(c->name, str, len)) {
5983 } else if (in_commasep_string(c->delayed_name, str, len)) {
5984 if (s->userauth_succeeded) {
5988 s->pending_compression = TRUE; /* try this later */
5992 if (s->pending_compression) {
5993 logevent("Server supports delayed compression; "
5994 "will try this later");
5996 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5997 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5998 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6000 ssh->exhash = ssh->kex->hash->init();
6001 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6002 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6003 hash_string(ssh->kex->hash, ssh->exhash,
6004 s->our_kexinit, s->our_kexinitlen);
6005 sfree(s->our_kexinit);
6006 /* Include the type byte in the hash of server's KEXINIT */
6007 hash_string(ssh->kex->hash, ssh->exhash,
6008 pktin->body - 1, pktin->length + 1);
6011 ssh_set_frozen(ssh, 1);
6012 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6014 ssh_dialog_callback, ssh);
6015 if (s->dlgret < 0) {
6019 bombout(("Unexpected data from server while"
6020 " waiting for user response"));
6023 } while (pktin || inlen > 0);
6024 s->dlgret = ssh->user_response;
6026 ssh_set_frozen(ssh, 0);
6027 if (s->dlgret == 0) {
6028 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6034 if (s->warn_cscipher) {
6035 ssh_set_frozen(ssh, 1);
6036 s->dlgret = askalg(ssh->frontend,
6037 "client-to-server cipher",
6038 s->cscipher_tobe->name,
6039 ssh_dialog_callback, ssh);
6040 if (s->dlgret < 0) {
6044 bombout(("Unexpected data from server while"
6045 " waiting for user response"));
6048 } while (pktin || inlen > 0);
6049 s->dlgret = ssh->user_response;
6051 ssh_set_frozen(ssh, 0);
6052 if (s->dlgret == 0) {
6053 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6059 if (s->warn_sccipher) {
6060 ssh_set_frozen(ssh, 1);
6061 s->dlgret = askalg(ssh->frontend,
6062 "server-to-client cipher",
6063 s->sccipher_tobe->name,
6064 ssh_dialog_callback, ssh);
6065 if (s->dlgret < 0) {
6069 bombout(("Unexpected data from server while"
6070 " waiting for user response"));
6073 } while (pktin || inlen > 0);
6074 s->dlgret = ssh->user_response;
6076 ssh_set_frozen(ssh, 0);
6077 if (s->dlgret == 0) {
6078 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6084 if (s->ignorepkt) /* first_kex_packet_follows */
6085 crWaitUntilV(pktin); /* Ignore packet */
6088 if (ssh->kex->main_type == KEXTYPE_DH) {
6090 * Work out the number of bits of key we will need from the
6091 * key exchange. We start with the maximum key length of
6097 csbits = s->cscipher_tobe->keylen;
6098 scbits = s->sccipher_tobe->keylen;
6099 s->nbits = (csbits > scbits ? csbits : scbits);
6101 /* The keys only have hlen-bit entropy, since they're based on
6102 * a hash. So cap the key size at hlen bits. */
6103 if (s->nbits > ssh->kex->hash->hlen * 8)
6104 s->nbits = ssh->kex->hash->hlen * 8;
6107 * If we're doing Diffie-Hellman group exchange, start by
6108 * requesting a group.
6110 if (!ssh->kex->pdata) {
6111 logevent("Doing Diffie-Hellman group exchange");
6112 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6114 * Work out how big a DH group we will need to allow that
6117 s->pbits = 512 << ((s->nbits - 1) / 64);
6118 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6119 ssh2_pkt_adduint32(s->pktout, s->pbits);
6120 ssh2_pkt_send_noqueue(ssh, s->pktout);
6122 crWaitUntilV(pktin);
6123 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6124 bombout(("expected key exchange group packet from server"));
6127 s->p = ssh2_pkt_getmp(pktin);
6128 s->g = ssh2_pkt_getmp(pktin);
6129 if (!s->p || !s->g) {
6130 bombout(("unable to read mp-ints from incoming group packet"));
6133 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6134 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6135 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6137 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6138 ssh->kex_ctx = dh_setup_group(ssh->kex);
6139 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6140 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6141 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6142 ssh->kex->groupname);
6145 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6146 ssh->kex->hash->text_name);
6148 * Now generate and send e for Diffie-Hellman.
6150 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6151 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6152 s->pktout = ssh2_pkt_init(s->kex_init_value);
6153 ssh2_pkt_addmp(s->pktout, s->e);
6154 ssh2_pkt_send_noqueue(ssh, s->pktout);
6156 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6157 crWaitUntilV(pktin);
6158 if (pktin->type != s->kex_reply_value) {
6159 bombout(("expected key exchange reply packet from server"));
6162 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6163 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6164 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6165 s->f = ssh2_pkt_getmp(pktin);
6167 bombout(("unable to parse key exchange reply packet"));
6170 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6172 s->K = dh_find_K(ssh->kex_ctx, s->f);
6174 /* We assume everything from now on will be quick, and it might
6175 * involve user interaction. */
6176 set_busy_status(ssh->frontend, BUSY_NOT);
6178 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6179 if (!ssh->kex->pdata) {
6180 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6181 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6182 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6184 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6185 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6187 dh_cleanup(ssh->kex_ctx);
6189 if (!ssh->kex->pdata) {
6194 logeventf(ssh, "Doing RSA key exchange with hash %s",
6195 ssh->kex->hash->text_name);
6196 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6198 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6201 crWaitUntilV(pktin);
6202 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6203 bombout(("expected RSA public key packet from server"));
6207 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6208 hash_string(ssh->kex->hash, ssh->exhash,
6209 s->hostkeydata, s->hostkeylen);
6210 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6214 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6215 s->rsakeydata = snewn(s->rsakeylen, char);
6216 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6219 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6221 sfree(s->rsakeydata);
6222 bombout(("unable to parse RSA public key from server"));
6226 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6229 * Next, set up a shared secret K, of precisely KLEN -
6230 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6231 * RSA key modulus and HLEN is the bit length of the hash
6235 int klen = ssh_rsakex_klen(s->rsakey);
6236 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6238 unsigned char *kstr1, *kstr2, *outstr;
6239 int kstr1len, kstr2len, outstrlen;
6241 s->K = bn_power_2(nbits - 1);
6243 for (i = 0; i < nbits; i++) {
6245 byte = random_byte();
6247 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6251 * Encode this as an mpint.
6253 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6254 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6255 PUT_32BIT(kstr2, kstr1len);
6256 memcpy(kstr2 + 4, kstr1, kstr1len);
6259 * Encrypt it with the given RSA key.
6261 outstrlen = (klen + 7) / 8;
6262 outstr = snewn(outstrlen, unsigned char);
6263 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6264 outstr, outstrlen, s->rsakey);
6267 * And send it off in a return packet.
6269 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6270 ssh2_pkt_addstring_start(s->pktout);
6271 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6272 ssh2_pkt_send_noqueue(ssh, s->pktout);
6274 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6281 ssh_rsakex_freekey(s->rsakey);
6283 crWaitUntilV(pktin);
6284 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6285 sfree(s->rsakeydata);
6286 bombout(("expected signature packet from server"));
6290 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6292 sfree(s->rsakeydata);
6295 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6296 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6297 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6299 ssh->kex_ctx = NULL;
6302 debug(("Exchange hash is:\n"));
6303 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6307 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6308 (char *)s->exchange_hash,
6309 ssh->kex->hash->hlen)) {
6310 bombout(("Server's host key did not match the signature supplied"));
6314 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6315 if (!s->got_session_id) {
6317 * Authenticate remote host: verify host key. (We've already
6318 * checked the signature of the exchange hash.)
6320 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6321 ssh_set_frozen(ssh, 1);
6322 s->dlgret = verify_ssh_host_key(ssh->frontend,
6323 ssh->savedhost, ssh->savedport,
6324 ssh->hostkey->keytype, s->keystr,
6326 ssh_dialog_callback, ssh);
6327 if (s->dlgret < 0) {
6331 bombout(("Unexpected data from server while waiting"
6332 " for user host key response"));
6335 } while (pktin || inlen > 0);
6336 s->dlgret = ssh->user_response;
6338 ssh_set_frozen(ssh, 0);
6339 if (s->dlgret == 0) {
6340 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6344 logevent("Host key fingerprint is:");
6345 logevent(s->fingerprint);
6346 sfree(s->fingerprint);
6348 * Save this host key, to check against the one presented in
6349 * subsequent rekeys.
6351 ssh->hostkey_str = s->keystr;
6354 * In a rekey, we never present an interactive host key
6355 * verification request to the user. Instead, we simply
6356 * enforce that the key we're seeing this time is identical to
6357 * the one we saw before.
6359 if (strcmp(ssh->hostkey_str, s->keystr)) {
6360 bombout(("Host key was different in repeat key exchange"));
6365 ssh->hostkey->freekey(s->hkey);
6368 * The exchange hash from the very first key exchange is also
6369 * the session id, used in session key construction and
6372 if (!s->got_session_id) {
6373 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6374 memcpy(ssh->v2_session_id, s->exchange_hash,
6375 sizeof(s->exchange_hash));
6376 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6377 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6378 s->got_session_id = TRUE;
6382 * Send SSH2_MSG_NEWKEYS.
6384 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6385 ssh2_pkt_send_noqueue(ssh, s->pktout);
6386 ssh->outgoing_data_size = 0; /* start counting from here */
6389 * We've sent client NEWKEYS, so create and initialise
6390 * client-to-server session keys.
6392 if (ssh->cs_cipher_ctx)
6393 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6394 ssh->cscipher = s->cscipher_tobe;
6395 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6397 if (ssh->cs_mac_ctx)
6398 ssh->csmac->free_context(ssh->cs_mac_ctx);
6399 ssh->csmac = s->csmac_tobe;
6400 ssh->cs_mac_ctx = ssh->csmac->make_context();
6402 if (ssh->cs_comp_ctx)
6403 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6404 ssh->cscomp = s->cscomp_tobe;
6405 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6408 * Set IVs on client-to-server keys. Here we use the exchange
6409 * hash from the _first_ key exchange.
6412 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6413 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6414 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6415 assert((ssh->cscipher->keylen+7) / 8 <=
6416 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6417 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6418 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6419 assert(ssh->cscipher->blksize <=
6420 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6421 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6422 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6423 assert(ssh->csmac->len <=
6424 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6425 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6426 smemclr(keyspace, sizeof(keyspace));
6429 logeventf(ssh, "Initialised %.200s client->server encryption",
6430 ssh->cscipher->text_name);
6431 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6432 ssh->csmac->text_name);
6433 if (ssh->cscomp->text_name)
6434 logeventf(ssh, "Initialised %s compression",
6435 ssh->cscomp->text_name);
6438 * Now our end of the key exchange is complete, we can send all
6439 * our queued higher-layer packets.
6441 ssh->queueing = FALSE;
6442 ssh2_pkt_queuesend(ssh);
6445 * Expect SSH2_MSG_NEWKEYS from server.
6447 crWaitUntilV(pktin);
6448 if (pktin->type != SSH2_MSG_NEWKEYS) {
6449 bombout(("expected new-keys packet from server"));
6452 ssh->incoming_data_size = 0; /* start counting from here */
6455 * We've seen server NEWKEYS, so create and initialise
6456 * server-to-client session keys.
6458 if (ssh->sc_cipher_ctx)
6459 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6460 ssh->sccipher = s->sccipher_tobe;
6461 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6463 if (ssh->sc_mac_ctx)
6464 ssh->scmac->free_context(ssh->sc_mac_ctx);
6465 ssh->scmac = s->scmac_tobe;
6466 ssh->sc_mac_ctx = ssh->scmac->make_context();
6468 if (ssh->sc_comp_ctx)
6469 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6470 ssh->sccomp = s->sccomp_tobe;
6471 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6474 * Set IVs on server-to-client keys. Here we use the exchange
6475 * hash from the _first_ key exchange.
6478 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6479 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6480 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6481 assert((ssh->sccipher->keylen+7) / 8 <=
6482 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6483 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6484 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6485 assert(ssh->sccipher->blksize <=
6486 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6487 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6488 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6489 assert(ssh->scmac->len <=
6490 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6491 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6492 smemclr(keyspace, sizeof(keyspace));
6494 logeventf(ssh, "Initialised %.200s server->client encryption",
6495 ssh->sccipher->text_name);
6496 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6497 ssh->scmac->text_name);
6498 if (ssh->sccomp->text_name)
6499 logeventf(ssh, "Initialised %s decompression",
6500 ssh->sccomp->text_name);
6503 * Free shared secret.
6508 * Key exchange is over. Loop straight back round if we have a
6509 * deferred rekey reason.
6511 if (ssh->deferred_rekey_reason) {
6512 logevent(ssh->deferred_rekey_reason);
6514 ssh->deferred_rekey_reason = NULL;
6515 goto begin_key_exchange;
6519 * Otherwise, schedule a timer for our next rekey.
6521 ssh->kex_in_progress = FALSE;
6522 ssh->last_rekey = GETTICKCOUNT();
6523 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6524 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6528 * Now we're encrypting. Begin returning 1 to the protocol main
6529 * function so that other things can run on top of the
6530 * transport. If we ever see a KEXINIT, we must go back to the
6533 * We _also_ go back to the start if we see pktin==NULL and
6534 * inlen negative, because this is a special signal meaning
6535 * `initiate client-driven rekey', and `in' contains a message
6536 * giving the reason for the rekey.
6538 * inlen==-1 means always initiate a rekey;
6539 * inlen==-2 means that userauth has completed successfully and
6540 * we should consider rekeying (for delayed compression).
6542 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6543 (!pktin && inlen < 0))) {
6545 if (!ssh->protocol_initial_phase_done) {
6546 ssh->protocol_initial_phase_done = TRUE;
6548 * Allow authconn to initialise itself.
6550 do_ssh2_authconn(ssh, NULL, 0, NULL);
6555 logevent("Server initiated key re-exchange");
6559 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6560 * delayed compression, if it's available.
6562 * draft-miller-secsh-compression-delayed-00 says that you
6563 * negotiate delayed compression in the first key exchange, and
6564 * both sides start compressing when the server has sent
6565 * USERAUTH_SUCCESS. This has a race condition -- the server
6566 * can't know when the client has seen it, and thus which incoming
6567 * packets it should treat as compressed.
6569 * Instead, we do the initial key exchange without offering the
6570 * delayed methods, but note if the server offers them; when we
6571 * get here, if a delayed method was available that was higher
6572 * on our list than what we got, we initiate a rekey in which we
6573 * _do_ list the delayed methods (and hopefully get it as a
6574 * result). Subsequent rekeys will do the same.
6576 assert(!s->userauth_succeeded); /* should only happen once */
6577 s->userauth_succeeded = TRUE;
6578 if (!s->pending_compression)
6579 /* Can't see any point rekeying. */
6580 goto wait_for_rekey; /* this is utterly horrid */
6581 /* else fall through to rekey... */
6582 s->pending_compression = FALSE;
6585 * Now we've decided to rekey.
6587 * Special case: if the server bug is set that doesn't
6588 * allow rekeying, we give a different log message and
6589 * continue waiting. (If such a server _initiates_ a rekey,
6590 * we process it anyway!)
6592 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6593 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6595 /* Reset the counters, so that at least this message doesn't
6596 * hit the event log _too_ often. */
6597 ssh->outgoing_data_size = 0;
6598 ssh->incoming_data_size = 0;
6599 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
6601 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6604 goto wait_for_rekey; /* this is still utterly horrid */
6606 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6609 goto begin_key_exchange;
6615 * Add data to an SSH-2 channel output buffer.
6617 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6620 bufchain_add(&c->v.v2.outbuffer, buf, len);
6624 * Attempt to send data on an SSH-2 channel.
6626 static int ssh2_try_send(struct ssh_channel *c)
6629 struct Packet *pktout;
6632 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6635 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6636 if ((unsigned)len > c->v.v2.remwindow)
6637 len = c->v.v2.remwindow;
6638 if ((unsigned)len > c->v.v2.remmaxpkt)
6639 len = c->v.v2.remmaxpkt;
6640 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6641 ssh2_pkt_adduint32(pktout, c->remoteid);
6642 ssh2_pkt_addstring_start(pktout);
6643 ssh2_pkt_addstring_data(pktout, data, len);
6644 ssh2_pkt_send(ssh, pktout);
6645 bufchain_consume(&c->v.v2.outbuffer, len);
6646 c->v.v2.remwindow -= len;
6650 * After having sent as much data as we can, return the amount
6653 ret = bufchain_size(&c->v.v2.outbuffer);
6656 * And if there's no data pending but we need to send an EOF, send
6659 if (!ret && c->pending_eof)
6660 ssh_channel_try_eof(c);
6665 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
6668 if (c->closes & CLOSES_SENT_EOF)
6669 return; /* don't send on channels we've EOFed */
6670 bufsize = ssh2_try_send(c);
6673 case CHAN_MAINSESSION:
6674 /* stdin need not receive an unthrottle
6675 * notification since it will be polled */
6678 x11_unthrottle(c->u.x11.xconn);
6681 /* agent sockets are request/response and need no
6682 * buffer management */
6685 pfd_unthrottle(c->u.pfd.pf);
6692 * Set up most of a new ssh_channel for SSH-2.
6694 static void ssh2_channel_init(struct ssh_channel *c)
6697 c->localid = alloc_channel_id(ssh);
6699 c->pending_eof = FALSE;
6700 c->throttling_conn = FALSE;
6701 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6702 conf_get_int(ssh->conf, CONF_ssh_simple) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6703 c->v.v2.chanreq_head = NULL;
6704 c->v.v2.throttle_state = UNTHROTTLED;
6705 bufchain_init(&c->v.v2.outbuffer);
6709 * Construct the common parts of a CHANNEL_OPEN.
6711 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c, char *type)
6713 struct Packet *pktout;
6715 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
6716 ssh2_pkt_addstring(pktout, type);
6717 ssh2_pkt_adduint32(pktout, c->localid);
6718 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
6719 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
6724 * CHANNEL_FAILURE doesn't come with any indication of what message
6725 * caused it, so we have to keep track of the outstanding
6726 * CHANNEL_REQUESTs ourselves.
6728 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
6729 cchandler_fn_t handler, void *ctx)
6731 struct outstanding_channel_request *ocr =
6732 snew(struct outstanding_channel_request);
6734 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
6735 ocr->handler = handler;
6738 if (!c->v.v2.chanreq_head)
6739 c->v.v2.chanreq_head = ocr;
6741 c->v.v2.chanreq_tail->next = ocr;
6742 c->v.v2.chanreq_tail = ocr;
6746 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
6747 * NULL then a reply will be requested and the handler will be called
6748 * when it arrives. The returned packet is ready to have any
6749 * request-specific data added and be sent. Note that if a handler is
6750 * provided, it's essential that the request actually be sent.
6752 * The handler will usually be passed the response packet in pktin.
6753 * If pktin is NULL, this means that no reply will ever be forthcoming
6754 * (e.g. because the entire connection is being destroyed) and the
6755 * handler should free any storage it's holding.
6757 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c, char *type,
6758 cchandler_fn_t handler, void *ctx)
6760 struct Packet *pktout;
6762 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
6763 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6764 ssh2_pkt_adduint32(pktout, c->remoteid);
6765 ssh2_pkt_addstring(pktout, type);
6766 ssh2_pkt_addbool(pktout, handler != NULL);
6767 if (handler != NULL)
6768 ssh2_queue_chanreq_handler(c, handler, ctx);
6773 * Potentially enlarge the window on an SSH-2 channel.
6775 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
6777 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6782 * Never send WINDOW_ADJUST for a channel that the remote side has
6783 * already sent EOF on; there's no point, since it won't be
6784 * sending any more data anyway. Ditto if _we've_ already sent
6787 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6791 * If the remote end has a habit of ignoring maxpkt, limit the
6792 * window so that it has no choice (assuming it doesn't ignore the
6795 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6796 newwin = OUR_V2_MAXPKT;
6799 * Only send a WINDOW_ADJUST if there's significantly more window
6800 * available than the other end thinks there is. This saves us
6801 * sending a WINDOW_ADJUST for every character in a shell session.
6803 * "Significant" is arbitrarily defined as half the window size.
6805 if (newwin / 2 >= c->v.v2.locwindow) {
6806 struct Packet *pktout;
6810 * In order to keep track of how much window the client
6811 * actually has available, we'd like it to acknowledge each
6812 * WINDOW_ADJUST. We can't do that directly, so we accompany
6813 * it with a CHANNEL_REQUEST that has to be acknowledged.
6815 * This is only necessary if we're opening the window wide.
6816 * If we're not, then throughput is being constrained by
6817 * something other than the maximum window size anyway.
6819 if (newwin == c->v.v2.locmaxwin &&
6820 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
6821 up = snew(unsigned);
6822 *up = newwin - c->v.v2.locwindow;
6823 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
6824 ssh2_handle_winadj_response, up);
6825 ssh2_pkt_send(ssh, pktout);
6827 if (c->v.v2.throttle_state != UNTHROTTLED)
6828 c->v.v2.throttle_state = UNTHROTTLING;
6830 /* Pretend the WINDOW_ADJUST was acked immediately. */
6831 c->v.v2.remlocwin = newwin;
6832 c->v.v2.throttle_state = THROTTLED;
6834 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6835 ssh2_pkt_adduint32(pktout, c->remoteid);
6836 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6837 ssh2_pkt_send(ssh, pktout);
6838 c->v.v2.locwindow = newwin;
6843 * Find the channel associated with a message. If there's no channel,
6844 * or it's not properly open, make a noise about it and return NULL.
6846 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6848 unsigned localid = ssh_pkt_getuint32(pktin);
6849 struct ssh_channel *c;
6851 c = find234(ssh->channels, &localid, ssh_channelfind);
6853 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6854 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6855 char *buf = dupprintf("Received %s for %s channel %u",
6856 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6858 c ? "half-open" : "nonexistent", localid);
6859 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6866 static void ssh2_handle_winadj_response(struct ssh_channel *c,
6867 struct Packet *pktin, void *ctx)
6869 unsigned *sizep = ctx;
6872 * Winadj responses should always be failures. However, at least
6873 * one server ("boks_sshd") is known to return SUCCESS for channel
6874 * requests it's never heard of, such as "winadj@putty". Raised
6875 * with foxt.com as bug 090916-090424, but for the sake of a quiet
6876 * life, we don't worry about what kind of response we got.
6879 c->v.v2.remlocwin += *sizep;
6882 * winadj messages are only sent when the window is fully open, so
6883 * if we get an ack of one, we know any pending unthrottle is
6886 if (c->v.v2.throttle_state == UNTHROTTLING)
6887 c->v.v2.throttle_state = UNTHROTTLED;
6890 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
6892 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
6893 struct outstanding_channel_request *ocr;
6896 ocr = c->v.v2.chanreq_head;
6898 ssh2_msg_unexpected(ssh, pktin);
6901 ocr->handler(c, pktin, ocr->ctx);
6902 c->v.v2.chanreq_head = ocr->next;
6905 * We may now initiate channel-closing procedures, if that
6906 * CHANNEL_REQUEST was the last thing outstanding before we send
6909 ssh2_channel_check_close(c);
6912 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6914 struct ssh_channel *c;
6915 c = ssh2_channel_msg(ssh, pktin);
6918 if (!(c->closes & CLOSES_SENT_EOF)) {
6919 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6920 ssh2_try_send_and_unthrottle(ssh, c);
6924 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6928 struct ssh_channel *c;
6929 c = ssh2_channel_msg(ssh, pktin);
6932 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6933 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6934 return; /* extended but not stderr */
6935 ssh_pkt_getstring(pktin, &data, &length);
6938 c->v.v2.locwindow -= length;
6939 c->v.v2.remlocwin -= length;
6941 case CHAN_MAINSESSION:
6943 from_backend(ssh->frontend, pktin->type ==
6944 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6948 bufsize = x11_send(c->u.x11.xconn, data, length);
6951 bufsize = pfd_send(c->u.pfd.pf, data, length);
6954 while (length > 0) {
6955 if (c->u.a.lensofar < 4) {
6956 unsigned int l = min(4 - c->u.a.lensofar,
6958 memcpy(c->u.a.msglen + c->u.a.lensofar,
6962 c->u.a.lensofar += l;
6964 if (c->u.a.lensofar == 4) {
6966 4 + GET_32BIT(c->u.a.msglen);
6967 c->u.a.message = snewn(c->u.a.totallen,
6969 memcpy(c->u.a.message, c->u.a.msglen, 4);
6971 if (c->u.a.lensofar >= 4 && length > 0) {
6973 min(c->u.a.totallen - c->u.a.lensofar,
6975 memcpy(c->u.a.message + c->u.a.lensofar,
6979 c->u.a.lensofar += l;
6981 if (c->u.a.lensofar == c->u.a.totallen) {
6984 c->u.a.outstanding_requests++;
6985 if (agent_query(c->u.a.message,
6988 ssh_agentf_callback, c))
6989 ssh_agentf_callback(c, reply, replylen);
6990 sfree(c->u.a.message);
6991 c->u.a.message = NULL;
6992 c->u.a.lensofar = 0;
6999 * If it looks like the remote end hit the end of its window,
7000 * and we didn't want it to do that, think about using a
7003 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
7004 c->v.v2.locmaxwin < 0x40000000)
7005 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
7007 * If we are not buffering too much data,
7008 * enlarge the window again at the remote side.
7009 * If we are buffering too much, we may still
7010 * need to adjust the window if the server's
7013 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7014 c->v.v2.locmaxwin - bufsize : 0);
7016 * If we're either buffering way too much data, or if we're
7017 * buffering anything at all and we're in "simple" mode,
7018 * throttle the whole channel.
7020 if ((bufsize > c->v.v2.locmaxwin ||
7021 (conf_get_int(ssh->conf, CONF_ssh_simple) && bufsize > 0)) &&
7022 !c->throttling_conn) {
7023 c->throttling_conn = 1;
7024 ssh_throttle_conn(ssh, +1);
7029 static void ssh_channel_destroy(struct ssh_channel *c)
7034 case CHAN_MAINSESSION:
7035 ssh->mainchan = NULL;
7036 update_specials_menu(ssh->frontend);
7039 if (c->u.x11.xconn != NULL)
7040 x11_close(c->u.x11.xconn);
7041 logevent("Forwarded X11 connection terminated");
7044 sfree(c->u.a.message);
7047 if (c->u.pfd.pf != NULL)
7048 pfd_close(c->u.pfd.pf);
7049 logevent("Forwarded port closed");
7053 del234(ssh->channels, c);
7054 if (ssh->version == 2) {
7055 bufchain_clear(&c->v.v2.outbuffer);
7056 assert(c->v.v2.chanreq_head == NULL);
7061 * See if that was the last channel left open.
7062 * (This is only our termination condition if we're
7063 * not running in -N mode.)
7065 if (ssh->version == 2 &&
7066 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7067 count234(ssh->channels) == 0) {
7069 * We used to send SSH_MSG_DISCONNECT here,
7070 * because I'd believed that _every_ conforming
7071 * SSH-2 connection had to end with a disconnect
7072 * being sent by at least one side; apparently
7073 * I was wrong and it's perfectly OK to
7074 * unceremoniously slam the connection shut
7075 * when you're done, and indeed OpenSSH feels
7076 * this is more polite than sending a
7077 * DISCONNECT. So now we don't.
7079 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7083 static void ssh2_channel_check_close(struct ssh_channel *c)
7086 struct Packet *pktout;
7090 * If we've sent out our own CHANNEL_OPEN but not yet seen
7091 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
7092 * it's too early to be sending close messages of any kind.
7097 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
7098 c->type == CHAN_ZOMBIE) &&
7099 !c->v.v2.chanreq_head &&
7100 !(c->closes & CLOSES_SENT_CLOSE)) {
7102 * We have both sent and received EOF (or the channel is a
7103 * zombie), and we have no outstanding channel requests, which
7104 * means the channel is in final wind-up. But we haven't sent
7105 * CLOSE, so let's do so now.
7107 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
7108 ssh2_pkt_adduint32(pktout, c->remoteid);
7109 ssh2_pkt_send(ssh, pktout);
7110 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
7113 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
7114 assert(c->v.v2.chanreq_head == NULL);
7116 * We have both sent and received CLOSE, which means we're
7117 * completely done with the channel.
7119 ssh_channel_destroy(c);
7123 static void ssh2_channel_got_eof(struct ssh_channel *c)
7125 if (c->closes & CLOSES_RCVD_EOF)
7126 return; /* already seen EOF */
7127 c->closes |= CLOSES_RCVD_EOF;
7129 if (c->type == CHAN_X11) {
7130 x11_send_eof(c->u.x11.xconn);
7131 } else if (c->type == CHAN_AGENT) {
7132 if (c->u.a.outstanding_requests == 0) {
7133 /* Manufacture an outgoing EOF in response to the incoming one. */
7134 sshfwd_write_eof(c);
7136 } else if (c->type == CHAN_SOCKDATA) {
7137 pfd_send_eof(c->u.pfd.pf);
7138 } else if (c->type == CHAN_MAINSESSION) {
7141 if (!ssh->sent_console_eof &&
7142 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
7144 * Either from_backend_eof told us that the front end
7145 * wants us to close the outgoing side of the connection
7146 * as soon as we see EOF from the far end, or else we've
7147 * unilaterally decided to do that because we've allocated
7148 * a remote pty and hence EOF isn't a particularly
7149 * meaningful concept.
7151 sshfwd_write_eof(c);
7153 ssh->sent_console_eof = TRUE;
7156 ssh2_channel_check_close(c);
7159 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
7161 struct ssh_channel *c;
7163 c = ssh2_channel_msg(ssh, pktin);
7166 ssh2_channel_got_eof(c);
7169 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7171 struct ssh_channel *c;
7173 c = ssh2_channel_msg(ssh, pktin);
7178 * When we receive CLOSE on a channel, we assume it comes with an
7179 * implied EOF if we haven't seen EOF yet.
7181 ssh2_channel_got_eof(c);
7184 * And we also send an outgoing EOF, if we haven't already, on the
7185 * assumption that CLOSE is a pretty forceful announcement that
7186 * the remote side is doing away with the entire channel. (If it
7187 * had wanted to send us EOF and continue receiving data from us,
7188 * it would have just sent CHANNEL_EOF.)
7190 if (!(c->closes & CLOSES_SENT_EOF)) {
7192 * Make sure we don't read any more from whatever our local
7193 * data source is for this channel.
7196 case CHAN_MAINSESSION:
7197 ssh->send_ok = 0; /* stop trying to read from stdin */
7200 x11_override_throttle(c->u.x11.xconn, 1);
7203 pfd_override_throttle(c->u.pfd.pf, 1);
7208 * Abandon any buffered data we still wanted to send to this
7209 * channel. Receiving a CHANNEL_CLOSE is an indication that
7210 * the server really wants to get on and _destroy_ this
7211 * channel, and it isn't going to send us any further
7212 * WINDOW_ADJUSTs to permit us to send pending stuff.
7214 bufchain_clear(&c->v.v2.outbuffer);
7217 * Send outgoing EOF.
7219 sshfwd_write_eof(c);
7223 * Now process the actual close.
7225 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7226 c->closes |= CLOSES_RCVD_CLOSE;
7227 ssh2_channel_check_close(c);
7231 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7233 struct ssh_channel *c;
7235 c = ssh2_channel_msg(ssh, pktin);
7238 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7239 c->remoteid = ssh_pkt_getuint32(pktin);
7240 c->halfopen = FALSE;
7241 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7242 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7244 if (c->type == CHAN_SOCKDATA_DORMANT) {
7245 c->type = CHAN_SOCKDATA;
7247 pfd_confirm(c->u.pfd.pf);
7248 } else if (c->type == CHAN_ZOMBIE) {
7250 * This case can occur if a local socket error occurred
7251 * between us sending out CHANNEL_OPEN and receiving
7252 * OPEN_CONFIRMATION. In this case, all we can do is
7253 * immediately initiate close proceedings now that we know the
7254 * server's id to put in the close message.
7256 ssh2_channel_check_close(c);
7259 * We never expect to receive OPEN_CONFIRMATION for any
7260 * *other* channel type (since only local-to-remote port
7261 * forwardings cause us to send CHANNEL_OPEN after the main
7262 * channel is live - all other auxiliary channel types are
7263 * initiated from the server end). It's safe to enforce this
7264 * by assertion rather than by ssh_disconnect, because the
7265 * real point is that we never constructed a half-open channel
7266 * structure in the first place with any type other than the
7269 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
7273 ssh_channel_try_eof(c); /* in case we had a pending EOF */
7276 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7278 static const char *const reasons[] = {
7279 "<unknown reason code>",
7280 "Administratively prohibited",
7282 "Unknown channel type",
7283 "Resource shortage",
7285 unsigned reason_code;
7286 char *reason_string;
7288 struct ssh_channel *c;
7290 c = ssh2_channel_msg(ssh, pktin);
7293 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7295 if (c->type == CHAN_SOCKDATA_DORMANT) {
7296 reason_code = ssh_pkt_getuint32(pktin);
7297 if (reason_code >= lenof(reasons))
7298 reason_code = 0; /* ensure reasons[reason_code] in range */
7299 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7300 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7301 reasons[reason_code], reason_length, reason_string);
7303 pfd_close(c->u.pfd.pf);
7304 } else if (c->type == CHAN_ZOMBIE) {
7306 * This case can occur if a local socket error occurred
7307 * between us sending out CHANNEL_OPEN and receiving
7308 * OPEN_FAILURE. In this case, we need do nothing except allow
7309 * the code below to throw the half-open channel away.
7313 * We never expect to receive OPEN_FAILURE for any *other*
7314 * channel type (since only local-to-remote port forwardings
7315 * cause us to send CHANNEL_OPEN after the main channel is
7316 * live - all other auxiliary channel types are initiated from
7317 * the server end). It's safe to enforce this by assertion
7318 * rather than by ssh_disconnect, because the real point is
7319 * that we never constructed a half-open channel structure in
7320 * the first place with any type other than the above.
7322 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
7325 del234(ssh->channels, c);
7329 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7332 int typelen, want_reply;
7333 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7334 struct ssh_channel *c;
7335 struct Packet *pktout;
7337 c = ssh2_channel_msg(ssh, pktin);
7340 ssh_pkt_getstring(pktin, &type, &typelen);
7341 want_reply = ssh2_pkt_getbool(pktin);
7344 * Having got the channel number, we now look at
7345 * the request type string to see if it's something
7348 if (c == ssh->mainchan) {
7350 * We recognise "exit-status" and "exit-signal" on
7351 * the primary channel.
7353 if (typelen == 11 &&
7354 !memcmp(type, "exit-status", 11)) {
7356 ssh->exitcode = ssh_pkt_getuint32(pktin);
7357 logeventf(ssh, "Server sent command exit status %d",
7359 reply = SSH2_MSG_CHANNEL_SUCCESS;
7361 } else if (typelen == 11 &&
7362 !memcmp(type, "exit-signal", 11)) {
7364 int is_plausible = TRUE, is_int = FALSE;
7365 char *fmt_sig = "", *fmt_msg = "";
7367 int msglen = 0, core = FALSE;
7368 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7369 * provide an `int' for the signal, despite its
7370 * having been a `string' in the drafts of RFC 4254 since at
7371 * least 2001. (Fixed in session.c 1.147.) Try to
7372 * infer which we can safely parse it as. */
7374 unsigned char *p = pktin->body +
7376 long len = pktin->length - pktin->savedpos;
7377 unsigned long num = GET_32BIT(p); /* what is it? */
7378 /* If it's 0, it hardly matters; assume string */
7382 int maybe_int = FALSE, maybe_str = FALSE;
7383 #define CHECK_HYPOTHESIS(offset, result) \
7386 int q = toint(offset); \
7387 if (q >= 0 && q+4 <= len) { \
7388 q = toint(q + 4 + GET_32BIT(p+q)); \
7389 if (q >= 0 && q+4 <= len && \
7390 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
7395 CHECK_HYPOTHESIS(4+1, maybe_int);
7396 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7397 #undef CHECK_HYPOTHESIS
7398 if (maybe_int && !maybe_str)
7400 else if (!maybe_int && maybe_str)
7403 /* Crikey. Either or neither. Panic. */
7404 is_plausible = FALSE;
7407 ssh->exitcode = 128; /* means `unknown signal' */
7410 /* Old non-standard OpenSSH. */
7411 int signum = ssh_pkt_getuint32(pktin);
7412 fmt_sig = dupprintf(" %d", signum);
7413 ssh->exitcode = 128 + signum;
7415 /* As per RFC 4254. */
7418 ssh_pkt_getstring(pktin, &sig, &siglen);
7419 /* Signal name isn't supposed to be blank, but
7420 * let's cope gracefully if it is. */
7422 fmt_sig = dupprintf(" \"%.*s\"",
7427 * Really hideous method of translating the
7428 * signal description back into a locally
7429 * meaningful number.
7434 #define TRANSLATE_SIGNAL(s) \
7435 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7436 ssh->exitcode = 128 + SIG ## s
7438 TRANSLATE_SIGNAL(ABRT);
7441 TRANSLATE_SIGNAL(ALRM);
7444 TRANSLATE_SIGNAL(FPE);
7447 TRANSLATE_SIGNAL(HUP);
7450 TRANSLATE_SIGNAL(ILL);
7453 TRANSLATE_SIGNAL(INT);
7456 TRANSLATE_SIGNAL(KILL);
7459 TRANSLATE_SIGNAL(PIPE);
7462 TRANSLATE_SIGNAL(QUIT);
7465 TRANSLATE_SIGNAL(SEGV);
7468 TRANSLATE_SIGNAL(TERM);
7471 TRANSLATE_SIGNAL(USR1);
7474 TRANSLATE_SIGNAL(USR2);
7476 #undef TRANSLATE_SIGNAL
7478 ssh->exitcode = 128;
7480 core = ssh2_pkt_getbool(pktin);
7481 ssh_pkt_getstring(pktin, &msg, &msglen);
7483 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7485 /* ignore lang tag */
7486 } /* else don't attempt to parse */
7487 logeventf(ssh, "Server exited on signal%s%s%s",
7488 fmt_sig, core ? " (core dumped)" : "",
7490 if (*fmt_sig) sfree(fmt_sig);
7491 if (*fmt_msg) sfree(fmt_msg);
7492 reply = SSH2_MSG_CHANNEL_SUCCESS;
7497 * This is a channel request we don't know
7498 * about, so we now either ignore the request
7499 * or respond with CHANNEL_FAILURE, depending
7502 reply = SSH2_MSG_CHANNEL_FAILURE;
7505 pktout = ssh2_pkt_init(reply);
7506 ssh2_pkt_adduint32(pktout, c->remoteid);
7507 ssh2_pkt_send(ssh, pktout);
7511 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7514 int typelen, want_reply;
7515 struct Packet *pktout;
7517 ssh_pkt_getstring(pktin, &type, &typelen);
7518 want_reply = ssh2_pkt_getbool(pktin);
7521 * We currently don't support any global requests
7522 * at all, so we either ignore the request or
7523 * respond with REQUEST_FAILURE, depending on
7527 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7528 ssh2_pkt_send(ssh, pktout);
7532 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7540 struct ssh_channel *c;
7541 unsigned remid, winsize, pktsize;
7542 struct Packet *pktout;
7544 ssh_pkt_getstring(pktin, &type, &typelen);
7545 c = snew(struct ssh_channel);
7548 remid = ssh_pkt_getuint32(pktin);
7549 winsize = ssh_pkt_getuint32(pktin);
7550 pktsize = ssh_pkt_getuint32(pktin);
7552 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7555 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7556 addrstr = snewn(peeraddrlen+1, char);
7557 memcpy(addrstr, peeraddr, peeraddrlen);
7558 addrstr[peeraddrlen] = '\0';
7559 peerport = ssh_pkt_getuint32(pktin);
7561 logeventf(ssh, "Received X11 connect request from %s:%d",
7564 if (!ssh->X11_fwd_enabled)
7565 error = "X11 forwarding is not enabled";
7567 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
7571 logevent("Opened X11 forward channel");
7575 } else if (typelen == 15 &&
7576 !memcmp(type, "forwarded-tcpip", 15)) {
7577 struct ssh_rportfwd pf, *realpf;
7580 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
7581 pf.shost = dupprintf("%.*s", shostlen, shost);
7582 pf.sport = ssh_pkt_getuint32(pktin);
7583 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7584 peerport = ssh_pkt_getuint32(pktin);
7585 realpf = find234(ssh->rportfwds, &pf, NULL);
7586 logeventf(ssh, "Received remote port %s:%d open request "
7587 "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
7590 if (realpf == NULL) {
7591 error = "Remote port is not recognised";
7593 char *err = pfd_connect(&c->u.pfd.pf,
7597 realpf->pfrec->addressfamily);
7598 logeventf(ssh, "Attempting to forward remote port to "
7599 "%s:%d", realpf->dhost, realpf->dport);
7601 logeventf(ssh, "Port open failed: %s", err);
7603 error = "Port open failed";
7605 logevent("Forwarded port opened successfully");
7606 c->type = CHAN_SOCKDATA;
7609 } else if (typelen == 22 &&
7610 !memcmp(type, "auth-agent@openssh.com", 22)) {
7611 if (!ssh->agentfwd_enabled)
7612 error = "Agent forwarding is not enabled";
7614 c->type = CHAN_AGENT; /* identify channel type */
7615 c->u.a.lensofar = 0;
7616 c->u.a.message = NULL;
7617 c->u.a.outstanding_requests = 0;
7620 error = "Unsupported channel type requested";
7623 c->remoteid = remid;
7624 c->halfopen = FALSE;
7626 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7627 ssh2_pkt_adduint32(pktout, c->remoteid);
7628 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7629 ssh2_pkt_addstring(pktout, error);
7630 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7631 ssh2_pkt_send(ssh, pktout);
7632 logeventf(ssh, "Rejected channel open: %s", error);
7635 ssh2_channel_init(c);
7636 c->v.v2.remwindow = winsize;
7637 c->v.v2.remmaxpkt = pktsize;
7638 add234(ssh->channels, c);
7639 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7640 ssh2_pkt_adduint32(pktout, c->remoteid);
7641 ssh2_pkt_adduint32(pktout, c->localid);
7642 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7643 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7644 ssh2_pkt_send(ssh, pktout);
7649 * Buffer banner messages for later display at some convenient point,
7650 * if we're going to display them.
7652 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7654 /* Arbitrary limit to prevent unbounded inflation of buffer */
7655 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
7656 bufchain_size(&ssh->banner) <= 131072) {
7657 char *banner = NULL;
7659 ssh_pkt_getstring(pktin, &banner, &size);
7661 bufchain_add(&ssh->banner, banner, size);
7665 /* Helper function to deal with sending tty modes for "pty-req" */
7666 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7668 struct Packet *pktout = (struct Packet *)data;
7670 unsigned int arg = 0;
7671 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7672 if (i == lenof(ssh_ttymodes)) return;
7673 switch (ssh_ttymodes[i].type) {
7675 arg = ssh_tty_parse_specchar(val);
7678 arg = ssh_tty_parse_boolean(val);
7681 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7682 ssh2_pkt_adduint32(pktout, arg);
7685 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
7688 struct ssh2_setup_x11_state {
7692 struct Packet *pktout;
7693 crStateP(ssh2_setup_x11_state, ctx);
7697 logevent("Requesting X11 forwarding");
7698 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
7700 ssh2_pkt_addbool(pktout, 0); /* many connections */
7701 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
7702 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
7703 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
7704 ssh2_pkt_send(ssh, pktout);
7706 /* Wait to be called back with either a response packet, or NULL
7707 * meaning clean up and free our data */
7711 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7712 logevent("X11 forwarding enabled");
7713 ssh->X11_fwd_enabled = TRUE;
7715 logevent("X11 forwarding refused");
7721 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
7724 struct ssh2_setup_agent_state {
7728 struct Packet *pktout;
7729 crStateP(ssh2_setup_agent_state, ctx);
7733 logevent("Requesting OpenSSH-style agent forwarding");
7734 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
7735 ssh2_setup_agent, s);
7736 ssh2_pkt_send(ssh, pktout);
7738 /* Wait to be called back with either a response packet, or NULL
7739 * meaning clean up and free our data */
7743 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7744 logevent("Agent forwarding enabled");
7745 ssh->agentfwd_enabled = TRUE;
7747 logevent("Agent forwarding refused");
7753 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
7756 struct ssh2_setup_pty_state {
7760 struct Packet *pktout;
7761 crStateP(ssh2_setup_pty_state, ctx);
7765 /* Unpick the terminal-speed string. */
7766 /* XXX perhaps we should allow no speeds to be sent. */
7767 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
7768 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
7769 /* Build the pty request. */
7770 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
7772 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
7773 ssh2_pkt_adduint32(pktout, ssh->term_width);
7774 ssh2_pkt_adduint32(pktout, ssh->term_height);
7775 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
7776 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
7777 ssh2_pkt_addstring_start(pktout);
7778 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
7779 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
7780 ssh2_pkt_adduint32(pktout, ssh->ispeed);
7781 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
7782 ssh2_pkt_adduint32(pktout, ssh->ospeed);
7783 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
7784 ssh2_pkt_send(ssh, pktout);
7785 ssh->state = SSH_STATE_INTERMED;
7787 /* Wait to be called back with either a response packet, or NULL
7788 * meaning clean up and free our data */
7792 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7793 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
7794 ssh->ospeed, ssh->ispeed);
7795 ssh->got_pty = TRUE;
7797 c_write_str(ssh, "Server refused to allocate pty\r\n");
7798 ssh->editing = ssh->echoing = 1;
7805 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
7808 struct ssh2_setup_env_state {
7810 int num_env, env_left, env_ok;
7813 struct Packet *pktout;
7814 crStateP(ssh2_setup_env_state, ctx);
7819 * Send environment variables.
7821 * Simplest thing here is to send all the requests at once, and
7822 * then wait for a whole bunch of successes or failures.
7828 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
7830 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
7831 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
7832 ssh2_pkt_addstring(pktout, key);
7833 ssh2_pkt_addstring(pktout, val);
7834 ssh2_pkt_send(ssh, pktout);
7839 logeventf(ssh, "Sent %d environment variables", s->num_env);
7844 s->env_left = s->num_env;
7846 while (s->env_left > 0) {
7847 /* Wait to be called back with either a response packet,
7848 * or NULL meaning clean up and free our data */
7850 if (!pktin) goto out;
7851 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
7856 if (s->env_ok == s->num_env) {
7857 logevent("All environment variables successfully set");
7858 } else if (s->env_ok == 0) {
7859 logevent("All environment variables refused");
7860 c_write_str(ssh, "Server refused to set environment variables\r\n");
7862 logeventf(ssh, "%d environment variables refused",
7863 s->num_env - s->env_ok);
7864 c_write_str(ssh, "Server refused to set all environment variables\r\n");
7872 * Handle the SSH-2 userauth and connection layers.
7874 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
7876 do_ssh2_authconn(ssh, NULL, 0, pktin);
7879 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
7882 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
7885 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7886 struct Packet *pktin)
7888 struct do_ssh2_authconn_state {
7892 AUTH_TYPE_PUBLICKEY,
7893 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7894 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7896 AUTH_TYPE_GSSAPI, /* always QUIET */
7897 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7898 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7900 int done_service_req;
7901 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7902 int tried_pubkey_config, done_agent;
7907 int kbd_inter_refused;
7908 int we_are_in, userauth_success;
7909 prompts_t *cur_prompt;
7914 void *publickey_blob;
7915 int publickey_bloblen;
7916 int publickey_encrypted;
7917 char *publickey_algorithm;
7918 char *publickey_comment;
7919 unsigned char agent_request[5], *agent_response, *agentp;
7920 int agent_responselen;
7921 unsigned char *pkblob_in_agent;
7923 char *pkblob, *alg, *commentp;
7924 int pklen, alglen, commentlen;
7925 int siglen, retlen, len;
7926 char *q, *agentreq, *ret;
7928 struct Packet *pktout;
7931 struct ssh_gss_library *gsslib;
7932 Ssh_gss_ctx gss_ctx;
7933 Ssh_gss_buf gss_buf;
7934 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7935 Ssh_gss_name gss_srv_name;
7936 Ssh_gss_stat gss_stat;
7939 crState(do_ssh2_authconn_state);
7943 /* Register as a handler for all the messages this coroutine handles. */
7944 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
7945 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
7946 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
7947 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
7948 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
7949 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
7950 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
7951 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
7952 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
7953 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
7954 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
7955 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
7956 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
7957 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
7958 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
7959 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
7960 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
7961 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
7962 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
7963 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
7965 s->done_service_req = FALSE;
7966 s->we_are_in = s->userauth_success = FALSE;
7968 s->tried_gssapi = FALSE;
7971 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
7973 * Request userauth protocol, and await a response to it.
7975 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7976 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7977 ssh2_pkt_send(ssh, s->pktout);
7978 crWaitUntilV(pktin);
7979 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7980 s->done_service_req = TRUE;
7982 if (!s->done_service_req) {
7984 * Request connection protocol directly, without authentication.
7986 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7987 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7988 ssh2_pkt_send(ssh, s->pktout);
7989 crWaitUntilV(pktin);
7990 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7991 s->we_are_in = TRUE; /* no auth required */
7993 bombout(("Server refused service request"));
7998 /* Arrange to be able to deal with any BANNERs that come in.
7999 * (We do this now as packets may come in during the next bit.) */
8000 bufchain_init(&ssh->banner);
8001 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
8002 ssh2_msg_userauth_banner;
8005 * Misc one-time setup for authentication.
8007 s->publickey_blob = NULL;
8008 if (!s->we_are_in) {
8011 * Load the public half of any configured public key file
8014 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8015 if (!filename_is_null(s->keyfile)) {
8017 logeventf(ssh, "Reading private key file \"%.150s\"",
8018 filename_to_str(s->keyfile));
8019 keytype = key_type(s->keyfile);
8020 if (keytype == SSH_KEYTYPE_SSH2) {
8023 ssh2_userkey_loadpub(s->keyfile,
8024 &s->publickey_algorithm,
8025 &s->publickey_bloblen,
8026 &s->publickey_comment, &error);
8027 if (s->publickey_blob) {
8028 s->publickey_encrypted =
8029 ssh2_userkey_encrypted(s->keyfile, NULL);
8032 logeventf(ssh, "Unable to load private key (%s)",
8034 msgbuf = dupprintf("Unable to load private key file "
8035 "\"%.150s\" (%s)\r\n",
8036 filename_to_str(s->keyfile),
8038 c_write_str(ssh, msgbuf);
8043 logeventf(ssh, "Unable to use this key file (%s)",
8044 key_type_to_str(keytype));
8045 msgbuf = dupprintf("Unable to use key file \"%.150s\""
8047 filename_to_str(s->keyfile),
8048 key_type_to_str(keytype));
8049 c_write_str(ssh, msgbuf);
8051 s->publickey_blob = NULL;
8056 * Find out about any keys Pageant has (but if there's a
8057 * public key configured, filter out all others).
8060 s->agent_response = NULL;
8061 s->pkblob_in_agent = NULL;
8062 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
8066 logevent("Pageant is running. Requesting keys.");
8068 /* Request the keys held by the agent. */
8069 PUT_32BIT(s->agent_request, 1);
8070 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
8071 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
8072 ssh_agent_callback, ssh)) {
8076 bombout(("Unexpected data from server while"
8077 " waiting for agent response"));
8080 } while (pktin || inlen > 0);
8081 r = ssh->agent_response;
8082 s->agent_responselen = ssh->agent_response_len;
8084 s->agent_response = (unsigned char *) r;
8085 if (s->agent_response && s->agent_responselen >= 5 &&
8086 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
8089 p = s->agent_response + 5;
8090 s->nkeys = toint(GET_32BIT(p));
8093 * Vet the Pageant response to ensure that the key
8094 * count and blob lengths make sense.
8097 logeventf(ssh, "Pageant response contained a negative"
8098 " key count %d", s->nkeys);
8100 goto done_agent_query;
8102 unsigned char *q = p + 4;
8103 int lenleft = s->agent_responselen - 5 - 4;
8105 for (keyi = 0; keyi < s->nkeys; keyi++) {
8106 int bloblen, commentlen;
8108 logeventf(ssh, "Pageant response was truncated");
8110 goto done_agent_query;
8112 bloblen = toint(GET_32BIT(q));
8113 if (bloblen < 0 || bloblen > lenleft) {
8114 logeventf(ssh, "Pageant response was truncated");
8116 goto done_agent_query;
8118 lenleft -= 4 + bloblen;
8120 commentlen = toint(GET_32BIT(q));
8121 if (commentlen < 0 || commentlen > lenleft) {
8122 logeventf(ssh, "Pageant response was truncated");
8124 goto done_agent_query;
8126 lenleft -= 4 + commentlen;
8127 q += 4 + commentlen;
8132 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
8133 if (s->publickey_blob) {
8134 /* See if configured key is in agent. */
8135 for (keyi = 0; keyi < s->nkeys; keyi++) {
8136 s->pklen = toint(GET_32BIT(p));
8137 if (s->pklen == s->publickey_bloblen &&
8138 !memcmp(p+4, s->publickey_blob,
8139 s->publickey_bloblen)) {
8140 logeventf(ssh, "Pageant key #%d matches "
8141 "configured key file", keyi);
8143 s->pkblob_in_agent = p;
8147 p += toint(GET_32BIT(p)) + 4; /* comment */
8149 if (!s->pkblob_in_agent) {
8150 logevent("Configured key file not in Pageant");
8155 logevent("Failed to get reply from Pageant");
8163 * We repeat this whole loop, including the username prompt,
8164 * until we manage a successful authentication. If the user
8165 * types the wrong _password_, they can be sent back to the
8166 * beginning to try another username, if this is configured on.
8167 * (If they specify a username in the config, they are never
8168 * asked, even if they do give a wrong password.)
8170 * I think this best serves the needs of
8172 * - the people who have no configuration, no keys, and just
8173 * want to try repeated (username,password) pairs until they
8174 * type both correctly
8176 * - people who have keys and configuration but occasionally
8177 * need to fall back to passwords
8179 * - people with a key held in Pageant, who might not have
8180 * logged in to a particular machine before; so they want to
8181 * type a username, and then _either_ their key will be
8182 * accepted, _or_ they will type a password. If they mistype
8183 * the username they will want to be able to get back and
8186 s->got_username = FALSE;
8187 while (!s->we_are_in) {
8191 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
8193 * We got a username last time round this loop, and
8194 * with change_username turned off we don't try to get
8197 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
8198 int ret; /* need not be kept over crReturn */
8199 s->cur_prompt = new_prompts(ssh->frontend);
8200 s->cur_prompt->to_server = TRUE;
8201 s->cur_prompt->name = dupstr("SSH login name");
8202 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
8203 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8206 crWaitUntilV(!pktin);
8207 ret = get_userpass_input(s->cur_prompt, in, inlen);
8212 * get_userpass_input() failed to get a username.
8215 free_prompts(s->cur_prompt);
8216 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
8219 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
8220 free_prompts(s->cur_prompt);
8223 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
8224 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
8225 c_write_str(ssh, stuff);
8229 s->got_username = TRUE;
8232 * Send an authentication request using method "none": (a)
8233 * just in case it succeeds, and (b) so that we know what
8234 * authentication methods we can usefully try next.
8236 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8238 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8239 ssh2_pkt_addstring(s->pktout, ssh->username);
8240 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
8241 ssh2_pkt_addstring(s->pktout, "none"); /* method */
8242 ssh2_pkt_send(ssh, s->pktout);
8243 s->type = AUTH_TYPE_NONE;
8245 s->we_are_in = FALSE;
8247 s->tried_pubkey_config = FALSE;
8248 s->kbd_inter_refused = FALSE;
8250 /* Reset agent request state. */
8251 s->done_agent = FALSE;
8252 if (s->agent_response) {
8253 if (s->pkblob_in_agent) {
8254 s->agentp = s->pkblob_in_agent;
8256 s->agentp = s->agent_response + 5 + 4;
8262 char *methods = NULL;
8266 * Wait for the result of the last authentication request.
8269 crWaitUntilV(pktin);
8271 * Now is a convenient point to spew any banner material
8272 * that we've accumulated. (This should ensure that when
8273 * we exit the auth loop, we haven't any left to deal
8277 int size = bufchain_size(&ssh->banner);
8279 * Don't show the banner if we're operating in
8280 * non-verbose non-interactive mode. (It's probably
8281 * a script, which means nobody will read the
8282 * banner _anyway_, and moreover the printing of
8283 * the banner will screw up processing on the
8284 * output of (say) plink.)
8286 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
8287 char *banner = snewn(size, char);
8288 bufchain_fetch(&ssh->banner, banner, size);
8289 c_write_untrusted(ssh, banner, size);
8292 bufchain_clear(&ssh->banner);
8294 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
8295 logevent("Access granted");
8296 s->we_are_in = s->userauth_success = TRUE;
8300 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
8301 bombout(("Strange packet received during authentication: "
8302 "type %d", pktin->type));
8309 * OK, we're now sitting on a USERAUTH_FAILURE message, so
8310 * we can look at the string in it and know what we can
8311 * helpfully try next.
8313 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
8314 ssh_pkt_getstring(pktin, &methods, &methlen);
8315 if (!ssh2_pkt_getbool(pktin)) {
8317 * We have received an unequivocal Access
8318 * Denied. This can translate to a variety of
8319 * messages, or no message at all.
8321 * For forms of authentication which are attempted
8322 * implicitly, by which I mean without printing
8323 * anything in the window indicating that we're
8324 * trying them, we should never print 'Access
8327 * If we do print a message saying that we're
8328 * attempting some kind of authentication, it's OK
8329 * to print a followup message saying it failed -
8330 * but the message may sometimes be more specific
8331 * than simply 'Access denied'.
8333 * Additionally, if we'd just tried password
8334 * authentication, we should break out of this
8335 * whole loop so as to go back to the username
8336 * prompt (iff we're configured to allow
8337 * username change attempts).
8339 if (s->type == AUTH_TYPE_NONE) {
8341 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
8342 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
8343 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
8344 c_write_str(ssh, "Server refused our key\r\n");
8345 logevent("Server refused our key");
8346 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
8347 /* This _shouldn't_ happen except by a
8348 * protocol bug causing client and server to
8349 * disagree on what is a correct signature. */
8350 c_write_str(ssh, "Server refused public-key signature"
8351 " despite accepting key!\r\n");
8352 logevent("Server refused public-key signature"
8353 " despite accepting key!");
8354 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
8355 /* quiet, so no c_write */
8356 logevent("Server refused keyboard-interactive authentication");
8357 } else if (s->type==AUTH_TYPE_GSSAPI) {
8358 /* always quiet, so no c_write */
8359 /* also, the code down in the GSSAPI block has
8360 * already logged this in the Event Log */
8361 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
8362 logevent("Keyboard-interactive authentication failed");
8363 c_write_str(ssh, "Access denied\r\n");
8365 assert(s->type == AUTH_TYPE_PASSWORD);
8366 logevent("Password authentication failed");
8367 c_write_str(ssh, "Access denied\r\n");
8369 if (conf_get_int(ssh->conf, CONF_change_username)) {
8370 /* XXX perhaps we should allow
8371 * keyboard-interactive to do this too? */
8372 s->we_are_in = FALSE;
8377 c_write_str(ssh, "Further authentication required\r\n");
8378 logevent("Further authentication required");
8382 in_commasep_string("publickey", methods, methlen);
8384 in_commasep_string("password", methods, methlen);
8385 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
8386 in_commasep_string("keyboard-interactive", methods, methlen);
8389 ssh->gsslibs = ssh_gss_setup(ssh->conf);
8390 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
8391 in_commasep_string("gssapi-with-mic", methods, methlen) &&
8392 ssh->gsslibs->nlibraries > 0;
8396 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8398 if (s->can_pubkey && !s->done_agent && s->nkeys) {
8401 * Attempt public-key authentication using a key from Pageant.
8404 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8406 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
8408 /* Unpack key from agent response */
8409 s->pklen = toint(GET_32BIT(s->agentp));
8411 s->pkblob = (char *)s->agentp;
8412 s->agentp += s->pklen;
8413 s->alglen = toint(GET_32BIT(s->pkblob));
8414 s->alg = s->pkblob + 4;
8415 s->commentlen = toint(GET_32BIT(s->agentp));
8417 s->commentp = (char *)s->agentp;
8418 s->agentp += s->commentlen;
8419 /* s->agentp now points at next key, if any */
8421 /* See if server will accept it */
8422 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8423 ssh2_pkt_addstring(s->pktout, ssh->username);
8424 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8425 /* service requested */
8426 ssh2_pkt_addstring(s->pktout, "publickey");
8428 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
8429 ssh2_pkt_addstring_start(s->pktout);
8430 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
8431 ssh2_pkt_addstring_start(s->pktout);
8432 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
8433 ssh2_pkt_send(ssh, s->pktout);
8434 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
8436 crWaitUntilV(pktin);
8437 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8439 /* Offer of key refused. */
8446 if (flags & FLAG_VERBOSE) {
8447 c_write_str(ssh, "Authenticating with "
8449 c_write(ssh, s->commentp, s->commentlen);
8450 c_write_str(ssh, "\" from agent\r\n");
8454 * Server is willing to accept the key.
8455 * Construct a SIGN_REQUEST.
8457 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8458 ssh2_pkt_addstring(s->pktout, ssh->username);
8459 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8460 /* service requested */
8461 ssh2_pkt_addstring(s->pktout, "publickey");
8463 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
8464 ssh2_pkt_addstring_start(s->pktout);
8465 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
8466 ssh2_pkt_addstring_start(s->pktout);
8467 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
8469 /* Ask agent for signature. */
8470 s->siglen = s->pktout->length - 5 + 4 +
8471 ssh->v2_session_id_len;
8472 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8474 s->len = 1; /* message type */
8475 s->len += 4 + s->pklen; /* key blob */
8476 s->len += 4 + s->siglen; /* data to sign */
8477 s->len += 4; /* flags */
8478 s->agentreq = snewn(4 + s->len, char);
8479 PUT_32BIT(s->agentreq, s->len);
8480 s->q = s->agentreq + 4;
8481 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
8482 PUT_32BIT(s->q, s->pklen);
8484 memcpy(s->q, s->pkblob, s->pklen);
8486 PUT_32BIT(s->q, s->siglen);
8488 /* Now the data to be signed... */
8489 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8490 PUT_32BIT(s->q, ssh->v2_session_id_len);
8493 memcpy(s->q, ssh->v2_session_id,
8494 ssh->v2_session_id_len);
8495 s->q += ssh->v2_session_id_len;
8496 memcpy(s->q, s->pktout->data + 5,
8497 s->pktout->length - 5);
8498 s->q += s->pktout->length - 5;
8499 /* And finally the (zero) flags word. */
8501 if (!agent_query(s->agentreq, s->len + 4,
8503 ssh_agent_callback, ssh)) {
8507 bombout(("Unexpected data from server"
8508 " while waiting for agent"
8512 } while (pktin || inlen > 0);
8513 vret = ssh->agent_response;
8514 s->retlen = ssh->agent_response_len;
8519 if (s->retlen >= 9 &&
8520 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
8521 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
8522 logevent("Sending Pageant's response");
8523 ssh2_add_sigblob(ssh, s->pktout,
8524 s->pkblob, s->pklen,
8526 GET_32BIT(s->ret + 5));
8527 ssh2_pkt_send(ssh, s->pktout);
8528 s->type = AUTH_TYPE_PUBLICKEY;
8530 /* FIXME: less drastic response */
8531 bombout(("Pageant failed to answer challenge"));
8537 /* Do we have any keys left to try? */
8538 if (s->pkblob_in_agent) {
8539 s->done_agent = TRUE;
8540 s->tried_pubkey_config = TRUE;
8543 if (s->keyi >= s->nkeys)
8544 s->done_agent = TRUE;
8547 } else if (s->can_pubkey && s->publickey_blob &&
8548 !s->tried_pubkey_config) {
8550 struct ssh2_userkey *key; /* not live over crReturn */
8551 char *passphrase; /* not live over crReturn */
8553 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8555 s->tried_pubkey_config = TRUE;
8558 * Try the public key supplied in the configuration.
8560 * First, offer the public blob to see if the server is
8561 * willing to accept it.
8563 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8564 ssh2_pkt_addstring(s->pktout, ssh->username);
8565 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8566 /* service requested */
8567 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
8568 ssh2_pkt_addbool(s->pktout, FALSE);
8569 /* no signature included */
8570 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
8571 ssh2_pkt_addstring_start(s->pktout);
8572 ssh2_pkt_addstring_data(s->pktout,
8573 (char *)s->publickey_blob,
8574 s->publickey_bloblen);
8575 ssh2_pkt_send(ssh, s->pktout);
8576 logevent("Offered public key");
8578 crWaitUntilV(pktin);
8579 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8580 /* Key refused. Give up. */
8581 s->gotit = TRUE; /* reconsider message next loop */
8582 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
8583 continue; /* process this new message */
8585 logevent("Offer of public key accepted");
8588 * Actually attempt a serious authentication using
8591 if (flags & FLAG_VERBOSE) {
8592 c_write_str(ssh, "Authenticating with public key \"");
8593 c_write_str(ssh, s->publickey_comment);
8594 c_write_str(ssh, "\"\r\n");
8598 const char *error; /* not live over crReturn */
8599 if (s->publickey_encrypted) {
8601 * Get a passphrase from the user.
8603 int ret; /* need not be kept over crReturn */
8604 s->cur_prompt = new_prompts(ssh->frontend);
8605 s->cur_prompt->to_server = FALSE;
8606 s->cur_prompt->name = dupstr("SSH key passphrase");
8607 add_prompt(s->cur_prompt,
8608 dupprintf("Passphrase for key \"%.100s\": ",
8609 s->publickey_comment),
8611 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8614 crWaitUntilV(!pktin);
8615 ret = get_userpass_input(s->cur_prompt,
8620 /* Failed to get a passphrase. Terminate. */
8621 free_prompts(s->cur_prompt);
8622 ssh_disconnect(ssh, NULL,
8623 "Unable to authenticate",
8624 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8629 dupstr(s->cur_prompt->prompts[0]->result);
8630 free_prompts(s->cur_prompt);
8632 passphrase = NULL; /* no passphrase needed */
8636 * Try decrypting the key.
8638 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8639 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
8641 /* burn the evidence */
8642 smemclr(passphrase, strlen(passphrase));
8645 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
8647 (key == SSH2_WRONG_PASSPHRASE)) {
8648 c_write_str(ssh, "Wrong passphrase\r\n");
8650 /* and loop again */
8652 c_write_str(ssh, "Unable to load private key (");
8653 c_write_str(ssh, error);
8654 c_write_str(ssh, ")\r\n");
8656 break; /* try something else */
8662 unsigned char *pkblob, *sigblob, *sigdata;
8663 int pkblob_len, sigblob_len, sigdata_len;
8667 * We have loaded the private key and the server
8668 * has announced that it's willing to accept it.
8669 * Hallelujah. Generate a signature and send it.
8671 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8672 ssh2_pkt_addstring(s->pktout, ssh->username);
8673 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8674 /* service requested */
8675 ssh2_pkt_addstring(s->pktout, "publickey");
8677 ssh2_pkt_addbool(s->pktout, TRUE);
8678 /* signature follows */
8679 ssh2_pkt_addstring(s->pktout, key->alg->name);
8680 pkblob = key->alg->public_blob(key->data,
8682 ssh2_pkt_addstring_start(s->pktout);
8683 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
8687 * The data to be signed is:
8691 * followed by everything so far placed in the
8694 sigdata_len = s->pktout->length - 5 + 4 +
8695 ssh->v2_session_id_len;
8696 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8698 sigdata = snewn(sigdata_len, unsigned char);
8700 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8701 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
8704 memcpy(sigdata+p, ssh->v2_session_id,
8705 ssh->v2_session_id_len);
8706 p += ssh->v2_session_id_len;
8707 memcpy(sigdata+p, s->pktout->data + 5,
8708 s->pktout->length - 5);
8709 p += s->pktout->length - 5;
8710 assert(p == sigdata_len);
8711 sigblob = key->alg->sign(key->data, (char *)sigdata,
8712 sigdata_len, &sigblob_len);
8713 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
8714 sigblob, sigblob_len);
8719 ssh2_pkt_send(ssh, s->pktout);
8720 logevent("Sent public key signature");
8721 s->type = AUTH_TYPE_PUBLICKEY;
8722 key->alg->freekey(key->data);
8726 } else if (s->can_gssapi && !s->tried_gssapi) {
8728 /* GSSAPI Authentication */
8733 s->type = AUTH_TYPE_GSSAPI;
8734 s->tried_gssapi = TRUE;
8736 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
8739 * Pick the highest GSS library on the preference
8745 for (i = 0; i < ngsslibs; i++) {
8746 int want_id = conf_get_int_int(ssh->conf,
8747 CONF_ssh_gsslist, i);
8748 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
8749 if (ssh->gsslibs->libraries[j].id == want_id) {
8750 s->gsslib = &ssh->gsslibs->libraries[j];
8751 goto got_gsslib; /* double break */
8756 * We always expect to have found something in
8757 * the above loop: we only came here if there
8758 * was at least one viable GSS library, and the
8759 * preference list should always mention
8760 * everything and only change the order.
8765 if (s->gsslib->gsslogmsg)
8766 logevent(s->gsslib->gsslogmsg);
8768 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8769 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8770 ssh2_pkt_addstring(s->pktout, ssh->username);
8771 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8772 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
8773 logevent("Attempting GSSAPI authentication");
8775 /* add mechanism info */
8776 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
8778 /* number of GSSAPI mechanisms */
8779 ssh2_pkt_adduint32(s->pktout,1);
8781 /* length of OID + 2 */
8782 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
8783 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
8786 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
8788 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
8790 ssh2_pkt_send(ssh, s->pktout);
8791 crWaitUntilV(pktin);
8792 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
8793 logevent("GSSAPI authentication request refused");
8797 /* check returned packet ... */
8799 ssh_pkt_getstring(pktin, &data, &len);
8800 s->gss_rcvtok.value = data;
8801 s->gss_rcvtok.length = len;
8802 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
8803 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
8804 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8805 memcmp((char *)s->gss_rcvtok.value + 2,
8806 s->gss_buf.value,s->gss_buf.length) ) {
8807 logevent("GSSAPI authentication - wrong response from server");
8811 /* now start running */
8812 s->gss_stat = s->gsslib->import_name(s->gsslib,
8815 if (s->gss_stat != SSH_GSS_OK) {
8816 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8817 logevent("GSSAPI import name failed - Bad service name");
8819 logevent("GSSAPI import name failed");
8823 /* fetch TGT into GSS engine */
8824 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
8826 if (s->gss_stat != SSH_GSS_OK) {
8827 logevent("GSSAPI authentication failed to get credentials");
8828 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8832 /* initial tokens are empty */
8833 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
8834 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
8836 /* now enter the loop */
8838 s->gss_stat = s->gsslib->init_sec_context
8842 conf_get_int(ssh->conf, CONF_gssapifwd),
8846 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8847 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8848 logevent("GSSAPI authentication initialisation failed");
8850 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8851 &s->gss_buf) == SSH_GSS_OK) {
8852 logevent(s->gss_buf.value);
8853 sfree(s->gss_buf.value);
8858 logevent("GSSAPI authentication initialised");
8860 /* Client and server now exchange tokens until GSSAPI
8861 * no longer says CONTINUE_NEEDED */
8863 if (s->gss_sndtok.length != 0) {
8864 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8865 ssh_pkt_addstring_start(s->pktout);
8866 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8867 ssh2_pkt_send(ssh, s->pktout);
8868 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
8871 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8872 crWaitUntilV(pktin);
8873 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8874 logevent("GSSAPI authentication - bad server response");
8875 s->gss_stat = SSH_GSS_FAILURE;
8878 ssh_pkt_getstring(pktin, &data, &len);
8879 s->gss_rcvtok.value = data;
8880 s->gss_rcvtok.length = len;
8882 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8884 if (s->gss_stat != SSH_GSS_OK) {
8885 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8886 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8889 logevent("GSSAPI authentication loop finished OK");
8891 /* Now send the MIC */
8893 s->pktout = ssh2_pkt_init(0);
8894 micoffset = s->pktout->length;
8895 ssh_pkt_addstring_start(s->pktout);
8896 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8897 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8898 ssh_pkt_addstring(s->pktout, ssh->username);
8899 ssh_pkt_addstring(s->pktout, "ssh-connection");
8900 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8902 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8903 s->gss_buf.length = s->pktout->length - micoffset;
8905 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
8906 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8907 ssh_pkt_addstring_start(s->pktout);
8908 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8909 ssh2_pkt_send(ssh, s->pktout);
8910 s->gsslib->free_mic(s->gsslib, &mic);
8914 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8915 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8918 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8921 * Keyboard-interactive authentication.
8924 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8926 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8928 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8929 ssh2_pkt_addstring(s->pktout, ssh->username);
8930 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8931 /* service requested */
8932 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8934 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8935 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8936 ssh2_pkt_send(ssh, s->pktout);
8938 logevent("Attempting keyboard-interactive authentication");
8940 crWaitUntilV(pktin);
8941 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8942 /* Server is not willing to do keyboard-interactive
8943 * at all (or, bizarrely but legally, accepts the
8944 * user without actually issuing any prompts).
8945 * Give up on it entirely. */
8947 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8948 s->kbd_inter_refused = TRUE; /* don't try it again */
8953 * Loop while the server continues to send INFO_REQUESTs.
8955 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8957 char *name, *inst, *lang;
8958 int name_len, inst_len, lang_len;
8962 * We've got a fresh USERAUTH_INFO_REQUEST.
8963 * Get the preamble and start building a prompt.
8965 ssh_pkt_getstring(pktin, &name, &name_len);
8966 ssh_pkt_getstring(pktin, &inst, &inst_len);
8967 ssh_pkt_getstring(pktin, &lang, &lang_len);
8968 s->cur_prompt = new_prompts(ssh->frontend);
8969 s->cur_prompt->to_server = TRUE;
8972 * Get any prompt(s) from the packet.
8974 s->num_prompts = ssh_pkt_getuint32(pktin);
8975 for (i = 0; i < s->num_prompts; i++) {
8979 static char noprompt[] =
8980 "<server failed to send prompt>: ";
8982 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8983 echo = ssh2_pkt_getbool(pktin);
8986 prompt_len = lenof(noprompt)-1;
8988 add_prompt(s->cur_prompt,
8989 dupprintf("%.*s", prompt_len, prompt),
8994 /* FIXME: better prefix to distinguish from
8996 s->cur_prompt->name =
8997 dupprintf("SSH server: %.*s", name_len, name);
8998 s->cur_prompt->name_reqd = TRUE;
9000 s->cur_prompt->name =
9001 dupstr("SSH server authentication");
9002 s->cur_prompt->name_reqd = FALSE;
9004 /* We add a prefix to try to make it clear that a prompt
9005 * has come from the server.
9006 * FIXME: ugly to print "Using..." in prompt _every_
9007 * time round. Can this be done more subtly? */
9008 /* Special case: for reasons best known to themselves,
9009 * some servers send k-i requests with no prompts and
9010 * nothing to display. Keep quiet in this case. */
9011 if (s->num_prompts || name_len || inst_len) {
9012 s->cur_prompt->instruction =
9013 dupprintf("Using keyboard-interactive authentication.%s%.*s",
9014 inst_len ? "\n" : "", inst_len, inst);
9015 s->cur_prompt->instr_reqd = TRUE;
9017 s->cur_prompt->instr_reqd = FALSE;
9021 * Display any instructions, and get the user's
9025 int ret; /* not live over crReturn */
9026 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9029 crWaitUntilV(!pktin);
9030 ret = get_userpass_input(s->cur_prompt, in, inlen);
9035 * Failed to get responses. Terminate.
9037 free_prompts(s->cur_prompt);
9038 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9039 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9046 * Send the response(s) to the server.
9048 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
9049 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
9050 for (i=0; i < s->num_prompts; i++) {
9051 ssh2_pkt_addstring(s->pktout,
9052 s->cur_prompt->prompts[i]->result);
9054 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9057 * Free the prompts structure from this iteration.
9058 * If there's another, a new one will be allocated
9059 * when we return to the top of this while loop.
9061 free_prompts(s->cur_prompt);
9064 * Get the next packet in case it's another
9067 crWaitUntilV(pktin);
9072 * We should have SUCCESS or FAILURE now.
9076 } else if (s->can_passwd) {
9079 * Plain old password authentication.
9081 int ret; /* not live over crReturn */
9082 int changereq_first_time; /* not live over crReturn */
9084 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
9086 s->cur_prompt = new_prompts(ssh->frontend);
9087 s->cur_prompt->to_server = TRUE;
9088 s->cur_prompt->name = dupstr("SSH password");
9089 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
9094 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9097 crWaitUntilV(!pktin);
9098 ret = get_userpass_input(s->cur_prompt, in, inlen);
9103 * Failed to get responses. Terminate.
9105 free_prompts(s->cur_prompt);
9106 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9107 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9112 * Squirrel away the password. (We may need it later if
9113 * asked to change it.)
9115 s->password = dupstr(s->cur_prompt->prompts[0]->result);
9116 free_prompts(s->cur_prompt);
9119 * Send the password packet.
9121 * We pad out the password packet to 256 bytes to make
9122 * it harder for an attacker to find the length of the
9125 * Anyone using a password longer than 256 bytes
9126 * probably doesn't have much to worry about from
9127 * people who find out how long their password is!
9129 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9130 ssh2_pkt_addstring(s->pktout, ssh->username);
9131 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9132 /* service requested */
9133 ssh2_pkt_addstring(s->pktout, "password");
9134 ssh2_pkt_addbool(s->pktout, FALSE);
9135 ssh2_pkt_addstring(s->pktout, s->password);
9136 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9137 logevent("Sent password");
9138 s->type = AUTH_TYPE_PASSWORD;
9141 * Wait for next packet, in case it's a password change
9144 crWaitUntilV(pktin);
9145 changereq_first_time = TRUE;
9147 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
9150 * We're being asked for a new password
9151 * (perhaps not for the first time).
9152 * Loop until the server accepts it.
9155 int got_new = FALSE; /* not live over crReturn */
9156 char *prompt; /* not live over crReturn */
9157 int prompt_len; /* not live over crReturn */
9161 if (changereq_first_time)
9162 msg = "Server requested password change";
9164 msg = "Server rejected new password";
9166 c_write_str(ssh, msg);
9167 c_write_str(ssh, "\r\n");
9170 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9172 s->cur_prompt = new_prompts(ssh->frontend);
9173 s->cur_prompt->to_server = TRUE;
9174 s->cur_prompt->name = dupstr("New SSH password");
9175 s->cur_prompt->instruction =
9176 dupprintf("%.*s", prompt_len, prompt);
9177 s->cur_prompt->instr_reqd = TRUE;
9179 * There's no explicit requirement in the protocol
9180 * for the "old" passwords in the original and
9181 * password-change messages to be the same, and
9182 * apparently some Cisco kit supports password change
9183 * by the user entering a blank password originally
9184 * and the real password subsequently, so,
9185 * reluctantly, we prompt for the old password again.
9187 * (On the other hand, some servers don't even bother
9188 * to check this field.)
9190 add_prompt(s->cur_prompt,
9191 dupstr("Current password (blank for previously entered password): "),
9193 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
9195 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
9199 * Loop until the user manages to enter the same
9204 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9207 crWaitUntilV(!pktin);
9208 ret = get_userpass_input(s->cur_prompt, in, inlen);
9213 * Failed to get responses. Terminate.
9215 /* burn the evidence */
9216 free_prompts(s->cur_prompt);
9217 smemclr(s->password, strlen(s->password));
9219 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9220 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9226 * If the user specified a new original password
9227 * (IYSWIM), overwrite any previously specified
9229 * (A side effect is that the user doesn't have to
9230 * re-enter it if they louse up the new password.)
9232 if (s->cur_prompt->prompts[0]->result[0]) {
9233 smemclr(s->password, strlen(s->password));
9234 /* burn the evidence */
9237 dupstr(s->cur_prompt->prompts[0]->result);
9241 * Check the two new passwords match.
9243 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
9244 s->cur_prompt->prompts[2]->result)
9247 /* They don't. Silly user. */
9248 c_write_str(ssh, "Passwords do not match\r\n");
9253 * Send the new password (along with the old one).
9254 * (see above for padding rationale)
9256 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9257 ssh2_pkt_addstring(s->pktout, ssh->username);
9258 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9259 /* service requested */
9260 ssh2_pkt_addstring(s->pktout, "password");
9261 ssh2_pkt_addbool(s->pktout, TRUE);
9262 ssh2_pkt_addstring(s->pktout, s->password);
9263 ssh2_pkt_addstring(s->pktout,
9264 s->cur_prompt->prompts[1]->result);
9265 free_prompts(s->cur_prompt);
9266 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9267 logevent("Sent new password");
9270 * Now see what the server has to say about it.
9271 * (If it's CHANGEREQ again, it's not happy with the
9274 crWaitUntilV(pktin);
9275 changereq_first_time = FALSE;
9280 * We need to reexamine the current pktin at the top
9281 * of the loop. Either:
9282 * - we weren't asked to change password at all, in
9283 * which case it's a SUCCESS or FAILURE with the
9285 * - we sent a new password, and the server was
9286 * either OK with it (SUCCESS or FAILURE w/partial
9287 * success) or unhappy with the _old_ password
9288 * (FAILURE w/o partial success)
9289 * In any of these cases, we go back to the top of
9290 * the loop and start again.
9295 * We don't need the old password any more, in any
9296 * case. Burn the evidence.
9298 smemclr(s->password, strlen(s->password));
9302 char *str = dupprintf("No supported authentication methods available"
9303 " (server sent: %.*s)",
9306 ssh_disconnect(ssh, str,
9307 "No supported authentication methods available",
9308 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
9318 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9320 /* Clear up various bits and pieces from authentication. */
9321 if (s->publickey_blob) {
9322 sfree(s->publickey_blob);
9323 sfree(s->publickey_comment);
9325 if (s->agent_response)
9326 sfree(s->agent_response);
9328 if (s->userauth_success) {
9330 * We've just received USERAUTH_SUCCESS, and we haven't sent any
9331 * packets since. Signal the transport layer to consider enacting
9332 * delayed compression.
9334 * (Relying on we_are_in is not sufficient, as
9335 * draft-miller-secsh-compression-delayed is quite clear that it
9336 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
9337 * become set for other reasons.)
9339 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
9343 * Now the connection protocol has started, one way or another.
9346 ssh->channels = newtree234(ssh_channelcmp);
9349 * Set up handlers for some connection protocol messages, so we
9350 * don't have to handle them repeatedly in this coroutine.
9352 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
9353 ssh2_msg_channel_window_adjust;
9354 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
9355 ssh2_msg_global_request;
9358 * Create the main session channel.
9360 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
9361 ssh->mainchan = NULL;
9363 ssh->mainchan = snew(struct ssh_channel);
9364 ssh->mainchan->ssh = ssh;
9365 ssh2_channel_init(ssh->mainchan);
9367 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
9369 * Just start a direct-tcpip channel and use it as the main
9372 ssh_send_port_open(ssh->mainchan,
9373 conf_get_str(ssh->conf, CONF_ssh_nc_host),
9374 conf_get_int(ssh->conf, CONF_ssh_nc_port),
9378 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
9379 logevent("Opening session as main channel");
9380 ssh2_pkt_send(ssh, s->pktout);
9381 ssh->ncmode = FALSE;
9383 crWaitUntilV(pktin);
9384 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
9385 bombout(("Server refused to open channel"));
9387 /* FIXME: error data comes back in FAILURE packet */
9389 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
9390 bombout(("Server's channel confirmation cited wrong channel"));
9393 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
9394 ssh->mainchan->halfopen = FALSE;
9395 ssh->mainchan->type = CHAN_MAINSESSION;
9396 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
9397 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
9398 add234(ssh->channels, ssh->mainchan);
9399 update_specials_menu(ssh->frontend);
9400 logevent("Opened main channel");
9404 * Now we have a channel, make dispatch table entries for
9405 * general channel-based messages.
9407 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
9408 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
9409 ssh2_msg_channel_data;
9410 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
9411 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
9412 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
9413 ssh2_msg_channel_open_confirmation;
9414 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
9415 ssh2_msg_channel_open_failure;
9416 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
9417 ssh2_msg_channel_request;
9418 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
9419 ssh2_msg_channel_open;
9420 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
9421 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
9424 if (ssh->mainchan && conf_get_int(ssh->conf, CONF_ssh_simple)) {
9426 * This message indicates to the server that we promise
9427 * not to try to run any other channel in parallel with
9428 * this one, so it's safe for it to advertise a very large
9429 * window and leave the flow control to TCP.
9431 s->pktout = ssh2_chanreq_init(ssh->mainchan,
9432 "simple@putty.projects.tartarus.org",
9434 ssh2_pkt_send(ssh, s->pktout);
9438 * Enable port forwardings.
9440 ssh_setup_portfwd(ssh, ssh->conf);
9442 if (ssh->mainchan && !ssh->ncmode) {
9444 * Send the CHANNEL_REQUESTS for the main session channel.
9445 * Each one is handled by its own little asynchronous
9449 /* Potentially enable X11 forwarding. */
9450 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
9452 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
9454 if (!ssh->x11disp) {
9455 /* FIXME: return an error message from x11_setup_display */
9456 logevent("X11 forwarding not enabled: unable to"
9457 " initialise X display");
9459 ssh->x11auth = x11_invent_fake_auth
9460 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
9461 ssh->x11auth->disp = ssh->x11disp;
9463 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
9467 /* Potentially enable agent forwarding. */
9468 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists())
9469 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
9471 /* Now allocate a pty for the session. */
9472 if (!conf_get_int(ssh->conf, CONF_nopty))
9473 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
9475 /* Send environment variables. */
9476 ssh2_setup_env(ssh->mainchan, NULL, NULL);
9479 * Start a shell or a remote command. We may have to attempt
9480 * this twice if the config data has provided a second choice
9487 if (ssh->fallback_cmd) {
9488 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
9489 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
9491 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
9492 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
9496 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
9497 ssh2_response_authconn, NULL);
9498 ssh2_pkt_addstring(s->pktout, cmd);
9500 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
9501 ssh2_response_authconn, NULL);
9502 ssh2_pkt_addstring(s->pktout, cmd);
9504 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
9505 ssh2_response_authconn, NULL);
9507 ssh2_pkt_send(ssh, s->pktout);
9509 crWaitUntilV(pktin);
9511 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9512 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9513 bombout(("Unexpected response to shell/command request:"
9514 " packet type %d", pktin->type));
9518 * We failed to start the command. If this is the
9519 * fallback command, we really are finished; if it's
9520 * not, and if the fallback command exists, try falling
9521 * back to it before complaining.
9523 if (!ssh->fallback_cmd &&
9524 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
9525 logevent("Primary command failed; attempting fallback");
9526 ssh->fallback_cmd = TRUE;
9529 bombout(("Server refused to start a shell/command"));
9532 logevent("Started a shell/command");
9537 ssh->editing = ssh->echoing = TRUE;
9540 ssh->state = SSH_STATE_SESSION;
9541 if (ssh->size_needed)
9542 ssh_size(ssh, ssh->term_width, ssh->term_height);
9543 if (ssh->eof_needed)
9544 ssh_special(ssh, TS_EOF);
9550 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
9555 s->try_send = FALSE;
9559 * _All_ the connection-layer packets we expect to
9560 * receive are now handled by the dispatch table.
9561 * Anything that reaches here must be bogus.
9564 bombout(("Strange packet received: type %d", pktin->type));
9566 } else if (ssh->mainchan) {
9568 * We have spare data. Add it to the channel buffer.
9570 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
9575 struct ssh_channel *c;
9577 * Try to send data on all channels if we can.
9579 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
9580 ssh2_try_send_and_unthrottle(ssh, c);
9588 * Handlers for SSH-2 messages that might arrive at any moment.
9590 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
9592 /* log reason code in disconnect message */
9596 reason = ssh_pkt_getuint32(pktin);
9597 ssh_pkt_getstring(pktin, &msg, &msglen);
9599 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
9600 buf = dupprintf("Received disconnect message (%s)",
9601 ssh2_disconnect_reasons[reason]);
9603 buf = dupprintf("Received disconnect message (unknown"
9604 " type %d)", reason);
9608 buf = dupprintf("Disconnection message text: %.*s",
9611 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9613 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
9614 ssh2_disconnect_reasons[reason] : "unknown",
9619 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
9621 /* log the debug message */
9625 /* XXX maybe we should actually take notice of the return value */
9626 ssh2_pkt_getbool(pktin);
9627 ssh_pkt_getstring(pktin, &msg, &msglen);
9629 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
9632 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
9634 do_ssh2_transport(ssh, NULL, 0, pktin);
9638 * Called if we receive a packet that isn't allowed by the protocol.
9639 * This only applies to packets whose meaning PuTTY understands.
9640 * Entirely unknown packets are handled below.
9642 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
9644 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
9645 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
9647 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
9651 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
9653 struct Packet *pktout;
9654 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
9655 ssh2_pkt_adduint32(pktout, pktin->sequence);
9657 * UNIMPLEMENTED messages MUST appear in the same order as the
9658 * messages they respond to. Hence, never queue them.
9660 ssh2_pkt_send_noqueue(ssh, pktout);
9664 * Handle the top-level SSH-2 protocol.
9666 static void ssh2_protocol_setup(Ssh ssh)
9671 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9673 for (i = 0; i < 256; i++)
9674 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9677 * Initially, we only accept transport messages (and a few generic
9678 * ones). do_ssh2_authconn will add more when it starts.
9679 * Messages that are understood but not currently acceptable go to
9680 * ssh2_msg_unexpected.
9682 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
9683 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
9684 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
9685 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
9686 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
9687 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
9688 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
9689 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
9690 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
9691 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
9692 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
9693 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
9694 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
9695 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
9696 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
9697 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
9698 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
9699 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
9700 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
9701 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
9702 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
9703 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
9704 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
9705 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
9706 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
9707 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
9708 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
9709 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
9710 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
9711 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
9712 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
9713 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
9714 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
9717 * These messages have a special handler from the start.
9719 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9720 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9721 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9724 static void ssh2_timer(void *ctx, unsigned long now)
9728 if (ssh->state == SSH_STATE_CLOSED)
9731 if (!ssh->kex_in_progress && conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
9732 now == ssh->next_rekey) {
9733 do_ssh2_transport(ssh, "timeout", -1, NULL);
9737 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9738 struct Packet *pktin)
9740 unsigned char *in = (unsigned char *)vin;
9741 if (ssh->state == SSH_STATE_CLOSED)
9745 ssh->incoming_data_size += pktin->encrypted_len;
9746 if (!ssh->kex_in_progress &&
9747 ssh->max_data_size != 0 &&
9748 ssh->incoming_data_size > ssh->max_data_size)
9749 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9753 ssh->packet_dispatch[pktin->type](ssh, pktin);
9754 else if (!ssh->protocol_initial_phase_done)
9755 do_ssh2_transport(ssh, in, inlen, pktin);
9757 do_ssh2_authconn(ssh, in, inlen, pktin);
9760 static void ssh_cache_conf_values(Ssh ssh)
9762 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
9766 * Called to set up the connection.
9768 * Returns an error message, or NULL on success.
9770 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9771 Conf *conf, char *host, int port, char **realhost,
9772 int nodelay, int keepalive)
9777 ssh = snew(struct ssh_tag);
9778 ssh->conf = conf_copy(conf);
9779 ssh_cache_conf_values(ssh);
9780 ssh->version = 0; /* when not ready yet */
9783 ssh->v1_cipher_ctx = NULL;
9784 ssh->crcda_ctx = NULL;
9785 ssh->cscipher = NULL;
9786 ssh->cs_cipher_ctx = NULL;
9787 ssh->sccipher = NULL;
9788 ssh->sc_cipher_ctx = NULL;
9790 ssh->cs_mac_ctx = NULL;
9792 ssh->sc_mac_ctx = NULL;
9794 ssh->cs_comp_ctx = NULL;
9796 ssh->sc_comp_ctx = NULL;
9798 ssh->kex_ctx = NULL;
9799 ssh->hostkey = NULL;
9800 ssh->hostkey_str = NULL;
9802 ssh->close_expected = FALSE;
9803 ssh->clean_exit = FALSE;
9804 ssh->state = SSH_STATE_PREPACKET;
9805 ssh->size_needed = FALSE;
9806 ssh->eof_needed = FALSE;
9809 ssh->deferred_send_data = NULL;
9810 ssh->deferred_len = 0;
9811 ssh->deferred_size = 0;
9812 ssh->fallback_cmd = 0;
9813 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9814 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9815 ssh->x11disp = NULL;
9816 ssh->x11auth = NULL;
9817 ssh->x11authtree = newtree234(x11_authcmp);
9818 ssh->v1_compressing = FALSE;
9819 ssh->v2_outgoing_sequence = 0;
9820 ssh->ssh1_rdpkt_crstate = 0;
9821 ssh->ssh2_rdpkt_crstate = 0;
9822 ssh->ssh_gotdata_crstate = 0;
9823 ssh->do_ssh1_connection_crstate = 0;
9824 ssh->do_ssh_init_state = NULL;
9825 ssh->do_ssh1_login_state = NULL;
9826 ssh->do_ssh2_transport_state = NULL;
9827 ssh->do_ssh2_authconn_state = NULL;
9830 ssh->mainchan = NULL;
9831 ssh->throttled_all = 0;
9832 ssh->v1_stdout_throttling = 0;
9834 ssh->queuelen = ssh->queuesize = 0;
9835 ssh->queueing = FALSE;
9836 ssh->qhead = ssh->qtail = NULL;
9837 ssh->deferred_rekey_reason = NULL;
9838 bufchain_init(&ssh->queued_incoming_data);
9839 ssh->frozen = FALSE;
9840 ssh->username = NULL;
9841 ssh->sent_console_eof = FALSE;
9842 ssh->got_pty = FALSE;
9844 *backend_handle = ssh;
9847 if (crypto_startup() == 0)
9848 return "Microsoft high encryption pack not installed!";
9851 ssh->frontend = frontend_handle;
9852 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
9853 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
9855 ssh->channels = NULL;
9856 ssh->rportfwds = NULL;
9857 ssh->portfwds = NULL;
9862 ssh->conn_throttle_count = 0;
9863 ssh->overall_bufsize = 0;
9864 ssh->fallback_cmd = 0;
9866 ssh->protocol = NULL;
9868 ssh->protocol_initial_phase_done = FALSE;
9872 ssh->incoming_data_size = ssh->outgoing_data_size =
9873 ssh->deferred_data_size = 0L;
9874 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9875 CONF_ssh_rekey_data));
9876 ssh->kex_in_progress = FALSE;
9879 ssh->gsslibs = NULL;
9882 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9891 static void ssh_free(void *handle)
9893 Ssh ssh = (Ssh) handle;
9894 struct ssh_channel *c;
9895 struct ssh_rportfwd *pf;
9896 struct X11FakeAuth *auth;
9898 if (ssh->v1_cipher_ctx)
9899 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9900 if (ssh->cs_cipher_ctx)
9901 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9902 if (ssh->sc_cipher_ctx)
9903 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9904 if (ssh->cs_mac_ctx)
9905 ssh->csmac->free_context(ssh->cs_mac_ctx);
9906 if (ssh->sc_mac_ctx)
9907 ssh->scmac->free_context(ssh->sc_mac_ctx);
9908 if (ssh->cs_comp_ctx) {
9910 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9912 zlib_compress_cleanup(ssh->cs_comp_ctx);
9914 if (ssh->sc_comp_ctx) {
9916 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9918 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9921 dh_cleanup(ssh->kex_ctx);
9922 sfree(ssh->savedhost);
9924 while (ssh->queuelen-- > 0)
9925 ssh_free_packet(ssh->queue[ssh->queuelen]);
9928 while (ssh->qhead) {
9929 struct queued_handler *qh = ssh->qhead;
9930 ssh->qhead = qh->next;
9933 ssh->qhead = ssh->qtail = NULL;
9935 if (ssh->channels) {
9936 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9939 if (c->u.x11.xconn != NULL)
9940 x11_close(c->u.x11.xconn);
9943 case CHAN_SOCKDATA_DORMANT:
9944 if (c->u.pfd.pf != NULL)
9945 pfd_close(c->u.pfd.pf);
9948 if (ssh->version == 2) {
9949 struct outstanding_channel_request *ocr, *nocr;
9950 ocr = c->v.v2.chanreq_head;
9952 ocr->handler(c, NULL, ocr->ctx);
9957 bufchain_clear(&c->v.v2.outbuffer);
9961 freetree234(ssh->channels);
9962 ssh->channels = NULL;
9965 if (ssh->rportfwds) {
9966 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9968 freetree234(ssh->rportfwds);
9969 ssh->rportfwds = NULL;
9971 sfree(ssh->deferred_send_data);
9973 x11_free_display(ssh->x11disp);
9974 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
9975 x11_free_fake_auth(auth);
9976 freetree234(ssh->x11authtree);
9977 sfree(ssh->do_ssh_init_state);
9978 sfree(ssh->do_ssh1_login_state);
9979 sfree(ssh->do_ssh2_transport_state);
9980 sfree(ssh->do_ssh2_authconn_state);
9983 sfree(ssh->fullhostname);
9984 sfree(ssh->hostkey_str);
9985 if (ssh->crcda_ctx) {
9986 crcda_free_context(ssh->crcda_ctx);
9987 ssh->crcda_ctx = NULL;
9990 ssh_do_close(ssh, TRUE);
9991 expire_timer_context(ssh);
9993 pinger_free(ssh->pinger);
9994 bufchain_clear(&ssh->queued_incoming_data);
9995 sfree(ssh->username);
9996 conf_free(ssh->conf);
9999 ssh_gss_cleanup(ssh->gsslibs);
10007 * Reconfigure the SSH backend.
10009 static void ssh_reconfig(void *handle, Conf *conf)
10011 Ssh ssh = (Ssh) handle;
10012 char *rekeying = NULL, rekey_mandatory = FALSE;
10013 unsigned long old_max_data_size;
10016 pinger_reconfig(ssh->pinger, ssh->conf, conf);
10018 ssh_setup_portfwd(ssh, conf);
10020 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
10021 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
10023 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
10024 unsigned long now = GETTICKCOUNT();
10026 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
10027 rekeying = "timeout shortened";
10029 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
10033 old_max_data_size = ssh->max_data_size;
10034 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10035 CONF_ssh_rekey_data));
10036 if (old_max_data_size != ssh->max_data_size &&
10037 ssh->max_data_size != 0) {
10038 if (ssh->outgoing_data_size > ssh->max_data_size ||
10039 ssh->incoming_data_size > ssh->max_data_size)
10040 rekeying = "data limit lowered";
10043 if (conf_get_int(ssh->conf, CONF_compression) !=
10044 conf_get_int(conf, CONF_compression)) {
10045 rekeying = "compression setting changed";
10046 rekey_mandatory = TRUE;
10049 for (i = 0; i < CIPHER_MAX; i++)
10050 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
10051 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
10052 rekeying = "cipher settings changed";
10053 rekey_mandatory = TRUE;
10055 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
10056 conf_get_int(conf, CONF_ssh2_des_cbc)) {
10057 rekeying = "cipher settings changed";
10058 rekey_mandatory = TRUE;
10061 conf_free(ssh->conf);
10062 ssh->conf = conf_copy(conf);
10063 ssh_cache_conf_values(ssh);
10066 if (!ssh->kex_in_progress) {
10067 do_ssh2_transport(ssh, rekeying, -1, NULL);
10068 } else if (rekey_mandatory) {
10069 ssh->deferred_rekey_reason = rekeying;
10075 * Called to send data down the SSH connection.
10077 static int ssh_send(void *handle, char *buf, int len)
10079 Ssh ssh = (Ssh) handle;
10081 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10084 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
10086 return ssh_sendbuffer(ssh);
10090 * Called to query the current amount of buffered stdin data.
10092 static int ssh_sendbuffer(void *handle)
10094 Ssh ssh = (Ssh) handle;
10095 int override_value;
10097 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10101 * If the SSH socket itself has backed up, add the total backup
10102 * size on that to any individual buffer on the stdin channel.
10104 override_value = 0;
10105 if (ssh->throttled_all)
10106 override_value = ssh->overall_bufsize;
10108 if (ssh->version == 1) {
10109 return override_value;
10110 } else if (ssh->version == 2) {
10111 if (!ssh->mainchan)
10112 return override_value;
10114 return (override_value +
10115 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
10122 * Called to set the size of the window from SSH's POV.
10124 static void ssh_size(void *handle, int width, int height)
10126 Ssh ssh = (Ssh) handle;
10127 struct Packet *pktout;
10129 ssh->term_width = width;
10130 ssh->term_height = height;
10132 switch (ssh->state) {
10133 case SSH_STATE_BEFORE_SIZE:
10134 case SSH_STATE_PREPACKET:
10135 case SSH_STATE_CLOSED:
10136 break; /* do nothing */
10137 case SSH_STATE_INTERMED:
10138 ssh->size_needed = TRUE; /* buffer for later */
10140 case SSH_STATE_SESSION:
10141 if (!conf_get_int(ssh->conf, CONF_nopty)) {
10142 if (ssh->version == 1) {
10143 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
10144 PKT_INT, ssh->term_height,
10145 PKT_INT, ssh->term_width,
10146 PKT_INT, 0, PKT_INT, 0, PKT_END);
10147 } else if (ssh->mainchan) {
10148 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
10150 ssh2_pkt_adduint32(pktout, ssh->term_width);
10151 ssh2_pkt_adduint32(pktout, ssh->term_height);
10152 ssh2_pkt_adduint32(pktout, 0);
10153 ssh2_pkt_adduint32(pktout, 0);
10154 ssh2_pkt_send(ssh, pktout);
10162 * Return a list of the special codes that make sense in this
10165 static const struct telnet_special *ssh_get_specials(void *handle)
10167 static const struct telnet_special ssh1_ignore_special[] = {
10168 {"IGNORE message", TS_NOP}
10170 static const struct telnet_special ssh2_ignore_special[] = {
10171 {"IGNORE message", TS_NOP},
10173 static const struct telnet_special ssh2_rekey_special[] = {
10174 {"Repeat key exchange", TS_REKEY},
10176 static const struct telnet_special ssh2_session_specials[] = {
10179 /* These are the signal names defined by RFC 4254.
10180 * They include all the ISO C signals, but are a subset of the POSIX
10181 * required signals. */
10182 {"SIGINT (Interrupt)", TS_SIGINT},
10183 {"SIGTERM (Terminate)", TS_SIGTERM},
10184 {"SIGKILL (Kill)", TS_SIGKILL},
10185 {"SIGQUIT (Quit)", TS_SIGQUIT},
10186 {"SIGHUP (Hangup)", TS_SIGHUP},
10187 {"More signals", TS_SUBMENU},
10188 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
10189 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
10190 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
10191 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
10192 {NULL, TS_EXITMENU}
10194 static const struct telnet_special specials_end[] = {
10195 {NULL, TS_EXITMENU}
10197 /* XXX review this length for any changes: */
10198 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
10199 lenof(ssh2_rekey_special) +
10200 lenof(ssh2_session_specials) +
10201 lenof(specials_end)];
10202 Ssh ssh = (Ssh) handle;
10204 #define ADD_SPECIALS(name) \
10206 assert((i + lenof(name)) <= lenof(ssh_specials)); \
10207 memcpy(&ssh_specials[i], name, sizeof name); \
10208 i += lenof(name); \
10211 if (ssh->version == 1) {
10212 /* Don't bother offering IGNORE if we've decided the remote
10213 * won't cope with it, since we wouldn't bother sending it if
10215 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10216 ADD_SPECIALS(ssh1_ignore_special);
10217 } else if (ssh->version == 2) {
10218 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
10219 ADD_SPECIALS(ssh2_ignore_special);
10220 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
10221 ADD_SPECIALS(ssh2_rekey_special);
10223 ADD_SPECIALS(ssh2_session_specials);
10224 } /* else we're not ready yet */
10227 ADD_SPECIALS(specials_end);
10228 return ssh_specials;
10232 #undef ADD_SPECIALS
10236 * Send special codes. TS_EOF is useful for `plink', so you
10237 * can send an EOF and collect resulting output (e.g. `plink
10240 static void ssh_special(void *handle, Telnet_Special code)
10242 Ssh ssh = (Ssh) handle;
10243 struct Packet *pktout;
10245 if (code == TS_EOF) {
10246 if (ssh->state != SSH_STATE_SESSION) {
10248 * Buffer the EOF in case we are pre-SESSION, so we can
10249 * send it as soon as we reach SESSION.
10251 if (code == TS_EOF)
10252 ssh->eof_needed = TRUE;
10255 if (ssh->version == 1) {
10256 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
10257 } else if (ssh->mainchan) {
10258 sshfwd_write_eof(ssh->mainchan);
10259 ssh->send_ok = 0; /* now stop trying to read from stdin */
10261 logevent("Sent EOF message");
10262 } else if (code == TS_PING || code == TS_NOP) {
10263 if (ssh->state == SSH_STATE_CLOSED
10264 || ssh->state == SSH_STATE_PREPACKET) return;
10265 if (ssh->version == 1) {
10266 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10267 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
10269 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
10270 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
10271 ssh2_pkt_addstring_start(pktout);
10272 ssh2_pkt_send_noqueue(ssh, pktout);
10275 } else if (code == TS_REKEY) {
10276 if (!ssh->kex_in_progress && ssh->version == 2) {
10277 do_ssh2_transport(ssh, "at user request", -1, NULL);
10279 } else if (code == TS_BRK) {
10280 if (ssh->state == SSH_STATE_CLOSED
10281 || ssh->state == SSH_STATE_PREPACKET) return;
10282 if (ssh->version == 1) {
10283 logevent("Unable to send BREAK signal in SSH-1");
10284 } else if (ssh->mainchan) {
10285 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
10286 ssh2_pkt_adduint32(pktout, 0); /* default break length */
10287 ssh2_pkt_send(ssh, pktout);
10290 /* Is is a POSIX signal? */
10291 char *signame = NULL;
10292 if (code == TS_SIGABRT) signame = "ABRT";
10293 if (code == TS_SIGALRM) signame = "ALRM";
10294 if (code == TS_SIGFPE) signame = "FPE";
10295 if (code == TS_SIGHUP) signame = "HUP";
10296 if (code == TS_SIGILL) signame = "ILL";
10297 if (code == TS_SIGINT) signame = "INT";
10298 if (code == TS_SIGKILL) signame = "KILL";
10299 if (code == TS_SIGPIPE) signame = "PIPE";
10300 if (code == TS_SIGQUIT) signame = "QUIT";
10301 if (code == TS_SIGSEGV) signame = "SEGV";
10302 if (code == TS_SIGTERM) signame = "TERM";
10303 if (code == TS_SIGUSR1) signame = "USR1";
10304 if (code == TS_SIGUSR2) signame = "USR2";
10305 /* The SSH-2 protocol does in principle support arbitrary named
10306 * signals, including signame@domain, but we don't support those. */
10308 /* It's a signal. */
10309 if (ssh->version == 2 && ssh->mainchan) {
10310 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
10311 ssh2_pkt_addstring(pktout, signame);
10312 ssh2_pkt_send(ssh, pktout);
10313 logeventf(ssh, "Sent signal SIG%s", signame);
10316 /* Never heard of it. Do nothing */
10321 void *new_sock_channel(void *handle, struct PortForwarding *pf)
10323 Ssh ssh = (Ssh) handle;
10324 struct ssh_channel *c;
10325 c = snew(struct ssh_channel);
10328 ssh2_channel_init(c);
10329 c->halfopen = TRUE;
10330 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
10332 add234(ssh->channels, c);
10337 * This is called when stdout/stderr (the entity to which
10338 * from_backend sends data) manages to clear some backlog.
10340 static void ssh_unthrottle(void *handle, int bufsize)
10342 Ssh ssh = (Ssh) handle;
10345 if (ssh->version == 1) {
10346 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
10347 ssh->v1_stdout_throttling = 0;
10348 ssh_throttle_conn(ssh, -1);
10351 if (ssh->mainchan) {
10352 ssh2_set_window(ssh->mainchan,
10353 bufsize < ssh->mainchan->v.v2.locmaxwin ?
10354 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
10355 if (conf_get_int(ssh->conf, CONF_ssh_simple))
10358 buflimit = ssh->mainchan->v.v2.locmaxwin;
10359 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
10360 ssh->mainchan->throttling_conn = 0;
10361 ssh_throttle_conn(ssh, -1);
10367 * Now process any SSH connection data that was stashed in our
10368 * queue while we were frozen.
10370 ssh_process_queued_incoming_data(ssh);
10373 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
10375 struct ssh_channel *c = (struct ssh_channel *)channel;
10377 struct Packet *pktout;
10379 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
10381 if (ssh->version == 1) {
10382 send_packet(ssh, SSH1_MSG_PORT_OPEN,
10383 PKT_INT, c->localid,
10386 /* PKT_STR, <org:orgport>, */
10389 pktout = ssh2_chanopen_init(c, "direct-tcpip");
10390 ssh2_pkt_addstring(pktout, hostname);
10391 ssh2_pkt_adduint32(pktout, port);
10393 * We make up values for the originator data; partly it's
10394 * too much hassle to keep track, and partly I'm not
10395 * convinced the server should be told details like that
10396 * about my local network configuration.
10397 * The "originator IP address" is syntactically a numeric
10398 * IP address, and some servers (e.g., Tectia) get upset
10399 * if it doesn't match this syntax.
10401 ssh2_pkt_addstring(pktout, "0.0.0.0");
10402 ssh2_pkt_adduint32(pktout, 0);
10403 ssh2_pkt_send(ssh, pktout);
10407 static int ssh_connected(void *handle)
10409 Ssh ssh = (Ssh) handle;
10410 return ssh->s != NULL;
10413 static int ssh_sendok(void *handle)
10415 Ssh ssh = (Ssh) handle;
10416 return ssh->send_ok;
10419 static int ssh_ldisc(void *handle, int option)
10421 Ssh ssh = (Ssh) handle;
10422 if (option == LD_ECHO)
10423 return ssh->echoing;
10424 if (option == LD_EDIT)
10425 return ssh->editing;
10429 static void ssh_provide_ldisc(void *handle, void *ldisc)
10431 Ssh ssh = (Ssh) handle;
10432 ssh->ldisc = ldisc;
10435 static void ssh_provide_logctx(void *handle, void *logctx)
10437 Ssh ssh = (Ssh) handle;
10438 ssh->logctx = logctx;
10441 static int ssh_return_exitcode(void *handle)
10443 Ssh ssh = (Ssh) handle;
10444 if (ssh->s != NULL)
10447 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
10451 * cfg_info for SSH is the currently running version of the
10452 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
10454 static int ssh_cfg_info(void *handle)
10456 Ssh ssh = (Ssh) handle;
10457 return ssh->version;
10461 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
10462 * that fails. This variable is the means by which scp.c can reach
10463 * into the SSH code and find out which one it got.
10465 extern int ssh_fallback_cmd(void *handle)
10467 Ssh ssh = (Ssh) handle;
10468 return ssh->fallback_cmd;
10471 Backend ssh_backend = {
10481 ssh_return_exitcode,
10485 ssh_provide_logctx,