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;
791 int conn_throttle_count;
794 int v1_stdout_throttling;
795 unsigned long v2_outgoing_sequence;
797 int ssh1_rdpkt_crstate;
798 int ssh2_rdpkt_crstate;
799 int ssh_gotdata_crstate;
800 int do_ssh1_connection_crstate;
802 void *do_ssh_init_state;
803 void *do_ssh1_login_state;
804 void *do_ssh2_transport_state;
805 void *do_ssh2_authconn_state;
807 struct rdpkt1_state_tag rdpkt1_state;
808 struct rdpkt2_state_tag rdpkt2_state;
810 /* SSH-1 and SSH-2 use this for different things, but both use it */
811 int protocol_initial_phase_done;
813 void (*protocol) (Ssh ssh, void *vin, int inlen,
815 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
818 * We maintain our own copy of a Conf structure here. That way,
819 * when we're passed a new one for reconfiguration, we can check
820 * the differences and potentially reconfigure port forwardings
821 * etc in mid-session.
826 * Values cached out of conf so as to avoid the tree234 lookup
827 * cost every time they're used.
832 * Dynamically allocated username string created during SSH
833 * login. Stored in here rather than in the coroutine state so
834 * that it'll be reliably freed if we shut down the SSH session
835 * at some unexpected moment.
840 * Used to transfer data back from async callbacks.
842 void *agent_response;
843 int agent_response_len;
847 * The SSH connection can be set as `frozen', meaning we are
848 * not currently accepting incoming data from the network. This
849 * is slightly more serious than setting the _socket_ as
850 * frozen, because we may already have had data passed to us
851 * from the network which we need to delay processing until
852 * after the freeze is lifted, so we also need a bufchain to
856 bufchain queued_incoming_data;
859 * Dispatch table for packet types that we may have to deal
862 handler_fn_t packet_dispatch[256];
865 * Queues of one-off handler functions for success/failure
866 * indications from a request.
868 struct queued_handler *qhead, *qtail;
869 handler_fn_t q_saved_handler1, q_saved_handler2;
872 * This module deals with sending keepalives.
877 * Track incoming and outgoing data sizes and time, for
880 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
881 unsigned long max_data_size;
883 unsigned long next_rekey, last_rekey;
884 char *deferred_rekey_reason; /* points to STATIC string; don't free */
887 * Fully qualified host name, which we need if doing GSSAPI.
893 * GSSAPI libraries for this session.
895 struct ssh_gss_liblist *gsslibs;
899 #define logevent(s) logevent(ssh->frontend, s)
901 /* logevent, only printf-formatted. */
902 static void logeventf(Ssh ssh, const char *fmt, ...)
908 buf = dupvprintf(fmt, ap);
914 static void bomb_out(Ssh ssh, char *text)
916 ssh_do_close(ssh, FALSE);
918 connection_fatal(ssh->frontend, "%s", text);
922 #define bombout(msg) bomb_out(ssh, dupprintf msg)
924 /* Helper function for common bits of parsing ttymodes. */
925 static void parse_ttymodes(Ssh ssh,
926 void (*do_mode)(void *data, char *mode, char *val),
931 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
933 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
935 * val[0] is either 'V', indicating that an explicit value
936 * follows it, or 'A' indicating that we should pass the
937 * value through from the local environment via get_ttymode.
940 val = get_ttymode(ssh->frontend, key);
942 do_mode(data, key, val);
946 do_mode(data, key, val + 1); /* skip the 'V' */
950 static int ssh_channelcmp(void *av, void *bv)
952 struct ssh_channel *a = (struct ssh_channel *) av;
953 struct ssh_channel *b = (struct ssh_channel *) bv;
954 if (a->localid < b->localid)
956 if (a->localid > b->localid)
960 static int ssh_channelfind(void *av, void *bv)
962 unsigned *a = (unsigned *) av;
963 struct ssh_channel *b = (struct ssh_channel *) bv;
971 static int ssh_rportcmp_ssh1(void *av, void *bv)
973 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
974 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
976 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
977 return i < 0 ? -1 : +1;
978 if (a->dport > b->dport)
980 if (a->dport < b->dport)
985 static int ssh_rportcmp_ssh2(void *av, void *bv)
987 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
988 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
990 if ( (i = strcmp(a->shost, b->shost)) != 0)
991 return i < 0 ? -1 : +1;
992 if (a->sport > b->sport)
994 if (a->sport < b->sport)
1000 * Special form of strcmp which can cope with NULL inputs. NULL is
1001 * defined to sort before even the empty string.
1003 static int nullstrcmp(const char *a, const char *b)
1005 if (a == NULL && b == NULL)
1011 return strcmp(a, b);
1014 static int ssh_portcmp(void *av, void *bv)
1016 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1017 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1019 if (a->type > b->type)
1021 if (a->type < b->type)
1023 if (a->addressfamily > b->addressfamily)
1025 if (a->addressfamily < b->addressfamily)
1027 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1028 return i < 0 ? -1 : +1;
1029 if (a->sport > b->sport)
1031 if (a->sport < b->sport)
1033 if (a->type != 'D') {
1034 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1035 return i < 0 ? -1 : +1;
1036 if (a->dport > b->dport)
1038 if (a->dport < b->dport)
1044 static int alloc_channel_id(Ssh ssh)
1046 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1047 unsigned low, high, mid;
1049 struct ssh_channel *c;
1052 * First-fit allocation of channel numbers: always pick the
1053 * lowest unused one. To do this, binary-search using the
1054 * counted B-tree to find the largest channel ID which is in a
1055 * contiguous sequence from the beginning. (Precisely
1056 * everything in that sequence must have ID equal to its tree
1057 * index plus CHANNEL_NUMBER_OFFSET.)
1059 tsize = count234(ssh->channels);
1063 while (high - low > 1) {
1064 mid = (high + low) / 2;
1065 c = index234(ssh->channels, mid);
1066 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1067 low = mid; /* this one is fine */
1069 high = mid; /* this one is past it */
1072 * Now low points to either -1, or the tree index of the
1073 * largest ID in the initial sequence.
1076 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1077 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1079 return low + 1 + CHANNEL_NUMBER_OFFSET;
1082 static void c_write_stderr(int trusted, const char *buf, int len)
1085 for (i = 0; i < len; i++)
1086 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1087 fputc(buf[i], stderr);
1090 static void c_write(Ssh ssh, const char *buf, int len)
1092 if (flags & FLAG_STDERR)
1093 c_write_stderr(1, buf, len);
1095 from_backend(ssh->frontend, 1, buf, len);
1098 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1100 if (flags & FLAG_STDERR)
1101 c_write_stderr(0, buf, len);
1103 from_backend_untrusted(ssh->frontend, buf, len);
1106 static void c_write_str(Ssh ssh, const char *buf)
1108 c_write(ssh, buf, strlen(buf));
1111 static void ssh_free_packet(struct Packet *pkt)
1116 static struct Packet *ssh_new_packet(void)
1118 struct Packet *pkt = snew(struct Packet);
1120 pkt->body = pkt->data = NULL;
1126 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1129 struct logblank_t blanks[4];
1135 if (ssh->logomitdata &&
1136 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1137 pkt->type == SSH1_SMSG_STDERR_DATA ||
1138 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1139 /* "Session data" packets - omit the data string. */
1140 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1141 ssh_pkt_getuint32(pkt); /* skip channel id */
1142 blanks[nblanks].offset = pkt->savedpos + 4;
1143 blanks[nblanks].type = PKTLOG_OMIT;
1144 ssh_pkt_getstring(pkt, &str, &slen);
1146 blanks[nblanks].len = slen;
1150 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1151 ssh1_pkt_type(pkt->type),
1152 pkt->body, pkt->length, nblanks, blanks, NULL);
1155 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1158 struct logblank_t blanks[4];
1163 * For outgoing packets, pkt->length represents the length of the
1164 * whole packet starting at pkt->data (including some header), and
1165 * pkt->body refers to the point within that where the log-worthy
1166 * payload begins. However, incoming packets expect pkt->length to
1167 * represent only the payload length (that is, it's measured from
1168 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1169 * packet to conform to the incoming-packet semantics, so that we
1170 * can analyse it with the ssh_pkt_get functions.
1172 pkt->length -= (pkt->body - pkt->data);
1175 if (ssh->logomitdata &&
1176 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1177 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1178 /* "Session data" packets - omit the data string. */
1179 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1180 ssh_pkt_getuint32(pkt); /* skip channel id */
1181 blanks[nblanks].offset = pkt->savedpos + 4;
1182 blanks[nblanks].type = PKTLOG_OMIT;
1183 ssh_pkt_getstring(pkt, &str, &slen);
1185 blanks[nblanks].len = slen;
1190 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1191 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1192 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1193 conf_get_int(ssh->conf, CONF_logomitpass)) {
1194 /* If this is a password or similar packet, blank the password(s). */
1195 blanks[nblanks].offset = 0;
1196 blanks[nblanks].len = pkt->length;
1197 blanks[nblanks].type = PKTLOG_BLANK;
1199 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1200 conf_get_int(ssh->conf, CONF_logomitpass)) {
1202 * If this is an X forwarding request packet, blank the fake
1205 * Note that while we blank the X authentication data here, we
1206 * don't take any special action to blank the start of an X11
1207 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1208 * an X connection without having session blanking enabled is
1209 * likely to leak your cookie into the log.
1212 ssh_pkt_getstring(pkt, &str, &slen);
1213 blanks[nblanks].offset = pkt->savedpos;
1214 blanks[nblanks].type = PKTLOG_BLANK;
1215 ssh_pkt_getstring(pkt, &str, &slen);
1217 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1222 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1223 ssh1_pkt_type(pkt->data[12]),
1224 pkt->body, pkt->length,
1225 nblanks, blanks, NULL);
1228 * Undo the above adjustment of pkt->length, to put the packet
1229 * back in the state we found it.
1231 pkt->length += (pkt->body - pkt->data);
1235 * Collect incoming data in the incoming packet buffer.
1236 * Decipher and verify the packet when it is completely read.
1237 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1238 * Update the *data and *datalen variables.
1239 * Return a Packet structure when a packet is completed.
1241 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1243 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1245 crBegin(ssh->ssh1_rdpkt_crstate);
1247 st->pktin = ssh_new_packet();
1249 st->pktin->type = 0;
1250 st->pktin->length = 0;
1252 for (st->i = st->len = 0; st->i < 4; st->i++) {
1253 while ((*datalen) == 0)
1255 st->len = (st->len << 8) + **data;
1256 (*data)++, (*datalen)--;
1259 st->pad = 8 - (st->len % 8);
1260 st->biglen = st->len + st->pad;
1261 st->pktin->length = st->len - 5;
1263 if (st->biglen < 0) {
1264 bombout(("Extremely large packet length from server suggests"
1265 " data stream corruption"));
1266 ssh_free_packet(st->pktin);
1270 st->pktin->maxlen = st->biglen;
1271 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1273 st->to_read = st->biglen;
1274 st->p = st->pktin->data;
1275 while (st->to_read > 0) {
1276 st->chunk = st->to_read;
1277 while ((*datalen) == 0)
1279 if (st->chunk > (*datalen))
1280 st->chunk = (*datalen);
1281 memcpy(st->p, *data, st->chunk);
1283 *datalen -= st->chunk;
1285 st->to_read -= st->chunk;
1288 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1289 st->biglen, NULL)) {
1290 bombout(("Network attack (CRC compensation) detected!"));
1291 ssh_free_packet(st->pktin);
1296 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1298 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1299 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1300 if (st->gotcrc != st->realcrc) {
1301 bombout(("Incorrect CRC received on packet"));
1302 ssh_free_packet(st->pktin);
1306 st->pktin->body = st->pktin->data + st->pad + 1;
1308 if (ssh->v1_compressing) {
1309 unsigned char *decompblk;
1311 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1312 st->pktin->body - 1, st->pktin->length + 1,
1313 &decompblk, &decomplen)) {
1314 bombout(("Zlib decompression encountered invalid data"));
1315 ssh_free_packet(st->pktin);
1319 if (st->pktin->maxlen < st->pad + decomplen) {
1320 st->pktin->maxlen = st->pad + decomplen;
1321 st->pktin->data = sresize(st->pktin->data,
1322 st->pktin->maxlen + APIEXTRA,
1324 st->pktin->body = st->pktin->data + st->pad + 1;
1327 memcpy(st->pktin->body - 1, decompblk, decomplen);
1329 st->pktin->length = decomplen - 1;
1332 st->pktin->type = st->pktin->body[-1];
1335 * Now pktin->body and pktin->length identify the semantic content
1336 * of the packet, excluding the initial type byte.
1340 ssh1_log_incoming_packet(ssh, st->pktin);
1342 st->pktin->savedpos = 0;
1344 crFinish(st->pktin);
1347 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1350 struct logblank_t blanks[4];
1356 if (ssh->logomitdata &&
1357 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1358 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1359 /* "Session data" packets - omit the data string. */
1360 ssh_pkt_getuint32(pkt); /* skip channel id */
1361 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1362 ssh_pkt_getuint32(pkt); /* skip extended data type */
1363 blanks[nblanks].offset = pkt->savedpos + 4;
1364 blanks[nblanks].type = PKTLOG_OMIT;
1365 ssh_pkt_getstring(pkt, &str, &slen);
1367 blanks[nblanks].len = slen;
1372 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1373 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1374 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence);
1377 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1380 struct logblank_t blanks[4];
1385 * For outgoing packets, pkt->length represents the length of the
1386 * whole packet starting at pkt->data (including some header), and
1387 * pkt->body refers to the point within that where the log-worthy
1388 * payload begins. However, incoming packets expect pkt->length to
1389 * represent only the payload length (that is, it's measured from
1390 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1391 * packet to conform to the incoming-packet semantics, so that we
1392 * can analyse it with the ssh_pkt_get functions.
1394 pkt->length -= (pkt->body - pkt->data);
1397 if (ssh->logomitdata &&
1398 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1399 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1400 /* "Session data" packets - omit the data string. */
1401 ssh_pkt_getuint32(pkt); /* skip channel id */
1402 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1403 ssh_pkt_getuint32(pkt); /* skip extended data type */
1404 blanks[nblanks].offset = pkt->savedpos + 4;
1405 blanks[nblanks].type = PKTLOG_OMIT;
1406 ssh_pkt_getstring(pkt, &str, &slen);
1408 blanks[nblanks].len = slen;
1413 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1414 conf_get_int(ssh->conf, CONF_logomitpass)) {
1415 /* If this is a password packet, blank the password(s). */
1417 ssh_pkt_getstring(pkt, &str, &slen);
1418 ssh_pkt_getstring(pkt, &str, &slen);
1419 ssh_pkt_getstring(pkt, &str, &slen);
1420 if (slen == 8 && !memcmp(str, "password", 8)) {
1421 ssh2_pkt_getbool(pkt);
1422 /* Blank the password field. */
1423 blanks[nblanks].offset = pkt->savedpos;
1424 blanks[nblanks].type = PKTLOG_BLANK;
1425 ssh_pkt_getstring(pkt, &str, &slen);
1427 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1429 /* If there's another password field beyond it (change of
1430 * password), blank that too. */
1431 ssh_pkt_getstring(pkt, &str, &slen);
1433 blanks[nblanks-1].len =
1434 pkt->savedpos - blanks[nblanks].offset;
1437 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1438 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1439 conf_get_int(ssh->conf, CONF_logomitpass)) {
1440 /* If this is a keyboard-interactive response packet, blank
1443 ssh_pkt_getuint32(pkt);
1444 blanks[nblanks].offset = pkt->savedpos;
1445 blanks[nblanks].type = PKTLOG_BLANK;
1447 ssh_pkt_getstring(pkt, &str, &slen);
1451 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1453 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1454 conf_get_int(ssh->conf, CONF_logomitpass)) {
1456 * If this is an X forwarding request packet, blank the fake
1459 * Note that while we blank the X authentication data here, we
1460 * don't take any special action to blank the start of an X11
1461 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1462 * an X connection without having session blanking enabled is
1463 * likely to leak your cookie into the log.
1466 ssh_pkt_getuint32(pkt);
1467 ssh_pkt_getstring(pkt, &str, &slen);
1468 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1469 ssh2_pkt_getbool(pkt);
1470 ssh2_pkt_getbool(pkt);
1471 ssh_pkt_getstring(pkt, &str, &slen);
1472 blanks[nblanks].offset = pkt->savedpos;
1473 blanks[nblanks].type = PKTLOG_BLANK;
1474 ssh_pkt_getstring(pkt, &str, &slen);
1476 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1482 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1483 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1484 pkt->body, pkt->length, nblanks, blanks,
1485 &ssh->v2_outgoing_sequence);
1488 * Undo the above adjustment of pkt->length, to put the packet
1489 * back in the state we found it.
1491 pkt->length += (pkt->body - pkt->data);
1494 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1496 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1498 crBegin(ssh->ssh2_rdpkt_crstate);
1500 st->pktin = ssh_new_packet();
1502 st->pktin->type = 0;
1503 st->pktin->length = 0;
1505 st->cipherblk = ssh->sccipher->blksize;
1508 if (st->cipherblk < 8)
1510 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1512 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1515 * When dealing with a CBC-mode cipher, we want to avoid the
1516 * possibility of an attacker's tweaking the ciphertext stream
1517 * so as to cause us to feed the same block to the block
1518 * cipher more than once and thus leak information
1519 * (VU#958563). The way we do this is not to take any
1520 * decisions on the basis of anything we've decrypted until
1521 * we've verified it with a MAC. That includes the packet
1522 * length, so we just read data and check the MAC repeatedly,
1523 * and when the MAC passes, see if the length we've got is
1527 /* May as well allocate the whole lot now. */
1528 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1531 /* Read an amount corresponding to the MAC. */
1532 for (st->i = 0; st->i < st->maclen; st->i++) {
1533 while ((*datalen) == 0)
1535 st->pktin->data[st->i] = *(*data)++;
1541 unsigned char seq[4];
1542 ssh->scmac->start(ssh->sc_mac_ctx);
1543 PUT_32BIT(seq, st->incoming_sequence);
1544 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1547 for (;;) { /* Once around this loop per cipher block. */
1548 /* Read another cipher-block's worth, and tack it onto the end. */
1549 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1550 while ((*datalen) == 0)
1552 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1555 /* Decrypt one more block (a little further back in the stream). */
1556 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1557 st->pktin->data + st->packetlen,
1559 /* Feed that block to the MAC. */
1560 ssh->scmac->bytes(ssh->sc_mac_ctx,
1561 st->pktin->data + st->packetlen, st->cipherblk);
1562 st->packetlen += st->cipherblk;
1563 /* See if that gives us a valid packet. */
1564 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1565 st->pktin->data + st->packetlen) &&
1566 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1569 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1570 bombout(("No valid incoming packet found"));
1571 ssh_free_packet(st->pktin);
1575 st->pktin->maxlen = st->packetlen + st->maclen;
1576 st->pktin->data = sresize(st->pktin->data,
1577 st->pktin->maxlen + APIEXTRA,
1580 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1583 * Acquire and decrypt the first block of the packet. This will
1584 * contain the length and padding details.
1586 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1587 while ((*datalen) == 0)
1589 st->pktin->data[st->i] = *(*data)++;
1594 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1595 st->pktin->data, st->cipherblk);
1598 * Now get the length figure.
1600 st->len = toint(GET_32BIT(st->pktin->data));
1603 * _Completely_ silly lengths should be stomped on before they
1604 * do us any more damage.
1606 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1607 (st->len + 4) % st->cipherblk != 0) {
1608 bombout(("Incoming packet was garbled on decryption"));
1609 ssh_free_packet(st->pktin);
1614 * So now we can work out the total packet length.
1616 st->packetlen = st->len + 4;
1619 * Allocate memory for the rest of the packet.
1621 st->pktin->maxlen = st->packetlen + st->maclen;
1622 st->pktin->data = sresize(st->pktin->data,
1623 st->pktin->maxlen + APIEXTRA,
1627 * Read and decrypt the remainder of the packet.
1629 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1631 while ((*datalen) == 0)
1633 st->pktin->data[st->i] = *(*data)++;
1636 /* Decrypt everything _except_ the MAC. */
1638 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1639 st->pktin->data + st->cipherblk,
1640 st->packetlen - st->cipherblk);
1646 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1647 st->len + 4, st->incoming_sequence)) {
1648 bombout(("Incorrect MAC received on packet"));
1649 ssh_free_packet(st->pktin);
1653 /* Get and sanity-check the amount of random padding. */
1654 st->pad = st->pktin->data[4];
1655 if (st->pad < 4 || st->len - st->pad < 1) {
1656 bombout(("Invalid padding length on received packet"));
1657 ssh_free_packet(st->pktin);
1661 * This enables us to deduce the payload length.
1663 st->payload = st->len - st->pad - 1;
1665 st->pktin->length = st->payload + 5;
1666 st->pktin->encrypted_len = st->packetlen;
1668 st->pktin->sequence = st->incoming_sequence++;
1671 * Decompress packet payload.
1674 unsigned char *newpayload;
1677 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1678 st->pktin->data + 5, st->pktin->length - 5,
1679 &newpayload, &newlen)) {
1680 if (st->pktin->maxlen < newlen + 5) {
1681 st->pktin->maxlen = newlen + 5;
1682 st->pktin->data = sresize(st->pktin->data,
1683 st->pktin->maxlen + APIEXTRA,
1686 st->pktin->length = 5 + newlen;
1687 memcpy(st->pktin->data + 5, newpayload, newlen);
1693 * pktin->body and pktin->length should identify the semantic
1694 * content of the packet, excluding the initial type byte.
1696 st->pktin->type = st->pktin->data[5];
1697 st->pktin->body = st->pktin->data + 6;
1698 st->pktin->length = st->packetlen - 6 - st->pad;
1699 assert(st->pktin->length >= 0); /* one last double-check */
1702 ssh2_log_incoming_packet(ssh, st->pktin);
1704 st->pktin->savedpos = 0;
1706 crFinish(st->pktin);
1709 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1711 int pad, biglen, i, pktoffs;
1715 * XXX various versions of SC (including 8.8.4) screw up the
1716 * register allocation in this function and use the same register
1717 * (D6) for len and as a temporary, with predictable results. The
1718 * following sledgehammer prevents this.
1725 ssh1_log_outgoing_packet(ssh, pkt);
1727 if (ssh->v1_compressing) {
1728 unsigned char *compblk;
1730 zlib_compress_block(ssh->cs_comp_ctx,
1731 pkt->data + 12, pkt->length - 12,
1732 &compblk, &complen);
1733 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1734 memcpy(pkt->data + 12, compblk, complen);
1736 pkt->length = complen + 12;
1739 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1741 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1742 pad = 8 - (len % 8);
1744 biglen = len + pad; /* len(padding+type+data+CRC) */
1746 for (i = pktoffs; i < 4+8; i++)
1747 pkt->data[i] = random_byte();
1748 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1749 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1750 PUT_32BIT(pkt->data + pktoffs, len);
1753 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1754 pkt->data + pktoffs + 4, biglen);
1756 if (offset_p) *offset_p = pktoffs;
1757 return biglen + 4; /* len(length+padding+type+data+CRC) */
1760 static int s_write(Ssh ssh, void *data, int len)
1763 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1765 return sk_write(ssh->s, (char *)data, len);
1768 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1770 int len, backlog, offset;
1771 len = s_wrpkt_prepare(ssh, pkt, &offset);
1772 backlog = s_write(ssh, pkt->data + offset, len);
1773 if (backlog > SSH_MAX_BACKLOG)
1774 ssh_throttle_all(ssh, 1, backlog);
1775 ssh_free_packet(pkt);
1778 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1781 len = s_wrpkt_prepare(ssh, pkt, &offset);
1782 if (ssh->deferred_len + len > ssh->deferred_size) {
1783 ssh->deferred_size = ssh->deferred_len + len + 128;
1784 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1788 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1789 pkt->data + offset, len);
1790 ssh->deferred_len += len;
1791 ssh_free_packet(pkt);
1795 * Construct a SSH-1 packet with the specified contents.
1796 * (This all-at-once interface used to be the only one, but now SSH-1
1797 * packets can also be constructed incrementally.)
1799 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1805 pkt = ssh1_pkt_init(pkttype);
1807 while ((argtype = va_arg(ap, int)) != PKT_END) {
1808 unsigned char *argp, argchar;
1810 unsigned long argint;
1813 /* Actual fields in the packet */
1815 argint = va_arg(ap, int);
1816 ssh_pkt_adduint32(pkt, argint);
1819 argchar = (unsigned char) va_arg(ap, int);
1820 ssh_pkt_addbyte(pkt, argchar);
1823 argp = va_arg(ap, unsigned char *);
1824 arglen = va_arg(ap, int);
1825 ssh_pkt_adddata(pkt, argp, arglen);
1828 sargp = va_arg(ap, char *);
1829 ssh_pkt_addstring(pkt, sargp);
1832 bn = va_arg(ap, Bignum);
1833 ssh1_pkt_addmp(pkt, bn);
1841 static void send_packet(Ssh ssh, int pkttype, ...)
1845 va_start(ap, pkttype);
1846 pkt = construct_packet(ssh, pkttype, ap);
1851 static void defer_packet(Ssh ssh, int pkttype, ...)
1855 va_start(ap, pkttype);
1856 pkt = construct_packet(ssh, pkttype, ap);
1858 s_wrpkt_defer(ssh, pkt);
1861 static int ssh_versioncmp(char *a, char *b)
1864 unsigned long av, bv;
1866 av = strtoul(a, &ae, 10);
1867 bv = strtoul(b, &be, 10);
1869 return (av < bv ? -1 : +1);
1874 av = strtoul(ae, &ae, 10);
1875 bv = strtoul(be, &be, 10);
1877 return (av < bv ? -1 : +1);
1882 * Utility routines for putting an SSH-protocol `string' and
1883 * `uint32' into a hash state.
1885 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1887 unsigned char lenblk[4];
1888 PUT_32BIT(lenblk, len);
1889 h->bytes(s, lenblk, 4);
1890 h->bytes(s, str, len);
1893 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
1895 unsigned char intblk[4];
1896 PUT_32BIT(intblk, i);
1897 h->bytes(s, intblk, 4);
1901 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
1903 static void ssh_pkt_ensure(struct Packet *pkt, int length)
1905 if (pkt->maxlen < length) {
1906 unsigned char *body = pkt->body;
1907 int offset = body ? body - pkt->data : 0;
1908 pkt->maxlen = length + 256;
1909 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
1910 if (body) pkt->body = pkt->data + offset;
1913 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
1916 ssh_pkt_ensure(pkt, pkt->length);
1917 memcpy(pkt->data + pkt->length - len, data, len);
1919 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
1921 ssh_pkt_adddata(pkt, &byte, 1);
1923 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
1925 ssh_pkt_adddata(pkt, &value, 1);
1927 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
1930 PUT_32BIT(x, value);
1931 ssh_pkt_adddata(pkt, x, 4);
1933 static void ssh_pkt_addstring_start(struct Packet *pkt)
1935 ssh_pkt_adduint32(pkt, 0);
1936 pkt->savedpos = pkt->length;
1938 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
1940 ssh_pkt_adddata(pkt, data, strlen(data));
1941 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1943 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
1946 ssh_pkt_adddata(pkt, data, len);
1947 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
1949 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
1951 ssh_pkt_addstring_start(pkt);
1952 ssh_pkt_addstring_str(pkt, data);
1954 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
1956 int len = ssh1_bignum_length(b);
1957 unsigned char *data = snewn(len, unsigned char);
1958 (void) ssh1_write_bignum(data, b);
1959 ssh_pkt_adddata(pkt, data, len);
1962 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
1965 int i, n = (bignum_bitcount(b) + 7) / 8;
1966 p = snewn(n + 1, unsigned char);
1968 for (i = 1; i <= n; i++)
1969 p[i] = bignum_byte(b, n - i);
1971 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1973 memmove(p, p + i, n + 1 - i);
1977 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
1981 p = ssh2_mpint_fmt(b, &len);
1982 ssh_pkt_addstring_start(pkt);
1983 ssh_pkt_addstring_data(pkt, (char *)p, len);
1987 static struct Packet *ssh1_pkt_init(int pkt_type)
1989 struct Packet *pkt = ssh_new_packet();
1990 pkt->length = 4 + 8; /* space for length + max padding */
1991 ssh_pkt_addbyte(pkt, pkt_type);
1992 pkt->body = pkt->data + pkt->length;
1993 pkt->type = pkt_type;
1997 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1998 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1999 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2000 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2001 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2002 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2003 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2004 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2005 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2007 static struct Packet *ssh2_pkt_init(int pkt_type)
2009 struct Packet *pkt = ssh_new_packet();
2010 pkt->length = 5; /* space for packet length + padding length */
2012 pkt->type = pkt_type;
2013 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2014 pkt->body = pkt->data + pkt->length; /* after packet type */
2019 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2020 * put the MAC on it. Final packet, ready to be sent, is stored in
2021 * pkt->data. Total length is returned.
2023 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2025 int cipherblk, maclen, padding, i;
2028 ssh2_log_outgoing_packet(ssh, pkt);
2031 * Compress packet payload.
2034 unsigned char *newpayload;
2037 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2039 &newpayload, &newlen)) {
2041 ssh2_pkt_adddata(pkt, newpayload, newlen);
2047 * Add padding. At least four bytes, and must also bring total
2048 * length (minus MAC) up to a multiple of the block size.
2049 * If pkt->forcepad is set, make sure the packet is at least that size
2052 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2053 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2055 if (pkt->length + padding < pkt->forcepad)
2056 padding = pkt->forcepad - pkt->length;
2058 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
2059 assert(padding <= 255);
2060 maclen = ssh->csmac ? ssh->csmac->len : 0;
2061 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2062 pkt->data[4] = padding;
2063 for (i = 0; i < padding; i++)
2064 pkt->data[pkt->length + i] = random_byte();
2065 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2067 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2068 pkt->length + padding,
2069 ssh->v2_outgoing_sequence);
2070 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2073 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2074 pkt->data, pkt->length + padding);
2076 pkt->encrypted_len = pkt->length + padding;
2078 /* Ready-to-send packet starts at pkt->data. We return length. */
2079 return pkt->length + padding + maclen;
2083 * Routines called from the main SSH code to send packets. There
2084 * are quite a few of these, because we have two separate
2085 * mechanisms for delaying the sending of packets:
2087 * - In order to send an IGNORE message and a password message in
2088 * a single fixed-length blob, we require the ability to
2089 * concatenate the encrypted forms of those two packets _into_ a
2090 * single blob and then pass it to our <network.h> transport
2091 * layer in one go. Hence, there's a deferment mechanism which
2092 * works after packet encryption.
2094 * - In order to avoid sending any connection-layer messages
2095 * during repeat key exchange, we have to queue up any such
2096 * outgoing messages _before_ they are encrypted (and in
2097 * particular before they're allocated sequence numbers), and
2098 * then send them once we've finished.
2100 * I call these mechanisms `defer' and `queue' respectively, so as
2101 * to distinguish them reasonably easily.
2103 * The functions send_noqueue() and defer_noqueue() free the packet
2104 * structure they are passed. Every outgoing packet goes through
2105 * precisely one of these functions in its life; packets passed to
2106 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2107 * these or get queued, and then when the queue is later emptied
2108 * the packets are all passed to defer_noqueue().
2110 * When using a CBC-mode cipher, it's necessary to ensure that an
2111 * attacker can't provide data to be encrypted using an IV that they
2112 * know. We ensure this by prefixing each packet that might contain
2113 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2114 * mechanism, so in this case send_noqueue() ends up redirecting to
2115 * defer_noqueue(). If you don't like this inefficiency, don't use
2119 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2120 static void ssh_pkt_defersend(Ssh);
2123 * Send an SSH-2 packet immediately, without queuing or deferring.
2125 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2129 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2130 /* We need to send two packets, so use the deferral mechanism. */
2131 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2132 ssh_pkt_defersend(ssh);
2135 len = ssh2_pkt_construct(ssh, pkt);
2136 backlog = s_write(ssh, pkt->data, len);
2137 if (backlog > SSH_MAX_BACKLOG)
2138 ssh_throttle_all(ssh, 1, backlog);
2140 ssh->outgoing_data_size += pkt->encrypted_len;
2141 if (!ssh->kex_in_progress &&
2142 ssh->max_data_size != 0 &&
2143 ssh->outgoing_data_size > ssh->max_data_size)
2144 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2146 ssh_free_packet(pkt);
2150 * Defer an SSH-2 packet.
2152 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2155 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2156 ssh->deferred_len == 0 && !noignore &&
2157 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2159 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2160 * get encrypted with a known IV.
2162 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2163 ssh2_pkt_addstring_start(ipkt);
2164 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2166 len = ssh2_pkt_construct(ssh, pkt);
2167 if (ssh->deferred_len + len > ssh->deferred_size) {
2168 ssh->deferred_size = ssh->deferred_len + len + 128;
2169 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2173 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
2174 ssh->deferred_len += len;
2175 ssh->deferred_data_size += pkt->encrypted_len;
2176 ssh_free_packet(pkt);
2180 * Queue an SSH-2 packet.
2182 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2184 assert(ssh->queueing);
2186 if (ssh->queuelen >= ssh->queuesize) {
2187 ssh->queuesize = ssh->queuelen + 32;
2188 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2191 ssh->queue[ssh->queuelen++] = pkt;
2195 * Either queue or send a packet, depending on whether queueing is
2198 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2201 ssh2_pkt_queue(ssh, pkt);
2203 ssh2_pkt_send_noqueue(ssh, pkt);
2207 * Either queue or defer a packet, depending on whether queueing is
2210 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2213 ssh2_pkt_queue(ssh, pkt);
2215 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2219 * Send the whole deferred data block constructed by
2220 * ssh2_pkt_defer() or SSH-1's defer_packet().
2222 * The expected use of the defer mechanism is that you call
2223 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2224 * not currently queueing, this simply sets up deferred_send_data
2225 * and then sends it. If we _are_ currently queueing, the calls to
2226 * ssh2_pkt_defer() put the deferred packets on to the queue
2227 * instead, and therefore ssh_pkt_defersend() has no deferred data
2228 * to send. Hence, there's no need to make it conditional on
2231 static void ssh_pkt_defersend(Ssh ssh)
2234 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2235 ssh->deferred_len = ssh->deferred_size = 0;
2236 sfree(ssh->deferred_send_data);
2237 ssh->deferred_send_data = NULL;
2238 if (backlog > SSH_MAX_BACKLOG)
2239 ssh_throttle_all(ssh, 1, backlog);
2241 ssh->outgoing_data_size += ssh->deferred_data_size;
2242 if (!ssh->kex_in_progress &&
2243 ssh->max_data_size != 0 &&
2244 ssh->outgoing_data_size > ssh->max_data_size)
2245 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2246 ssh->deferred_data_size = 0;
2250 * Send a packet whose length needs to be disguised (typically
2251 * passwords or keyboard-interactive responses).
2253 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2259 * The simplest way to do this is to adjust the
2260 * variable-length padding field in the outgoing packet.
2262 * Currently compiled out, because some Cisco SSH servers
2263 * don't like excessively padded packets (bah, why's it
2266 pkt->forcepad = padsize;
2267 ssh2_pkt_send(ssh, pkt);
2272 * If we can't do that, however, an alternative approach is
2273 * to use the pkt_defer mechanism to bundle the packet
2274 * tightly together with an SSH_MSG_IGNORE such that their
2275 * combined length is a constant. So first we construct the
2276 * final form of this packet and defer its sending.
2278 ssh2_pkt_defer(ssh, pkt);
2281 * Now construct an SSH_MSG_IGNORE which includes a string
2282 * that's an exact multiple of the cipher block size. (If
2283 * the cipher is NULL so that the block size is
2284 * unavailable, we don't do this trick at all, because we
2285 * gain nothing by it.)
2287 if (ssh->cscipher &&
2288 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2291 stringlen = (256 - ssh->deferred_len);
2292 stringlen += ssh->cscipher->blksize - 1;
2293 stringlen -= (stringlen % ssh->cscipher->blksize);
2296 * Temporarily disable actual compression, so we
2297 * can guarantee to get this string exactly the
2298 * length we want it. The compression-disabling
2299 * routine should return an integer indicating how
2300 * many bytes we should adjust our string length
2304 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2306 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2307 ssh2_pkt_addstring_start(pkt);
2308 for (i = 0; i < stringlen; i++) {
2309 char c = (char) random_byte();
2310 ssh2_pkt_addstring_data(pkt, &c, 1);
2312 ssh2_pkt_defer(ssh, pkt);
2314 ssh_pkt_defersend(ssh);
2319 * Send all queued SSH-2 packets. We send them by means of
2320 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2321 * packets that needed to be lumped together.
2323 static void ssh2_pkt_queuesend(Ssh ssh)
2327 assert(!ssh->queueing);
2329 for (i = 0; i < ssh->queuelen; i++)
2330 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2333 ssh_pkt_defersend(ssh);
2337 void bndebug(char *string, Bignum b)
2341 p = ssh2_mpint_fmt(b, &len);
2342 debug(("%s", string));
2343 for (i = 0; i < len; i++)
2344 debug((" %02x", p[i]));
2350 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2354 p = ssh2_mpint_fmt(b, &len);
2355 hash_string(h, s, p, len);
2360 * Packet decode functions for both SSH-1 and SSH-2.
2362 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2364 unsigned long value;
2365 if (pkt->length - pkt->savedpos < 4)
2366 return 0; /* arrgh, no way to decline (FIXME?) */
2367 value = GET_32BIT(pkt->body + pkt->savedpos);
2371 static int ssh2_pkt_getbool(struct Packet *pkt)
2373 unsigned long value;
2374 if (pkt->length - pkt->savedpos < 1)
2375 return 0; /* arrgh, no way to decline (FIXME?) */
2376 value = pkt->body[pkt->savedpos] != 0;
2380 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2385 if (pkt->length - pkt->savedpos < 4)
2387 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2392 if (pkt->length - pkt->savedpos < *length)
2394 *p = (char *)(pkt->body + pkt->savedpos);
2395 pkt->savedpos += *length;
2397 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2399 if (pkt->length - pkt->savedpos < length)
2401 pkt->savedpos += length;
2402 return pkt->body + (pkt->savedpos - length);
2404 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2405 unsigned char **keystr)
2409 j = makekey(pkt->body + pkt->savedpos,
2410 pkt->length - pkt->savedpos,
2417 assert(pkt->savedpos < pkt->length);
2421 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2426 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2427 pkt->length - pkt->savedpos, &b);
2435 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2441 ssh_pkt_getstring(pkt, &p, &length);
2446 b = bignum_from_bytes((unsigned char *)p, length);
2451 * Helper function to add an SSH-2 signature blob to a packet.
2452 * Expects to be shown the public key blob as well as the signature
2453 * blob. Normally works just like ssh2_pkt_addstring, but will
2454 * fiddle with the signature packet if necessary for
2455 * BUG_SSH2_RSA_PADDING.
2457 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2458 void *pkblob_v, int pkblob_len,
2459 void *sigblob_v, int sigblob_len)
2461 unsigned char *pkblob = (unsigned char *)pkblob_v;
2462 unsigned char *sigblob = (unsigned char *)sigblob_v;
2464 /* dmemdump(pkblob, pkblob_len); */
2465 /* dmemdump(sigblob, sigblob_len); */
2468 * See if this is in fact an ssh-rsa signature and a buggy
2469 * server; otherwise we can just do this the easy way.
2471 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2472 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2473 int pos, len, siglen;
2476 * Find the byte length of the modulus.
2479 pos = 4+7; /* skip over "ssh-rsa" */
2480 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2481 if (len < 0 || len > pkblob_len - pos - 4)
2483 pos += 4 + len; /* skip over exponent */
2484 if (pkblob_len - pos < 4)
2486 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2487 if (len < 0 || len > pkblob_len - pos - 4)
2489 pos += 4; /* find modulus itself */
2490 while (len > 0 && pkblob[pos] == 0)
2492 /* debug(("modulus length is %d\n", len)); */
2495 * Now find the signature integer.
2497 pos = 4+7; /* skip over "ssh-rsa" */
2498 if (sigblob_len < pos+4)
2500 siglen = toint(GET_32BIT(sigblob+pos));
2501 if (siglen != sigblob_len - pos - 4)
2503 /* debug(("signature length is %d\n", siglen)); */
2505 if (len != siglen) {
2506 unsigned char newlen[4];
2507 ssh2_pkt_addstring_start(pkt);
2508 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2509 /* dmemdump(sigblob, pos); */
2510 pos += 4; /* point to start of actual sig */
2511 PUT_32BIT(newlen, len);
2512 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2513 /* dmemdump(newlen, 4); */
2515 while (len-- > siglen) {
2516 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2517 /* dmemdump(newlen, 1); */
2519 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2520 /* dmemdump(sigblob+pos, siglen); */
2524 /* Otherwise fall through and do it the easy way. We also come
2525 * here as a fallback if we discover above that the key blob
2526 * is misformatted in some way. */
2530 ssh2_pkt_addstring_start(pkt);
2531 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2535 * Examine the remote side's version string and compare it against
2536 * a list of known buggy implementations.
2538 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2540 char *imp; /* pointer to implementation part */
2542 imp += strcspn(imp, "-");
2544 imp += strcspn(imp, "-");
2547 ssh->remote_bugs = 0;
2550 * General notes on server version strings:
2551 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2552 * here -- in particular, we've heard of one that's perfectly happy
2553 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2554 * so we can't distinguish them.
2556 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2557 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2558 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2559 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2560 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2561 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2563 * These versions don't support SSH1_MSG_IGNORE, so we have
2564 * to use a different defence against password length
2567 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2568 logevent("We believe remote version has SSH-1 ignore bug");
2571 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2572 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2573 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2575 * These versions need a plain password sent; they can't
2576 * handle having a null and a random length of data after
2579 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2580 logevent("We believe remote version needs a plain SSH-1 password");
2583 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2584 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2585 (!strcmp(imp, "Cisco-1.25")))) {
2587 * These versions apparently have no clue whatever about
2588 * RSA authentication and will panic and die if they see
2589 * an AUTH_RSA message.
2591 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2592 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2595 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2596 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2597 !wc_match("* VShell", imp) &&
2598 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2599 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2600 wc_match("2.1 *", imp)))) {
2602 * These versions have the HMAC bug.
2604 ssh->remote_bugs |= BUG_SSH2_HMAC;
2605 logevent("We believe remote version has SSH-2 HMAC bug");
2608 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2609 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2610 !wc_match("* VShell", imp) &&
2611 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2613 * These versions have the key-derivation bug (failing to
2614 * include the literal shared secret in the hashes that
2615 * generate the keys).
2617 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2618 logevent("We believe remote version has SSH-2 key-derivation bug");
2621 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2622 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2623 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2624 wc_match("OpenSSH_3.[0-2]*", imp)))) {
2626 * These versions have the SSH-2 RSA padding bug.
2628 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2629 logevent("We believe remote version has SSH-2 RSA padding bug");
2632 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2633 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2634 wc_match("OpenSSH_2.[0-2]*", imp))) {
2636 * These versions have the SSH-2 session-ID bug in
2637 * public-key authentication.
2639 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2640 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2643 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2644 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2645 (wc_match("DigiSSH_2.0", imp) ||
2646 wc_match("OpenSSH_2.[0-4]*", imp) ||
2647 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2648 wc_match("Sun_SSH_1.0", imp) ||
2649 wc_match("Sun_SSH_1.0.1", imp) ||
2650 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2651 wc_match("WeOnlyDo-*", imp)))) {
2653 * These versions have the SSH-2 rekey bug.
2655 ssh->remote_bugs |= BUG_SSH2_REKEY;
2656 logevent("We believe remote version has SSH-2 rekey bug");
2659 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2660 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2661 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2662 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2664 * This version ignores our makpkt and needs to be throttled.
2666 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2667 logevent("We believe remote version ignores SSH-2 maximum packet size");
2670 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2672 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2673 * none detected automatically.
2675 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2676 logevent("We believe remote version has SSH-2 ignore bug");
2679 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2681 * Servers that don't support our winadj request for one
2682 * reason or another. Currently, none detected automatically.
2684 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2685 logevent("We believe remote version has winadj bug");
2690 * The `software version' part of an SSH version string is required
2691 * to contain no spaces or minus signs.
2693 static void ssh_fix_verstring(char *str)
2695 /* Eat "SSH-<protoversion>-". */
2696 assert(*str == 'S'); str++;
2697 assert(*str == 'S'); str++;
2698 assert(*str == 'H'); str++;
2699 assert(*str == '-'); str++;
2700 while (*str && *str != '-') str++;
2701 assert(*str == '-'); str++;
2703 /* Convert minus signs and spaces in the remaining string into
2706 if (*str == '-' || *str == ' ')
2713 * Send an appropriate SSH version string.
2715 static void ssh_send_verstring(Ssh ssh, char *svers)
2719 if (ssh->version == 2) {
2721 * Construct a v2 version string.
2723 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2726 * Construct a v1 version string.
2728 verstring = dupprintf("SSH-%s-%s\012",
2729 (ssh_versioncmp(svers, "1.5") <= 0 ?
2734 ssh_fix_verstring(verstring);
2736 if (ssh->version == 2) {
2739 * Record our version string.
2741 len = strcspn(verstring, "\015\012");
2742 ssh->v_c = snewn(len + 1, char);
2743 memcpy(ssh->v_c, verstring, len);
2747 logeventf(ssh, "We claim version: %.*s",
2748 strcspn(verstring, "\015\012"), verstring);
2749 s_write(ssh, verstring, strlen(verstring));
2753 static int do_ssh_init(Ssh ssh, unsigned char c)
2755 struct do_ssh_init_state {
2764 crState(do_ssh_init_state);
2768 /* Search for a line beginning with the string "SSH-" in the input. */
2770 if (c != 'S') goto no;
2772 if (c != 'S') goto no;
2774 if (c != 'H') goto no;
2776 if (c != '-') goto no;
2785 s->vstring = snewn(s->vstrsize, char);
2786 strcpy(s->vstring, "SSH-");
2790 crReturn(1); /* get another char */
2791 if (s->vslen >= s->vstrsize - 1) {
2793 s->vstring = sresize(s->vstring, s->vstrsize, char);
2795 s->vstring[s->vslen++] = c;
2798 s->version[s->i] = '\0';
2800 } else if (s->i < sizeof(s->version) - 1)
2801 s->version[s->i++] = c;
2802 } else if (c == '\012')
2806 ssh->agentfwd_enabled = FALSE;
2807 ssh->rdpkt2_state.incoming_sequence = 0;
2809 s->vstring[s->vslen] = 0;
2810 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2811 logeventf(ssh, "Server version: %s", s->vstring);
2812 ssh_detect_bugs(ssh, s->vstring);
2815 * Decide which SSH protocol version to support.
2818 /* Anything strictly below "2.0" means protocol 1 is supported. */
2819 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2820 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2821 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2823 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2824 bombout(("SSH protocol version 1 required by user but not provided by server"));
2827 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2828 bombout(("SSH protocol version 2 required by user but not provided by server"));
2832 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2837 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2839 /* Send the version string, if we haven't already */
2840 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2841 ssh_send_verstring(ssh, s->version);
2843 if (ssh->version == 2) {
2846 * Record their version string.
2848 len = strcspn(s->vstring, "\015\012");
2849 ssh->v_s = snewn(len + 1, char);
2850 memcpy(ssh->v_s, s->vstring, len);
2854 * Initialise SSH-2 protocol.
2856 ssh->protocol = ssh2_protocol;
2857 ssh2_protocol_setup(ssh);
2858 ssh->s_rdpkt = ssh2_rdpkt;
2861 * Initialise SSH-1 protocol.
2863 ssh->protocol = ssh1_protocol;
2864 ssh1_protocol_setup(ssh);
2865 ssh->s_rdpkt = ssh1_rdpkt;
2867 if (ssh->version == 2)
2868 do_ssh2_transport(ssh, NULL, -1, NULL);
2870 update_specials_menu(ssh->frontend);
2871 ssh->state = SSH_STATE_BEFORE_SIZE;
2872 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
2879 static void ssh_process_incoming_data(Ssh ssh,
2880 unsigned char **data, int *datalen)
2882 struct Packet *pktin;
2884 pktin = ssh->s_rdpkt(ssh, data, datalen);
2886 ssh->protocol(ssh, NULL, 0, pktin);
2887 ssh_free_packet(pktin);
2891 static void ssh_queue_incoming_data(Ssh ssh,
2892 unsigned char **data, int *datalen)
2894 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2899 static void ssh_process_queued_incoming_data(Ssh ssh)
2902 unsigned char *data;
2905 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2906 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2910 while (!ssh->frozen && len > 0)
2911 ssh_process_incoming_data(ssh, &data, &len);
2914 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2918 static void ssh_set_frozen(Ssh ssh, int frozen)
2921 sk_set_frozen(ssh->s, frozen);
2922 ssh->frozen = frozen;
2925 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
2927 /* Log raw data, if we're in that mode. */
2929 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
2932 crBegin(ssh->ssh_gotdata_crstate);
2935 * To begin with, feed the characters one by one to the
2936 * protocol initialisation / selection function do_ssh_init().
2937 * When that returns 0, we're done with the initial greeting
2938 * exchange and can move on to packet discipline.
2941 int ret; /* need not be kept across crReturn */
2943 crReturnV; /* more data please */
2944 ret = do_ssh_init(ssh, *data);
2952 * We emerge from that loop when the initial negotiation is
2953 * over and we have selected an s_rdpkt function. Now pass
2954 * everything to s_rdpkt, and then pass the resulting packets
2955 * to the proper protocol handler.
2959 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2961 ssh_queue_incoming_data(ssh, &data, &datalen);
2962 /* This uses up all data and cannot cause anything interesting
2963 * to happen; indeed, for anything to happen at all, we must
2964 * return, so break out. */
2966 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2967 /* This uses up some or all data, and may freeze the
2969 ssh_process_queued_incoming_data(ssh);
2971 /* This uses up some or all data, and may freeze the
2973 ssh_process_incoming_data(ssh, &data, &datalen);
2975 /* FIXME this is probably EBW. */
2976 if (ssh->state == SSH_STATE_CLOSED)
2979 /* We're out of data. Go and get some more. */
2985 static int ssh_do_close(Ssh ssh, int notify_exit)
2988 struct ssh_channel *c;
2990 ssh->state = SSH_STATE_CLOSED;
2991 expire_timer_context(ssh);
2996 notify_remote_exit(ssh->frontend);
3001 * Now we must shut down any port- and X-forwarded channels going
3002 * through this connection.
3004 if (ssh->channels) {
3005 while (NULL != (c = index234(ssh->channels, 0))) {
3008 x11_close(c->u.x11.xconn);
3011 case CHAN_SOCKDATA_DORMANT:
3012 pfd_close(c->u.pfd.pf);
3015 del234(ssh->channels, c); /* moving next one to index 0 */
3016 if (ssh->version == 2)
3017 bufchain_clear(&c->v.v2.outbuffer);
3022 * Go through port-forwardings, and close any associated
3023 * listening sockets.
3025 if (ssh->portfwds) {
3026 struct ssh_portfwd *pf;
3027 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3028 /* Dispose of any listening socket. */
3030 pfl_terminate(pf->local);
3031 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3034 freetree234(ssh->portfwds);
3035 ssh->portfwds = NULL;
3041 static void ssh_log(Plug plug, int type, SockAddr addr, int port,
3042 const char *error_msg, int error_code)
3044 Ssh ssh = (Ssh) plug;
3045 char addrbuf[256], *msg;
3047 sk_getaddr(addr, addrbuf, lenof(addrbuf));
3050 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
3052 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
3058 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3061 Ssh ssh = (Ssh) plug;
3062 int need_notify = ssh_do_close(ssh, FALSE);
3065 if (!ssh->close_expected)
3066 error_msg = "Server unexpectedly closed network connection";
3068 error_msg = "Server closed network connection";
3071 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3075 notify_remote_exit(ssh->frontend);
3078 logevent(error_msg);
3079 if (!ssh->close_expected || !ssh->clean_exit)
3080 connection_fatal(ssh->frontend, "%s", error_msg);
3084 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3086 Ssh ssh = (Ssh) plug;
3087 ssh_gotdata(ssh, (unsigned char *)data, len);
3088 if (ssh->state == SSH_STATE_CLOSED) {
3089 ssh_do_close(ssh, TRUE);
3095 static void ssh_sent(Plug plug, int bufsize)
3097 Ssh ssh = (Ssh) plug;
3099 * If the send backlog on the SSH socket itself clears, we
3100 * should unthrottle the whole world if it was throttled.
3102 if (bufsize < SSH_MAX_BACKLOG)
3103 ssh_throttle_all(ssh, 0, bufsize);
3107 * Connect to specified host and port.
3108 * Returns an error message, or NULL on success.
3109 * Also places the canonical host name into `realhost'. It must be
3110 * freed by the caller.
3112 static const char *connect_to_host(Ssh ssh, char *host, int port,
3113 char **realhost, int nodelay, int keepalive)
3115 static const struct plug_function_table fn_table = {
3126 int addressfamily, sshprot;
3128 loghost = conf_get_str(ssh->conf, CONF_loghost);
3132 ssh->savedhost = dupstr(loghost);
3133 ssh->savedport = 22; /* default ssh port */
3136 * A colon suffix on savedhost also lets us affect
3139 * (FIXME: do something about IPv6 address literals here.)
3141 colon = strrchr(ssh->savedhost, ':');
3145 ssh->savedport = atoi(colon);
3148 ssh->savedhost = dupstr(host);
3150 port = 22; /* default ssh port */
3151 ssh->savedport = port;
3157 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3158 logeventf(ssh, "Looking up host \"%s\"%s", host,
3159 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3160 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3161 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3162 if ((err = sk_addr_error(addr)) != NULL) {
3166 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3171 ssh->fn = &fn_table;
3172 ssh->s = new_connection(addr, *realhost, port,
3173 0, 1, nodelay, keepalive, (Plug) ssh, ssh->conf);
3174 if ((err = sk_socket_error(ssh->s)) != NULL) {
3176 notify_remote_exit(ssh->frontend);
3181 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3182 * send the version string too.
3184 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3189 ssh_send_verstring(ssh, NULL);
3193 * loghost, if configured, overrides realhost.
3197 *realhost = dupstr(loghost);
3204 * Throttle or unthrottle the SSH connection.
3206 static void ssh_throttle_conn(Ssh ssh, int adjust)
3208 int old_count = ssh->conn_throttle_count;
3209 ssh->conn_throttle_count += adjust;
3210 assert(ssh->conn_throttle_count >= 0);
3211 if (ssh->conn_throttle_count && !old_count) {
3212 ssh_set_frozen(ssh, 1);
3213 } else if (!ssh->conn_throttle_count && old_count) {
3214 ssh_set_frozen(ssh, 0);
3219 * Throttle or unthrottle _all_ local data streams (for when sends
3220 * on the SSH connection itself back up).
3222 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3225 struct ssh_channel *c;
3227 if (enable == ssh->throttled_all)
3229 ssh->throttled_all = enable;
3230 ssh->overall_bufsize = bufsize;
3233 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3235 case CHAN_MAINSESSION:
3237 * This is treated separately, outside the switch.
3241 x11_override_throttle(c->u.x11.xconn, enable);
3244 /* Agent channels require no buffer management. */
3247 pfd_override_throttle(c->u.pfd.pf, enable);
3253 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3255 Ssh ssh = (Ssh) sshv;
3257 ssh->agent_response = reply;
3258 ssh->agent_response_len = replylen;
3260 if (ssh->version == 1)
3261 do_ssh1_login(ssh, NULL, -1, NULL);
3263 do_ssh2_authconn(ssh, NULL, -1, NULL);
3266 static void ssh_dialog_callback(void *sshv, int ret)
3268 Ssh ssh = (Ssh) sshv;
3270 ssh->user_response = ret;
3272 if (ssh->version == 1)
3273 do_ssh1_login(ssh, NULL, -1, NULL);
3275 do_ssh2_transport(ssh, NULL, -1, NULL);
3278 * This may have unfrozen the SSH connection, so do a
3281 ssh_process_queued_incoming_data(ssh);
3284 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3286 struct ssh_channel *c = (struct ssh_channel *)cv;
3288 void *sentreply = reply;
3290 c->u.a.outstanding_requests--;
3292 /* Fake SSH_AGENT_FAILURE. */
3293 sentreply = "\0\0\0\1\5";
3296 if (ssh->version == 2) {
3297 ssh2_add_channel_data(c, sentreply, replylen);
3300 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3301 PKT_INT, c->remoteid,
3303 PKT_DATA, sentreply, replylen,
3309 * If we've already seen an incoming EOF but haven't sent an
3310 * outgoing one, this may be the moment to send it.
3312 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3313 sshfwd_write_eof(c);
3317 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3318 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3319 * => log `wire_reason'.
3321 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3322 int code, int clean_exit)
3326 client_reason = wire_reason;
3328 error = dupprintf("Disconnected: %s", client_reason);
3330 error = dupstr("Disconnected");
3332 if (ssh->version == 1) {
3333 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3335 } else if (ssh->version == 2) {
3336 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3337 ssh2_pkt_adduint32(pktout, code);
3338 ssh2_pkt_addstring(pktout, wire_reason);
3339 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3340 ssh2_pkt_send_noqueue(ssh, pktout);
3343 ssh->close_expected = TRUE;
3344 ssh->clean_exit = clean_exit;
3345 ssh_closing((Plug)ssh, error, 0, 0);
3350 * Handle the key exchange and user authentication phases.
3352 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3353 struct Packet *pktin)
3356 unsigned char cookie[8], *ptr;
3357 struct MD5Context md5c;
3358 struct do_ssh1_login_state {
3361 unsigned char *rsabuf, *keystr1, *keystr2;
3362 unsigned long supported_ciphers_mask, supported_auths_mask;
3363 int tried_publickey, tried_agent;
3364 int tis_auth_refused, ccard_auth_refused;
3365 unsigned char session_id[16];
3367 void *publickey_blob;
3368 int publickey_bloblen;
3369 char *publickey_comment;
3370 int publickey_encrypted;
3371 prompts_t *cur_prompt;
3374 unsigned char request[5], *response, *p;
3384 struct RSAKey servkey, hostkey;
3386 crState(do_ssh1_login_state);
3393 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3394 bombout(("Public key packet not received"));
3398 logevent("Received public keys");
3400 ptr = ssh_pkt_getdata(pktin, 8);
3402 bombout(("SSH-1 public key packet stopped before random cookie"));
3405 memcpy(cookie, ptr, 8);
3407 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3408 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3409 bombout(("Failed to read SSH-1 public keys from public key packet"));
3414 * Log the host key fingerprint.
3418 logevent("Host key fingerprint is:");
3419 strcpy(logmsg, " ");
3420 s->hostkey.comment = NULL;
3421 rsa_fingerprint(logmsg + strlen(logmsg),
3422 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3426 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3427 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3428 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3429 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3430 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3432 ssh->v1_local_protoflags =
3433 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3434 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3437 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3438 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3439 MD5Update(&md5c, cookie, 8);
3440 MD5Final(s->session_id, &md5c);
3442 for (i = 0; i < 32; i++)
3443 ssh->session_key[i] = random_byte();
3446 * Verify that the `bits' and `bytes' parameters match.
3448 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3449 s->servkey.bits > s->servkey.bytes * 8) {
3450 bombout(("SSH-1 public keys were badly formatted"));
3454 s->len = (s->hostkey.bytes > s->servkey.bytes ?
3455 s->hostkey.bytes : s->servkey.bytes);
3457 s->rsabuf = snewn(s->len, unsigned char);
3460 * Verify the host key.
3464 * First format the key into a string.
3466 int len = rsastr_len(&s->hostkey);
3467 char fingerprint[100];
3468 char *keystr = snewn(len, char);
3469 rsastr_fmt(keystr, &s->hostkey);
3470 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
3472 ssh_set_frozen(ssh, 1);
3473 s->dlgret = verify_ssh_host_key(ssh->frontend,
3474 ssh->savedhost, ssh->savedport,
3475 "rsa", keystr, fingerprint,
3476 ssh_dialog_callback, ssh);
3478 if (s->dlgret < 0) {
3482 bombout(("Unexpected data from server while waiting"
3483 " for user host key response"));
3486 } while (pktin || inlen > 0);
3487 s->dlgret = ssh->user_response;
3489 ssh_set_frozen(ssh, 0);
3491 if (s->dlgret == 0) {
3492 ssh_disconnect(ssh, "User aborted at host key verification",
3498 for (i = 0; i < 32; i++) {
3499 s->rsabuf[i] = ssh->session_key[i];
3501 s->rsabuf[i] ^= s->session_id[i];
3504 if (s->hostkey.bytes > s->servkey.bytes) {
3505 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
3507 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
3509 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
3511 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
3514 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3518 logevent("Encrypted session key");
3521 int cipher_chosen = 0, warn = 0;
3522 char *cipher_string = NULL;
3524 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3525 int next_cipher = conf_get_int_int(ssh->conf,
3526 CONF_ssh_cipherlist, i);
3527 if (next_cipher == CIPHER_WARN) {
3528 /* If/when we choose a cipher, warn about it */
3530 } else if (next_cipher == CIPHER_AES) {
3531 /* XXX Probably don't need to mention this. */
3532 logevent("AES not supported in SSH-1, skipping");
3534 switch (next_cipher) {
3535 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3536 cipher_string = "3DES"; break;
3537 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3538 cipher_string = "Blowfish"; break;
3539 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3540 cipher_string = "single-DES"; break;
3542 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3546 if (!cipher_chosen) {
3547 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3548 bombout(("Server violates SSH-1 protocol by not "
3549 "supporting 3DES encryption"));
3551 /* shouldn't happen */
3552 bombout(("No supported ciphers found"));
3556 /* Warn about chosen cipher if necessary. */
3558 ssh_set_frozen(ssh, 1);
3559 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3560 ssh_dialog_callback, ssh);
3561 if (s->dlgret < 0) {
3565 bombout(("Unexpected data from server while waiting"
3566 " for user response"));
3569 } while (pktin || inlen > 0);
3570 s->dlgret = ssh->user_response;
3572 ssh_set_frozen(ssh, 0);
3573 if (s->dlgret == 0) {
3574 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3581 switch (s->cipher_type) {
3582 case SSH_CIPHER_3DES:
3583 logevent("Using 3DES encryption");
3585 case SSH_CIPHER_DES:
3586 logevent("Using single-DES encryption");
3588 case SSH_CIPHER_BLOWFISH:
3589 logevent("Using Blowfish encryption");
3593 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3594 PKT_CHAR, s->cipher_type,
3595 PKT_DATA, cookie, 8,
3596 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3597 PKT_DATA, s->rsabuf, s->len,
3598 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3600 logevent("Trying to enable encryption...");
3604 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3605 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3607 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3608 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3609 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3611 ssh->crcda_ctx = crcda_make_context();
3612 logevent("Installing CRC compensation attack detector");
3614 if (s->servkey.modulus) {
3615 sfree(s->servkey.modulus);
3616 s->servkey.modulus = NULL;
3618 if (s->servkey.exponent) {
3619 sfree(s->servkey.exponent);
3620 s->servkey.exponent = NULL;
3622 if (s->hostkey.modulus) {
3623 sfree(s->hostkey.modulus);
3624 s->hostkey.modulus = NULL;
3626 if (s->hostkey.exponent) {
3627 sfree(s->hostkey.exponent);
3628 s->hostkey.exponent = NULL;
3632 if (pktin->type != SSH1_SMSG_SUCCESS) {
3633 bombout(("Encryption not successfully enabled"));
3637 logevent("Successfully started encryption");
3639 fflush(stdout); /* FIXME eh? */
3641 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
3642 int ret; /* need not be kept over crReturn */
3643 s->cur_prompt = new_prompts(ssh->frontend);
3644 s->cur_prompt->to_server = TRUE;
3645 s->cur_prompt->name = dupstr("SSH login name");
3646 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
3647 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3650 crWaitUntil(!pktin);
3651 ret = get_userpass_input(s->cur_prompt, in, inlen);
3656 * Failed to get a username. Terminate.
3658 free_prompts(s->cur_prompt);
3659 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3662 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
3663 free_prompts(s->cur_prompt);
3666 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
3668 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
3670 if (flags & FLAG_INTERACTIVE &&
3671 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3672 c_write_str(ssh, userlog);
3673 c_write_str(ssh, "\r\n");
3681 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3682 /* We must not attempt PK auth. Pretend we've already tried it. */
3683 s->tried_publickey = s->tried_agent = 1;
3685 s->tried_publickey = s->tried_agent = 0;
3687 s->tis_auth_refused = s->ccard_auth_refused = 0;
3689 * Load the public half of any configured keyfile for later use.
3691 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3692 if (!filename_is_null(s->keyfile)) {
3694 logeventf(ssh, "Reading private key file \"%.150s\"",
3695 filename_to_str(s->keyfile));
3696 keytype = key_type(s->keyfile);
3697 if (keytype == SSH_KEYTYPE_SSH1) {
3699 if (rsakey_pubblob(s->keyfile,
3700 &s->publickey_blob, &s->publickey_bloblen,
3701 &s->publickey_comment, &error)) {
3702 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
3706 logeventf(ssh, "Unable to load private key (%s)", error);
3707 msgbuf = dupprintf("Unable to load private key file "
3708 "\"%.150s\" (%s)\r\n",
3709 filename_to_str(s->keyfile),
3711 c_write_str(ssh, msgbuf);
3713 s->publickey_blob = NULL;
3717 logeventf(ssh, "Unable to use this key file (%s)",
3718 key_type_to_str(keytype));
3719 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3721 filename_to_str(s->keyfile),
3722 key_type_to_str(keytype));
3723 c_write_str(ssh, msgbuf);
3725 s->publickey_blob = NULL;
3728 s->publickey_blob = NULL;
3730 while (pktin->type == SSH1_SMSG_FAILURE) {
3731 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
3733 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
3735 * Attempt RSA authentication using Pageant.
3741 logevent("Pageant is running. Requesting keys.");
3743 /* Request the keys held by the agent. */
3744 PUT_32BIT(s->request, 1);
3745 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
3746 if (!agent_query(s->request, 5, &r, &s->responselen,
3747 ssh_agent_callback, ssh)) {
3751 bombout(("Unexpected data from server while waiting"
3752 " for agent response"));
3755 } while (pktin || inlen > 0);
3756 r = ssh->agent_response;
3757 s->responselen = ssh->agent_response_len;
3759 s->response = (unsigned char *) r;
3760 if (s->response && s->responselen >= 5 &&
3761 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3762 s->p = s->response + 5;
3763 s->nkeys = toint(GET_32BIT(s->p));
3765 logeventf(ssh, "Pageant reported negative key count %d",
3770 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
3771 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
3772 unsigned char *pkblob = s->p;
3776 do { /* do while (0) to make breaking easy */
3777 n = ssh1_read_bignum
3778 (s->p, toint(s->responselen-(s->p-s->response)),
3783 n = ssh1_read_bignum
3784 (s->p, toint(s->responselen-(s->p-s->response)),
3789 if (s->responselen - (s->p-s->response) < 4)
3791 s->commentlen = toint(GET_32BIT(s->p));
3793 if (s->commentlen < 0 ||
3794 toint(s->responselen - (s->p-s->response)) <
3797 s->commentp = (char *)s->p;
3798 s->p += s->commentlen;
3802 logevent("Pageant key list packet was truncated");
3806 if (s->publickey_blob) {
3807 if (!memcmp(pkblob, s->publickey_blob,
3808 s->publickey_bloblen)) {
3809 logeventf(ssh, "Pageant key #%d matches "
3810 "configured key file", s->keyi);
3811 s->tried_publickey = 1;
3813 /* Skip non-configured key */
3816 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
3817 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3818 PKT_BIGNUM, s->key.modulus, PKT_END);
3820 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3821 logevent("Key refused");
3824 logevent("Received RSA challenge");
3825 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3826 bombout(("Server's RSA challenge was badly formatted"));
3831 char *agentreq, *q, *ret;
3834 len = 1 + 4; /* message type, bit count */
3835 len += ssh1_bignum_length(s->key.exponent);
3836 len += ssh1_bignum_length(s->key.modulus);
3837 len += ssh1_bignum_length(s->challenge);
3838 len += 16; /* session id */
3839 len += 4; /* response format */
3840 agentreq = snewn(4 + len, char);
3841 PUT_32BIT(agentreq, len);
3843 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
3844 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
3846 q += ssh1_write_bignum(q, s->key.exponent);
3847 q += ssh1_write_bignum(q, s->key.modulus);
3848 q += ssh1_write_bignum(q, s->challenge);
3849 memcpy(q, s->session_id, 16);
3851 PUT_32BIT(q, 1); /* response format */
3852 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3853 ssh_agent_callback, ssh)) {
3858 bombout(("Unexpected data from server"
3859 " while waiting for agent"
3863 } while (pktin || inlen > 0);
3864 vret = ssh->agent_response;
3865 retlen = ssh->agent_response_len;
3870 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3871 logevent("Sending Pageant's response");
3872 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3873 PKT_DATA, ret + 5, 16,
3877 if (pktin->type == SSH1_SMSG_SUCCESS) {
3879 ("Pageant's response accepted");
3880 if (flags & FLAG_VERBOSE) {
3881 c_write_str(ssh, "Authenticated using"
3883 c_write(ssh, s->commentp,
3885 c_write_str(ssh, "\" from agent\r\n");
3890 ("Pageant's response not accepted");
3893 ("Pageant failed to answer challenge");
3897 logevent("No reply received from Pageant");
3900 freebn(s->key.exponent);
3901 freebn(s->key.modulus);
3902 freebn(s->challenge);
3907 if (s->publickey_blob && !s->tried_publickey)
3908 logevent("Configured key file not in Pageant");
3910 logevent("Failed to get reply from Pageant");
3915 if (s->publickey_blob && !s->tried_publickey) {
3917 * Try public key authentication with the specified
3920 int got_passphrase; /* need not be kept over crReturn */
3921 if (flags & FLAG_VERBOSE)
3922 c_write_str(ssh, "Trying public key authentication.\r\n");
3923 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3924 logeventf(ssh, "Trying public key \"%s\"",
3925 filename_to_str(s->keyfile));
3926 s->tried_publickey = 1;
3927 got_passphrase = FALSE;
3928 while (!got_passphrase) {
3930 * Get a passphrase, if necessary.
3932 char *passphrase = NULL; /* only written after crReturn */
3934 if (!s->publickey_encrypted) {
3935 if (flags & FLAG_VERBOSE)
3936 c_write_str(ssh, "No passphrase required.\r\n");
3939 int ret; /* need not be kept over crReturn */
3940 s->cur_prompt = new_prompts(ssh->frontend);
3941 s->cur_prompt->to_server = FALSE;
3942 s->cur_prompt->name = dupstr("SSH key passphrase");
3943 add_prompt(s->cur_prompt,
3944 dupprintf("Passphrase for key \"%.100s\": ",
3945 s->publickey_comment), FALSE);
3946 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3949 crWaitUntil(!pktin);
3950 ret = get_userpass_input(s->cur_prompt, in, inlen);
3954 /* Failed to get a passphrase. Terminate. */
3955 free_prompts(s->cur_prompt);
3956 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3960 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3961 free_prompts(s->cur_prompt);
3964 * Try decrypting key with passphrase.
3966 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3967 ret = loadrsakey(s->keyfile, &s->key, passphrase,
3970 smemclr(passphrase, strlen(passphrase));
3974 /* Correct passphrase. */
3975 got_passphrase = TRUE;
3976 } else if (ret == 0) {
3977 c_write_str(ssh, "Couldn't load private key from ");
3978 c_write_str(ssh, filename_to_str(s->keyfile));
3979 c_write_str(ssh, " (");
3980 c_write_str(ssh, error);
3981 c_write_str(ssh, ").\r\n");
3982 got_passphrase = FALSE;
3983 break; /* go and try something else */
3984 } else if (ret == -1) {
3985 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
3986 got_passphrase = FALSE;
3989 assert(0 && "unexpected return from loadrsakey()");
3990 got_passphrase = FALSE; /* placate optimisers */
3994 if (got_passphrase) {
3997 * Send a public key attempt.
3999 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4000 PKT_BIGNUM, s->key.modulus, PKT_END);
4003 if (pktin->type == SSH1_SMSG_FAILURE) {
4004 c_write_str(ssh, "Server refused our public key.\r\n");
4005 continue; /* go and try something else */
4007 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4008 bombout(("Bizarre response to offer of public key"));
4014 unsigned char buffer[32];
4015 Bignum challenge, response;
4017 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4018 bombout(("Server's RSA challenge was badly formatted"));
4021 response = rsadecrypt(challenge, &s->key);
4022 freebn(s->key.private_exponent);/* burn the evidence */
4024 for (i = 0; i < 32; i++) {
4025 buffer[i] = bignum_byte(response, 31 - i);
4029 MD5Update(&md5c, buffer, 32);
4030 MD5Update(&md5c, s->session_id, 16);
4031 MD5Final(buffer, &md5c);
4033 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4034 PKT_DATA, buffer, 16, PKT_END);
4041 if (pktin->type == SSH1_SMSG_FAILURE) {
4042 if (flags & FLAG_VERBOSE)
4043 c_write_str(ssh, "Failed to authenticate with"
4044 " our public key.\r\n");
4045 continue; /* go and try something else */
4046 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4047 bombout(("Bizarre response to RSA authentication response"));
4051 break; /* we're through! */
4057 * Otherwise, try various forms of password-like authentication.
4059 s->cur_prompt = new_prompts(ssh->frontend);
4061 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4062 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4063 !s->tis_auth_refused) {
4064 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4065 logevent("Requested TIS authentication");
4066 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4068 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4069 logevent("TIS authentication declined");
4070 if (flags & FLAG_INTERACTIVE)
4071 c_write_str(ssh, "TIS authentication refused.\r\n");
4072 s->tis_auth_refused = 1;
4077 char *instr_suf, *prompt;
4079 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4081 bombout(("TIS challenge packet was badly formed"));
4084 logevent("Received TIS challenge");
4085 s->cur_prompt->to_server = TRUE;
4086 s->cur_prompt->name = dupstr("SSH TIS authentication");
4087 /* Prompt heuristic comes from OpenSSH */
4088 if (memchr(challenge, '\n', challengelen)) {
4089 instr_suf = dupstr("");
4090 prompt = dupprintf("%.*s", challengelen, challenge);
4092 instr_suf = dupprintf("%.*s", challengelen, challenge);
4093 prompt = dupstr("Response: ");
4095 s->cur_prompt->instruction =
4096 dupprintf("Using TIS authentication.%s%s",
4097 (*instr_suf) ? "\n" : "",
4099 s->cur_prompt->instr_reqd = TRUE;
4100 add_prompt(s->cur_prompt, prompt, FALSE);
4104 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4105 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4106 !s->ccard_auth_refused) {
4107 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4108 logevent("Requested CryptoCard authentication");
4109 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4111 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4112 logevent("CryptoCard authentication declined");
4113 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4114 s->ccard_auth_refused = 1;
4119 char *instr_suf, *prompt;
4121 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4123 bombout(("CryptoCard challenge packet was badly formed"));
4126 logevent("Received CryptoCard challenge");
4127 s->cur_prompt->to_server = TRUE;
4128 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4129 s->cur_prompt->name_reqd = FALSE;
4130 /* Prompt heuristic comes from OpenSSH */
4131 if (memchr(challenge, '\n', challengelen)) {
4132 instr_suf = dupstr("");
4133 prompt = dupprintf("%.*s", challengelen, challenge);
4135 instr_suf = dupprintf("%.*s", challengelen, challenge);
4136 prompt = dupstr("Response: ");
4138 s->cur_prompt->instruction =
4139 dupprintf("Using CryptoCard authentication.%s%s",
4140 (*instr_suf) ? "\n" : "",
4142 s->cur_prompt->instr_reqd = TRUE;
4143 add_prompt(s->cur_prompt, prompt, FALSE);
4147 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4148 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4149 bombout(("No supported authentication methods available"));
4152 s->cur_prompt->to_server = TRUE;
4153 s->cur_prompt->name = dupstr("SSH password");
4154 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4155 ssh->username, ssh->savedhost),
4160 * Show password prompt, having first obtained it via a TIS
4161 * or CryptoCard exchange if we're doing TIS or CryptoCard
4165 int ret; /* need not be kept over crReturn */
4166 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4169 crWaitUntil(!pktin);
4170 ret = get_userpass_input(s->cur_prompt, in, inlen);
4175 * Failed to get a password (for example
4176 * because one was supplied on the command line
4177 * which has already failed to work). Terminate.
4179 free_prompts(s->cur_prompt);
4180 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4185 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4187 * Defence against traffic analysis: we send a
4188 * whole bunch of packets containing strings of
4189 * different lengths. One of these strings is the
4190 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4191 * The others are all random data in
4192 * SSH1_MSG_IGNORE packets. This way a passive
4193 * listener can't tell which is the password, and
4194 * hence can't deduce the password length.
4196 * Anybody with a password length greater than 16
4197 * bytes is going to have enough entropy in their
4198 * password that a listener won't find it _that_
4199 * much help to know how long it is. So what we'll
4202 * - if password length < 16, we send 15 packets
4203 * containing string lengths 1 through 15
4205 * - otherwise, we let N be the nearest multiple
4206 * of 8 below the password length, and send 8
4207 * packets containing string lengths N through
4208 * N+7. This won't obscure the order of
4209 * magnitude of the password length, but it will
4210 * introduce a bit of extra uncertainty.
4212 * A few servers can't deal with SSH1_MSG_IGNORE, at
4213 * least in this context. For these servers, we need
4214 * an alternative defence. We make use of the fact
4215 * that the password is interpreted as a C string:
4216 * so we can append a NUL, then some random data.
4218 * A few servers can deal with neither SSH1_MSG_IGNORE
4219 * here _nor_ a padded password string.
4220 * For these servers we are left with no defences
4221 * against password length sniffing.
4223 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4224 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4226 * The server can deal with SSH1_MSG_IGNORE, so
4227 * we can use the primary defence.
4229 int bottom, top, pwlen, i;
4232 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4234 bottom = 0; /* zero length passwords are OK! :-) */
4237 bottom = pwlen & ~7;
4241 assert(pwlen >= bottom && pwlen <= top);
4243 randomstr = snewn(top + 1, char);
4245 for (i = bottom; i <= top; i++) {
4247 defer_packet(ssh, s->pwpkt_type,
4248 PKT_STR,s->cur_prompt->prompts[0]->result,
4251 for (j = 0; j < i; j++) {
4253 randomstr[j] = random_byte();
4254 } while (randomstr[j] == '\0');
4256 randomstr[i] = '\0';
4257 defer_packet(ssh, SSH1_MSG_IGNORE,
4258 PKT_STR, randomstr, PKT_END);
4261 logevent("Sending password with camouflage packets");
4262 ssh_pkt_defersend(ssh);
4265 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4267 * The server can't deal with SSH1_MSG_IGNORE
4268 * but can deal with padded passwords, so we
4269 * can use the secondary defence.
4275 len = strlen(s->cur_prompt->prompts[0]->result);
4276 if (len < sizeof(string)) {
4278 strcpy(string, s->cur_prompt->prompts[0]->result);
4279 len++; /* cover the zero byte */
4280 while (len < sizeof(string)) {
4281 string[len++] = (char) random_byte();
4284 ss = s->cur_prompt->prompts[0]->result;
4286 logevent("Sending length-padded password");
4287 send_packet(ssh, s->pwpkt_type,
4288 PKT_INT, len, PKT_DATA, ss, len,
4292 * The server is believed unable to cope with
4293 * any of our password camouflage methods.
4296 len = strlen(s->cur_prompt->prompts[0]->result);
4297 logevent("Sending unpadded password");
4298 send_packet(ssh, s->pwpkt_type,
4300 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4304 send_packet(ssh, s->pwpkt_type,
4305 PKT_STR, s->cur_prompt->prompts[0]->result,
4308 logevent("Sent password");
4309 free_prompts(s->cur_prompt);
4311 if (pktin->type == SSH1_SMSG_FAILURE) {
4312 if (flags & FLAG_VERBOSE)
4313 c_write_str(ssh, "Access denied\r\n");
4314 logevent("Authentication refused");
4315 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4316 bombout(("Strange packet received, type %d", pktin->type));
4322 if (s->publickey_blob) {
4323 sfree(s->publickey_blob);
4324 sfree(s->publickey_comment);
4327 logevent("Authentication successful");
4332 static void ssh_channel_try_eof(struct ssh_channel *c)
4335 assert(c->pending_eof); /* precondition for calling us */
4337 return; /* can't close: not even opened yet */
4338 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4339 return; /* can't send EOF: pending outgoing data */
4341 c->pending_eof = FALSE; /* we're about to send it */
4342 if (ssh->version == 1) {
4343 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4345 c->closes |= CLOSES_SENT_EOF;
4347 struct Packet *pktout;
4348 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4349 ssh2_pkt_adduint32(pktout, c->remoteid);
4350 ssh2_pkt_send(ssh, pktout);
4351 c->closes |= CLOSES_SENT_EOF;
4352 ssh2_channel_check_close(c);
4356 void sshfwd_write_eof(struct ssh_channel *c)
4360 if (ssh->state == SSH_STATE_CLOSED)
4363 if (c->closes & CLOSES_SENT_EOF)
4366 c->pending_eof = TRUE;
4367 ssh_channel_try_eof(c);
4370 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4374 if (ssh->state == SSH_STATE_CLOSED)
4379 x11_close(c->u.x11.xconn);
4380 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4384 case CHAN_SOCKDATA_DORMANT:
4385 pfd_close(c->u.pfd.pf);
4386 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4389 c->type = CHAN_ZOMBIE;
4390 c->pending_eof = FALSE; /* this will confuse a zombie channel */
4392 ssh2_channel_check_close(c);
4395 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4399 if (ssh->state == SSH_STATE_CLOSED)
4402 if (ssh->version == 1) {
4403 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4404 PKT_INT, c->remoteid,
4405 PKT_INT, len, PKT_DATA, buf, len,
4408 * In SSH-1 we can return 0 here - implying that forwarded
4409 * connections are never individually throttled - because
4410 * the only circumstance that can cause throttling will be
4411 * the whole SSH connection backing up, in which case
4412 * _everything_ will be throttled as a whole.
4416 ssh2_add_channel_data(c, buf, len);
4417 return ssh2_try_send(c);
4421 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4426 if (ssh->state == SSH_STATE_CLOSED)
4429 if (ssh->version == 1) {
4430 buflimit = SSH1_BUFFER_LIMIT;
4432 buflimit = c->v.v2.locmaxwin;
4433 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4435 if (c->throttling_conn && bufsize <= buflimit) {
4436 c->throttling_conn = 0;
4437 ssh_throttle_conn(ssh, -1);
4441 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4443 struct queued_handler *qh = ssh->qhead;
4447 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4450 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4451 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4454 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4455 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4459 ssh->qhead = qh->next;
4461 if (ssh->qhead->msg1 > 0) {
4462 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4463 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4465 if (ssh->qhead->msg2 > 0) {
4466 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4467 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4470 ssh->qhead = ssh->qtail = NULL;
4473 qh->handler(ssh, pktin, qh->ctx);
4478 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4479 chandler_fn_t handler, void *ctx)
4481 struct queued_handler *qh;
4483 qh = snew(struct queued_handler);
4486 qh->handler = handler;
4490 if (ssh->qtail == NULL) {
4494 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4495 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4498 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4499 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4502 ssh->qtail->next = qh;
4507 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4509 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4511 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4512 SSH2_MSG_REQUEST_SUCCESS)) {
4513 logeventf(ssh, "Remote port forwarding from %s enabled",
4516 logeventf(ssh, "Remote port forwarding from %s refused",
4519 rpf = del234(ssh->rportfwds, pf);
4521 pf->pfrec->remote = NULL;
4526 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4528 struct ssh_portfwd *epf;
4532 if (!ssh->portfwds) {
4533 ssh->portfwds = newtree234(ssh_portcmp);
4536 * Go through the existing port forwardings and tag them
4537 * with status==DESTROY. Any that we want to keep will be
4538 * re-enabled (status==KEEP) as we go through the
4539 * configuration and find out which bits are the same as
4542 struct ssh_portfwd *epf;
4544 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4545 epf->status = DESTROY;
4548 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4550 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4551 char *kp, *kp2, *vp, *vp2;
4552 char address_family, type;
4553 int sport,dport,sserv,dserv;
4554 char *sports, *dports, *saddr, *host;
4558 address_family = 'A';
4560 if (*kp == 'A' || *kp == '4' || *kp == '6')
4561 address_family = *kp++;
4562 if (*kp == 'L' || *kp == 'R')
4565 if ((kp2 = strchr(kp, ':')) != NULL) {
4567 * There's a colon in the middle of the source port
4568 * string, which means that the part before it is
4569 * actually a source address.
4571 saddr = dupprintf("%.*s", (int)(kp2 - kp), kp);
4577 sport = atoi(sports);
4581 sport = net_service_lookup(sports);
4583 logeventf(ssh, "Service lookup failed for source"
4584 " port \"%s\"", sports);
4588 if (type == 'L' && !strcmp(val, "D")) {
4589 /* dynamic forwarding */
4596 /* ordinary forwarding */
4598 vp2 = vp + strcspn(vp, ":");
4599 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
4603 dport = atoi(dports);
4607 dport = net_service_lookup(dports);
4609 logeventf(ssh, "Service lookup failed for destination"
4610 " port \"%s\"", dports);
4615 if (sport && dport) {
4616 /* Set up a description of the source port. */
4617 struct ssh_portfwd *pfrec, *epfrec;
4619 pfrec = snew(struct ssh_portfwd);
4621 pfrec->saddr = saddr;
4622 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4623 pfrec->sport = sport;
4624 pfrec->daddr = host;
4625 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4626 pfrec->dport = dport;
4627 pfrec->local = NULL;
4628 pfrec->remote = NULL;
4629 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4630 address_family == '6' ? ADDRTYPE_IPV6 :
4633 epfrec = add234(ssh->portfwds, pfrec);
4634 if (epfrec != pfrec) {
4635 if (epfrec->status == DESTROY) {
4637 * We already have a port forwarding up and running
4638 * with precisely these parameters. Hence, no need
4639 * to do anything; simply re-tag the existing one
4642 epfrec->status = KEEP;
4645 * Anything else indicates that there was a duplicate
4646 * in our input, which we'll silently ignore.
4648 free_portfwd(pfrec);
4650 pfrec->status = CREATE;
4659 * Now go through and destroy any port forwardings which were
4662 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4663 if (epf->status == DESTROY) {
4666 message = dupprintf("%s port forwarding from %s%s%d",
4667 epf->type == 'L' ? "local" :
4668 epf->type == 'R' ? "remote" : "dynamic",
4669 epf->saddr ? epf->saddr : "",
4670 epf->saddr ? ":" : "",
4673 if (epf->type != 'D') {
4674 char *msg2 = dupprintf("%s to %s:%d", message,
4675 epf->daddr, epf->dport);
4680 logeventf(ssh, "Cancelling %s", message);
4683 /* epf->remote or epf->local may be NULL if setting up a
4684 * forwarding failed. */
4686 struct ssh_rportfwd *rpf = epf->remote;
4687 struct Packet *pktout;
4690 * Cancel the port forwarding at the server
4693 if (ssh->version == 1) {
4695 * We cannot cancel listening ports on the
4696 * server side in SSH-1! There's no message
4697 * to support it. Instead, we simply remove
4698 * the rportfwd record from the local end
4699 * so that any connections the server tries
4700 * to make on it are rejected.
4703 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4704 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4705 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4707 ssh2_pkt_addstring(pktout, epf->saddr);
4708 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4709 /* XXX: rport_acceptall may not represent
4710 * what was used to open the original connection,
4711 * since it's reconfigurable. */
4712 ssh2_pkt_addstring(pktout, "");
4714 ssh2_pkt_addstring(pktout, "localhost");
4716 ssh2_pkt_adduint32(pktout, epf->sport);
4717 ssh2_pkt_send(ssh, pktout);
4720 del234(ssh->rportfwds, rpf);
4722 } else if (epf->local) {
4723 pfl_terminate(epf->local);
4726 delpos234(ssh->portfwds, i);
4728 i--; /* so we don't skip one in the list */
4732 * And finally, set up any new port forwardings (status==CREATE).
4734 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4735 if (epf->status == CREATE) {
4736 char *sportdesc, *dportdesc;
4737 sportdesc = dupprintf("%s%s%s%s%d%s",
4738 epf->saddr ? epf->saddr : "",
4739 epf->saddr ? ":" : "",
4740 epf->sserv ? epf->sserv : "",
4741 epf->sserv ? "(" : "",
4743 epf->sserv ? ")" : "");
4744 if (epf->type == 'D') {
4747 dportdesc = dupprintf("%s:%s%s%d%s",
4749 epf->dserv ? epf->dserv : "",
4750 epf->dserv ? "(" : "",
4752 epf->dserv ? ")" : "");
4755 if (epf->type == 'L') {
4756 char *err = pfl_listen(epf->daddr, epf->dport,
4757 epf->saddr, epf->sport,
4758 ssh, conf, &epf->local,
4759 epf->addressfamily);
4761 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4762 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4763 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4764 sportdesc, dportdesc,
4765 err ? " failed: " : "", err ? err : "");
4768 } else if (epf->type == 'D') {
4769 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
4770 ssh, conf, &epf->local,
4771 epf->addressfamily);
4773 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4774 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4775 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4777 err ? " failed: " : "", err ? err : "");
4782 struct ssh_rportfwd *pf;
4785 * Ensure the remote port forwardings tree exists.
4787 if (!ssh->rportfwds) {
4788 if (ssh->version == 1)
4789 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4791 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4794 pf = snew(struct ssh_rportfwd);
4795 pf->dhost = dupstr(epf->daddr);
4796 pf->dport = epf->dport;
4798 pf->shost = dupstr(epf->saddr);
4799 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4800 pf->shost = dupstr("");
4802 pf->shost = dupstr("localhost");
4804 pf->sport = epf->sport;
4805 if (add234(ssh->rportfwds, pf) != pf) {
4806 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
4807 epf->daddr, epf->dport);
4810 logeventf(ssh, "Requesting remote port %s"
4811 " forward to %s", sportdesc, dportdesc);
4813 pf->sportdesc = sportdesc;
4818 if (ssh->version == 1) {
4819 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
4820 PKT_INT, epf->sport,
4821 PKT_STR, epf->daddr,
4822 PKT_INT, epf->dport,
4824 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4826 ssh_rportfwd_succfail, pf);
4828 struct Packet *pktout;
4829 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4830 ssh2_pkt_addstring(pktout, "tcpip-forward");
4831 ssh2_pkt_addbool(pktout, 1);/* want reply */
4832 ssh2_pkt_addstring(pktout, pf->shost);
4833 ssh2_pkt_adduint32(pktout, pf->sport);
4834 ssh2_pkt_send(ssh, pktout);
4836 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4837 SSH2_MSG_REQUEST_FAILURE,
4838 ssh_rportfwd_succfail, pf);
4847 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4850 int stringlen, bufsize;
4852 ssh_pkt_getstring(pktin, &string, &stringlen);
4853 if (string == NULL) {
4854 bombout(("Incoming terminal data packet was badly formed"));
4858 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4860 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4861 ssh->v1_stdout_throttling = 1;
4862 ssh_throttle_conn(ssh, +1);
4866 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4868 /* Remote side is trying to open a channel to talk to our
4869 * X-Server. Give them back a local channel number. */
4870 struct ssh_channel *c;
4871 int remoteid = ssh_pkt_getuint32(pktin);
4873 logevent("Received X11 connect request");
4874 /* Refuse if X11 forwarding is disabled. */
4875 if (!ssh->X11_fwd_enabled) {
4876 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4877 PKT_INT, remoteid, PKT_END);
4878 logevent("Rejected X11 connect request");
4882 c = snew(struct ssh_channel);
4885 if ((err = x11_init(&c->u.x11.xconn, ssh->x11disp, c,
4886 NULL, -1, ssh->conf)) != NULL) {
4887 logeventf(ssh, "Opening X11 forward connection failed: %s", err);
4890 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4891 PKT_INT, remoteid, PKT_END);
4894 ("Opening X11 forward connection succeeded");
4895 c->remoteid = remoteid;
4896 c->halfopen = FALSE;
4897 c->localid = alloc_channel_id(ssh);
4899 c->pending_eof = FALSE;
4900 c->throttling_conn = 0;
4901 c->type = CHAN_X11; /* identify channel type */
4902 add234(ssh->channels, c);
4903 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4904 PKT_INT, c->remoteid, PKT_INT,
4905 c->localid, PKT_END);
4906 logevent("Opened X11 forward channel");
4911 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4913 /* Remote side is trying to open a channel to talk to our
4914 * agent. Give them back a local channel number. */
4915 struct ssh_channel *c;
4916 int remoteid = ssh_pkt_getuint32(pktin);
4918 /* Refuse if agent forwarding is disabled. */
4919 if (!ssh->agentfwd_enabled) {
4920 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4921 PKT_INT, remoteid, PKT_END);
4923 c = snew(struct ssh_channel);
4925 c->remoteid = remoteid;
4926 c->halfopen = FALSE;
4927 c->localid = alloc_channel_id(ssh);
4929 c->pending_eof = FALSE;
4930 c->throttling_conn = 0;
4931 c->type = CHAN_AGENT; /* identify channel type */
4932 c->u.a.lensofar = 0;
4933 c->u.a.message = NULL;
4934 c->u.a.outstanding_requests = 0;
4935 add234(ssh->channels, c);
4936 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4937 PKT_INT, c->remoteid, PKT_INT, c->localid,
4942 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4944 /* Remote side is trying to open a channel to talk to a
4945 * forwarded port. Give them back a local channel number. */
4946 struct ssh_rportfwd pf, *pfp;
4952 remoteid = ssh_pkt_getuint32(pktin);
4953 ssh_pkt_getstring(pktin, &host, &hostsize);
4954 port = ssh_pkt_getuint32(pktin);
4956 pf.dhost = dupprintf(".*s", hostsize, host);
4958 pfp = find234(ssh->rportfwds, &pf, NULL);
4961 logeventf(ssh, "Rejected remote port open request for %s:%d",
4963 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4964 PKT_INT, remoteid, PKT_END);
4966 struct ssh_channel *c = snew(struct ssh_channel);
4969 logeventf(ssh, "Received remote port open request for %s:%d",
4971 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
4972 c, ssh->conf, pfp->pfrec->addressfamily);
4974 logeventf(ssh, "Port open failed: %s", err);
4977 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4978 PKT_INT, remoteid, PKT_END);
4980 c->remoteid = remoteid;
4981 c->halfopen = FALSE;
4982 c->localid = alloc_channel_id(ssh);
4984 c->pending_eof = FALSE;
4985 c->throttling_conn = 0;
4986 c->type = CHAN_SOCKDATA; /* identify channel type */
4987 add234(ssh->channels, c);
4988 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4989 PKT_INT, c->remoteid, PKT_INT,
4990 c->localid, PKT_END);
4991 logevent("Forwarded port opened successfully");
4998 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5000 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5001 unsigned int localid = ssh_pkt_getuint32(pktin);
5002 struct ssh_channel *c;
5004 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5005 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5006 c->remoteid = localid;
5007 c->halfopen = FALSE;
5008 c->type = CHAN_SOCKDATA;
5009 c->throttling_conn = 0;
5010 pfd_confirm(c->u.pfd.pf);
5013 if (c && c->pending_eof) {
5015 * We have a pending close on this channel,
5016 * which we decided on before the server acked
5017 * the channel open. So now we know the
5018 * remoteid, we can close it again.
5020 ssh_channel_try_eof(c);
5024 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5026 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5027 struct ssh_channel *c;
5029 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5030 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5031 logevent("Forwarded connection refused by server");
5032 pfd_close(c->u.pfd.pf);
5033 del234(ssh->channels, c);
5038 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5040 /* Remote side closes a channel. */
5041 unsigned i = ssh_pkt_getuint32(pktin);
5042 struct ssh_channel *c;
5043 c = find234(ssh->channels, &i, ssh_channelfind);
5044 if (c && !c->halfopen) {
5046 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5047 !(c->closes & CLOSES_RCVD_EOF)) {
5049 * Received CHANNEL_CLOSE, which we translate into
5052 int send_close = FALSE;
5054 c->closes |= CLOSES_RCVD_EOF;
5059 x11_send_eof(c->u.x11.xconn);
5065 pfd_send_eof(c->u.pfd.pf);
5074 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5075 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5077 c->closes |= CLOSES_SENT_EOF;
5081 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5082 !(c->closes & CLOSES_RCVD_CLOSE)) {
5084 if (!(c->closes & CLOSES_SENT_EOF)) {
5085 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5086 " for which we never sent CHANNEL_CLOSE\n", i));
5089 c->closes |= CLOSES_RCVD_CLOSE;
5092 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5093 !(c->closes & CLOSES_SENT_CLOSE)) {
5094 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5095 PKT_INT, c->remoteid, PKT_END);
5096 c->closes |= CLOSES_SENT_CLOSE;
5099 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5100 ssh_channel_destroy(c);
5102 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5103 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5104 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5109 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5111 /* Data sent down one of our channels. */
5112 int i = ssh_pkt_getuint32(pktin);
5115 struct ssh_channel *c;
5117 ssh_pkt_getstring(pktin, &p, &len);
5119 c = find234(ssh->channels, &i, ssh_channelfind);
5124 bufsize = x11_send(c->u.x11.xconn, p, len);
5127 bufsize = pfd_send(c->u.pfd.pf, p, len);
5130 /* Data for an agent message. Buffer it. */
5132 if (c->u.a.lensofar < 4) {
5133 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5134 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5138 c->u.a.lensofar += l;
5140 if (c->u.a.lensofar == 4) {
5142 4 + GET_32BIT(c->u.a.msglen);
5143 c->u.a.message = snewn(c->u.a.totallen,
5145 memcpy(c->u.a.message, c->u.a.msglen, 4);
5147 if (c->u.a.lensofar >= 4 && len > 0) {
5149 min(c->u.a.totallen - c->u.a.lensofar,
5151 memcpy(c->u.a.message + c->u.a.lensofar, p,
5155 c->u.a.lensofar += l;
5157 if (c->u.a.lensofar == c->u.a.totallen) {
5160 c->u.a.outstanding_requests++;
5161 if (agent_query(c->u.a.message,
5164 ssh_agentf_callback, c))
5165 ssh_agentf_callback(c, reply, replylen);
5166 sfree(c->u.a.message);
5167 c->u.a.lensofar = 0;
5170 bufsize = 0; /* agent channels never back up */
5173 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5174 c->throttling_conn = 1;
5175 ssh_throttle_conn(ssh, +1);
5180 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5182 ssh->exitcode = ssh_pkt_getuint32(pktin);
5183 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5184 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5186 * In case `helpful' firewalls or proxies tack
5187 * extra human-readable text on the end of the
5188 * session which we might mistake for another
5189 * encrypted packet, we close the session once
5190 * we've sent EXIT_CONFIRMATION.
5192 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5195 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5196 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5198 struct Packet *pktout = (struct Packet *)data;
5200 unsigned int arg = 0;
5201 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5202 if (i == lenof(ssh_ttymodes)) return;
5203 switch (ssh_ttymodes[i].type) {
5205 arg = ssh_tty_parse_specchar(val);
5208 arg = ssh_tty_parse_boolean(val);
5211 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5212 ssh2_pkt_addbyte(pktout, arg);
5216 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5217 struct Packet *pktin)
5219 crBegin(ssh->do_ssh1_connection_crstate);
5221 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5222 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5223 ssh1_smsg_stdout_stderr_data;
5225 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5226 ssh1_msg_channel_open_confirmation;
5227 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5228 ssh1_msg_channel_open_failure;
5229 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5230 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5231 ssh1_msg_channel_close;
5232 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5233 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5235 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
5236 logevent("Requesting agent forwarding");
5237 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5241 if (pktin->type != SSH1_SMSG_SUCCESS
5242 && pktin->type != SSH1_SMSG_FAILURE) {
5243 bombout(("Protocol confusion"));
5245 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5246 logevent("Agent forwarding refused");
5248 logevent("Agent forwarding enabled");
5249 ssh->agentfwd_enabled = TRUE;
5250 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5254 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
5255 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5256 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
5257 logevent("Requesting X11 forwarding");
5258 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5259 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5260 PKT_STR, ssh->x11disp->remoteauthprotoname,
5261 PKT_STR, ssh->x11disp->remoteauthdatastring,
5262 PKT_INT, ssh->x11disp->screennum,
5265 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5266 PKT_STR, ssh->x11disp->remoteauthprotoname,
5267 PKT_STR, ssh->x11disp->remoteauthdatastring,
5273 if (pktin->type != SSH1_SMSG_SUCCESS
5274 && pktin->type != SSH1_SMSG_FAILURE) {
5275 bombout(("Protocol confusion"));
5277 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5278 logevent("X11 forwarding refused");
5280 logevent("X11 forwarding enabled");
5281 ssh->X11_fwd_enabled = TRUE;
5282 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5286 ssh_setup_portfwd(ssh, ssh->conf);
5287 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5289 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5291 /* Unpick the terminal-speed string. */
5292 /* XXX perhaps we should allow no speeds to be sent. */
5293 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5294 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5295 /* Send the pty request. */
5296 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5297 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5298 ssh_pkt_adduint32(pkt, ssh->term_height);
5299 ssh_pkt_adduint32(pkt, ssh->term_width);
5300 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5301 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5302 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5303 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5304 ssh_pkt_adduint32(pkt, ssh->ispeed);
5305 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5306 ssh_pkt_adduint32(pkt, ssh->ospeed);
5307 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5309 ssh->state = SSH_STATE_INTERMED;
5313 if (pktin->type != SSH1_SMSG_SUCCESS
5314 && pktin->type != SSH1_SMSG_FAILURE) {
5315 bombout(("Protocol confusion"));
5317 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5318 c_write_str(ssh, "Server refused to allocate pty\r\n");
5319 ssh->editing = ssh->echoing = 1;
5321 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5322 ssh->ospeed, ssh->ispeed);
5323 ssh->got_pty = TRUE;
5326 ssh->editing = ssh->echoing = 1;
5329 if (conf_get_int(ssh->conf, CONF_compression)) {
5330 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5334 if (pktin->type != SSH1_SMSG_SUCCESS
5335 && pktin->type != SSH1_SMSG_FAILURE) {
5336 bombout(("Protocol confusion"));
5338 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5339 c_write_str(ssh, "Server refused to compress\r\n");
5341 logevent("Started compression");
5342 ssh->v1_compressing = TRUE;
5343 ssh->cs_comp_ctx = zlib_compress_init();
5344 logevent("Initialised zlib (RFC1950) compression");
5345 ssh->sc_comp_ctx = zlib_decompress_init();
5346 logevent("Initialised zlib (RFC1950) decompression");
5350 * Start the shell or command.
5352 * Special case: if the first-choice command is an SSH-2
5353 * subsystem (hence not usable here) and the second choice
5354 * exists, we fall straight back to that.
5357 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5359 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5360 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5361 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5362 ssh->fallback_cmd = TRUE;
5365 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5367 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5368 logevent("Started session");
5371 ssh->state = SSH_STATE_SESSION;
5372 if (ssh->size_needed)
5373 ssh_size(ssh, ssh->term_width, ssh->term_height);
5374 if (ssh->eof_needed)
5375 ssh_special(ssh, TS_EOF);
5378 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5380 ssh->channels = newtree234(ssh_channelcmp);
5384 * By this point, most incoming packets are already being
5385 * handled by the dispatch table, and we need only pay
5386 * attention to the unusual ones.
5391 if (pktin->type == SSH1_SMSG_SUCCESS) {
5392 /* may be from EXEC_SHELL on some servers */
5393 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5394 /* may be from EXEC_SHELL on some servers
5395 * if no pty is available or in other odd cases. Ignore */
5397 bombout(("Strange packet received: type %d", pktin->type));
5402 int len = min(inlen, 512);
5403 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5404 PKT_INT, len, PKT_DATA, in, len,
5416 * Handle the top-level SSH-2 protocol.
5418 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5423 ssh_pkt_getstring(pktin, &msg, &msglen);
5424 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5427 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5429 /* log reason code in disconnect message */
5433 ssh_pkt_getstring(pktin, &msg, &msglen);
5434 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5437 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5439 /* Do nothing, because we're ignoring it! Duhh. */
5442 static void ssh1_protocol_setup(Ssh ssh)
5447 * Most messages are handled by the coroutines.
5449 for (i = 0; i < 256; i++)
5450 ssh->packet_dispatch[i] = NULL;
5453 * These special message types we install handlers for.
5455 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5456 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5457 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5460 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5461 struct Packet *pktin)
5463 unsigned char *in=(unsigned char*)vin;
5464 if (ssh->state == SSH_STATE_CLOSED)
5467 if (pktin && ssh->packet_dispatch[pktin->type]) {
5468 ssh->packet_dispatch[pktin->type](ssh, pktin);
5472 if (!ssh->protocol_initial_phase_done) {
5473 if (do_ssh1_login(ssh, in, inlen, pktin))
5474 ssh->protocol_initial_phase_done = TRUE;
5479 do_ssh1_connection(ssh, in, inlen, pktin);
5483 * Utility routine for decoding comma-separated strings in KEXINIT.
5485 static int in_commasep_string(char *needle, char *haystack, int haylen)
5488 if (!needle || !haystack) /* protect against null pointers */
5490 needlen = strlen(needle);
5493 * Is it at the start of the string?
5495 if (haylen >= needlen && /* haystack is long enough */
5496 !memcmp(needle, haystack, needlen) && /* initial match */
5497 (haylen == needlen || haystack[needlen] == ',')
5498 /* either , or EOS follows */
5502 * If not, search for the next comma and resume after that.
5503 * If no comma found, terminate.
5505 while (haylen > 0 && *haystack != ',')
5506 haylen--, haystack++;
5509 haylen--, haystack++; /* skip over comma itself */
5514 * Similar routine for checking whether we have the first string in a list.
5516 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5519 if (!needle || !haystack) /* protect against null pointers */
5521 needlen = strlen(needle);
5523 * Is it at the start of the string?
5525 if (haylen >= needlen && /* haystack is long enough */
5526 !memcmp(needle, haystack, needlen) && /* initial match */
5527 (haylen == needlen || haystack[needlen] == ',')
5528 /* either , or EOS follows */
5536 * SSH-2 key creation method.
5537 * (Currently assumes 2 lots of any hash are sufficient to generate
5538 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5540 #define SSH2_MKKEY_ITERS (2)
5541 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5542 unsigned char *keyspace)
5544 const struct ssh_hash *h = ssh->kex->hash;
5546 /* First hlen bytes. */
5548 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5549 hash_mpint(h, s, K);
5550 h->bytes(s, H, h->hlen);
5551 h->bytes(s, &chr, 1);
5552 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5553 h->final(s, keyspace);
5554 /* Next hlen bytes. */
5556 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5557 hash_mpint(h, s, K);
5558 h->bytes(s, H, h->hlen);
5559 h->bytes(s, keyspace, h->hlen);
5560 h->final(s, keyspace + h->hlen);
5564 * Handle the SSH-2 transport layer.
5566 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5567 struct Packet *pktin)
5569 unsigned char *in = (unsigned char *)vin;
5570 struct do_ssh2_transport_state {
5572 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5573 Bignum p, g, e, f, K;
5576 int kex_init_value, kex_reply_value;
5577 const struct ssh_mac **maclist;
5579 const struct ssh2_cipher *cscipher_tobe;
5580 const struct ssh2_cipher *sccipher_tobe;
5581 const struct ssh_mac *csmac_tobe;
5582 const struct ssh_mac *scmac_tobe;
5583 const struct ssh_compress *cscomp_tobe;
5584 const struct ssh_compress *sccomp_tobe;
5585 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5586 int hostkeylen, siglen, rsakeylen;
5587 void *hkey; /* actual host key */
5588 void *rsakey; /* for RSA kex */
5589 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5590 int n_preferred_kex;
5591 const struct ssh_kexes *preferred_kex[KEX_MAX];
5592 int n_preferred_ciphers;
5593 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5594 const struct ssh_compress *preferred_comp;
5595 int userauth_succeeded; /* for delayed compression */
5596 int pending_compression;
5597 int got_session_id, activated_authconn;
5598 struct Packet *pktout;
5603 crState(do_ssh2_transport_state);
5607 s->cscipher_tobe = s->sccipher_tobe = NULL;
5608 s->csmac_tobe = s->scmac_tobe = NULL;
5609 s->cscomp_tobe = s->sccomp_tobe = NULL;
5611 s->got_session_id = s->activated_authconn = FALSE;
5612 s->userauth_succeeded = FALSE;
5613 s->pending_compression = FALSE;
5616 * Be prepared to work around the buggy MAC problem.
5618 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5619 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5621 s->maclist = macs, s->nmacs = lenof(macs);
5624 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5626 int i, j, k, commalist_started;
5629 * Set up the preferred key exchange. (NULL => warn below here)
5631 s->n_preferred_kex = 0;
5632 for (i = 0; i < KEX_MAX; i++) {
5633 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
5635 s->preferred_kex[s->n_preferred_kex++] =
5636 &ssh_diffiehellman_gex;
5639 s->preferred_kex[s->n_preferred_kex++] =
5640 &ssh_diffiehellman_group14;
5643 s->preferred_kex[s->n_preferred_kex++] =
5644 &ssh_diffiehellman_group1;
5647 s->preferred_kex[s->n_preferred_kex++] =
5651 /* Flag for later. Don't bother if it's the last in
5653 if (i < KEX_MAX - 1) {
5654 s->preferred_kex[s->n_preferred_kex++] = NULL;
5661 * Set up the preferred ciphers. (NULL => warn below here)
5663 s->n_preferred_ciphers = 0;
5664 for (i = 0; i < CIPHER_MAX; i++) {
5665 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
5666 case CIPHER_BLOWFISH:
5667 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5670 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
5671 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5675 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5678 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5680 case CIPHER_ARCFOUR:
5681 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5684 /* Flag for later. Don't bother if it's the last in
5686 if (i < CIPHER_MAX - 1) {
5687 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5694 * Set up preferred compression.
5696 if (conf_get_int(ssh->conf, CONF_compression))
5697 s->preferred_comp = &ssh_zlib;
5699 s->preferred_comp = &ssh_comp_none;
5702 * Enable queueing of outgoing auth- or connection-layer
5703 * packets while we are in the middle of a key exchange.
5705 ssh->queueing = TRUE;
5708 * Flag that KEX is in progress.
5710 ssh->kex_in_progress = TRUE;
5713 * Construct and send our key exchange packet.
5715 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
5716 for (i = 0; i < 16; i++)
5717 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
5718 /* List key exchange algorithms. */
5719 ssh2_pkt_addstring_start(s->pktout);
5720 commalist_started = 0;
5721 for (i = 0; i < s->n_preferred_kex; i++) {
5722 const struct ssh_kexes *k = s->preferred_kex[i];
5723 if (!k) continue; /* warning flag */
5724 for (j = 0; j < k->nkexes; j++) {
5725 if (commalist_started)
5726 ssh2_pkt_addstring_str(s->pktout, ",");
5727 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5728 commalist_started = 1;
5731 /* List server host key algorithms. */
5732 if (!s->got_session_id) {
5734 * In the first key exchange, we list all the algorithms
5735 * we're prepared to cope with.
5737 ssh2_pkt_addstring_start(s->pktout);
5738 for (i = 0; i < lenof(hostkey_algs); i++) {
5739 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
5740 if (i < lenof(hostkey_algs) - 1)
5741 ssh2_pkt_addstring_str(s->pktout, ",");
5745 * In subsequent key exchanges, we list only the kex
5746 * algorithm that was selected in the first key exchange,
5747 * so that we keep getting the same host key and hence
5748 * don't have to interrupt the user's session to ask for
5752 ssh2_pkt_addstring(s->pktout, ssh->hostkey->name);
5754 /* List encryption algorithms (client->server then server->client). */
5755 for (k = 0; k < 2; k++) {
5756 ssh2_pkt_addstring_start(s->pktout);
5757 commalist_started = 0;
5758 for (i = 0; i < s->n_preferred_ciphers; i++) {
5759 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5760 if (!c) continue; /* warning flag */
5761 for (j = 0; j < c->nciphers; j++) {
5762 if (commalist_started)
5763 ssh2_pkt_addstring_str(s->pktout, ",");
5764 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
5765 commalist_started = 1;
5769 /* List MAC algorithms (client->server then server->client). */
5770 for (j = 0; j < 2; j++) {
5771 ssh2_pkt_addstring_start(s->pktout);
5772 for (i = 0; i < s->nmacs; i++) {
5773 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5774 if (i < s->nmacs - 1)
5775 ssh2_pkt_addstring_str(s->pktout, ",");
5778 /* List client->server compression algorithms,
5779 * then server->client compression algorithms. (We use the
5780 * same set twice.) */
5781 for (j = 0; j < 2; j++) {
5782 ssh2_pkt_addstring_start(s->pktout);
5783 assert(lenof(compressions) > 1);
5784 /* Prefer non-delayed versions */
5785 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5786 /* We don't even list delayed versions of algorithms until
5787 * they're allowed to be used, to avoid a race. See the end of
5789 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
5790 ssh2_pkt_addstring_str(s->pktout, ",");
5791 ssh2_pkt_addstring_str(s->pktout,
5792 s->preferred_comp->delayed_name);
5794 for (i = 0; i < lenof(compressions); i++) {
5795 const struct ssh_compress *c = compressions[i];
5796 if (c != s->preferred_comp) {
5797 ssh2_pkt_addstring_str(s->pktout, ",");
5798 ssh2_pkt_addstring_str(s->pktout, c->name);
5799 if (s->userauth_succeeded && c->delayed_name) {
5800 ssh2_pkt_addstring_str(s->pktout, ",");
5801 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
5806 /* List client->server languages. Empty list. */
5807 ssh2_pkt_addstring_start(s->pktout);
5808 /* List server->client languages. Empty list. */
5809 ssh2_pkt_addstring_start(s->pktout);
5810 /* First KEX packet does _not_ follow, because we're not that brave. */
5811 ssh2_pkt_addbool(s->pktout, FALSE);
5813 ssh2_pkt_adduint32(s->pktout, 0);
5816 s->our_kexinitlen = s->pktout->length - 5;
5817 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5818 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
5820 ssh2_pkt_send_noqueue(ssh, s->pktout);
5823 crWaitUntilV(pktin);
5826 * Now examine the other side's KEXINIT to see what we're up
5830 char *str, *preferred;
5833 if (pktin->type != SSH2_MSG_KEXINIT) {
5834 bombout(("expected key exchange packet from server"));
5838 ssh->hostkey = NULL;
5839 s->cscipher_tobe = NULL;
5840 s->sccipher_tobe = NULL;
5841 s->csmac_tobe = NULL;
5842 s->scmac_tobe = NULL;
5843 s->cscomp_tobe = NULL;
5844 s->sccomp_tobe = NULL;
5845 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5847 pktin->savedpos += 16; /* skip garbage cookie */
5848 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
5851 for (i = 0; i < s->n_preferred_kex; i++) {
5852 const struct ssh_kexes *k = s->preferred_kex[i];
5856 for (j = 0; j < k->nkexes; j++) {
5857 if (!preferred) preferred = k->list[j]->name;
5858 if (in_commasep_string(k->list[j]->name, str, len)) {
5859 ssh->kex = k->list[j];
5868 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5869 str ? str : "(null)"));
5873 * Note that the server's guess is considered wrong if it doesn't match
5874 * the first algorithm in our list, even if it's still the algorithm
5877 s->guessok = first_in_commasep_string(preferred, str, len);
5878 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
5879 for (i = 0; i < lenof(hostkey_algs); i++) {
5880 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5881 ssh->hostkey = hostkey_algs[i];
5885 if (!ssh->hostkey) {
5886 bombout(("Couldn't agree a host key algorithm (available: %s)",
5887 str ? str : "(null)"));
5891 s->guessok = s->guessok &&
5892 first_in_commasep_string(hostkey_algs[0]->name, str, len);
5893 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
5894 for (i = 0; i < s->n_preferred_ciphers; i++) {
5895 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5897 s->warn_cscipher = TRUE;
5899 for (j = 0; j < c->nciphers; j++) {
5900 if (in_commasep_string(c->list[j]->name, str, len)) {
5901 s->cscipher_tobe = c->list[j];
5906 if (s->cscipher_tobe)
5909 if (!s->cscipher_tobe) {
5910 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5911 str ? str : "(null)"));
5915 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
5916 for (i = 0; i < s->n_preferred_ciphers; i++) {
5917 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5919 s->warn_sccipher = TRUE;
5921 for (j = 0; j < c->nciphers; j++) {
5922 if (in_commasep_string(c->list[j]->name, str, len)) {
5923 s->sccipher_tobe = c->list[j];
5928 if (s->sccipher_tobe)
5931 if (!s->sccipher_tobe) {
5932 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5933 str ? str : "(null)"));
5937 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
5938 for (i = 0; i < s->nmacs; i++) {
5939 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5940 s->csmac_tobe = s->maclist[i];
5944 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
5945 for (i = 0; i < s->nmacs; i++) {
5946 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5947 s->scmac_tobe = s->maclist[i];
5951 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
5952 for (i = 0; i < lenof(compressions) + 1; i++) {
5953 const struct ssh_compress *c =
5954 i == 0 ? s->preferred_comp : compressions[i - 1];
5955 if (in_commasep_string(c->name, str, len)) {
5958 } else if (in_commasep_string(c->delayed_name, str, len)) {
5959 if (s->userauth_succeeded) {
5963 s->pending_compression = TRUE; /* try this later */
5967 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
5968 for (i = 0; i < lenof(compressions) + 1; i++) {
5969 const struct ssh_compress *c =
5970 i == 0 ? s->preferred_comp : compressions[i - 1];
5971 if (in_commasep_string(c->name, str, len)) {
5974 } else if (in_commasep_string(c->delayed_name, str, len)) {
5975 if (s->userauth_succeeded) {
5979 s->pending_compression = TRUE; /* try this later */
5983 if (s->pending_compression) {
5984 logevent("Server supports delayed compression; "
5985 "will try this later");
5987 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5988 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
5989 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5991 ssh->exhash = ssh->kex->hash->init();
5992 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5993 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5994 hash_string(ssh->kex->hash, ssh->exhash,
5995 s->our_kexinit, s->our_kexinitlen);
5996 sfree(s->our_kexinit);
5997 /* Include the type byte in the hash of server's KEXINIT */
5998 hash_string(ssh->kex->hash, ssh->exhash,
5999 pktin->body - 1, pktin->length + 1);
6002 ssh_set_frozen(ssh, 1);
6003 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6005 ssh_dialog_callback, ssh);
6006 if (s->dlgret < 0) {
6010 bombout(("Unexpected data from server while"
6011 " waiting for user response"));
6014 } while (pktin || inlen > 0);
6015 s->dlgret = ssh->user_response;
6017 ssh_set_frozen(ssh, 0);
6018 if (s->dlgret == 0) {
6019 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6025 if (s->warn_cscipher) {
6026 ssh_set_frozen(ssh, 1);
6027 s->dlgret = askalg(ssh->frontend,
6028 "client-to-server cipher",
6029 s->cscipher_tobe->name,
6030 ssh_dialog_callback, ssh);
6031 if (s->dlgret < 0) {
6035 bombout(("Unexpected data from server while"
6036 " waiting for user response"));
6039 } while (pktin || inlen > 0);
6040 s->dlgret = ssh->user_response;
6042 ssh_set_frozen(ssh, 0);
6043 if (s->dlgret == 0) {
6044 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6050 if (s->warn_sccipher) {
6051 ssh_set_frozen(ssh, 1);
6052 s->dlgret = askalg(ssh->frontend,
6053 "server-to-client cipher",
6054 s->sccipher_tobe->name,
6055 ssh_dialog_callback, ssh);
6056 if (s->dlgret < 0) {
6060 bombout(("Unexpected data from server while"
6061 " waiting for user response"));
6064 } while (pktin || inlen > 0);
6065 s->dlgret = ssh->user_response;
6067 ssh_set_frozen(ssh, 0);
6068 if (s->dlgret == 0) {
6069 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6075 if (s->ignorepkt) /* first_kex_packet_follows */
6076 crWaitUntilV(pktin); /* Ignore packet */
6079 if (ssh->kex->main_type == KEXTYPE_DH) {
6081 * Work out the number of bits of key we will need from the
6082 * key exchange. We start with the maximum key length of
6088 csbits = s->cscipher_tobe->keylen;
6089 scbits = s->sccipher_tobe->keylen;
6090 s->nbits = (csbits > scbits ? csbits : scbits);
6092 /* The keys only have hlen-bit entropy, since they're based on
6093 * a hash. So cap the key size at hlen bits. */
6094 if (s->nbits > ssh->kex->hash->hlen * 8)
6095 s->nbits = ssh->kex->hash->hlen * 8;
6098 * If we're doing Diffie-Hellman group exchange, start by
6099 * requesting a group.
6101 if (!ssh->kex->pdata) {
6102 logevent("Doing Diffie-Hellman group exchange");
6103 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6105 * Work out how big a DH group we will need to allow that
6108 s->pbits = 512 << ((s->nbits - 1) / 64);
6109 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6110 ssh2_pkt_adduint32(s->pktout, s->pbits);
6111 ssh2_pkt_send_noqueue(ssh, s->pktout);
6113 crWaitUntilV(pktin);
6114 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6115 bombout(("expected key exchange group packet from server"));
6118 s->p = ssh2_pkt_getmp(pktin);
6119 s->g = ssh2_pkt_getmp(pktin);
6120 if (!s->p || !s->g) {
6121 bombout(("unable to read mp-ints from incoming group packet"));
6124 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6125 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6126 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6128 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6129 ssh->kex_ctx = dh_setup_group(ssh->kex);
6130 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6131 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6132 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6133 ssh->kex->groupname);
6136 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6137 ssh->kex->hash->text_name);
6139 * Now generate and send e for Diffie-Hellman.
6141 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6142 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6143 s->pktout = ssh2_pkt_init(s->kex_init_value);
6144 ssh2_pkt_addmp(s->pktout, s->e);
6145 ssh2_pkt_send_noqueue(ssh, s->pktout);
6147 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6148 crWaitUntilV(pktin);
6149 if (pktin->type != s->kex_reply_value) {
6150 bombout(("expected key exchange reply packet from server"));
6153 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6154 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6155 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6156 s->f = ssh2_pkt_getmp(pktin);
6158 bombout(("unable to parse key exchange reply packet"));
6161 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6163 s->K = dh_find_K(ssh->kex_ctx, s->f);
6165 /* We assume everything from now on will be quick, and it might
6166 * involve user interaction. */
6167 set_busy_status(ssh->frontend, BUSY_NOT);
6169 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6170 if (!ssh->kex->pdata) {
6171 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6172 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6173 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6175 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6176 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6178 dh_cleanup(ssh->kex_ctx);
6180 if (!ssh->kex->pdata) {
6185 logeventf(ssh, "Doing RSA key exchange with hash %s",
6186 ssh->kex->hash->text_name);
6187 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6189 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6192 crWaitUntilV(pktin);
6193 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6194 bombout(("expected RSA public key packet from server"));
6198 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6199 hash_string(ssh->kex->hash, ssh->exhash,
6200 s->hostkeydata, s->hostkeylen);
6201 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6205 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6206 s->rsakeydata = snewn(s->rsakeylen, char);
6207 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6210 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6212 sfree(s->rsakeydata);
6213 bombout(("unable to parse RSA public key from server"));
6217 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6220 * Next, set up a shared secret K, of precisely KLEN -
6221 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6222 * RSA key modulus and HLEN is the bit length of the hash
6226 int klen = ssh_rsakex_klen(s->rsakey);
6227 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6229 unsigned char *kstr1, *kstr2, *outstr;
6230 int kstr1len, kstr2len, outstrlen;
6232 s->K = bn_power_2(nbits - 1);
6234 for (i = 0; i < nbits; i++) {
6236 byte = random_byte();
6238 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6242 * Encode this as an mpint.
6244 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6245 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6246 PUT_32BIT(kstr2, kstr1len);
6247 memcpy(kstr2 + 4, kstr1, kstr1len);
6250 * Encrypt it with the given RSA key.
6252 outstrlen = (klen + 7) / 8;
6253 outstr = snewn(outstrlen, unsigned char);
6254 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6255 outstr, outstrlen, s->rsakey);
6258 * And send it off in a return packet.
6260 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6261 ssh2_pkt_addstring_start(s->pktout);
6262 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6263 ssh2_pkt_send_noqueue(ssh, s->pktout);
6265 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6272 ssh_rsakex_freekey(s->rsakey);
6274 crWaitUntilV(pktin);
6275 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6276 sfree(s->rsakeydata);
6277 bombout(("expected signature packet from server"));
6281 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6283 sfree(s->rsakeydata);
6286 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6287 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6288 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6290 ssh->kex_ctx = NULL;
6293 debug(("Exchange hash is:\n"));
6294 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6298 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6299 (char *)s->exchange_hash,
6300 ssh->kex->hash->hlen)) {
6301 bombout(("Server's host key did not match the signature supplied"));
6305 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6306 if (!s->got_session_id) {
6308 * Authenticate remote host: verify host key. (We've already
6309 * checked the signature of the exchange hash.)
6311 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6312 ssh_set_frozen(ssh, 1);
6313 s->dlgret = verify_ssh_host_key(ssh->frontend,
6314 ssh->savedhost, ssh->savedport,
6315 ssh->hostkey->keytype, s->keystr,
6317 ssh_dialog_callback, ssh);
6318 if (s->dlgret < 0) {
6322 bombout(("Unexpected data from server while waiting"
6323 " for user host key response"));
6326 } while (pktin || inlen > 0);
6327 s->dlgret = ssh->user_response;
6329 ssh_set_frozen(ssh, 0);
6330 if (s->dlgret == 0) {
6331 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6335 logevent("Host key fingerprint is:");
6336 logevent(s->fingerprint);
6337 sfree(s->fingerprint);
6339 * Save this host key, to check against the one presented in
6340 * subsequent rekeys.
6342 ssh->hostkey_str = s->keystr;
6345 * In a rekey, we never present an interactive host key
6346 * verification request to the user. Instead, we simply
6347 * enforce that the key we're seeing this time is identical to
6348 * the one we saw before.
6350 if (strcmp(ssh->hostkey_str, s->keystr)) {
6351 bombout(("Host key was different in repeat key exchange"));
6356 ssh->hostkey->freekey(s->hkey);
6359 * The exchange hash from the very first key exchange is also
6360 * the session id, used in session key construction and
6363 if (!s->got_session_id) {
6364 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6365 memcpy(ssh->v2_session_id, s->exchange_hash,
6366 sizeof(s->exchange_hash));
6367 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6368 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6369 s->got_session_id = TRUE;
6373 * Send SSH2_MSG_NEWKEYS.
6375 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6376 ssh2_pkt_send_noqueue(ssh, s->pktout);
6377 ssh->outgoing_data_size = 0; /* start counting from here */
6380 * We've sent client NEWKEYS, so create and initialise
6381 * client-to-server session keys.
6383 if (ssh->cs_cipher_ctx)
6384 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6385 ssh->cscipher = s->cscipher_tobe;
6386 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6388 if (ssh->cs_mac_ctx)
6389 ssh->csmac->free_context(ssh->cs_mac_ctx);
6390 ssh->csmac = s->csmac_tobe;
6391 ssh->cs_mac_ctx = ssh->csmac->make_context();
6393 if (ssh->cs_comp_ctx)
6394 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6395 ssh->cscomp = s->cscomp_tobe;
6396 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6399 * Set IVs on client-to-server keys. Here we use the exchange
6400 * hash from the _first_ key exchange.
6403 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6404 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6405 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6406 assert((ssh->cscipher->keylen+7) / 8 <=
6407 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6408 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6409 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6410 assert(ssh->cscipher->blksize <=
6411 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6412 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6413 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6414 assert(ssh->csmac->len <=
6415 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6416 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6417 smemclr(keyspace, sizeof(keyspace));
6420 logeventf(ssh, "Initialised %.200s client->server encryption",
6421 ssh->cscipher->text_name);
6422 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6423 ssh->csmac->text_name);
6424 if (ssh->cscomp->text_name)
6425 logeventf(ssh, "Initialised %s compression",
6426 ssh->cscomp->text_name);
6429 * Now our end of the key exchange is complete, we can send all
6430 * our queued higher-layer packets.
6432 ssh->queueing = FALSE;
6433 ssh2_pkt_queuesend(ssh);
6436 * Expect SSH2_MSG_NEWKEYS from server.
6438 crWaitUntilV(pktin);
6439 if (pktin->type != SSH2_MSG_NEWKEYS) {
6440 bombout(("expected new-keys packet from server"));
6443 ssh->incoming_data_size = 0; /* start counting from here */
6446 * We've seen server NEWKEYS, so create and initialise
6447 * server-to-client session keys.
6449 if (ssh->sc_cipher_ctx)
6450 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6451 ssh->sccipher = s->sccipher_tobe;
6452 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6454 if (ssh->sc_mac_ctx)
6455 ssh->scmac->free_context(ssh->sc_mac_ctx);
6456 ssh->scmac = s->scmac_tobe;
6457 ssh->sc_mac_ctx = ssh->scmac->make_context();
6459 if (ssh->sc_comp_ctx)
6460 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6461 ssh->sccomp = s->sccomp_tobe;
6462 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6465 * Set IVs on server-to-client keys. Here we use the exchange
6466 * hash from the _first_ key exchange.
6469 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6470 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6471 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6472 assert((ssh->sccipher->keylen+7) / 8 <=
6473 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6474 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6475 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6476 assert(ssh->sccipher->blksize <=
6477 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6478 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6479 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6480 assert(ssh->scmac->len <=
6481 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6482 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6483 smemclr(keyspace, sizeof(keyspace));
6485 logeventf(ssh, "Initialised %.200s server->client encryption",
6486 ssh->sccipher->text_name);
6487 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6488 ssh->scmac->text_name);
6489 if (ssh->sccomp->text_name)
6490 logeventf(ssh, "Initialised %s decompression",
6491 ssh->sccomp->text_name);
6494 * Free shared secret.
6499 * Key exchange is over. Loop straight back round if we have a
6500 * deferred rekey reason.
6502 if (ssh->deferred_rekey_reason) {
6503 logevent(ssh->deferred_rekey_reason);
6505 ssh->deferred_rekey_reason = NULL;
6506 goto begin_key_exchange;
6510 * Otherwise, schedule a timer for our next rekey.
6512 ssh->kex_in_progress = FALSE;
6513 ssh->last_rekey = GETTICKCOUNT();
6514 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6515 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6519 * Now we're encrypting. Begin returning 1 to the protocol main
6520 * function so that other things can run on top of the
6521 * transport. If we ever see a KEXINIT, we must go back to the
6524 * We _also_ go back to the start if we see pktin==NULL and
6525 * inlen negative, because this is a special signal meaning
6526 * `initiate client-driven rekey', and `in' contains a message
6527 * giving the reason for the rekey.
6529 * inlen==-1 means always initiate a rekey;
6530 * inlen==-2 means that userauth has completed successfully and
6531 * we should consider rekeying (for delayed compression).
6533 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6534 (!pktin && inlen < 0))) {
6536 if (!ssh->protocol_initial_phase_done) {
6537 ssh->protocol_initial_phase_done = TRUE;
6539 * Allow authconn to initialise itself.
6541 do_ssh2_authconn(ssh, NULL, 0, NULL);
6546 logevent("Server initiated key re-exchange");
6550 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6551 * delayed compression, if it's available.
6553 * draft-miller-secsh-compression-delayed-00 says that you
6554 * negotiate delayed compression in the first key exchange, and
6555 * both sides start compressing when the server has sent
6556 * USERAUTH_SUCCESS. This has a race condition -- the server
6557 * can't know when the client has seen it, and thus which incoming
6558 * packets it should treat as compressed.
6560 * Instead, we do the initial key exchange without offering the
6561 * delayed methods, but note if the server offers them; when we
6562 * get here, if a delayed method was available that was higher
6563 * on our list than what we got, we initiate a rekey in which we
6564 * _do_ list the delayed methods (and hopefully get it as a
6565 * result). Subsequent rekeys will do the same.
6567 assert(!s->userauth_succeeded); /* should only happen once */
6568 s->userauth_succeeded = TRUE;
6569 if (!s->pending_compression)
6570 /* Can't see any point rekeying. */
6571 goto wait_for_rekey; /* this is utterly horrid */
6572 /* else fall through to rekey... */
6573 s->pending_compression = FALSE;
6576 * Now we've decided to rekey.
6578 * Special case: if the server bug is set that doesn't
6579 * allow rekeying, we give a different log message and
6580 * continue waiting. (If such a server _initiates_ a rekey,
6581 * we process it anyway!)
6583 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6584 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6586 /* Reset the counters, so that at least this message doesn't
6587 * hit the event log _too_ often. */
6588 ssh->outgoing_data_size = 0;
6589 ssh->incoming_data_size = 0;
6590 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
6592 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6595 goto wait_for_rekey; /* this is still utterly horrid */
6597 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6600 goto begin_key_exchange;
6606 * Add data to an SSH-2 channel output buffer.
6608 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6611 bufchain_add(&c->v.v2.outbuffer, buf, len);
6615 * Attempt to send data on an SSH-2 channel.
6617 static int ssh2_try_send(struct ssh_channel *c)
6620 struct Packet *pktout;
6623 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6626 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6627 if ((unsigned)len > c->v.v2.remwindow)
6628 len = c->v.v2.remwindow;
6629 if ((unsigned)len > c->v.v2.remmaxpkt)
6630 len = c->v.v2.remmaxpkt;
6631 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6632 ssh2_pkt_adduint32(pktout, c->remoteid);
6633 ssh2_pkt_addstring_start(pktout);
6634 ssh2_pkt_addstring_data(pktout, data, len);
6635 ssh2_pkt_send(ssh, pktout);
6636 bufchain_consume(&c->v.v2.outbuffer, len);
6637 c->v.v2.remwindow -= len;
6641 * After having sent as much data as we can, return the amount
6644 ret = bufchain_size(&c->v.v2.outbuffer);
6647 * And if there's no data pending but we need to send an EOF, send
6650 if (!ret && c->pending_eof)
6651 ssh_channel_try_eof(c);
6656 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
6659 if (c->closes & CLOSES_SENT_EOF)
6660 return; /* don't send on channels we've EOFed */
6661 bufsize = ssh2_try_send(c);
6664 case CHAN_MAINSESSION:
6665 /* stdin need not receive an unthrottle
6666 * notification since it will be polled */
6669 x11_unthrottle(c->u.x11.xconn);
6672 /* agent sockets are request/response and need no
6673 * buffer management */
6676 pfd_unthrottle(c->u.pfd.pf);
6683 * Set up most of a new ssh_channel for SSH-2.
6685 static void ssh2_channel_init(struct ssh_channel *c)
6688 c->localid = alloc_channel_id(ssh);
6690 c->pending_eof = FALSE;
6691 c->throttling_conn = FALSE;
6692 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
6693 conf_get_int(ssh->conf, CONF_ssh_simple) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
6694 c->v.v2.chanreq_head = NULL;
6695 c->v.v2.throttle_state = UNTHROTTLED;
6696 bufchain_init(&c->v.v2.outbuffer);
6700 * Construct the common parts of a CHANNEL_OPEN.
6702 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c, char *type)
6704 struct Packet *pktout;
6706 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
6707 ssh2_pkt_addstring(pktout, type);
6708 ssh2_pkt_adduint32(pktout, c->localid);
6709 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
6710 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
6715 * CHANNEL_FAILURE doesn't come with any indication of what message
6716 * caused it, so we have to keep track of the outstanding
6717 * CHANNEL_REQUESTs ourselves.
6719 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
6720 cchandler_fn_t handler, void *ctx)
6722 struct outstanding_channel_request *ocr =
6723 snew(struct outstanding_channel_request);
6725 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
6726 ocr->handler = handler;
6729 if (!c->v.v2.chanreq_head)
6730 c->v.v2.chanreq_head = ocr;
6732 c->v.v2.chanreq_tail->next = ocr;
6733 c->v.v2.chanreq_tail = ocr;
6737 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
6738 * NULL then a reply will be requested and the handler will be called
6739 * when it arrives. The returned packet is ready to have any
6740 * request-specific data added and be sent. Note that if a handler is
6741 * provided, it's essential that the request actually be sent.
6743 * The handler will usually be passed the response packet in pktin.
6744 * If pktin is NULL, this means that no reply will ever be forthcoming
6745 * (e.g. because the entire connection is being destroyed) and the
6746 * handler should free any storage it's holding.
6748 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c, char *type,
6749 cchandler_fn_t handler, void *ctx)
6751 struct Packet *pktout;
6753 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
6754 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6755 ssh2_pkt_adduint32(pktout, c->remoteid);
6756 ssh2_pkt_addstring(pktout, type);
6757 ssh2_pkt_addbool(pktout, handler != NULL);
6758 if (handler != NULL)
6759 ssh2_queue_chanreq_handler(c, handler, ctx);
6764 * Potentially enlarge the window on an SSH-2 channel.
6766 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
6768 static void ssh2_set_window(struct ssh_channel *c, int newwin)
6773 * Never send WINDOW_ADJUST for a channel that the remote side has
6774 * already sent EOF on; there's no point, since it won't be
6775 * sending any more data anyway. Ditto if _we've_ already sent
6778 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6782 * If the remote end has a habit of ignoring maxpkt, limit the
6783 * window so that it has no choice (assuming it doesn't ignore the
6786 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6787 newwin = OUR_V2_MAXPKT;
6790 * Only send a WINDOW_ADJUST if there's significantly more window
6791 * available than the other end thinks there is. This saves us
6792 * sending a WINDOW_ADJUST for every character in a shell session.
6794 * "Significant" is arbitrarily defined as half the window size.
6796 if (newwin / 2 >= c->v.v2.locwindow) {
6797 struct Packet *pktout;
6801 * In order to keep track of how much window the client
6802 * actually has available, we'd like it to acknowledge each
6803 * WINDOW_ADJUST. We can't do that directly, so we accompany
6804 * it with a CHANNEL_REQUEST that has to be acknowledged.
6806 * This is only necessary if we're opening the window wide.
6807 * If we're not, then throughput is being constrained by
6808 * something other than the maximum window size anyway.
6810 if (newwin == c->v.v2.locmaxwin &&
6811 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
6812 up = snew(unsigned);
6813 *up = newwin - c->v.v2.locwindow;
6814 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
6815 ssh2_handle_winadj_response, up);
6816 ssh2_pkt_send(ssh, pktout);
6818 if (c->v.v2.throttle_state != UNTHROTTLED)
6819 c->v.v2.throttle_state = UNTHROTTLING;
6821 /* Pretend the WINDOW_ADJUST was acked immediately. */
6822 c->v.v2.remlocwin = newwin;
6823 c->v.v2.throttle_state = THROTTLED;
6825 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6826 ssh2_pkt_adduint32(pktout, c->remoteid);
6827 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6828 ssh2_pkt_send(ssh, pktout);
6829 c->v.v2.locwindow = newwin;
6834 * Find the channel associated with a message. If there's no channel,
6835 * or it's not properly open, make a noise about it and return NULL.
6837 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6839 unsigned localid = ssh_pkt_getuint32(pktin);
6840 struct ssh_channel *c;
6842 c = find234(ssh->channels, &localid, ssh_channelfind);
6844 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6845 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6846 char *buf = dupprintf("Received %s for %s channel %u",
6847 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6849 c ? "half-open" : "nonexistent", localid);
6850 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6857 static void ssh2_handle_winadj_response(struct ssh_channel *c,
6858 struct Packet *pktin, void *ctx)
6860 unsigned *sizep = ctx;
6863 * Winadj responses should always be failures. However, at least
6864 * one server ("boks_sshd") is known to return SUCCESS for channel
6865 * requests it's never heard of, such as "winadj@putty". Raised
6866 * with foxt.com as bug 090916-090424, but for the sake of a quiet
6867 * life, we don't worry about what kind of response we got.
6870 c->v.v2.remlocwin += *sizep;
6873 * winadj messages are only sent when the window is fully open, so
6874 * if we get an ack of one, we know any pending unthrottle is
6877 if (c->v.v2.throttle_state == UNTHROTTLING)
6878 c->v.v2.throttle_state = UNTHROTTLED;
6881 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
6883 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
6884 struct outstanding_channel_request *ocr;
6887 ocr = c->v.v2.chanreq_head;
6889 ssh2_msg_unexpected(ssh, pktin);
6892 ocr->handler(c, pktin, ocr->ctx);
6893 c->v.v2.chanreq_head = ocr->next;
6896 * We may now initiate channel-closing procedures, if that
6897 * CHANNEL_REQUEST was the last thing outstanding before we send
6900 ssh2_channel_check_close(c);
6903 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
6905 struct ssh_channel *c;
6906 c = ssh2_channel_msg(ssh, pktin);
6909 if (!(c->closes & CLOSES_SENT_EOF)) {
6910 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
6911 ssh2_try_send_and_unthrottle(ssh, c);
6915 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6919 struct ssh_channel *c;
6920 c = ssh2_channel_msg(ssh, pktin);
6923 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6924 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6925 return; /* extended but not stderr */
6926 ssh_pkt_getstring(pktin, &data, &length);
6929 c->v.v2.locwindow -= length;
6930 c->v.v2.remlocwin -= length;
6932 case CHAN_MAINSESSION:
6934 from_backend(ssh->frontend, pktin->type ==
6935 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6939 bufsize = x11_send(c->u.x11.xconn, data, length);
6942 bufsize = pfd_send(c->u.pfd.pf, data, length);
6945 while (length > 0) {
6946 if (c->u.a.lensofar < 4) {
6947 unsigned int l = min(4 - c->u.a.lensofar,
6949 memcpy(c->u.a.msglen + c->u.a.lensofar,
6953 c->u.a.lensofar += l;
6955 if (c->u.a.lensofar == 4) {
6957 4 + GET_32BIT(c->u.a.msglen);
6958 c->u.a.message = snewn(c->u.a.totallen,
6960 memcpy(c->u.a.message, c->u.a.msglen, 4);
6962 if (c->u.a.lensofar >= 4 && length > 0) {
6964 min(c->u.a.totallen - c->u.a.lensofar,
6966 memcpy(c->u.a.message + c->u.a.lensofar,
6970 c->u.a.lensofar += l;
6972 if (c->u.a.lensofar == c->u.a.totallen) {
6975 c->u.a.outstanding_requests++;
6976 if (agent_query(c->u.a.message,
6979 ssh_agentf_callback, c))
6980 ssh_agentf_callback(c, reply, replylen);
6981 sfree(c->u.a.message);
6982 c->u.a.message = NULL;
6983 c->u.a.lensofar = 0;
6990 * If it looks like the remote end hit the end of its window,
6991 * and we didn't want it to do that, think about using a
6994 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6995 c->v.v2.locmaxwin < 0x40000000)
6996 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6998 * If we are not buffering too much data,
6999 * enlarge the window again at the remote side.
7000 * If we are buffering too much, we may still
7001 * need to adjust the window if the server's
7004 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7005 c->v.v2.locmaxwin - bufsize : 0);
7007 * If we're either buffering way too much data, or if we're
7008 * buffering anything at all and we're in "simple" mode,
7009 * throttle the whole channel.
7011 if ((bufsize > c->v.v2.locmaxwin ||
7012 (conf_get_int(ssh->conf, CONF_ssh_simple) && bufsize > 0)) &&
7013 !c->throttling_conn) {
7014 c->throttling_conn = 1;
7015 ssh_throttle_conn(ssh, +1);
7020 static void ssh_channel_destroy(struct ssh_channel *c)
7025 case CHAN_MAINSESSION:
7026 ssh->mainchan = NULL;
7027 update_specials_menu(ssh->frontend);
7030 if (c->u.x11.xconn != NULL)
7031 x11_close(c->u.x11.xconn);
7032 logevent("Forwarded X11 connection terminated");
7035 sfree(c->u.a.message);
7038 if (c->u.pfd.pf != NULL)
7039 pfd_close(c->u.pfd.pf);
7040 logevent("Forwarded port closed");
7044 del234(ssh->channels, c);
7045 if (ssh->version == 2) {
7046 bufchain_clear(&c->v.v2.outbuffer);
7047 assert(c->v.v2.chanreq_head == NULL);
7052 * See if that was the last channel left open.
7053 * (This is only our termination condition if we're
7054 * not running in -N mode.)
7056 if (ssh->version == 2 &&
7057 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7058 count234(ssh->channels) == 0) {
7060 * We used to send SSH_MSG_DISCONNECT here,
7061 * because I'd believed that _every_ conforming
7062 * SSH-2 connection had to end with a disconnect
7063 * being sent by at least one side; apparently
7064 * I was wrong and it's perfectly OK to
7065 * unceremoniously slam the connection shut
7066 * when you're done, and indeed OpenSSH feels
7067 * this is more polite than sending a
7068 * DISCONNECT. So now we don't.
7070 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7074 static void ssh2_channel_check_close(struct ssh_channel *c)
7077 struct Packet *pktout;
7081 * If we've sent out our own CHANNEL_OPEN but not yet seen
7082 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
7083 * it's too early to be sending close messages of any kind.
7088 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
7089 c->type == CHAN_ZOMBIE) &&
7090 !c->v.v2.chanreq_head &&
7091 !(c->closes & CLOSES_SENT_CLOSE)) {
7093 * We have both sent and received EOF (or the channel is a
7094 * zombie), and we have no outstanding channel requests, which
7095 * means the channel is in final wind-up. But we haven't sent
7096 * CLOSE, so let's do so now.
7098 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
7099 ssh2_pkt_adduint32(pktout, c->remoteid);
7100 ssh2_pkt_send(ssh, pktout);
7101 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
7104 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
7105 assert(c->v.v2.chanreq_head == NULL);
7107 * We have both sent and received CLOSE, which means we're
7108 * completely done with the channel.
7110 ssh_channel_destroy(c);
7114 static void ssh2_channel_got_eof(struct ssh_channel *c)
7116 if (c->closes & CLOSES_RCVD_EOF)
7117 return; /* already seen EOF */
7118 c->closes |= CLOSES_RCVD_EOF;
7120 if (c->type == CHAN_X11) {
7121 x11_send_eof(c->u.x11.xconn);
7122 } else if (c->type == CHAN_AGENT) {
7123 if (c->u.a.outstanding_requests == 0) {
7124 /* Manufacture an outgoing EOF in response to the incoming one. */
7125 sshfwd_write_eof(c);
7127 } else if (c->type == CHAN_SOCKDATA) {
7128 pfd_send_eof(c->u.pfd.pf);
7129 } else if (c->type == CHAN_MAINSESSION) {
7132 if (!ssh->sent_console_eof &&
7133 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
7135 * Either from_backend_eof told us that the front end
7136 * wants us to close the outgoing side of the connection
7137 * as soon as we see EOF from the far end, or else we've
7138 * unilaterally decided to do that because we've allocated
7139 * a remote pty and hence EOF isn't a particularly
7140 * meaningful concept.
7142 sshfwd_write_eof(c);
7144 ssh->sent_console_eof = TRUE;
7147 ssh2_channel_check_close(c);
7150 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
7152 struct ssh_channel *c;
7154 c = ssh2_channel_msg(ssh, pktin);
7157 ssh2_channel_got_eof(c);
7160 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7162 struct ssh_channel *c;
7164 c = ssh2_channel_msg(ssh, pktin);
7169 * When we receive CLOSE on a channel, we assume it comes with an
7170 * implied EOF if we haven't seen EOF yet.
7172 ssh2_channel_got_eof(c);
7175 * And we also send an outgoing EOF, if we haven't already, on the
7176 * assumption that CLOSE is a pretty forceful announcement that
7177 * the remote side is doing away with the entire channel. (If it
7178 * had wanted to send us EOF and continue receiving data from us,
7179 * it would have just sent CHANNEL_EOF.)
7181 if (!(c->closes & CLOSES_SENT_EOF)) {
7183 * Make sure we don't read any more from whatever our local
7184 * data source is for this channel.
7187 case CHAN_MAINSESSION:
7188 ssh->send_ok = 0; /* stop trying to read from stdin */
7191 x11_override_throttle(c->u.x11.xconn, 1);
7194 pfd_override_throttle(c->u.pfd.pf, 1);
7199 * Abandon any buffered data we still wanted to send to this
7200 * channel. Receiving a CHANNEL_CLOSE is an indication that
7201 * the server really wants to get on and _destroy_ this
7202 * channel, and it isn't going to send us any further
7203 * WINDOW_ADJUSTs to permit us to send pending stuff.
7205 bufchain_clear(&c->v.v2.outbuffer);
7208 * Send outgoing EOF.
7210 sshfwd_write_eof(c);
7214 * Now process the actual close.
7216 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7217 c->closes |= CLOSES_RCVD_CLOSE;
7218 ssh2_channel_check_close(c);
7222 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7224 struct ssh_channel *c;
7226 c = ssh2_channel_msg(ssh, pktin);
7229 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7230 c->remoteid = ssh_pkt_getuint32(pktin);
7231 c->halfopen = FALSE;
7232 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7233 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7235 if (c->type == CHAN_SOCKDATA_DORMANT) {
7236 c->type = CHAN_SOCKDATA;
7238 pfd_confirm(c->u.pfd.pf);
7239 } else if (c->type == CHAN_ZOMBIE) {
7241 * This case can occur if a local socket error occurred
7242 * between us sending out CHANNEL_OPEN and receiving
7243 * OPEN_CONFIRMATION. In this case, all we can do is
7244 * immediately initiate close proceedings now that we know the
7245 * server's id to put in the close message.
7247 ssh2_channel_check_close(c);
7250 * We never expect to receive OPEN_CONFIRMATION for any
7251 * *other* channel type (since only local-to-remote port
7252 * forwardings cause us to send CHANNEL_OPEN after the main
7253 * channel is live - all other auxiliary channel types are
7254 * initiated from the server end). It's safe to enforce this
7255 * by assertion rather than by ssh_disconnect, because the
7256 * real point is that we never constructed a half-open channel
7257 * structure in the first place with any type other than the
7260 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
7264 ssh_channel_try_eof(c); /* in case we had a pending EOF */
7267 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7269 static const char *const reasons[] = {
7270 "<unknown reason code>",
7271 "Administratively prohibited",
7273 "Unknown channel type",
7274 "Resource shortage",
7276 unsigned reason_code;
7277 char *reason_string;
7279 struct ssh_channel *c;
7281 c = ssh2_channel_msg(ssh, pktin);
7284 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7286 if (c->type == CHAN_SOCKDATA_DORMANT) {
7287 reason_code = ssh_pkt_getuint32(pktin);
7288 if (reason_code >= lenof(reasons))
7289 reason_code = 0; /* ensure reasons[reason_code] in range */
7290 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7291 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7292 reasons[reason_code], reason_length, reason_string);
7294 pfd_close(c->u.pfd.pf);
7295 } else if (c->type == CHAN_ZOMBIE) {
7297 * This case can occur if a local socket error occurred
7298 * between us sending out CHANNEL_OPEN and receiving
7299 * OPEN_FAILURE. In this case, we need do nothing except allow
7300 * the code below to throw the half-open channel away.
7304 * We never expect to receive OPEN_FAILURE for any *other*
7305 * channel type (since only local-to-remote port forwardings
7306 * cause us to send CHANNEL_OPEN after the main channel is
7307 * live - all other auxiliary channel types are initiated from
7308 * the server end). It's safe to enforce this by assertion
7309 * rather than by ssh_disconnect, because the real point is
7310 * that we never constructed a half-open channel structure in
7311 * the first place with any type other than the above.
7313 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
7316 del234(ssh->channels, c);
7320 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7323 int typelen, want_reply;
7324 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7325 struct ssh_channel *c;
7326 struct Packet *pktout;
7328 c = ssh2_channel_msg(ssh, pktin);
7331 ssh_pkt_getstring(pktin, &type, &typelen);
7332 want_reply = ssh2_pkt_getbool(pktin);
7335 * Having got the channel number, we now look at
7336 * the request type string to see if it's something
7339 if (c == ssh->mainchan) {
7341 * We recognise "exit-status" and "exit-signal" on
7342 * the primary channel.
7344 if (typelen == 11 &&
7345 !memcmp(type, "exit-status", 11)) {
7347 ssh->exitcode = ssh_pkt_getuint32(pktin);
7348 logeventf(ssh, "Server sent command exit status %d",
7350 reply = SSH2_MSG_CHANNEL_SUCCESS;
7352 } else if (typelen == 11 &&
7353 !memcmp(type, "exit-signal", 11)) {
7355 int is_plausible = TRUE, is_int = FALSE;
7356 char *fmt_sig = "", *fmt_msg = "";
7358 int msglen = 0, core = FALSE;
7359 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7360 * provide an `int' for the signal, despite its
7361 * having been a `string' in the drafts of RFC 4254 since at
7362 * least 2001. (Fixed in session.c 1.147.) Try to
7363 * infer which we can safely parse it as. */
7365 unsigned char *p = pktin->body +
7367 long len = pktin->length - pktin->savedpos;
7368 unsigned long num = GET_32BIT(p); /* what is it? */
7369 /* If it's 0, it hardly matters; assume string */
7373 int maybe_int = FALSE, maybe_str = FALSE;
7374 #define CHECK_HYPOTHESIS(offset, result) \
7377 int q = toint(offset); \
7378 if (q >= 0 && q+4 <= len) { \
7379 q = toint(q + 4 + GET_32BIT(p+q)); \
7380 if (q >= 0 && q+4 <= len && \
7381 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
7386 CHECK_HYPOTHESIS(4+1, maybe_int);
7387 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7388 #undef CHECK_HYPOTHESIS
7389 if (maybe_int && !maybe_str)
7391 else if (!maybe_int && maybe_str)
7394 /* Crikey. Either or neither. Panic. */
7395 is_plausible = FALSE;
7398 ssh->exitcode = 128; /* means `unknown signal' */
7401 /* Old non-standard OpenSSH. */
7402 int signum = ssh_pkt_getuint32(pktin);
7403 fmt_sig = dupprintf(" %d", signum);
7404 ssh->exitcode = 128 + signum;
7406 /* As per RFC 4254. */
7409 ssh_pkt_getstring(pktin, &sig, &siglen);
7410 /* Signal name isn't supposed to be blank, but
7411 * let's cope gracefully if it is. */
7413 fmt_sig = dupprintf(" \"%.*s\"",
7418 * Really hideous method of translating the
7419 * signal description back into a locally
7420 * meaningful number.
7425 #define TRANSLATE_SIGNAL(s) \
7426 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7427 ssh->exitcode = 128 + SIG ## s
7429 TRANSLATE_SIGNAL(ABRT);
7432 TRANSLATE_SIGNAL(ALRM);
7435 TRANSLATE_SIGNAL(FPE);
7438 TRANSLATE_SIGNAL(HUP);
7441 TRANSLATE_SIGNAL(ILL);
7444 TRANSLATE_SIGNAL(INT);
7447 TRANSLATE_SIGNAL(KILL);
7450 TRANSLATE_SIGNAL(PIPE);
7453 TRANSLATE_SIGNAL(QUIT);
7456 TRANSLATE_SIGNAL(SEGV);
7459 TRANSLATE_SIGNAL(TERM);
7462 TRANSLATE_SIGNAL(USR1);
7465 TRANSLATE_SIGNAL(USR2);
7467 #undef TRANSLATE_SIGNAL
7469 ssh->exitcode = 128;
7471 core = ssh2_pkt_getbool(pktin);
7472 ssh_pkt_getstring(pktin, &msg, &msglen);
7474 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7476 /* ignore lang tag */
7477 } /* else don't attempt to parse */
7478 logeventf(ssh, "Server exited on signal%s%s%s",
7479 fmt_sig, core ? " (core dumped)" : "",
7481 if (*fmt_sig) sfree(fmt_sig);
7482 if (*fmt_msg) sfree(fmt_msg);
7483 reply = SSH2_MSG_CHANNEL_SUCCESS;
7488 * This is a channel request we don't know
7489 * about, so we now either ignore the request
7490 * or respond with CHANNEL_FAILURE, depending
7493 reply = SSH2_MSG_CHANNEL_FAILURE;
7496 pktout = ssh2_pkt_init(reply);
7497 ssh2_pkt_adduint32(pktout, c->remoteid);
7498 ssh2_pkt_send(ssh, pktout);
7502 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7505 int typelen, want_reply;
7506 struct Packet *pktout;
7508 ssh_pkt_getstring(pktin, &type, &typelen);
7509 want_reply = ssh2_pkt_getbool(pktin);
7512 * We currently don't support any global requests
7513 * at all, so we either ignore the request or
7514 * respond with REQUEST_FAILURE, depending on
7518 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7519 ssh2_pkt_send(ssh, pktout);
7523 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7531 struct ssh_channel *c;
7532 unsigned remid, winsize, pktsize;
7533 struct Packet *pktout;
7535 ssh_pkt_getstring(pktin, &type, &typelen);
7536 c = snew(struct ssh_channel);
7539 remid = ssh_pkt_getuint32(pktin);
7540 winsize = ssh_pkt_getuint32(pktin);
7541 pktsize = ssh_pkt_getuint32(pktin);
7543 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7547 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7548 addrstr = snewn(peeraddrlen+1, char);
7549 memcpy(addrstr, peeraddr, peeraddrlen);
7550 addrstr[peeraddrlen] = '\0';
7551 peerport = ssh_pkt_getuint32(pktin);
7553 logeventf(ssh, "Received X11 connect request from %s:%d",
7556 if (!ssh->X11_fwd_enabled)
7557 error = "X11 forwarding is not enabled";
7558 else if ((x11err = x11_init(&c->u.x11.xconn, ssh->x11disp, c,
7559 addrstr, peerport, ssh->conf)) != NULL) {
7560 logeventf(ssh, "Local X11 connection failed: %s", x11err);
7562 error = "Unable to open an X11 connection";
7564 logevent("Opening X11 forward connection succeeded");
7569 } else if (typelen == 15 &&
7570 !memcmp(type, "forwarded-tcpip", 15)) {
7571 struct ssh_rportfwd pf, *realpf;
7574 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
7575 pf.shost = dupprintf("%.*s", shostlen, shost);
7576 pf.sport = ssh_pkt_getuint32(pktin);
7577 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7578 peerport = ssh_pkt_getuint32(pktin);
7579 realpf = find234(ssh->rportfwds, &pf, NULL);
7580 logeventf(ssh, "Received remote port %s:%d open request "
7581 "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
7584 if (realpf == NULL) {
7585 error = "Remote port is not recognised";
7587 char *err = pfd_connect(&c->u.pfd.pf,
7591 realpf->pfrec->addressfamily);
7592 logeventf(ssh, "Attempting to forward remote port to "
7593 "%s:%d", realpf->dhost, realpf->dport);
7595 logeventf(ssh, "Port open failed: %s", err);
7597 error = "Port open failed";
7599 logevent("Forwarded port opened successfully");
7600 c->type = CHAN_SOCKDATA;
7603 } else if (typelen == 22 &&
7604 !memcmp(type, "auth-agent@openssh.com", 22)) {
7605 if (!ssh->agentfwd_enabled)
7606 error = "Agent forwarding is not enabled";
7608 c->type = CHAN_AGENT; /* identify channel type */
7609 c->u.a.lensofar = 0;
7610 c->u.a.message = NULL;
7611 c->u.a.outstanding_requests = 0;
7614 error = "Unsupported channel type requested";
7617 c->remoteid = remid;
7618 c->halfopen = FALSE;
7620 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7621 ssh2_pkt_adduint32(pktout, c->remoteid);
7622 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7623 ssh2_pkt_addstring(pktout, error);
7624 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7625 ssh2_pkt_send(ssh, pktout);
7626 logeventf(ssh, "Rejected channel open: %s", error);
7629 ssh2_channel_init(c);
7630 c->v.v2.remwindow = winsize;
7631 c->v.v2.remmaxpkt = pktsize;
7632 add234(ssh->channels, c);
7633 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7634 ssh2_pkt_adduint32(pktout, c->remoteid);
7635 ssh2_pkt_adduint32(pktout, c->localid);
7636 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
7637 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7638 ssh2_pkt_send(ssh, pktout);
7643 * Buffer banner messages for later display at some convenient point,
7644 * if we're going to display them.
7646 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7648 /* Arbitrary limit to prevent unbounded inflation of buffer */
7649 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
7650 bufchain_size(&ssh->banner) <= 131072) {
7651 char *banner = NULL;
7653 ssh_pkt_getstring(pktin, &banner, &size);
7655 bufchain_add(&ssh->banner, banner, size);
7659 /* Helper function to deal with sending tty modes for "pty-req" */
7660 static void ssh2_send_ttymode(void *data, char *mode, char *val)
7662 struct Packet *pktout = (struct Packet *)data;
7664 unsigned int arg = 0;
7665 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7666 if (i == lenof(ssh_ttymodes)) return;
7667 switch (ssh_ttymodes[i].type) {
7669 arg = ssh_tty_parse_specchar(val);
7672 arg = ssh_tty_parse_boolean(val);
7675 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7676 ssh2_pkt_adduint32(pktout, arg);
7679 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
7682 struct ssh2_setup_x11_state {
7686 struct Packet *pktout;
7687 crStateP(ssh2_setup_x11_state, ctx);
7691 logevent("Requesting X11 forwarding");
7692 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
7694 ssh2_pkt_addbool(pktout, 0); /* many connections */
7695 ssh2_pkt_addstring(pktout, ssh->x11disp->remoteauthprotoname);
7696 ssh2_pkt_addstring(pktout, ssh->x11disp->remoteauthdatastring);
7697 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
7698 ssh2_pkt_send(ssh, pktout);
7700 /* Wait to be called back with either a response packet, or NULL
7701 * meaning clean up and free our data */
7705 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7706 logevent("X11 forwarding enabled");
7707 ssh->X11_fwd_enabled = TRUE;
7709 logevent("X11 forwarding refused");
7715 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
7718 struct ssh2_setup_agent_state {
7722 struct Packet *pktout;
7723 crStateP(ssh2_setup_agent_state, ctx);
7727 logevent("Requesting OpenSSH-style agent forwarding");
7728 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
7729 ssh2_setup_agent, s);
7730 ssh2_pkt_send(ssh, pktout);
7732 /* Wait to be called back with either a response packet, or NULL
7733 * meaning clean up and free our data */
7737 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7738 logevent("Agent forwarding enabled");
7739 ssh->agentfwd_enabled = TRUE;
7741 logevent("Agent forwarding refused");
7747 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
7750 struct ssh2_setup_pty_state {
7754 struct Packet *pktout;
7755 crStateP(ssh2_setup_pty_state, ctx);
7759 /* Unpick the terminal-speed string. */
7760 /* XXX perhaps we should allow no speeds to be sent. */
7761 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
7762 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
7763 /* Build the pty request. */
7764 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
7766 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
7767 ssh2_pkt_adduint32(pktout, ssh->term_width);
7768 ssh2_pkt_adduint32(pktout, ssh->term_height);
7769 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
7770 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
7771 ssh2_pkt_addstring_start(pktout);
7772 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
7773 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
7774 ssh2_pkt_adduint32(pktout, ssh->ispeed);
7775 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
7776 ssh2_pkt_adduint32(pktout, ssh->ospeed);
7777 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
7778 ssh2_pkt_send(ssh, pktout);
7779 ssh->state = SSH_STATE_INTERMED;
7781 /* Wait to be called back with either a response packet, or NULL
7782 * meaning clean up and free our data */
7786 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
7787 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
7788 ssh->ospeed, ssh->ispeed);
7789 ssh->got_pty = TRUE;
7791 c_write_str(ssh, "Server refused to allocate pty\r\n");
7792 ssh->editing = ssh->echoing = 1;
7799 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
7802 struct ssh2_setup_env_state {
7804 int num_env, env_left, env_ok;
7807 struct Packet *pktout;
7808 crStateP(ssh2_setup_env_state, ctx);
7813 * Send environment variables.
7815 * Simplest thing here is to send all the requests at once, and
7816 * then wait for a whole bunch of successes or failures.
7822 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
7824 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
7825 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
7826 ssh2_pkt_addstring(pktout, key);
7827 ssh2_pkt_addstring(pktout, val);
7828 ssh2_pkt_send(ssh, pktout);
7833 logeventf(ssh, "Sent %d environment variables", s->num_env);
7838 s->env_left = s->num_env;
7840 while (s->env_left > 0) {
7841 /* Wait to be called back with either a response packet,
7842 * or NULL meaning clean up and free our data */
7844 if (!pktin) goto out;
7845 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
7850 if (s->env_ok == s->num_env) {
7851 logevent("All environment variables successfully set");
7852 } else if (s->env_ok == 0) {
7853 logevent("All environment variables refused");
7854 c_write_str(ssh, "Server refused to set environment variables\r\n");
7856 logeventf(ssh, "%d environment variables refused",
7857 s->num_env - s->env_ok);
7858 c_write_str(ssh, "Server refused to set all environment variables\r\n");
7866 * Handle the SSH-2 userauth and connection layers.
7868 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
7870 do_ssh2_authconn(ssh, NULL, 0, pktin);
7873 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
7876 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
7879 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7880 struct Packet *pktin)
7882 struct do_ssh2_authconn_state {
7886 AUTH_TYPE_PUBLICKEY,
7887 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7888 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7890 AUTH_TYPE_GSSAPI, /* always QUIET */
7891 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7892 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7894 int done_service_req;
7895 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
7896 int tried_pubkey_config, done_agent;
7901 int kbd_inter_refused;
7902 int we_are_in, userauth_success;
7903 prompts_t *cur_prompt;
7908 void *publickey_blob;
7909 int publickey_bloblen;
7910 int publickey_encrypted;
7911 char *publickey_algorithm;
7912 char *publickey_comment;
7913 unsigned char agent_request[5], *agent_response, *agentp;
7914 int agent_responselen;
7915 unsigned char *pkblob_in_agent;
7917 char *pkblob, *alg, *commentp;
7918 int pklen, alglen, commentlen;
7919 int siglen, retlen, len;
7920 char *q, *agentreq, *ret;
7922 struct Packet *pktout;
7925 struct ssh_gss_library *gsslib;
7926 Ssh_gss_ctx gss_ctx;
7927 Ssh_gss_buf gss_buf;
7928 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7929 Ssh_gss_name gss_srv_name;
7930 Ssh_gss_stat gss_stat;
7933 crState(do_ssh2_authconn_state);
7937 /* Register as a handler for all the messages this coroutine handles. */
7938 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
7939 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
7940 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
7941 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
7942 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
7943 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
7944 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
7945 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
7946 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
7947 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
7948 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
7949 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
7950 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
7951 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
7952 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
7953 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
7954 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
7955 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
7956 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
7957 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
7959 s->done_service_req = FALSE;
7960 s->we_are_in = s->userauth_success = FALSE;
7962 s->tried_gssapi = FALSE;
7965 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
7967 * Request userauth protocol, and await a response to it.
7969 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7970 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7971 ssh2_pkt_send(ssh, s->pktout);
7972 crWaitUntilV(pktin);
7973 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7974 s->done_service_req = TRUE;
7976 if (!s->done_service_req) {
7978 * Request connection protocol directly, without authentication.
7980 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7981 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7982 ssh2_pkt_send(ssh, s->pktout);
7983 crWaitUntilV(pktin);
7984 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7985 s->we_are_in = TRUE; /* no auth required */
7987 bombout(("Server refused service request"));
7992 /* Arrange to be able to deal with any BANNERs that come in.
7993 * (We do this now as packets may come in during the next bit.) */
7994 bufchain_init(&ssh->banner);
7995 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7996 ssh2_msg_userauth_banner;
7999 * Misc one-time setup for authentication.
8001 s->publickey_blob = NULL;
8002 if (!s->we_are_in) {
8005 * Load the public half of any configured public key file
8008 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8009 if (!filename_is_null(s->keyfile)) {
8011 logeventf(ssh, "Reading private key file \"%.150s\"",
8012 filename_to_str(s->keyfile));
8013 keytype = key_type(s->keyfile);
8014 if (keytype == SSH_KEYTYPE_SSH2) {
8017 ssh2_userkey_loadpub(s->keyfile,
8018 &s->publickey_algorithm,
8019 &s->publickey_bloblen,
8020 &s->publickey_comment, &error);
8021 if (s->publickey_blob) {
8022 s->publickey_encrypted =
8023 ssh2_userkey_encrypted(s->keyfile, NULL);
8026 logeventf(ssh, "Unable to load private key (%s)",
8028 msgbuf = dupprintf("Unable to load private key file "
8029 "\"%.150s\" (%s)\r\n",
8030 filename_to_str(s->keyfile),
8032 c_write_str(ssh, msgbuf);
8037 logeventf(ssh, "Unable to use this key file (%s)",
8038 key_type_to_str(keytype));
8039 msgbuf = dupprintf("Unable to use key file \"%.150s\""
8041 filename_to_str(s->keyfile),
8042 key_type_to_str(keytype));
8043 c_write_str(ssh, msgbuf);
8045 s->publickey_blob = NULL;
8050 * Find out about any keys Pageant has (but if there's a
8051 * public key configured, filter out all others).
8054 s->agent_response = NULL;
8055 s->pkblob_in_agent = NULL;
8056 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
8060 logevent("Pageant is running. Requesting keys.");
8062 /* Request the keys held by the agent. */
8063 PUT_32BIT(s->agent_request, 1);
8064 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
8065 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
8066 ssh_agent_callback, ssh)) {
8070 bombout(("Unexpected data from server while"
8071 " waiting for agent response"));
8074 } while (pktin || inlen > 0);
8075 r = ssh->agent_response;
8076 s->agent_responselen = ssh->agent_response_len;
8078 s->agent_response = (unsigned char *) r;
8079 if (s->agent_response && s->agent_responselen >= 5 &&
8080 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
8083 p = s->agent_response + 5;
8084 s->nkeys = toint(GET_32BIT(p));
8087 * Vet the Pageant response to ensure that the key
8088 * count and blob lengths make sense.
8091 logeventf(ssh, "Pageant response contained a negative"
8092 " key count %d", s->nkeys);
8094 goto done_agent_query;
8096 unsigned char *q = p + 4;
8097 int lenleft = s->agent_responselen - 5 - 4;
8099 for (keyi = 0; keyi < s->nkeys; keyi++) {
8100 int bloblen, commentlen;
8102 logeventf(ssh, "Pageant response was truncated");
8104 goto done_agent_query;
8106 bloblen = toint(GET_32BIT(q));
8107 if (bloblen < 0 || bloblen > lenleft) {
8108 logeventf(ssh, "Pageant response was truncated");
8110 goto done_agent_query;
8112 lenleft -= 4 + bloblen;
8114 commentlen = toint(GET_32BIT(q));
8115 if (commentlen < 0 || commentlen > lenleft) {
8116 logeventf(ssh, "Pageant response was truncated");
8118 goto done_agent_query;
8120 lenleft -= 4 + commentlen;
8121 q += 4 + commentlen;
8126 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
8127 if (s->publickey_blob) {
8128 /* See if configured key is in agent. */
8129 for (keyi = 0; keyi < s->nkeys; keyi++) {
8130 s->pklen = toint(GET_32BIT(p));
8131 if (s->pklen == s->publickey_bloblen &&
8132 !memcmp(p+4, s->publickey_blob,
8133 s->publickey_bloblen)) {
8134 logeventf(ssh, "Pageant key #%d matches "
8135 "configured key file", keyi);
8137 s->pkblob_in_agent = p;
8141 p += toint(GET_32BIT(p)) + 4; /* comment */
8143 if (!s->pkblob_in_agent) {
8144 logevent("Configured key file not in Pageant");
8149 logevent("Failed to get reply from Pageant");
8157 * We repeat this whole loop, including the username prompt,
8158 * until we manage a successful authentication. If the user
8159 * types the wrong _password_, they can be sent back to the
8160 * beginning to try another username, if this is configured on.
8161 * (If they specify a username in the config, they are never
8162 * asked, even if they do give a wrong password.)
8164 * I think this best serves the needs of
8166 * - the people who have no configuration, no keys, and just
8167 * want to try repeated (username,password) pairs until they
8168 * type both correctly
8170 * - people who have keys and configuration but occasionally
8171 * need to fall back to passwords
8173 * - people with a key held in Pageant, who might not have
8174 * logged in to a particular machine before; so they want to
8175 * type a username, and then _either_ their key will be
8176 * accepted, _or_ they will type a password. If they mistype
8177 * the username they will want to be able to get back and
8180 s->got_username = FALSE;
8181 while (!s->we_are_in) {
8185 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
8187 * We got a username last time round this loop, and
8188 * with change_username turned off we don't try to get
8191 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
8192 int ret; /* need not be kept over crReturn */
8193 s->cur_prompt = new_prompts(ssh->frontend);
8194 s->cur_prompt->to_server = TRUE;
8195 s->cur_prompt->name = dupstr("SSH login name");
8196 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
8197 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8200 crWaitUntilV(!pktin);
8201 ret = get_userpass_input(s->cur_prompt, in, inlen);
8206 * get_userpass_input() failed to get a username.
8209 free_prompts(s->cur_prompt);
8210 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
8213 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
8214 free_prompts(s->cur_prompt);
8217 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
8218 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
8219 c_write_str(ssh, stuff);
8223 s->got_username = TRUE;
8226 * Send an authentication request using method "none": (a)
8227 * just in case it succeeds, and (b) so that we know what
8228 * authentication methods we can usefully try next.
8230 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8232 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8233 ssh2_pkt_addstring(s->pktout, ssh->username);
8234 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
8235 ssh2_pkt_addstring(s->pktout, "none"); /* method */
8236 ssh2_pkt_send(ssh, s->pktout);
8237 s->type = AUTH_TYPE_NONE;
8239 s->we_are_in = FALSE;
8241 s->tried_pubkey_config = FALSE;
8242 s->kbd_inter_refused = FALSE;
8244 /* Reset agent request state. */
8245 s->done_agent = FALSE;
8246 if (s->agent_response) {
8247 if (s->pkblob_in_agent) {
8248 s->agentp = s->pkblob_in_agent;
8250 s->agentp = s->agent_response + 5 + 4;
8256 char *methods = NULL;
8260 * Wait for the result of the last authentication request.
8263 crWaitUntilV(pktin);
8265 * Now is a convenient point to spew any banner material
8266 * that we've accumulated. (This should ensure that when
8267 * we exit the auth loop, we haven't any left to deal
8271 int size = bufchain_size(&ssh->banner);
8273 * Don't show the banner if we're operating in
8274 * non-verbose non-interactive mode. (It's probably
8275 * a script, which means nobody will read the
8276 * banner _anyway_, and moreover the printing of
8277 * the banner will screw up processing on the
8278 * output of (say) plink.)
8280 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
8281 char *banner = snewn(size, char);
8282 bufchain_fetch(&ssh->banner, banner, size);
8283 c_write_untrusted(ssh, banner, size);
8286 bufchain_clear(&ssh->banner);
8288 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
8289 logevent("Access granted");
8290 s->we_are_in = s->userauth_success = TRUE;
8294 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
8295 bombout(("Strange packet received during authentication: "
8296 "type %d", pktin->type));
8303 * OK, we're now sitting on a USERAUTH_FAILURE message, so
8304 * we can look at the string in it and know what we can
8305 * helpfully try next.
8307 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
8308 ssh_pkt_getstring(pktin, &methods, &methlen);
8309 if (!ssh2_pkt_getbool(pktin)) {
8311 * We have received an unequivocal Access
8312 * Denied. This can translate to a variety of
8313 * messages, or no message at all.
8315 * For forms of authentication which are attempted
8316 * implicitly, by which I mean without printing
8317 * anything in the window indicating that we're
8318 * trying them, we should never print 'Access
8321 * If we do print a message saying that we're
8322 * attempting some kind of authentication, it's OK
8323 * to print a followup message saying it failed -
8324 * but the message may sometimes be more specific
8325 * than simply 'Access denied'.
8327 * Additionally, if we'd just tried password
8328 * authentication, we should break out of this
8329 * whole loop so as to go back to the username
8330 * prompt (iff we're configured to allow
8331 * username change attempts).
8333 if (s->type == AUTH_TYPE_NONE) {
8335 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
8336 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
8337 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
8338 c_write_str(ssh, "Server refused our key\r\n");
8339 logevent("Server refused our key");
8340 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
8341 /* This _shouldn't_ happen except by a
8342 * protocol bug causing client and server to
8343 * disagree on what is a correct signature. */
8344 c_write_str(ssh, "Server refused public-key signature"
8345 " despite accepting key!\r\n");
8346 logevent("Server refused public-key signature"
8347 " despite accepting key!");
8348 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
8349 /* quiet, so no c_write */
8350 logevent("Server refused keyboard-interactive authentication");
8351 } else if (s->type==AUTH_TYPE_GSSAPI) {
8352 /* always quiet, so no c_write */
8353 /* also, the code down in the GSSAPI block has
8354 * already logged this in the Event Log */
8355 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
8356 logevent("Keyboard-interactive authentication failed");
8357 c_write_str(ssh, "Access denied\r\n");
8359 assert(s->type == AUTH_TYPE_PASSWORD);
8360 logevent("Password authentication failed");
8361 c_write_str(ssh, "Access denied\r\n");
8363 if (conf_get_int(ssh->conf, CONF_change_username)) {
8364 /* XXX perhaps we should allow
8365 * keyboard-interactive to do this too? */
8366 s->we_are_in = FALSE;
8371 c_write_str(ssh, "Further authentication required\r\n");
8372 logevent("Further authentication required");
8376 in_commasep_string("publickey", methods, methlen);
8378 in_commasep_string("password", methods, methlen);
8379 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
8380 in_commasep_string("keyboard-interactive", methods, methlen);
8383 ssh->gsslibs = ssh_gss_setup(ssh->conf);
8384 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
8385 in_commasep_string("gssapi-with-mic", methods, methlen) &&
8386 ssh->gsslibs->nlibraries > 0;
8390 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8392 if (s->can_pubkey && !s->done_agent && s->nkeys) {
8395 * Attempt public-key authentication using a key from Pageant.
8398 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8400 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
8402 /* Unpack key from agent response */
8403 s->pklen = toint(GET_32BIT(s->agentp));
8405 s->pkblob = (char *)s->agentp;
8406 s->agentp += s->pklen;
8407 s->alglen = toint(GET_32BIT(s->pkblob));
8408 s->alg = s->pkblob + 4;
8409 s->commentlen = toint(GET_32BIT(s->agentp));
8411 s->commentp = (char *)s->agentp;
8412 s->agentp += s->commentlen;
8413 /* s->agentp now points at next key, if any */
8415 /* See if server will accept it */
8416 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8417 ssh2_pkt_addstring(s->pktout, ssh->username);
8418 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8419 /* service requested */
8420 ssh2_pkt_addstring(s->pktout, "publickey");
8422 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
8423 ssh2_pkt_addstring_start(s->pktout);
8424 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
8425 ssh2_pkt_addstring_start(s->pktout);
8426 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
8427 ssh2_pkt_send(ssh, s->pktout);
8428 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
8430 crWaitUntilV(pktin);
8431 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8433 /* Offer of key refused. */
8440 if (flags & FLAG_VERBOSE) {
8441 c_write_str(ssh, "Authenticating with "
8443 c_write(ssh, s->commentp, s->commentlen);
8444 c_write_str(ssh, "\" from agent\r\n");
8448 * Server is willing to accept the key.
8449 * Construct a SIGN_REQUEST.
8451 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8452 ssh2_pkt_addstring(s->pktout, ssh->username);
8453 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8454 /* service requested */
8455 ssh2_pkt_addstring(s->pktout, "publickey");
8457 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
8458 ssh2_pkt_addstring_start(s->pktout);
8459 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
8460 ssh2_pkt_addstring_start(s->pktout);
8461 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
8463 /* Ask agent for signature. */
8464 s->siglen = s->pktout->length - 5 + 4 +
8465 ssh->v2_session_id_len;
8466 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8468 s->len = 1; /* message type */
8469 s->len += 4 + s->pklen; /* key blob */
8470 s->len += 4 + s->siglen; /* data to sign */
8471 s->len += 4; /* flags */
8472 s->agentreq = snewn(4 + s->len, char);
8473 PUT_32BIT(s->agentreq, s->len);
8474 s->q = s->agentreq + 4;
8475 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
8476 PUT_32BIT(s->q, s->pklen);
8478 memcpy(s->q, s->pkblob, s->pklen);
8480 PUT_32BIT(s->q, s->siglen);
8482 /* Now the data to be signed... */
8483 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8484 PUT_32BIT(s->q, ssh->v2_session_id_len);
8487 memcpy(s->q, ssh->v2_session_id,
8488 ssh->v2_session_id_len);
8489 s->q += ssh->v2_session_id_len;
8490 memcpy(s->q, s->pktout->data + 5,
8491 s->pktout->length - 5);
8492 s->q += s->pktout->length - 5;
8493 /* And finally the (zero) flags word. */
8495 if (!agent_query(s->agentreq, s->len + 4,
8497 ssh_agent_callback, ssh)) {
8501 bombout(("Unexpected data from server"
8502 " while waiting for agent"
8506 } while (pktin || inlen > 0);
8507 vret = ssh->agent_response;
8508 s->retlen = ssh->agent_response_len;
8513 if (s->retlen >= 9 &&
8514 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
8515 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
8516 logevent("Sending Pageant's response");
8517 ssh2_add_sigblob(ssh, s->pktout,
8518 s->pkblob, s->pklen,
8520 GET_32BIT(s->ret + 5));
8521 ssh2_pkt_send(ssh, s->pktout);
8522 s->type = AUTH_TYPE_PUBLICKEY;
8524 /* FIXME: less drastic response */
8525 bombout(("Pageant failed to answer challenge"));
8531 /* Do we have any keys left to try? */
8532 if (s->pkblob_in_agent) {
8533 s->done_agent = TRUE;
8534 s->tried_pubkey_config = TRUE;
8537 if (s->keyi >= s->nkeys)
8538 s->done_agent = TRUE;
8541 } else if (s->can_pubkey && s->publickey_blob &&
8542 !s->tried_pubkey_config) {
8544 struct ssh2_userkey *key; /* not live over crReturn */
8545 char *passphrase; /* not live over crReturn */
8547 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8549 s->tried_pubkey_config = TRUE;
8552 * Try the public key supplied in the configuration.
8554 * First, offer the public blob to see if the server is
8555 * willing to accept it.
8557 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8558 ssh2_pkt_addstring(s->pktout, ssh->username);
8559 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8560 /* service requested */
8561 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
8562 ssh2_pkt_addbool(s->pktout, FALSE);
8563 /* no signature included */
8564 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
8565 ssh2_pkt_addstring_start(s->pktout);
8566 ssh2_pkt_addstring_data(s->pktout,
8567 (char *)s->publickey_blob,
8568 s->publickey_bloblen);
8569 ssh2_pkt_send(ssh, s->pktout);
8570 logevent("Offered public key");
8572 crWaitUntilV(pktin);
8573 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8574 /* Key refused. Give up. */
8575 s->gotit = TRUE; /* reconsider message next loop */
8576 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
8577 continue; /* process this new message */
8579 logevent("Offer of public key accepted");
8582 * Actually attempt a serious authentication using
8585 if (flags & FLAG_VERBOSE) {
8586 c_write_str(ssh, "Authenticating with public key \"");
8587 c_write_str(ssh, s->publickey_comment);
8588 c_write_str(ssh, "\"\r\n");
8592 const char *error; /* not live over crReturn */
8593 if (s->publickey_encrypted) {
8595 * Get a passphrase from the user.
8597 int ret; /* need not be kept over crReturn */
8598 s->cur_prompt = new_prompts(ssh->frontend);
8599 s->cur_prompt->to_server = FALSE;
8600 s->cur_prompt->name = dupstr("SSH key passphrase");
8601 add_prompt(s->cur_prompt,
8602 dupprintf("Passphrase for key \"%.100s\": ",
8603 s->publickey_comment),
8605 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8608 crWaitUntilV(!pktin);
8609 ret = get_userpass_input(s->cur_prompt,
8614 /* Failed to get a passphrase. Terminate. */
8615 free_prompts(s->cur_prompt);
8616 ssh_disconnect(ssh, NULL,
8617 "Unable to authenticate",
8618 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8623 dupstr(s->cur_prompt->prompts[0]->result);
8624 free_prompts(s->cur_prompt);
8626 passphrase = NULL; /* no passphrase needed */
8630 * Try decrypting the key.
8632 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8633 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
8635 /* burn the evidence */
8636 smemclr(passphrase, strlen(passphrase));
8639 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
8641 (key == SSH2_WRONG_PASSPHRASE)) {
8642 c_write_str(ssh, "Wrong passphrase\r\n");
8644 /* and loop again */
8646 c_write_str(ssh, "Unable to load private key (");
8647 c_write_str(ssh, error);
8648 c_write_str(ssh, ")\r\n");
8650 break; /* try something else */
8656 unsigned char *pkblob, *sigblob, *sigdata;
8657 int pkblob_len, sigblob_len, sigdata_len;
8661 * We have loaded the private key and the server
8662 * has announced that it's willing to accept it.
8663 * Hallelujah. Generate a signature and send it.
8665 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8666 ssh2_pkt_addstring(s->pktout, ssh->username);
8667 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8668 /* service requested */
8669 ssh2_pkt_addstring(s->pktout, "publickey");
8671 ssh2_pkt_addbool(s->pktout, TRUE);
8672 /* signature follows */
8673 ssh2_pkt_addstring(s->pktout, key->alg->name);
8674 pkblob = key->alg->public_blob(key->data,
8676 ssh2_pkt_addstring_start(s->pktout);
8677 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
8681 * The data to be signed is:
8685 * followed by everything so far placed in the
8688 sigdata_len = s->pktout->length - 5 + 4 +
8689 ssh->v2_session_id_len;
8690 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8692 sigdata = snewn(sigdata_len, unsigned char);
8694 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8695 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
8698 memcpy(sigdata+p, ssh->v2_session_id,
8699 ssh->v2_session_id_len);
8700 p += ssh->v2_session_id_len;
8701 memcpy(sigdata+p, s->pktout->data + 5,
8702 s->pktout->length - 5);
8703 p += s->pktout->length - 5;
8704 assert(p == sigdata_len);
8705 sigblob = key->alg->sign(key->data, (char *)sigdata,
8706 sigdata_len, &sigblob_len);
8707 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
8708 sigblob, sigblob_len);
8713 ssh2_pkt_send(ssh, s->pktout);
8714 logevent("Sent public key signature");
8715 s->type = AUTH_TYPE_PUBLICKEY;
8716 key->alg->freekey(key->data);
8720 } else if (s->can_gssapi && !s->tried_gssapi) {
8722 /* GSSAPI Authentication */
8727 s->type = AUTH_TYPE_GSSAPI;
8728 s->tried_gssapi = TRUE;
8730 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
8733 * Pick the highest GSS library on the preference
8739 for (i = 0; i < ngsslibs; i++) {
8740 int want_id = conf_get_int_int(ssh->conf,
8741 CONF_ssh_gsslist, i);
8742 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
8743 if (ssh->gsslibs->libraries[j].id == want_id) {
8744 s->gsslib = &ssh->gsslibs->libraries[j];
8745 goto got_gsslib; /* double break */
8750 * We always expect to have found something in
8751 * the above loop: we only came here if there
8752 * was at least one viable GSS library, and the
8753 * preference list should always mention
8754 * everything and only change the order.
8759 if (s->gsslib->gsslogmsg)
8760 logevent(s->gsslib->gsslogmsg);
8762 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8763 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8764 ssh2_pkt_addstring(s->pktout, ssh->username);
8765 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8766 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
8767 logevent("Attempting GSSAPI authentication");
8769 /* add mechanism info */
8770 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
8772 /* number of GSSAPI mechanisms */
8773 ssh2_pkt_adduint32(s->pktout,1);
8775 /* length of OID + 2 */
8776 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
8777 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
8780 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
8782 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
8784 ssh2_pkt_send(ssh, s->pktout);
8785 crWaitUntilV(pktin);
8786 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
8787 logevent("GSSAPI authentication request refused");
8791 /* check returned packet ... */
8793 ssh_pkt_getstring(pktin, &data, &len);
8794 s->gss_rcvtok.value = data;
8795 s->gss_rcvtok.length = len;
8796 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
8797 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
8798 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8799 memcmp((char *)s->gss_rcvtok.value + 2,
8800 s->gss_buf.value,s->gss_buf.length) ) {
8801 logevent("GSSAPI authentication - wrong response from server");
8805 /* now start running */
8806 s->gss_stat = s->gsslib->import_name(s->gsslib,
8809 if (s->gss_stat != SSH_GSS_OK) {
8810 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8811 logevent("GSSAPI import name failed - Bad service name");
8813 logevent("GSSAPI import name failed");
8817 /* fetch TGT into GSS engine */
8818 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
8820 if (s->gss_stat != SSH_GSS_OK) {
8821 logevent("GSSAPI authentication failed to get credentials");
8822 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8826 /* initial tokens are empty */
8827 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
8828 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
8830 /* now enter the loop */
8832 s->gss_stat = s->gsslib->init_sec_context
8836 conf_get_int(ssh->conf, CONF_gssapifwd),
8840 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8841 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8842 logevent("GSSAPI authentication initialisation failed");
8844 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8845 &s->gss_buf) == SSH_GSS_OK) {
8846 logevent(s->gss_buf.value);
8847 sfree(s->gss_buf.value);
8852 logevent("GSSAPI authentication initialised");
8854 /* Client and server now exchange tokens until GSSAPI
8855 * no longer says CONTINUE_NEEDED */
8857 if (s->gss_sndtok.length != 0) {
8858 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8859 ssh_pkt_addstring_start(s->pktout);
8860 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
8861 ssh2_pkt_send(ssh, s->pktout);
8862 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
8865 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8866 crWaitUntilV(pktin);
8867 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8868 logevent("GSSAPI authentication - bad server response");
8869 s->gss_stat = SSH_GSS_FAILURE;
8872 ssh_pkt_getstring(pktin, &data, &len);
8873 s->gss_rcvtok.value = data;
8874 s->gss_rcvtok.length = len;
8876 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8878 if (s->gss_stat != SSH_GSS_OK) {
8879 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8880 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8883 logevent("GSSAPI authentication loop finished OK");
8885 /* Now send the MIC */
8887 s->pktout = ssh2_pkt_init(0);
8888 micoffset = s->pktout->length;
8889 ssh_pkt_addstring_start(s->pktout);
8890 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8891 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
8892 ssh_pkt_addstring(s->pktout, ssh->username);
8893 ssh_pkt_addstring(s->pktout, "ssh-connection");
8894 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8896 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8897 s->gss_buf.length = s->pktout->length - micoffset;
8899 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
8900 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8901 ssh_pkt_addstring_start(s->pktout);
8902 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
8903 ssh2_pkt_send(ssh, s->pktout);
8904 s->gsslib->free_mic(s->gsslib, &mic);
8908 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8909 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
8912 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8915 * Keyboard-interactive authentication.
8918 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8920 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
8922 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8923 ssh2_pkt_addstring(s->pktout, ssh->username);
8924 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8925 /* service requested */
8926 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8928 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8929 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8930 ssh2_pkt_send(ssh, s->pktout);
8932 logevent("Attempting keyboard-interactive authentication");
8934 crWaitUntilV(pktin);
8935 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8936 /* Server is not willing to do keyboard-interactive
8937 * at all (or, bizarrely but legally, accepts the
8938 * user without actually issuing any prompts).
8939 * Give up on it entirely. */
8941 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8942 s->kbd_inter_refused = TRUE; /* don't try it again */
8947 * Loop while the server continues to send INFO_REQUESTs.
8949 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
8951 char *name, *inst, *lang;
8952 int name_len, inst_len, lang_len;
8956 * We've got a fresh USERAUTH_INFO_REQUEST.
8957 * Get the preamble and start building a prompt.
8959 ssh_pkt_getstring(pktin, &name, &name_len);
8960 ssh_pkt_getstring(pktin, &inst, &inst_len);
8961 ssh_pkt_getstring(pktin, &lang, &lang_len);
8962 s->cur_prompt = new_prompts(ssh->frontend);
8963 s->cur_prompt->to_server = TRUE;
8966 * Get any prompt(s) from the packet.
8968 s->num_prompts = ssh_pkt_getuint32(pktin);
8969 for (i = 0; i < s->num_prompts; i++) {
8973 static char noprompt[] =
8974 "<server failed to send prompt>: ";
8976 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8977 echo = ssh2_pkt_getbool(pktin);
8980 prompt_len = lenof(noprompt)-1;
8982 add_prompt(s->cur_prompt,
8983 dupprintf("%.*s", prompt_len, prompt),
8988 /* FIXME: better prefix to distinguish from
8990 s->cur_prompt->name =
8991 dupprintf("SSH server: %.*s", name_len, name);
8992 s->cur_prompt->name_reqd = TRUE;
8994 s->cur_prompt->name =
8995 dupstr("SSH server authentication");
8996 s->cur_prompt->name_reqd = FALSE;
8998 /* We add a prefix to try to make it clear that a prompt
8999 * has come from the server.
9000 * FIXME: ugly to print "Using..." in prompt _every_
9001 * time round. Can this be done more subtly? */
9002 /* Special case: for reasons best known to themselves,
9003 * some servers send k-i requests with no prompts and
9004 * nothing to display. Keep quiet in this case. */
9005 if (s->num_prompts || name_len || inst_len) {
9006 s->cur_prompt->instruction =
9007 dupprintf("Using keyboard-interactive authentication.%s%.*s",
9008 inst_len ? "\n" : "", inst_len, inst);
9009 s->cur_prompt->instr_reqd = TRUE;
9011 s->cur_prompt->instr_reqd = FALSE;
9015 * Display any instructions, and get the user's
9019 int ret; /* not live over crReturn */
9020 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9023 crWaitUntilV(!pktin);
9024 ret = get_userpass_input(s->cur_prompt, in, inlen);
9029 * Failed to get responses. Terminate.
9031 free_prompts(s->cur_prompt);
9032 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9033 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9040 * Send the response(s) to the server.
9042 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
9043 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
9044 for (i=0; i < s->num_prompts; i++) {
9045 ssh2_pkt_addstring(s->pktout,
9046 s->cur_prompt->prompts[i]->result);
9048 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9051 * Free the prompts structure from this iteration.
9052 * If there's another, a new one will be allocated
9053 * when we return to the top of this while loop.
9055 free_prompts(s->cur_prompt);
9058 * Get the next packet in case it's another
9061 crWaitUntilV(pktin);
9066 * We should have SUCCESS or FAILURE now.
9070 } else if (s->can_passwd) {
9073 * Plain old password authentication.
9075 int ret; /* not live over crReturn */
9076 int changereq_first_time; /* not live over crReturn */
9078 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
9080 s->cur_prompt = new_prompts(ssh->frontend);
9081 s->cur_prompt->to_server = TRUE;
9082 s->cur_prompt->name = dupstr("SSH password");
9083 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
9088 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9091 crWaitUntilV(!pktin);
9092 ret = get_userpass_input(s->cur_prompt, in, inlen);
9097 * Failed to get responses. Terminate.
9099 free_prompts(s->cur_prompt);
9100 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9101 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9106 * Squirrel away the password. (We may need it later if
9107 * asked to change it.)
9109 s->password = dupstr(s->cur_prompt->prompts[0]->result);
9110 free_prompts(s->cur_prompt);
9113 * Send the password packet.
9115 * We pad out the password packet to 256 bytes to make
9116 * it harder for an attacker to find the length of the
9119 * Anyone using a password longer than 256 bytes
9120 * probably doesn't have much to worry about from
9121 * people who find out how long their password is!
9123 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9124 ssh2_pkt_addstring(s->pktout, ssh->username);
9125 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9126 /* service requested */
9127 ssh2_pkt_addstring(s->pktout, "password");
9128 ssh2_pkt_addbool(s->pktout, FALSE);
9129 ssh2_pkt_addstring(s->pktout, s->password);
9130 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9131 logevent("Sent password");
9132 s->type = AUTH_TYPE_PASSWORD;
9135 * Wait for next packet, in case it's a password change
9138 crWaitUntilV(pktin);
9139 changereq_first_time = TRUE;
9141 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
9144 * We're being asked for a new password
9145 * (perhaps not for the first time).
9146 * Loop until the server accepts it.
9149 int got_new = FALSE; /* not live over crReturn */
9150 char *prompt; /* not live over crReturn */
9151 int prompt_len; /* not live over crReturn */
9155 if (changereq_first_time)
9156 msg = "Server requested password change";
9158 msg = "Server rejected new password";
9160 c_write_str(ssh, msg);
9161 c_write_str(ssh, "\r\n");
9164 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9166 s->cur_prompt = new_prompts(ssh->frontend);
9167 s->cur_prompt->to_server = TRUE;
9168 s->cur_prompt->name = dupstr("New SSH password");
9169 s->cur_prompt->instruction =
9170 dupprintf("%.*s", prompt_len, prompt);
9171 s->cur_prompt->instr_reqd = TRUE;
9173 * There's no explicit requirement in the protocol
9174 * for the "old" passwords in the original and
9175 * password-change messages to be the same, and
9176 * apparently some Cisco kit supports password change
9177 * by the user entering a blank password originally
9178 * and the real password subsequently, so,
9179 * reluctantly, we prompt for the old password again.
9181 * (On the other hand, some servers don't even bother
9182 * to check this field.)
9184 add_prompt(s->cur_prompt,
9185 dupstr("Current password (blank for previously entered password): "),
9187 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
9189 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
9193 * Loop until the user manages to enter the same
9198 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9201 crWaitUntilV(!pktin);
9202 ret = get_userpass_input(s->cur_prompt, in, inlen);
9207 * Failed to get responses. Terminate.
9209 /* burn the evidence */
9210 free_prompts(s->cur_prompt);
9211 smemclr(s->password, strlen(s->password));
9213 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9214 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9220 * If the user specified a new original password
9221 * (IYSWIM), overwrite any previously specified
9223 * (A side effect is that the user doesn't have to
9224 * re-enter it if they louse up the new password.)
9226 if (s->cur_prompt->prompts[0]->result[0]) {
9227 smemclr(s->password, strlen(s->password));
9228 /* burn the evidence */
9231 dupstr(s->cur_prompt->prompts[0]->result);
9235 * Check the two new passwords match.
9237 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
9238 s->cur_prompt->prompts[2]->result)
9241 /* They don't. Silly user. */
9242 c_write_str(ssh, "Passwords do not match\r\n");
9247 * Send the new password (along with the old one).
9248 * (see above for padding rationale)
9250 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9251 ssh2_pkt_addstring(s->pktout, ssh->username);
9252 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9253 /* service requested */
9254 ssh2_pkt_addstring(s->pktout, "password");
9255 ssh2_pkt_addbool(s->pktout, TRUE);
9256 ssh2_pkt_addstring(s->pktout, s->password);
9257 ssh2_pkt_addstring(s->pktout,
9258 s->cur_prompt->prompts[1]->result);
9259 free_prompts(s->cur_prompt);
9260 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9261 logevent("Sent new password");
9264 * Now see what the server has to say about it.
9265 * (If it's CHANGEREQ again, it's not happy with the
9268 crWaitUntilV(pktin);
9269 changereq_first_time = FALSE;
9274 * We need to reexamine the current pktin at the top
9275 * of the loop. Either:
9276 * - we weren't asked to change password at all, in
9277 * which case it's a SUCCESS or FAILURE with the
9279 * - we sent a new password, and the server was
9280 * either OK with it (SUCCESS or FAILURE w/partial
9281 * success) or unhappy with the _old_ password
9282 * (FAILURE w/o partial success)
9283 * In any of these cases, we go back to the top of
9284 * the loop and start again.
9289 * We don't need the old password any more, in any
9290 * case. Burn the evidence.
9292 smemclr(s->password, strlen(s->password));
9296 char *str = dupprintf("No supported authentication methods available"
9297 " (server sent: %.*s)",
9300 ssh_disconnect(ssh, str,
9301 "No supported authentication methods available",
9302 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
9312 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9314 /* Clear up various bits and pieces from authentication. */
9315 if (s->publickey_blob) {
9316 sfree(s->publickey_blob);
9317 sfree(s->publickey_comment);
9319 if (s->agent_response)
9320 sfree(s->agent_response);
9322 if (s->userauth_success) {
9324 * We've just received USERAUTH_SUCCESS, and we haven't sent any
9325 * packets since. Signal the transport layer to consider enacting
9326 * delayed compression.
9328 * (Relying on we_are_in is not sufficient, as
9329 * draft-miller-secsh-compression-delayed is quite clear that it
9330 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
9331 * become set for other reasons.)
9333 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
9337 * Now the connection protocol has started, one way or another.
9340 ssh->channels = newtree234(ssh_channelcmp);
9343 * Set up handlers for some connection protocol messages, so we
9344 * don't have to handle them repeatedly in this coroutine.
9346 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
9347 ssh2_msg_channel_window_adjust;
9348 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
9349 ssh2_msg_global_request;
9352 * Create the main session channel.
9354 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
9355 ssh->mainchan = NULL;
9357 ssh->mainchan = snew(struct ssh_channel);
9358 ssh->mainchan->ssh = ssh;
9359 ssh2_channel_init(ssh->mainchan);
9361 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
9363 * Just start a direct-tcpip channel and use it as the main
9366 ssh_send_port_open(ssh->mainchan,
9367 conf_get_str(ssh->conf, CONF_ssh_nc_host),
9368 conf_get_int(ssh->conf, CONF_ssh_nc_port),
9372 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
9373 logevent("Opening session as main channel");
9374 ssh2_pkt_send(ssh, s->pktout);
9375 ssh->ncmode = FALSE;
9377 crWaitUntilV(pktin);
9378 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
9379 bombout(("Server refused to open channel"));
9381 /* FIXME: error data comes back in FAILURE packet */
9383 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
9384 bombout(("Server's channel confirmation cited wrong channel"));
9387 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
9388 ssh->mainchan->halfopen = FALSE;
9389 ssh->mainchan->type = CHAN_MAINSESSION;
9390 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
9391 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
9392 add234(ssh->channels, ssh->mainchan);
9393 update_specials_menu(ssh->frontend);
9394 logevent("Opened main channel");
9398 * Now we have a channel, make dispatch table entries for
9399 * general channel-based messages.
9401 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
9402 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
9403 ssh2_msg_channel_data;
9404 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
9405 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
9406 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
9407 ssh2_msg_channel_open_confirmation;
9408 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
9409 ssh2_msg_channel_open_failure;
9410 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
9411 ssh2_msg_channel_request;
9412 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
9413 ssh2_msg_channel_open;
9414 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
9415 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
9418 if (ssh->mainchan && conf_get_int(ssh->conf, CONF_ssh_simple)) {
9420 * This message indicates to the server that we promise
9421 * not to try to run any other channel in parallel with
9422 * this one, so it's safe for it to advertise a very large
9423 * window and leave the flow control to TCP.
9425 s->pktout = ssh2_chanreq_init(ssh->mainchan,
9426 "simple@putty.projects.tartarus.org",
9428 ssh2_pkt_send(ssh, s->pktout);
9432 * Enable port forwardings.
9434 ssh_setup_portfwd(ssh, ssh->conf);
9436 if (ssh->mainchan && !ssh->ncmode) {
9438 * Send the CHANNEL_REQUESTS for the main session channel.
9439 * Each one is handled by its own little asynchronous
9443 /* Potentially enable X11 forwarding. */
9444 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
9446 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
9447 conf_get_int(ssh->conf, CONF_x11_auth),
9449 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
9451 /* Potentially enable agent forwarding. */
9452 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists())
9453 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
9455 /* Now allocate a pty for the session. */
9456 if (!conf_get_int(ssh->conf, CONF_nopty))
9457 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
9459 /* Send environment variables. */
9460 ssh2_setup_env(ssh->mainchan, NULL, NULL);
9463 * Start a shell or a remote command. We may have to attempt
9464 * this twice if the config data has provided a second choice
9471 if (ssh->fallback_cmd) {
9472 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
9473 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
9475 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
9476 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
9480 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
9481 ssh2_response_authconn, NULL);
9482 ssh2_pkt_addstring(s->pktout, cmd);
9484 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
9485 ssh2_response_authconn, NULL);
9486 ssh2_pkt_addstring(s->pktout, cmd);
9488 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
9489 ssh2_response_authconn, NULL);
9491 ssh2_pkt_send(ssh, s->pktout);
9493 crWaitUntilV(pktin);
9495 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9496 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9497 bombout(("Unexpected response to shell/command request:"
9498 " packet type %d", pktin->type));
9502 * We failed to start the command. If this is the
9503 * fallback command, we really are finished; if it's
9504 * not, and if the fallback command exists, try falling
9505 * back to it before complaining.
9507 if (!ssh->fallback_cmd &&
9508 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
9509 logevent("Primary command failed; attempting fallback");
9510 ssh->fallback_cmd = TRUE;
9513 bombout(("Server refused to start a shell/command"));
9516 logevent("Started a shell/command");
9521 ssh->editing = ssh->echoing = TRUE;
9524 ssh->state = SSH_STATE_SESSION;
9525 if (ssh->size_needed)
9526 ssh_size(ssh, ssh->term_width, ssh->term_height);
9527 if (ssh->eof_needed)
9528 ssh_special(ssh, TS_EOF);
9534 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
9539 s->try_send = FALSE;
9543 * _All_ the connection-layer packets we expect to
9544 * receive are now handled by the dispatch table.
9545 * Anything that reaches here must be bogus.
9548 bombout(("Strange packet received: type %d", pktin->type));
9550 } else if (ssh->mainchan) {
9552 * We have spare data. Add it to the channel buffer.
9554 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
9559 struct ssh_channel *c;
9561 * Try to send data on all channels if we can.
9563 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
9564 ssh2_try_send_and_unthrottle(ssh, c);
9572 * Handlers for SSH-2 messages that might arrive at any moment.
9574 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
9576 /* log reason code in disconnect message */
9580 reason = ssh_pkt_getuint32(pktin);
9581 ssh_pkt_getstring(pktin, &msg, &msglen);
9583 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
9584 buf = dupprintf("Received disconnect message (%s)",
9585 ssh2_disconnect_reasons[reason]);
9587 buf = dupprintf("Received disconnect message (unknown"
9588 " type %d)", reason);
9592 buf = dupprintf("Disconnection message text: %.*s",
9595 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
9597 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
9598 ssh2_disconnect_reasons[reason] : "unknown",
9603 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
9605 /* log the debug message */
9609 /* XXX maybe we should actually take notice of the return value */
9610 ssh2_pkt_getbool(pktin);
9611 ssh_pkt_getstring(pktin, &msg, &msglen);
9613 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
9616 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
9618 do_ssh2_transport(ssh, NULL, 0, pktin);
9622 * Called if we receive a packet that isn't allowed by the protocol.
9623 * This only applies to packets whose meaning PuTTY understands.
9624 * Entirely unknown packets are handled below.
9626 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
9628 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
9629 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
9631 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
9635 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
9637 struct Packet *pktout;
9638 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
9639 ssh2_pkt_adduint32(pktout, pktin->sequence);
9641 * UNIMPLEMENTED messages MUST appear in the same order as the
9642 * messages they respond to. Hence, never queue them.
9644 ssh2_pkt_send_noqueue(ssh, pktout);
9648 * Handle the top-level SSH-2 protocol.
9650 static void ssh2_protocol_setup(Ssh ssh)
9655 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9657 for (i = 0; i < 256; i++)
9658 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9661 * Initially, we only accept transport messages (and a few generic
9662 * ones). do_ssh2_authconn will add more when it starts.
9663 * Messages that are understood but not currently acceptable go to
9664 * ssh2_msg_unexpected.
9666 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
9667 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
9668 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
9669 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
9670 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
9671 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
9672 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
9673 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
9674 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
9675 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
9676 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
9677 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
9678 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
9679 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
9680 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
9681 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
9682 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
9683 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
9684 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
9685 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
9686 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
9687 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
9688 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
9689 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
9690 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
9691 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
9692 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
9693 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
9694 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
9695 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
9696 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
9697 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
9698 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
9701 * These messages have a special handler from the start.
9703 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
9704 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
9705 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9708 static void ssh2_timer(void *ctx, unsigned long now)
9712 if (ssh->state == SSH_STATE_CLOSED)
9715 if (!ssh->kex_in_progress && conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
9716 now == ssh->next_rekey) {
9717 do_ssh2_transport(ssh, "timeout", -1, NULL);
9721 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
9722 struct Packet *pktin)
9724 unsigned char *in = (unsigned char *)vin;
9725 if (ssh->state == SSH_STATE_CLOSED)
9729 ssh->incoming_data_size += pktin->encrypted_len;
9730 if (!ssh->kex_in_progress &&
9731 ssh->max_data_size != 0 &&
9732 ssh->incoming_data_size > ssh->max_data_size)
9733 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9737 ssh->packet_dispatch[pktin->type](ssh, pktin);
9738 else if (!ssh->protocol_initial_phase_done)
9739 do_ssh2_transport(ssh, in, inlen, pktin);
9741 do_ssh2_authconn(ssh, in, inlen, pktin);
9744 static void ssh_cache_conf_values(Ssh ssh)
9746 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
9750 * Called to set up the connection.
9752 * Returns an error message, or NULL on success.
9754 static const char *ssh_init(void *frontend_handle, void **backend_handle,
9755 Conf *conf, char *host, int port, char **realhost,
9756 int nodelay, int keepalive)
9761 ssh = snew(struct ssh_tag);
9762 ssh->conf = conf_copy(conf);
9763 ssh_cache_conf_values(ssh);
9764 ssh->version = 0; /* when not ready yet */
9767 ssh->v1_cipher_ctx = NULL;
9768 ssh->crcda_ctx = NULL;
9769 ssh->cscipher = NULL;
9770 ssh->cs_cipher_ctx = NULL;
9771 ssh->sccipher = NULL;
9772 ssh->sc_cipher_ctx = NULL;
9774 ssh->cs_mac_ctx = NULL;
9776 ssh->sc_mac_ctx = NULL;
9778 ssh->cs_comp_ctx = NULL;
9780 ssh->sc_comp_ctx = NULL;
9782 ssh->kex_ctx = NULL;
9783 ssh->hostkey = NULL;
9784 ssh->hostkey_str = NULL;
9786 ssh->close_expected = FALSE;
9787 ssh->clean_exit = FALSE;
9788 ssh->state = SSH_STATE_PREPACKET;
9789 ssh->size_needed = FALSE;
9790 ssh->eof_needed = FALSE;
9793 ssh->deferred_send_data = NULL;
9794 ssh->deferred_len = 0;
9795 ssh->deferred_size = 0;
9796 ssh->fallback_cmd = 0;
9797 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9798 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9799 ssh->x11disp = NULL;
9800 ssh->v1_compressing = FALSE;
9801 ssh->v2_outgoing_sequence = 0;
9802 ssh->ssh1_rdpkt_crstate = 0;
9803 ssh->ssh2_rdpkt_crstate = 0;
9804 ssh->ssh_gotdata_crstate = 0;
9805 ssh->do_ssh1_connection_crstate = 0;
9806 ssh->do_ssh_init_state = NULL;
9807 ssh->do_ssh1_login_state = NULL;
9808 ssh->do_ssh2_transport_state = NULL;
9809 ssh->do_ssh2_authconn_state = NULL;
9812 ssh->mainchan = NULL;
9813 ssh->throttled_all = 0;
9814 ssh->v1_stdout_throttling = 0;
9816 ssh->queuelen = ssh->queuesize = 0;
9817 ssh->queueing = FALSE;
9818 ssh->qhead = ssh->qtail = NULL;
9819 ssh->deferred_rekey_reason = NULL;
9820 bufchain_init(&ssh->queued_incoming_data);
9821 ssh->frozen = FALSE;
9822 ssh->username = NULL;
9823 ssh->sent_console_eof = FALSE;
9824 ssh->got_pty = FALSE;
9826 *backend_handle = ssh;
9829 if (crypto_startup() == 0)
9830 return "Microsoft high encryption pack not installed!";
9833 ssh->frontend = frontend_handle;
9834 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
9835 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
9837 ssh->channels = NULL;
9838 ssh->rportfwds = NULL;
9839 ssh->portfwds = NULL;
9844 ssh->conn_throttle_count = 0;
9845 ssh->overall_bufsize = 0;
9846 ssh->fallback_cmd = 0;
9848 ssh->protocol = NULL;
9850 ssh->protocol_initial_phase_done = FALSE;
9854 ssh->incoming_data_size = ssh->outgoing_data_size =
9855 ssh->deferred_data_size = 0L;
9856 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9857 CONF_ssh_rekey_data));
9858 ssh->kex_in_progress = FALSE;
9861 ssh->gsslibs = NULL;
9864 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
9873 static void ssh_free(void *handle)
9875 Ssh ssh = (Ssh) handle;
9876 struct ssh_channel *c;
9877 struct ssh_rportfwd *pf;
9879 if (ssh->v1_cipher_ctx)
9880 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9881 if (ssh->cs_cipher_ctx)
9882 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9883 if (ssh->sc_cipher_ctx)
9884 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9885 if (ssh->cs_mac_ctx)
9886 ssh->csmac->free_context(ssh->cs_mac_ctx);
9887 if (ssh->sc_mac_ctx)
9888 ssh->scmac->free_context(ssh->sc_mac_ctx);
9889 if (ssh->cs_comp_ctx) {
9891 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9893 zlib_compress_cleanup(ssh->cs_comp_ctx);
9895 if (ssh->sc_comp_ctx) {
9897 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9899 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9902 dh_cleanup(ssh->kex_ctx);
9903 sfree(ssh->savedhost);
9905 while (ssh->queuelen-- > 0)
9906 ssh_free_packet(ssh->queue[ssh->queuelen]);
9909 while (ssh->qhead) {
9910 struct queued_handler *qh = ssh->qhead;
9911 ssh->qhead = qh->next;
9914 ssh->qhead = ssh->qtail = NULL;
9916 if (ssh->channels) {
9917 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9920 if (c->u.x11.xconn != NULL)
9921 x11_close(c->u.x11.xconn);
9924 case CHAN_SOCKDATA_DORMANT:
9925 if (c->u.pfd.pf != NULL)
9926 pfd_close(c->u.pfd.pf);
9929 if (ssh->version == 2) {
9930 struct outstanding_channel_request *ocr, *nocr;
9931 ocr = c->v.v2.chanreq_head;
9933 ocr->handler(c, NULL, ocr->ctx);
9938 bufchain_clear(&c->v.v2.outbuffer);
9942 freetree234(ssh->channels);
9943 ssh->channels = NULL;
9946 if (ssh->rportfwds) {
9947 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
9949 freetree234(ssh->rportfwds);
9950 ssh->rportfwds = NULL;
9952 sfree(ssh->deferred_send_data);
9954 x11_free_display(ssh->x11disp);
9955 sfree(ssh->do_ssh_init_state);
9956 sfree(ssh->do_ssh1_login_state);
9957 sfree(ssh->do_ssh2_transport_state);
9958 sfree(ssh->do_ssh2_authconn_state);
9961 sfree(ssh->fullhostname);
9962 sfree(ssh->hostkey_str);
9963 if (ssh->crcda_ctx) {
9964 crcda_free_context(ssh->crcda_ctx);
9965 ssh->crcda_ctx = NULL;
9968 ssh_do_close(ssh, TRUE);
9969 expire_timer_context(ssh);
9971 pinger_free(ssh->pinger);
9972 bufchain_clear(&ssh->queued_incoming_data);
9973 sfree(ssh->username);
9974 conf_free(ssh->conf);
9977 ssh_gss_cleanup(ssh->gsslibs);
9985 * Reconfigure the SSH backend.
9987 static void ssh_reconfig(void *handle, Conf *conf)
9989 Ssh ssh = (Ssh) handle;
9990 char *rekeying = NULL, rekey_mandatory = FALSE;
9991 unsigned long old_max_data_size;
9994 pinger_reconfig(ssh->pinger, ssh->conf, conf);
9996 ssh_setup_portfwd(ssh, conf);
9998 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
9999 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
10001 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
10002 unsigned long now = GETTICKCOUNT();
10004 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
10005 rekeying = "timeout shortened";
10007 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
10011 old_max_data_size = ssh->max_data_size;
10012 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10013 CONF_ssh_rekey_data));
10014 if (old_max_data_size != ssh->max_data_size &&
10015 ssh->max_data_size != 0) {
10016 if (ssh->outgoing_data_size > ssh->max_data_size ||
10017 ssh->incoming_data_size > ssh->max_data_size)
10018 rekeying = "data limit lowered";
10021 if (conf_get_int(ssh->conf, CONF_compression) !=
10022 conf_get_int(conf, CONF_compression)) {
10023 rekeying = "compression setting changed";
10024 rekey_mandatory = TRUE;
10027 for (i = 0; i < CIPHER_MAX; i++)
10028 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
10029 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
10030 rekeying = "cipher settings changed";
10031 rekey_mandatory = TRUE;
10033 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
10034 conf_get_int(conf, CONF_ssh2_des_cbc)) {
10035 rekeying = "cipher settings changed";
10036 rekey_mandatory = TRUE;
10039 conf_free(ssh->conf);
10040 ssh->conf = conf_copy(conf);
10041 ssh_cache_conf_values(ssh);
10044 if (!ssh->kex_in_progress) {
10045 do_ssh2_transport(ssh, rekeying, -1, NULL);
10046 } else if (rekey_mandatory) {
10047 ssh->deferred_rekey_reason = rekeying;
10053 * Called to send data down the SSH connection.
10055 static int ssh_send(void *handle, char *buf, int len)
10057 Ssh ssh = (Ssh) handle;
10059 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10062 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
10064 return ssh_sendbuffer(ssh);
10068 * Called to query the current amount of buffered stdin data.
10070 static int ssh_sendbuffer(void *handle)
10072 Ssh ssh = (Ssh) handle;
10073 int override_value;
10075 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10079 * If the SSH socket itself has backed up, add the total backup
10080 * size on that to any individual buffer on the stdin channel.
10082 override_value = 0;
10083 if (ssh->throttled_all)
10084 override_value = ssh->overall_bufsize;
10086 if (ssh->version == 1) {
10087 return override_value;
10088 } else if (ssh->version == 2) {
10089 if (!ssh->mainchan)
10090 return override_value;
10092 return (override_value +
10093 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
10100 * Called to set the size of the window from SSH's POV.
10102 static void ssh_size(void *handle, int width, int height)
10104 Ssh ssh = (Ssh) handle;
10105 struct Packet *pktout;
10107 ssh->term_width = width;
10108 ssh->term_height = height;
10110 switch (ssh->state) {
10111 case SSH_STATE_BEFORE_SIZE:
10112 case SSH_STATE_PREPACKET:
10113 case SSH_STATE_CLOSED:
10114 break; /* do nothing */
10115 case SSH_STATE_INTERMED:
10116 ssh->size_needed = TRUE; /* buffer for later */
10118 case SSH_STATE_SESSION:
10119 if (!conf_get_int(ssh->conf, CONF_nopty)) {
10120 if (ssh->version == 1) {
10121 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
10122 PKT_INT, ssh->term_height,
10123 PKT_INT, ssh->term_width,
10124 PKT_INT, 0, PKT_INT, 0, PKT_END);
10125 } else if (ssh->mainchan) {
10126 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
10128 ssh2_pkt_adduint32(pktout, ssh->term_width);
10129 ssh2_pkt_adduint32(pktout, ssh->term_height);
10130 ssh2_pkt_adduint32(pktout, 0);
10131 ssh2_pkt_adduint32(pktout, 0);
10132 ssh2_pkt_send(ssh, pktout);
10140 * Return a list of the special codes that make sense in this
10143 static const struct telnet_special *ssh_get_specials(void *handle)
10145 static const struct telnet_special ssh1_ignore_special[] = {
10146 {"IGNORE message", TS_NOP}
10148 static const struct telnet_special ssh2_ignore_special[] = {
10149 {"IGNORE message", TS_NOP},
10151 static const struct telnet_special ssh2_rekey_special[] = {
10152 {"Repeat key exchange", TS_REKEY},
10154 static const struct telnet_special ssh2_session_specials[] = {
10157 /* These are the signal names defined by RFC 4254.
10158 * They include all the ISO C signals, but are a subset of the POSIX
10159 * required signals. */
10160 {"SIGINT (Interrupt)", TS_SIGINT},
10161 {"SIGTERM (Terminate)", TS_SIGTERM},
10162 {"SIGKILL (Kill)", TS_SIGKILL},
10163 {"SIGQUIT (Quit)", TS_SIGQUIT},
10164 {"SIGHUP (Hangup)", TS_SIGHUP},
10165 {"More signals", TS_SUBMENU},
10166 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
10167 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
10168 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
10169 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
10170 {NULL, TS_EXITMENU}
10172 static const struct telnet_special specials_end[] = {
10173 {NULL, TS_EXITMENU}
10175 /* XXX review this length for any changes: */
10176 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
10177 lenof(ssh2_rekey_special) +
10178 lenof(ssh2_session_specials) +
10179 lenof(specials_end)];
10180 Ssh ssh = (Ssh) handle;
10182 #define ADD_SPECIALS(name) \
10184 assert((i + lenof(name)) <= lenof(ssh_specials)); \
10185 memcpy(&ssh_specials[i], name, sizeof name); \
10186 i += lenof(name); \
10189 if (ssh->version == 1) {
10190 /* Don't bother offering IGNORE if we've decided the remote
10191 * won't cope with it, since we wouldn't bother sending it if
10193 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10194 ADD_SPECIALS(ssh1_ignore_special);
10195 } else if (ssh->version == 2) {
10196 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
10197 ADD_SPECIALS(ssh2_ignore_special);
10198 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
10199 ADD_SPECIALS(ssh2_rekey_special);
10201 ADD_SPECIALS(ssh2_session_specials);
10202 } /* else we're not ready yet */
10205 ADD_SPECIALS(specials_end);
10206 return ssh_specials;
10210 #undef ADD_SPECIALS
10214 * Send special codes. TS_EOF is useful for `plink', so you
10215 * can send an EOF and collect resulting output (e.g. `plink
10218 static void ssh_special(void *handle, Telnet_Special code)
10220 Ssh ssh = (Ssh) handle;
10221 struct Packet *pktout;
10223 if (code == TS_EOF) {
10224 if (ssh->state != SSH_STATE_SESSION) {
10226 * Buffer the EOF in case we are pre-SESSION, so we can
10227 * send it as soon as we reach SESSION.
10229 if (code == TS_EOF)
10230 ssh->eof_needed = TRUE;
10233 if (ssh->version == 1) {
10234 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
10235 } else if (ssh->mainchan) {
10236 sshfwd_write_eof(ssh->mainchan);
10237 ssh->send_ok = 0; /* now stop trying to read from stdin */
10239 logevent("Sent EOF message");
10240 } else if (code == TS_PING || code == TS_NOP) {
10241 if (ssh->state == SSH_STATE_CLOSED
10242 || ssh->state == SSH_STATE_PREPACKET) return;
10243 if (ssh->version == 1) {
10244 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10245 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
10247 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
10248 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
10249 ssh2_pkt_addstring_start(pktout);
10250 ssh2_pkt_send_noqueue(ssh, pktout);
10253 } else if (code == TS_REKEY) {
10254 if (!ssh->kex_in_progress && ssh->version == 2) {
10255 do_ssh2_transport(ssh, "at user request", -1, NULL);
10257 } else if (code == TS_BRK) {
10258 if (ssh->state == SSH_STATE_CLOSED
10259 || ssh->state == SSH_STATE_PREPACKET) return;
10260 if (ssh->version == 1) {
10261 logevent("Unable to send BREAK signal in SSH-1");
10262 } else if (ssh->mainchan) {
10263 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
10264 ssh2_pkt_adduint32(pktout, 0); /* default break length */
10265 ssh2_pkt_send(ssh, pktout);
10268 /* Is is a POSIX signal? */
10269 char *signame = NULL;
10270 if (code == TS_SIGABRT) signame = "ABRT";
10271 if (code == TS_SIGALRM) signame = "ALRM";
10272 if (code == TS_SIGFPE) signame = "FPE";
10273 if (code == TS_SIGHUP) signame = "HUP";
10274 if (code == TS_SIGILL) signame = "ILL";
10275 if (code == TS_SIGINT) signame = "INT";
10276 if (code == TS_SIGKILL) signame = "KILL";
10277 if (code == TS_SIGPIPE) signame = "PIPE";
10278 if (code == TS_SIGQUIT) signame = "QUIT";
10279 if (code == TS_SIGSEGV) signame = "SEGV";
10280 if (code == TS_SIGTERM) signame = "TERM";
10281 if (code == TS_SIGUSR1) signame = "USR1";
10282 if (code == TS_SIGUSR2) signame = "USR2";
10283 /* The SSH-2 protocol does in principle support arbitrary named
10284 * signals, including signame@domain, but we don't support those. */
10286 /* It's a signal. */
10287 if (ssh->version == 2 && ssh->mainchan) {
10288 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
10289 ssh2_pkt_addstring(pktout, signame);
10290 ssh2_pkt_send(ssh, pktout);
10291 logeventf(ssh, "Sent signal SIG%s", signame);
10294 /* Never heard of it. Do nothing */
10299 void *new_sock_channel(void *handle, struct PortForwarding *pf)
10301 Ssh ssh = (Ssh) handle;
10302 struct ssh_channel *c;
10303 c = snew(struct ssh_channel);
10306 ssh2_channel_init(c);
10307 c->halfopen = TRUE;
10308 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
10310 add234(ssh->channels, c);
10315 * This is called when stdout/stderr (the entity to which
10316 * from_backend sends data) manages to clear some backlog.
10318 static void ssh_unthrottle(void *handle, int bufsize)
10320 Ssh ssh = (Ssh) handle;
10323 if (ssh->version == 1) {
10324 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
10325 ssh->v1_stdout_throttling = 0;
10326 ssh_throttle_conn(ssh, -1);
10329 if (ssh->mainchan) {
10330 ssh2_set_window(ssh->mainchan,
10331 bufsize < ssh->mainchan->v.v2.locmaxwin ?
10332 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
10333 if (conf_get_int(ssh->conf, CONF_ssh_simple))
10336 buflimit = ssh->mainchan->v.v2.locmaxwin;
10337 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
10338 ssh->mainchan->throttling_conn = 0;
10339 ssh_throttle_conn(ssh, -1);
10345 * Now process any SSH connection data that was stashed in our
10346 * queue while we were frozen.
10348 ssh_process_queued_incoming_data(ssh);
10351 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
10353 struct ssh_channel *c = (struct ssh_channel *)channel;
10355 struct Packet *pktout;
10357 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
10359 if (ssh->version == 1) {
10360 send_packet(ssh, SSH1_MSG_PORT_OPEN,
10361 PKT_INT, c->localid,
10364 /* PKT_STR, <org:orgport>, */
10367 pktout = ssh2_chanopen_init(c, "direct-tcpip");
10368 ssh2_pkt_addstring(pktout, hostname);
10369 ssh2_pkt_adduint32(pktout, port);
10371 * We make up values for the originator data; partly it's
10372 * too much hassle to keep track, and partly I'm not
10373 * convinced the server should be told details like that
10374 * about my local network configuration.
10375 * The "originator IP address" is syntactically a numeric
10376 * IP address, and some servers (e.g., Tectia) get upset
10377 * if it doesn't match this syntax.
10379 ssh2_pkt_addstring(pktout, "0.0.0.0");
10380 ssh2_pkt_adduint32(pktout, 0);
10381 ssh2_pkt_send(ssh, pktout);
10385 static int ssh_connected(void *handle)
10387 Ssh ssh = (Ssh) handle;
10388 return ssh->s != NULL;
10391 static int ssh_sendok(void *handle)
10393 Ssh ssh = (Ssh) handle;
10394 return ssh->send_ok;
10397 static int ssh_ldisc(void *handle, int option)
10399 Ssh ssh = (Ssh) handle;
10400 if (option == LD_ECHO)
10401 return ssh->echoing;
10402 if (option == LD_EDIT)
10403 return ssh->editing;
10407 static void ssh_provide_ldisc(void *handle, void *ldisc)
10409 Ssh ssh = (Ssh) handle;
10410 ssh->ldisc = ldisc;
10413 static void ssh_provide_logctx(void *handle, void *logctx)
10415 Ssh ssh = (Ssh) handle;
10416 ssh->logctx = logctx;
10419 static int ssh_return_exitcode(void *handle)
10421 Ssh ssh = (Ssh) handle;
10422 if (ssh->s != NULL)
10425 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
10429 * cfg_info for SSH is the currently running version of the
10430 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
10432 static int ssh_cfg_info(void *handle)
10434 Ssh ssh = (Ssh) handle;
10435 return ssh->version;
10439 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
10440 * that fails. This variable is the means by which scp.c can reach
10441 * into the SSH code and find out which one it got.
10443 extern int ssh_fallback_cmd(void *handle)
10445 Ssh ssh = (Ssh) handle;
10446 return ssh->fallback_cmd;
10449 Backend ssh_backend = {
10459 ssh_return_exitcode,
10463 ssh_provide_logctx,