28 * Packet type contexts, so that ssh2_pkt_type can correctly decode
29 * the ambiguous type numbers back into the correct type strings.
40 SSH2_PKTCTX_PUBLICKEY,
46 static const char *const ssh2_disconnect_reasons[] = {
48 "host not allowed to connect",
50 "key exchange failed",
51 "host authentication failed",
54 "service not available",
55 "protocol version not supported",
56 "host key not verifiable",
59 "too many connections",
60 "auth cancelled by user",
61 "no more auth methods available",
66 * Various remote-bug flags.
68 #define BUG_CHOKES_ON_SSH1_IGNORE 1
69 #define BUG_SSH2_HMAC 2
70 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
71 #define BUG_CHOKES_ON_RSA 8
72 #define BUG_SSH2_RSA_PADDING 16
73 #define BUG_SSH2_DERIVEKEY 32
74 #define BUG_SSH2_REKEY 64
75 #define BUG_SSH2_PK_SESSIONID 128
76 #define BUG_SSH2_MAXPKT 256
77 #define BUG_CHOKES_ON_SSH2_IGNORE 512
78 #define BUG_CHOKES_ON_WINADJ 1024
79 #define BUG_SENDS_LATE_REQUEST_REPLY 2048
80 #define BUG_SSH2_OLDGEX 4096
82 #define DH_MIN_SIZE 1024
83 #define DH_MAX_SIZE 8192
86 * Codes for terminal modes.
87 * Most of these are the same in SSH-1 and SSH-2.
88 * This list is derived from RFC 4254 and
92 const char* const mode;
94 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
96 /* "V" prefix discarded for special characters relative to SSH specs */
97 { "INTR", 1, TTY_OP_CHAR },
98 { "QUIT", 2, TTY_OP_CHAR },
99 { "ERASE", 3, TTY_OP_CHAR },
100 { "KILL", 4, TTY_OP_CHAR },
101 { "EOF", 5, TTY_OP_CHAR },
102 { "EOL", 6, TTY_OP_CHAR },
103 { "EOL2", 7, TTY_OP_CHAR },
104 { "START", 8, TTY_OP_CHAR },
105 { "STOP", 9, TTY_OP_CHAR },
106 { "SUSP", 10, TTY_OP_CHAR },
107 { "DSUSP", 11, TTY_OP_CHAR },
108 { "REPRINT", 12, TTY_OP_CHAR },
109 { "WERASE", 13, TTY_OP_CHAR },
110 { "LNEXT", 14, TTY_OP_CHAR },
111 { "FLUSH", 15, TTY_OP_CHAR },
112 { "SWTCH", 16, TTY_OP_CHAR },
113 { "STATUS", 17, TTY_OP_CHAR },
114 { "DISCARD", 18, TTY_OP_CHAR },
115 { "IGNPAR", 30, TTY_OP_BOOL },
116 { "PARMRK", 31, TTY_OP_BOOL },
117 { "INPCK", 32, TTY_OP_BOOL },
118 { "ISTRIP", 33, TTY_OP_BOOL },
119 { "INLCR", 34, TTY_OP_BOOL },
120 { "IGNCR", 35, TTY_OP_BOOL },
121 { "ICRNL", 36, TTY_OP_BOOL },
122 { "IUCLC", 37, TTY_OP_BOOL },
123 { "IXON", 38, TTY_OP_BOOL },
124 { "IXANY", 39, TTY_OP_BOOL },
125 { "IXOFF", 40, TTY_OP_BOOL },
126 { "IMAXBEL", 41, TTY_OP_BOOL },
127 { "ISIG", 50, TTY_OP_BOOL },
128 { "ICANON", 51, TTY_OP_BOOL },
129 { "XCASE", 52, TTY_OP_BOOL },
130 { "ECHO", 53, TTY_OP_BOOL },
131 { "ECHOE", 54, TTY_OP_BOOL },
132 { "ECHOK", 55, TTY_OP_BOOL },
133 { "ECHONL", 56, TTY_OP_BOOL },
134 { "NOFLSH", 57, TTY_OP_BOOL },
135 { "TOSTOP", 58, TTY_OP_BOOL },
136 { "IEXTEN", 59, TTY_OP_BOOL },
137 { "ECHOCTL", 60, TTY_OP_BOOL },
138 { "ECHOKE", 61, TTY_OP_BOOL },
139 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
140 { "OPOST", 70, TTY_OP_BOOL },
141 { "OLCUC", 71, TTY_OP_BOOL },
142 { "ONLCR", 72, TTY_OP_BOOL },
143 { "OCRNL", 73, TTY_OP_BOOL },
144 { "ONOCR", 74, TTY_OP_BOOL },
145 { "ONLRET", 75, TTY_OP_BOOL },
146 { "CS7", 90, TTY_OP_BOOL },
147 { "CS8", 91, TTY_OP_BOOL },
148 { "PARENB", 92, TTY_OP_BOOL },
149 { "PARODD", 93, TTY_OP_BOOL }
152 /* Miscellaneous other tty-related constants. */
153 #define SSH_TTY_OP_END 0
154 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
155 #define SSH1_TTY_OP_ISPEED 192
156 #define SSH1_TTY_OP_OSPEED 193
157 #define SSH2_TTY_OP_ISPEED 128
158 #define SSH2_TTY_OP_OSPEED 129
160 /* Helper functions for parsing tty-related config. */
161 static unsigned int ssh_tty_parse_specchar(char *s)
166 ret = ctrlparse(s, &next);
167 if (!next) ret = s[0];
169 ret = 255; /* special value meaning "don't set" */
173 static unsigned int ssh_tty_parse_boolean(char *s)
175 if (stricmp(s, "yes") == 0 ||
176 stricmp(s, "on") == 0 ||
177 stricmp(s, "true") == 0 ||
178 stricmp(s, "+") == 0)
180 else if (stricmp(s, "no") == 0 ||
181 stricmp(s, "off") == 0 ||
182 stricmp(s, "false") == 0 ||
183 stricmp(s, "-") == 0)
184 return 0; /* false */
186 return (atoi(s) != 0);
189 #define translate(x) if (type == x) return #x
190 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
191 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
192 static char *ssh1_pkt_type(int type)
194 translate(SSH1_MSG_DISCONNECT);
195 translate(SSH1_SMSG_PUBLIC_KEY);
196 translate(SSH1_CMSG_SESSION_KEY);
197 translate(SSH1_CMSG_USER);
198 translate(SSH1_CMSG_AUTH_RSA);
199 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
200 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
201 translate(SSH1_CMSG_AUTH_PASSWORD);
202 translate(SSH1_CMSG_REQUEST_PTY);
203 translate(SSH1_CMSG_WINDOW_SIZE);
204 translate(SSH1_CMSG_EXEC_SHELL);
205 translate(SSH1_CMSG_EXEC_CMD);
206 translate(SSH1_SMSG_SUCCESS);
207 translate(SSH1_SMSG_FAILURE);
208 translate(SSH1_CMSG_STDIN_DATA);
209 translate(SSH1_SMSG_STDOUT_DATA);
210 translate(SSH1_SMSG_STDERR_DATA);
211 translate(SSH1_CMSG_EOF);
212 translate(SSH1_SMSG_EXIT_STATUS);
213 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
214 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
215 translate(SSH1_MSG_CHANNEL_DATA);
216 translate(SSH1_MSG_CHANNEL_CLOSE);
217 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
218 translate(SSH1_SMSG_X11_OPEN);
219 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
220 translate(SSH1_MSG_PORT_OPEN);
221 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
222 translate(SSH1_SMSG_AGENT_OPEN);
223 translate(SSH1_MSG_IGNORE);
224 translate(SSH1_CMSG_EXIT_CONFIRMATION);
225 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
226 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
227 translate(SSH1_MSG_DEBUG);
228 translate(SSH1_CMSG_REQUEST_COMPRESSION);
229 translate(SSH1_CMSG_AUTH_TIS);
230 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
231 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
232 translate(SSH1_CMSG_AUTH_CCARD);
233 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
234 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
237 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
239 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
240 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
241 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
242 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
243 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
244 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
245 translate(SSH2_MSG_DISCONNECT);
246 translate(SSH2_MSG_IGNORE);
247 translate(SSH2_MSG_UNIMPLEMENTED);
248 translate(SSH2_MSG_DEBUG);
249 translate(SSH2_MSG_SERVICE_REQUEST);
250 translate(SSH2_MSG_SERVICE_ACCEPT);
251 translate(SSH2_MSG_KEXINIT);
252 translate(SSH2_MSG_NEWKEYS);
253 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
254 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
255 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD, SSH2_PKTCTX_DHGEX);
256 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
257 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
258 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
259 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
260 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
261 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
262 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
263 translatek(SSH2_MSG_KEX_ECDH_INIT, SSH2_PKTCTX_ECDHKEX);
264 translatek(SSH2_MSG_KEX_ECDH_REPLY, SSH2_PKTCTX_ECDHKEX);
265 translate(SSH2_MSG_USERAUTH_REQUEST);
266 translate(SSH2_MSG_USERAUTH_FAILURE);
267 translate(SSH2_MSG_USERAUTH_SUCCESS);
268 translate(SSH2_MSG_USERAUTH_BANNER);
269 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
270 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
271 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
272 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
273 translate(SSH2_MSG_GLOBAL_REQUEST);
274 translate(SSH2_MSG_REQUEST_SUCCESS);
275 translate(SSH2_MSG_REQUEST_FAILURE);
276 translate(SSH2_MSG_CHANNEL_OPEN);
277 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
278 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
279 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
280 translate(SSH2_MSG_CHANNEL_DATA);
281 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
282 translate(SSH2_MSG_CHANNEL_EOF);
283 translate(SSH2_MSG_CHANNEL_CLOSE);
284 translate(SSH2_MSG_CHANNEL_REQUEST);
285 translate(SSH2_MSG_CHANNEL_SUCCESS);
286 translate(SSH2_MSG_CHANNEL_FAILURE);
292 /* Enumeration values for fields in SSH-1 packets */
294 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
298 * Coroutine mechanics for the sillier bits of the code. If these
299 * macros look impenetrable to you, you might find it helpful to
302 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
304 * which explains the theory behind these macros.
306 * In particular, if you are getting `case expression not constant'
307 * errors when building with MS Visual Studio, this is because MS's
308 * Edit and Continue debugging feature causes their compiler to
309 * violate ANSI C. To disable Edit and Continue debugging:
311 * - right-click ssh.c in the FileView
313 * - select the C/C++ tab and the General category
314 * - under `Debug info:', select anything _other_ than `Program
315 * Database for Edit and Continue'.
317 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
318 #define crBeginState crBegin(s->crLine)
319 #define crStateP(t, v) \
321 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
323 #define crState(t) crStateP(t, ssh->t)
324 #define crFinish(z) } *crLine = 0; return (z); }
325 #define crFinishV } *crLine = 0; return; }
326 #define crFinishFree(z) } sfree(s); return (z); }
327 #define crFinishFreeV } sfree(s); return; }
328 #define crReturn(z) \
330 *crLine =__LINE__; return (z); case __LINE__:;\
334 *crLine=__LINE__; return; case __LINE__:;\
336 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
337 #define crStopV do{ *crLine = 0; return; }while(0)
338 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
339 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
343 static struct Packet *ssh1_pkt_init(int pkt_type);
344 static struct Packet *ssh2_pkt_init(int pkt_type);
345 static void ssh_pkt_ensure(struct Packet *, int length);
346 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
347 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
348 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
349 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
350 static void ssh_pkt_addstring_start(struct Packet *);
351 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
352 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
353 static void ssh_pkt_addstring(struct Packet *, const char *data);
354 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
355 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
356 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
357 static int ssh2_pkt_construct(Ssh, struct Packet *);
358 static void ssh2_pkt_send(Ssh, struct Packet *);
359 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
360 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
361 struct Packet *pktin);
362 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
363 struct Packet *pktin);
364 static void ssh2_channel_check_close(struct ssh_channel *c);
365 static void ssh_channel_destroy(struct ssh_channel *c);
368 * Buffer management constants. There are several of these for
369 * various different purposes:
371 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
372 * on a local data stream before we throttle the whole SSH
373 * connection (in SSH-1 only). Throttling the whole connection is
374 * pretty drastic so we set this high in the hope it won't
377 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
378 * on the SSH connection itself before we defensively throttle
379 * _all_ local data streams. This is pretty drastic too (though
380 * thankfully unlikely in SSH-2 since the window mechanism should
381 * ensure that the server never has any need to throttle its end
382 * of the connection), so we set this high as well.
384 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
387 * - OUR_V2_BIGWIN is the window size we advertise for the only
388 * channel in a simple connection. It must be <= INT_MAX.
390 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
391 * to the remote side. This actually has nothing to do with the
392 * size of the _packet_, but is instead a limit on the amount
393 * of data we're willing to receive in a single SSH2 channel
396 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
397 * _packet_ we're prepared to cope with. It must be a multiple
398 * of the cipher block size, and must be at least 35000.
401 #define SSH1_BUFFER_LIMIT 32768
402 #define SSH_MAX_BACKLOG 32768
403 #define OUR_V2_WINSIZE 16384
404 #define OUR_V2_BIGWIN 0x7fffffff
405 #define OUR_V2_MAXPKT 0x4000UL
406 #define OUR_V2_PACKETLIMIT 0x9000UL
408 const static struct ssh_signkey *hostkey_algs[] = {
409 &ssh_ecdsa_nistp256, &ssh_ecdsa_nistp384, &ssh_ecdsa_nistp521,
413 const static struct ssh_mac *macs[] = {
414 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
416 const static struct ssh_mac *buggymacs[] = {
417 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
420 static void *ssh_comp_none_init(void)
424 static void ssh_comp_none_cleanup(void *handle)
427 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
428 unsigned char **outblock, int *outlen)
432 static int ssh_comp_none_disable(void *handle)
436 const static struct ssh_compress ssh_comp_none = {
438 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
439 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
440 ssh_comp_none_disable, NULL
442 extern const struct ssh_compress ssh_zlib;
443 const static struct ssh_compress *compressions[] = {
444 &ssh_zlib, &ssh_comp_none
447 enum { /* channel types */
452 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
454 * CHAN_SHARING indicates a channel which is tracked here on
455 * behalf of a connection-sharing downstream. We do almost nothing
456 * with these channels ourselves: all messages relating to them
457 * get thrown straight to sshshare.c and passed on almost
458 * unmodified to downstream.
462 * CHAN_ZOMBIE is used to indicate a channel for which we've
463 * already destroyed the local data source: for instance, if a
464 * forwarded port experiences a socket error on the local side, we
465 * immediately destroy its local socket and turn the SSH channel
471 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
472 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
473 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
476 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
479 struct outstanding_channel_request {
480 cchandler_fn_t handler;
482 struct outstanding_channel_request *next;
486 * 2-3-4 tree storing channels.
489 Ssh ssh; /* pointer back to main context */
490 unsigned remoteid, localid;
492 /* True if we opened this channel but server hasn't confirmed. */
495 * In SSH-1, this value contains four bits:
497 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
498 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
499 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
500 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
502 * A channel is completely finished with when all four bits are set.
504 * In SSH-2, the four bits mean:
506 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
507 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
508 * 4 We have received SSH2_MSG_CHANNEL_EOF.
509 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
511 * A channel is completely finished with when we have both sent
512 * and received CLOSE.
514 * The symbolic constants below use the SSH-2 terminology, which
515 * is a bit confusing in SSH-1, but we have to use _something_.
517 #define CLOSES_SENT_EOF 1
518 #define CLOSES_SENT_CLOSE 2
519 #define CLOSES_RCVD_EOF 4
520 #define CLOSES_RCVD_CLOSE 8
524 * This flag indicates that an EOF is pending on the outgoing side
525 * of the channel: that is, wherever we're getting the data for
526 * this channel has sent us some data followed by EOF. We can't
527 * actually send the EOF until we've finished sending the data, so
528 * we set this flag instead to remind us to do so once our buffer
534 * True if this channel is causing the underlying connection to be
539 struct ssh2_data_channel {
541 unsigned remwindow, remmaxpkt;
542 /* locwindow is signed so we can cope with excess data. */
543 int locwindow, locmaxwin;
545 * remlocwin is the amount of local window that we think
546 * the remote end had available to it after it sent the
547 * last data packet or window adjust ack.
551 * These store the list of channel requests that haven't
554 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
555 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
559 struct ssh_agent_channel {
560 unsigned char *message;
561 unsigned char msglen[4];
562 unsigned lensofar, totallen;
563 int outstanding_requests;
565 struct ssh_x11_channel {
566 struct X11Connection *xconn;
569 struct ssh_pfd_channel {
570 struct PortForwarding *pf;
572 struct ssh_sharing_channel {
579 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
580 * use this structure in different ways, reflecting SSH-2's
581 * altogether saner approach to port forwarding.
583 * In SSH-1, you arrange a remote forwarding by sending the server
584 * the remote port number, and the local destination host:port.
585 * When a connection comes in, the server sends you back that
586 * host:port pair, and you connect to it. This is a ready-made
587 * security hole if you're not on the ball: a malicious server
588 * could send you back _any_ host:port pair, so if you trustingly
589 * connect to the address it gives you then you've just opened the
590 * entire inside of your corporate network just by connecting
591 * through it to a dodgy SSH server. Hence, we must store a list of
592 * host:port pairs we _are_ trying to forward to, and reject a
593 * connection request from the server if it's not in the list.
595 * In SSH-2, each side of the connection minds its own business and
596 * doesn't send unnecessary information to the other. You arrange a
597 * remote forwarding by sending the server just the remote port
598 * number. When a connection comes in, the server tells you which
599 * of its ports was connected to; and _you_ have to remember what
600 * local host:port pair went with that port number.
602 * Hence, in SSH-1 this structure is indexed by destination
603 * host:port pair, whereas in SSH-2 it is indexed by source port.
605 struct ssh_portfwd; /* forward declaration */
607 struct ssh_rportfwd {
608 unsigned sport, dport;
612 struct ssh_portfwd *pfrec;
615 static void free_rportfwd(struct ssh_rportfwd *pf)
618 sfree(pf->sportdesc);
626 * Separately to the rportfwd tree (which is for looking up port
627 * open requests from the server), a tree of _these_ structures is
628 * used to keep track of all the currently open port forwardings,
629 * so that we can reconfigure in mid-session if the user requests
633 enum { DESTROY, KEEP, CREATE } status;
635 unsigned sport, dport;
638 struct ssh_rportfwd *remote;
640 struct PortListener *local;
642 #define free_portfwd(pf) ( \
643 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
644 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
647 long length; /* length of packet: see below */
648 long forcepad; /* SSH-2: force padding to at least this length */
649 int type; /* only used for incoming packets */
650 unsigned long sequence; /* SSH-2 incoming sequence number */
651 unsigned char *data; /* allocated storage */
652 unsigned char *body; /* offset of payload within `data' */
653 long savedpos; /* dual-purpose saved packet position: see below */
654 long maxlen; /* amount of storage allocated for `data' */
655 long encrypted_len; /* for SSH-2 total-size counting */
658 * A note on the 'length' and 'savedpos' fields above.
660 * Incoming packets are set up so that pkt->length is measured
661 * relative to pkt->body, which itself points to a few bytes after
662 * pkt->data (skipping some uninteresting header fields including
663 * the packet type code). The ssh_pkt_get* functions all expect
664 * this setup, and they also use pkt->savedpos to indicate how far
665 * through the packet being decoded they've got - and that, too,
666 * is an offset from pkt->body rather than pkt->data.
668 * During construction of an outgoing packet, however, pkt->length
669 * is measured relative to the base pointer pkt->data, and
670 * pkt->body is not really used for anything until the packet is
671 * ready for sending. In this mode, pkt->savedpos is reused as a
672 * temporary variable by the addstring functions, which write out
673 * a string length field and then keep going back and updating it
674 * as more data is appended to the subsequent string data field;
675 * pkt->savedpos stores the offset (again relative to pkt->data)
676 * of the start of the string data field.
679 /* Extra metadata used in SSH packet logging mode, allowing us to
680 * log in the packet header line that the packet came from a
681 * connection-sharing downstream and what if anything unusual was
682 * done to it. The additional_log_text field is expected to be a
683 * static string - it will not be freed. */
684 unsigned downstream_id;
685 const char *additional_log_text;
688 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
689 struct Packet *pktin);
690 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
691 struct Packet *pktin);
692 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
693 struct Packet *pktin);
694 static void ssh1_protocol_setup(Ssh ssh);
695 static void ssh2_protocol_setup(Ssh ssh);
696 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
697 static void ssh_size(void *handle, int width, int height);
698 static void ssh_special(void *handle, Telnet_Special);
699 static int ssh2_try_send(struct ssh_channel *c);
700 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
701 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
702 static void ssh2_set_window(struct ssh_channel *c, int newwin);
703 static int ssh_sendbuffer(void *handle);
704 static int ssh_do_close(Ssh ssh, int notify_exit);
705 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
706 static int ssh2_pkt_getbool(struct Packet *pkt);
707 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
708 static void ssh2_timer(void *ctx, unsigned long now);
709 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
710 struct Packet *pktin);
711 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
713 struct rdpkt1_state_tag {
714 long len, pad, biglen, to_read;
715 unsigned long realcrc, gotcrc;
719 struct Packet *pktin;
722 struct rdpkt2_state_tag {
723 long len, pad, payload, packetlen, maclen;
726 unsigned long incoming_sequence;
727 struct Packet *pktin;
730 struct rdpkt2_bare_state_tag {
734 unsigned long incoming_sequence;
735 struct Packet *pktin;
738 struct queued_handler;
739 struct queued_handler {
741 chandler_fn_t handler;
743 struct queued_handler *next;
747 const struct plug_function_table *fn;
748 /* the above field _must_ be first in the structure */
758 unsigned char session_key[32];
760 int v1_remote_protoflags;
761 int v1_local_protoflags;
762 int agentfwd_enabled;
765 const struct ssh_cipher *cipher;
768 const struct ssh2_cipher *cscipher, *sccipher;
769 void *cs_cipher_ctx, *sc_cipher_ctx;
770 const struct ssh_mac *csmac, *scmac;
771 int csmac_etm, scmac_etm;
772 void *cs_mac_ctx, *sc_mac_ctx;
773 const struct ssh_compress *cscomp, *sccomp;
774 void *cs_comp_ctx, *sc_comp_ctx;
775 const struct ssh_kex *kex;
776 const struct ssh_signkey *hostkey;
777 char *hostkey_str; /* string representation, for easy checking in rekeys */
778 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
779 int v2_session_id_len;
783 int attempting_connshare;
789 int echoing, editing;
793 int ospeed, ispeed; /* temporaries */
794 int term_width, term_height;
796 tree234 *channels; /* indexed by local id */
797 struct ssh_channel *mainchan; /* primary session channel */
798 int ncmode; /* is primary channel direct-tcpip? */
803 tree234 *rportfwds, *portfwds;
807 SSH_STATE_BEFORE_SIZE,
813 int size_needed, eof_needed;
814 int sent_console_eof;
815 int got_pty; /* affects EOF behaviour on main channel */
817 struct Packet **queue;
818 int queuelen, queuesize;
820 unsigned char *deferred_send_data;
821 int deferred_len, deferred_size;
824 * Gross hack: pscp will try to start SFTP but fall back to
825 * scp1 if that fails. This variable is the means by which
826 * scp.c can reach into the SSH code and find out which one it
831 bufchain banner; /* accumulates banners during do_ssh2_authconn */
836 struct X11Display *x11disp;
837 struct X11FakeAuth *x11auth;
838 tree234 *x11authtree;
841 int conn_throttle_count;
844 int v1_stdout_throttling;
845 unsigned long v2_outgoing_sequence;
847 int ssh1_rdpkt_crstate;
848 int ssh2_rdpkt_crstate;
849 int ssh2_bare_rdpkt_crstate;
850 int ssh_gotdata_crstate;
851 int do_ssh1_connection_crstate;
853 void *do_ssh_init_state;
854 void *do_ssh1_login_state;
855 void *do_ssh2_transport_state;
856 void *do_ssh2_authconn_state;
857 void *do_ssh_connection_init_state;
859 struct rdpkt1_state_tag rdpkt1_state;
860 struct rdpkt2_state_tag rdpkt2_state;
861 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
863 /* SSH-1 and SSH-2 use this for different things, but both use it */
864 int protocol_initial_phase_done;
866 void (*protocol) (Ssh ssh, void *vin, int inlen,
868 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
869 int (*do_ssh_init)(Ssh ssh, unsigned char c);
872 * We maintain our own copy of a Conf structure here. That way,
873 * when we're passed a new one for reconfiguration, we can check
874 * the differences and potentially reconfigure port forwardings
875 * etc in mid-session.
880 * Values cached out of conf so as to avoid the tree234 lookup
881 * cost every time they're used.
886 * Dynamically allocated username string created during SSH
887 * login. Stored in here rather than in the coroutine state so
888 * that it'll be reliably freed if we shut down the SSH session
889 * at some unexpected moment.
894 * Used to transfer data back from async callbacks.
896 void *agent_response;
897 int agent_response_len;
901 * The SSH connection can be set as `frozen', meaning we are
902 * not currently accepting incoming data from the network. This
903 * is slightly more serious than setting the _socket_ as
904 * frozen, because we may already have had data passed to us
905 * from the network which we need to delay processing until
906 * after the freeze is lifted, so we also need a bufchain to
910 bufchain queued_incoming_data;
913 * Dispatch table for packet types that we may have to deal
916 handler_fn_t packet_dispatch[256];
919 * Queues of one-off handler functions for success/failure
920 * indications from a request.
922 struct queued_handler *qhead, *qtail;
923 handler_fn_t q_saved_handler1, q_saved_handler2;
926 * This module deals with sending keepalives.
931 * Track incoming and outgoing data sizes and time, for
934 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
935 unsigned long max_data_size;
937 unsigned long next_rekey, last_rekey;
938 char *deferred_rekey_reason; /* points to STATIC string; don't free */
941 * Fully qualified host name, which we need if doing GSSAPI.
947 * GSSAPI libraries for this session.
949 struct ssh_gss_liblist *gsslibs;
953 #define logevent(s) logevent(ssh->frontend, s)
955 /* logevent, only printf-formatted. */
956 static void logeventf(Ssh ssh, const char *fmt, ...)
962 buf = dupvprintf(fmt, ap);
968 static void bomb_out(Ssh ssh, char *text)
970 ssh_do_close(ssh, FALSE);
972 connection_fatal(ssh->frontend, "%s", text);
976 #define bombout(msg) bomb_out(ssh, dupprintf msg)
978 /* Helper function for common bits of parsing ttymodes. */
979 static void parse_ttymodes(Ssh ssh,
980 void (*do_mode)(void *data, char *mode, char *val),
985 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
987 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
989 * val[0] is either 'V', indicating that an explicit value
990 * follows it, or 'A' indicating that we should pass the
991 * value through from the local environment via get_ttymode.
994 val = get_ttymode(ssh->frontend, key);
996 do_mode(data, key, val);
1000 do_mode(data, key, val + 1); /* skip the 'V' */
1004 static int ssh_channelcmp(void *av, void *bv)
1006 struct ssh_channel *a = (struct ssh_channel *) av;
1007 struct ssh_channel *b = (struct ssh_channel *) bv;
1008 if (a->localid < b->localid)
1010 if (a->localid > b->localid)
1014 static int ssh_channelfind(void *av, void *bv)
1016 unsigned *a = (unsigned *) av;
1017 struct ssh_channel *b = (struct ssh_channel *) bv;
1018 if (*a < b->localid)
1020 if (*a > b->localid)
1025 static int ssh_rportcmp_ssh1(void *av, void *bv)
1027 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1028 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1030 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1031 return i < 0 ? -1 : +1;
1032 if (a->dport > b->dport)
1034 if (a->dport < b->dport)
1039 static int ssh_rportcmp_ssh2(void *av, void *bv)
1041 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1042 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1044 if ( (i = strcmp(a->shost, b->shost)) != 0)
1045 return i < 0 ? -1 : +1;
1046 if (a->sport > b->sport)
1048 if (a->sport < b->sport)
1054 * Special form of strcmp which can cope with NULL inputs. NULL is
1055 * defined to sort before even the empty string.
1057 static int nullstrcmp(const char *a, const char *b)
1059 if (a == NULL && b == NULL)
1065 return strcmp(a, b);
1068 static int ssh_portcmp(void *av, void *bv)
1070 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1071 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1073 if (a->type > b->type)
1075 if (a->type < b->type)
1077 if (a->addressfamily > b->addressfamily)
1079 if (a->addressfamily < b->addressfamily)
1081 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1082 return i < 0 ? -1 : +1;
1083 if (a->sport > b->sport)
1085 if (a->sport < b->sport)
1087 if (a->type != 'D') {
1088 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1089 return i < 0 ? -1 : +1;
1090 if (a->dport > b->dport)
1092 if (a->dport < b->dport)
1098 static int alloc_channel_id(Ssh ssh)
1100 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1101 unsigned low, high, mid;
1103 struct ssh_channel *c;
1106 * First-fit allocation of channel numbers: always pick the
1107 * lowest unused one. To do this, binary-search using the
1108 * counted B-tree to find the largest channel ID which is in a
1109 * contiguous sequence from the beginning. (Precisely
1110 * everything in that sequence must have ID equal to its tree
1111 * index plus CHANNEL_NUMBER_OFFSET.)
1113 tsize = count234(ssh->channels);
1117 while (high - low > 1) {
1118 mid = (high + low) / 2;
1119 c = index234(ssh->channels, mid);
1120 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1121 low = mid; /* this one is fine */
1123 high = mid; /* this one is past it */
1126 * Now low points to either -1, or the tree index of the
1127 * largest ID in the initial sequence.
1130 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1131 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1133 return low + 1 + CHANNEL_NUMBER_OFFSET;
1136 static void c_write_stderr(int trusted, const char *buf, int len)
1139 for (i = 0; i < len; i++)
1140 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1141 fputc(buf[i], stderr);
1144 static void c_write(Ssh ssh, const char *buf, int len)
1146 if (flags & FLAG_STDERR)
1147 c_write_stderr(1, buf, len);
1149 from_backend(ssh->frontend, 1, buf, len);
1152 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1154 if (flags & FLAG_STDERR)
1155 c_write_stderr(0, buf, len);
1157 from_backend_untrusted(ssh->frontend, buf, len);
1160 static void c_write_str(Ssh ssh, const char *buf)
1162 c_write(ssh, buf, strlen(buf));
1165 static void ssh_free_packet(struct Packet *pkt)
1170 static struct Packet *ssh_new_packet(void)
1172 struct Packet *pkt = snew(struct Packet);
1174 pkt->body = pkt->data = NULL;
1180 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1183 struct logblank_t blanks[4];
1189 if (ssh->logomitdata &&
1190 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1191 pkt->type == SSH1_SMSG_STDERR_DATA ||
1192 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1193 /* "Session data" packets - omit the data string. */
1194 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1195 ssh_pkt_getuint32(pkt); /* skip channel id */
1196 blanks[nblanks].offset = pkt->savedpos + 4;
1197 blanks[nblanks].type = PKTLOG_OMIT;
1198 ssh_pkt_getstring(pkt, &str, &slen);
1200 blanks[nblanks].len = slen;
1204 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1205 ssh1_pkt_type(pkt->type),
1206 pkt->body, pkt->length, nblanks, blanks, NULL,
1210 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1213 struct logblank_t blanks[4];
1218 * For outgoing packets, pkt->length represents the length of the
1219 * whole packet starting at pkt->data (including some header), and
1220 * pkt->body refers to the point within that where the log-worthy
1221 * payload begins. However, incoming packets expect pkt->length to
1222 * represent only the payload length (that is, it's measured from
1223 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1224 * packet to conform to the incoming-packet semantics, so that we
1225 * can analyse it with the ssh_pkt_get functions.
1227 pkt->length -= (pkt->body - pkt->data);
1230 if (ssh->logomitdata &&
1231 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1232 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1233 /* "Session data" packets - omit the data string. */
1234 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1235 ssh_pkt_getuint32(pkt); /* skip channel id */
1236 blanks[nblanks].offset = pkt->savedpos + 4;
1237 blanks[nblanks].type = PKTLOG_OMIT;
1238 ssh_pkt_getstring(pkt, &str, &slen);
1240 blanks[nblanks].len = slen;
1245 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1246 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1247 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1248 conf_get_int(ssh->conf, CONF_logomitpass)) {
1249 /* If this is a password or similar packet, blank the password(s). */
1250 blanks[nblanks].offset = 0;
1251 blanks[nblanks].len = pkt->length;
1252 blanks[nblanks].type = PKTLOG_BLANK;
1254 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1255 conf_get_int(ssh->conf, CONF_logomitpass)) {
1257 * If this is an X forwarding request packet, blank the fake
1260 * Note that while we blank the X authentication data here, we
1261 * don't take any special action to blank the start of an X11
1262 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1263 * an X connection without having session blanking enabled is
1264 * likely to leak your cookie into the log.
1267 ssh_pkt_getstring(pkt, &str, &slen);
1268 blanks[nblanks].offset = pkt->savedpos;
1269 blanks[nblanks].type = PKTLOG_BLANK;
1270 ssh_pkt_getstring(pkt, &str, &slen);
1272 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1277 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1278 ssh1_pkt_type(pkt->data[12]),
1279 pkt->body, pkt->length,
1280 nblanks, blanks, NULL, 0, NULL);
1283 * Undo the above adjustment of pkt->length, to put the packet
1284 * back in the state we found it.
1286 pkt->length += (pkt->body - pkt->data);
1290 * Collect incoming data in the incoming packet buffer.
1291 * Decipher and verify the packet when it is completely read.
1292 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1293 * Update the *data and *datalen variables.
1294 * Return a Packet structure when a packet is completed.
1296 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1298 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1300 crBegin(ssh->ssh1_rdpkt_crstate);
1302 st->pktin = ssh_new_packet();
1304 st->pktin->type = 0;
1305 st->pktin->length = 0;
1307 for (st->i = st->len = 0; st->i < 4; st->i++) {
1308 while ((*datalen) == 0)
1310 st->len = (st->len << 8) + **data;
1311 (*data)++, (*datalen)--;
1314 st->pad = 8 - (st->len % 8);
1315 st->biglen = st->len + st->pad;
1316 st->pktin->length = st->len - 5;
1318 if (st->biglen < 0) {
1319 bombout(("Extremely large packet length from server suggests"
1320 " data stream corruption"));
1321 ssh_free_packet(st->pktin);
1325 st->pktin->maxlen = st->biglen;
1326 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1328 st->to_read = st->biglen;
1329 st->p = st->pktin->data;
1330 while (st->to_read > 0) {
1331 st->chunk = st->to_read;
1332 while ((*datalen) == 0)
1334 if (st->chunk > (*datalen))
1335 st->chunk = (*datalen);
1336 memcpy(st->p, *data, st->chunk);
1338 *datalen -= st->chunk;
1340 st->to_read -= st->chunk;
1343 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1344 st->biglen, NULL)) {
1345 bombout(("Network attack (CRC compensation) detected!"));
1346 ssh_free_packet(st->pktin);
1351 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1353 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1354 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1355 if (st->gotcrc != st->realcrc) {
1356 bombout(("Incorrect CRC received on packet"));
1357 ssh_free_packet(st->pktin);
1361 st->pktin->body = st->pktin->data + st->pad + 1;
1363 if (ssh->v1_compressing) {
1364 unsigned char *decompblk;
1366 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1367 st->pktin->body - 1, st->pktin->length + 1,
1368 &decompblk, &decomplen)) {
1369 bombout(("Zlib decompression encountered invalid data"));
1370 ssh_free_packet(st->pktin);
1374 if (st->pktin->maxlen < st->pad + decomplen) {
1375 st->pktin->maxlen = st->pad + decomplen;
1376 st->pktin->data = sresize(st->pktin->data,
1377 st->pktin->maxlen + APIEXTRA,
1379 st->pktin->body = st->pktin->data + st->pad + 1;
1382 memcpy(st->pktin->body - 1, decompblk, decomplen);
1384 st->pktin->length = decomplen - 1;
1387 st->pktin->type = st->pktin->body[-1];
1390 * Now pktin->body and pktin->length identify the semantic content
1391 * of the packet, excluding the initial type byte.
1395 ssh1_log_incoming_packet(ssh, st->pktin);
1397 st->pktin->savedpos = 0;
1399 crFinish(st->pktin);
1402 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1405 struct logblank_t blanks[4];
1411 if (ssh->logomitdata &&
1412 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1413 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1414 /* "Session data" packets - omit the data string. */
1415 ssh_pkt_getuint32(pkt); /* skip channel id */
1416 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1417 ssh_pkt_getuint32(pkt); /* skip extended data type */
1418 blanks[nblanks].offset = pkt->savedpos + 4;
1419 blanks[nblanks].type = PKTLOG_OMIT;
1420 ssh_pkt_getstring(pkt, &str, &slen);
1422 blanks[nblanks].len = slen;
1427 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1428 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1429 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1433 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1436 struct logblank_t blanks[4];
1441 * For outgoing packets, pkt->length represents the length of the
1442 * whole packet starting at pkt->data (including some header), and
1443 * pkt->body refers to the point within that where the log-worthy
1444 * payload begins. However, incoming packets expect pkt->length to
1445 * represent only the payload length (that is, it's measured from
1446 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1447 * packet to conform to the incoming-packet semantics, so that we
1448 * can analyse it with the ssh_pkt_get functions.
1450 pkt->length -= (pkt->body - pkt->data);
1453 if (ssh->logomitdata &&
1454 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1455 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1456 /* "Session data" packets - omit the data string. */
1457 ssh_pkt_getuint32(pkt); /* skip channel id */
1458 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1459 ssh_pkt_getuint32(pkt); /* skip extended data type */
1460 blanks[nblanks].offset = pkt->savedpos + 4;
1461 blanks[nblanks].type = PKTLOG_OMIT;
1462 ssh_pkt_getstring(pkt, &str, &slen);
1464 blanks[nblanks].len = slen;
1469 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1470 conf_get_int(ssh->conf, CONF_logomitpass)) {
1471 /* If this is a password packet, blank the password(s). */
1473 ssh_pkt_getstring(pkt, &str, &slen);
1474 ssh_pkt_getstring(pkt, &str, &slen);
1475 ssh_pkt_getstring(pkt, &str, &slen);
1476 if (slen == 8 && !memcmp(str, "password", 8)) {
1477 ssh2_pkt_getbool(pkt);
1478 /* Blank the password field. */
1479 blanks[nblanks].offset = pkt->savedpos;
1480 blanks[nblanks].type = PKTLOG_BLANK;
1481 ssh_pkt_getstring(pkt, &str, &slen);
1483 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1485 /* If there's another password field beyond it (change of
1486 * password), blank that too. */
1487 ssh_pkt_getstring(pkt, &str, &slen);
1489 blanks[nblanks-1].len =
1490 pkt->savedpos - blanks[nblanks].offset;
1493 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1494 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1495 conf_get_int(ssh->conf, CONF_logomitpass)) {
1496 /* If this is a keyboard-interactive response packet, blank
1499 ssh_pkt_getuint32(pkt);
1500 blanks[nblanks].offset = pkt->savedpos;
1501 blanks[nblanks].type = PKTLOG_BLANK;
1503 ssh_pkt_getstring(pkt, &str, &slen);
1507 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1509 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1510 conf_get_int(ssh->conf, CONF_logomitpass)) {
1512 * If this is an X forwarding request packet, blank the fake
1515 * Note that while we blank the X authentication data here, we
1516 * don't take any special action to blank the start of an X11
1517 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1518 * an X connection without having session blanking enabled is
1519 * likely to leak your cookie into the log.
1522 ssh_pkt_getuint32(pkt);
1523 ssh_pkt_getstring(pkt, &str, &slen);
1524 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1525 ssh2_pkt_getbool(pkt);
1526 ssh2_pkt_getbool(pkt);
1527 ssh_pkt_getstring(pkt, &str, &slen);
1528 blanks[nblanks].offset = pkt->savedpos;
1529 blanks[nblanks].type = PKTLOG_BLANK;
1530 ssh_pkt_getstring(pkt, &str, &slen);
1532 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1538 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1539 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1540 pkt->body, pkt->length, nblanks, blanks,
1541 &ssh->v2_outgoing_sequence,
1542 pkt->downstream_id, pkt->additional_log_text);
1545 * Undo the above adjustment of pkt->length, to put the packet
1546 * back in the state we found it.
1548 pkt->length += (pkt->body - pkt->data);
1551 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1553 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1555 crBegin(ssh->ssh2_rdpkt_crstate);
1557 st->pktin = ssh_new_packet();
1559 st->pktin->type = 0;
1560 st->pktin->length = 0;
1562 st->cipherblk = ssh->sccipher->blksize;
1565 if (st->cipherblk < 8)
1567 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1569 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1570 ssh->scmac && !ssh->scmac_etm) {
1572 * When dealing with a CBC-mode cipher, we want to avoid the
1573 * possibility of an attacker's tweaking the ciphertext stream
1574 * so as to cause us to feed the same block to the block
1575 * cipher more than once and thus leak information
1576 * (VU#958563). The way we do this is not to take any
1577 * decisions on the basis of anything we've decrypted until
1578 * we've verified it with a MAC. That includes the packet
1579 * length, so we just read data and check the MAC repeatedly,
1580 * and when the MAC passes, see if the length we've got is
1583 * This defence is unnecessary in OpenSSH ETM mode, because
1584 * the whole point of ETM mode is that the attacker can't
1585 * tweak the ciphertext stream at all without the MAC
1586 * detecting it before we decrypt anything.
1589 /* May as well allocate the whole lot now. */
1590 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1593 /* Read an amount corresponding to the MAC. */
1594 for (st->i = 0; st->i < st->maclen; st->i++) {
1595 while ((*datalen) == 0)
1597 st->pktin->data[st->i] = *(*data)++;
1603 unsigned char seq[4];
1604 ssh->scmac->start(ssh->sc_mac_ctx);
1605 PUT_32BIT(seq, st->incoming_sequence);
1606 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1609 for (;;) { /* Once around this loop per cipher block. */
1610 /* Read another cipher-block's worth, and tack it onto the end. */
1611 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1612 while ((*datalen) == 0)
1614 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1617 /* Decrypt one more block (a little further back in the stream). */
1618 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1619 st->pktin->data + st->packetlen,
1621 /* Feed that block to the MAC. */
1622 ssh->scmac->bytes(ssh->sc_mac_ctx,
1623 st->pktin->data + st->packetlen, st->cipherblk);
1624 st->packetlen += st->cipherblk;
1625 /* See if that gives us a valid packet. */
1626 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1627 st->pktin->data + st->packetlen) &&
1628 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1631 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1632 bombout(("No valid incoming packet found"));
1633 ssh_free_packet(st->pktin);
1637 st->pktin->maxlen = st->packetlen + st->maclen;
1638 st->pktin->data = sresize(st->pktin->data,
1639 st->pktin->maxlen + APIEXTRA,
1641 } else if (ssh->scmac && ssh->scmac_etm) {
1642 st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1645 * OpenSSH encrypt-then-MAC mode: the packet length is
1648 for (st->i = st->len = 0; st->i < 4; st->i++) {
1649 while ((*datalen) == 0)
1651 st->pktin->data[st->i] = *(*data)++;
1654 st->len = toint(GET_32BIT(st->pktin->data));
1657 * _Completely_ silly lengths should be stomped on before they
1658 * do us any more damage.
1660 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1661 st->len % st->cipherblk != 0) {
1662 bombout(("Incoming packet length field was garbled"));
1663 ssh_free_packet(st->pktin);
1668 * So now we can work out the total packet length.
1670 st->packetlen = st->len + 4;
1673 * Allocate memory for the rest of the packet.
1675 st->pktin->maxlen = st->packetlen + st->maclen;
1676 st->pktin->data = sresize(st->pktin->data,
1677 st->pktin->maxlen + APIEXTRA,
1681 * Read the remainder of the packet.
1683 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1684 while ((*datalen) == 0)
1686 st->pktin->data[st->i] = *(*data)++;
1694 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1695 st->len + 4, st->incoming_sequence)) {
1696 bombout(("Incorrect MAC received on packet"));
1697 ssh_free_packet(st->pktin);
1701 /* Decrypt everything between the length field and the MAC. */
1703 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1704 st->pktin->data + 4,
1707 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1710 * Acquire and decrypt the first block of the packet. This will
1711 * contain the length and padding details.
1713 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1714 while ((*datalen) == 0)
1716 st->pktin->data[st->i] = *(*data)++;
1721 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1722 st->pktin->data, st->cipherblk);
1725 * Now get the length figure.
1727 st->len = toint(GET_32BIT(st->pktin->data));
1730 * _Completely_ silly lengths should be stomped on before they
1731 * do us any more damage.
1733 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1734 (st->len + 4) % st->cipherblk != 0) {
1735 bombout(("Incoming packet was garbled on decryption"));
1736 ssh_free_packet(st->pktin);
1741 * So now we can work out the total packet length.
1743 st->packetlen = st->len + 4;
1746 * Allocate memory for the rest of the packet.
1748 st->pktin->maxlen = st->packetlen + st->maclen;
1749 st->pktin->data = sresize(st->pktin->data,
1750 st->pktin->maxlen + APIEXTRA,
1754 * Read and decrypt the remainder of the packet.
1756 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1758 while ((*datalen) == 0)
1760 st->pktin->data[st->i] = *(*data)++;
1763 /* Decrypt everything _except_ the MAC. */
1765 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1766 st->pktin->data + st->cipherblk,
1767 st->packetlen - st->cipherblk);
1773 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1774 st->len + 4, st->incoming_sequence)) {
1775 bombout(("Incorrect MAC received on packet"));
1776 ssh_free_packet(st->pktin);
1780 /* Get and sanity-check the amount of random padding. */
1781 st->pad = st->pktin->data[4];
1782 if (st->pad < 4 || st->len - st->pad < 1) {
1783 bombout(("Invalid padding length on received packet"));
1784 ssh_free_packet(st->pktin);
1788 * This enables us to deduce the payload length.
1790 st->payload = st->len - st->pad - 1;
1792 st->pktin->length = st->payload + 5;
1793 st->pktin->encrypted_len = st->packetlen;
1795 st->pktin->sequence = st->incoming_sequence++;
1797 st->pktin->length = st->packetlen - st->pad;
1798 assert(st->pktin->length >= 0);
1801 * Decompress packet payload.
1804 unsigned char *newpayload;
1807 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1808 st->pktin->data + 5, st->pktin->length - 5,
1809 &newpayload, &newlen)) {
1810 if (st->pktin->maxlen < newlen + 5) {
1811 st->pktin->maxlen = newlen + 5;
1812 st->pktin->data = sresize(st->pktin->data,
1813 st->pktin->maxlen + APIEXTRA,
1816 st->pktin->length = 5 + newlen;
1817 memcpy(st->pktin->data + 5, newpayload, newlen);
1823 * pktin->body and pktin->length should identify the semantic
1824 * content of the packet, excluding the initial type byte.
1826 st->pktin->type = st->pktin->data[5];
1827 st->pktin->body = st->pktin->data + 6;
1828 st->pktin->length -= 6;
1829 assert(st->pktin->length >= 0); /* one last double-check */
1832 ssh2_log_incoming_packet(ssh, st->pktin);
1834 st->pktin->savedpos = 0;
1836 crFinish(st->pktin);
1839 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh, unsigned char **data,
1842 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1844 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1847 * Read the packet length field.
1849 for (st->i = 0; st->i < 4; st->i++) {
1850 while ((*datalen) == 0)
1852 st->length[st->i] = *(*data)++;
1856 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1857 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1858 bombout(("Invalid packet length received"));
1862 st->pktin = ssh_new_packet();
1863 st->pktin->data = snewn(st->packetlen, unsigned char);
1865 st->pktin->encrypted_len = st->packetlen;
1867 st->pktin->sequence = st->incoming_sequence++;
1870 * Read the remainder of the packet.
1872 for (st->i = 0; st->i < st->packetlen; st->i++) {
1873 while ((*datalen) == 0)
1875 st->pktin->data[st->i] = *(*data)++;
1880 * pktin->body and pktin->length should identify the semantic
1881 * content of the packet, excluding the initial type byte.
1883 st->pktin->type = st->pktin->data[0];
1884 st->pktin->body = st->pktin->data + 1;
1885 st->pktin->length = st->packetlen - 1;
1888 * Log incoming packet, possibly omitting sensitive fields.
1891 ssh2_log_incoming_packet(ssh, st->pktin);
1893 st->pktin->savedpos = 0;
1895 crFinish(st->pktin);
1898 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1900 int pad, biglen, i, pktoffs;
1904 * XXX various versions of SC (including 8.8.4) screw up the
1905 * register allocation in this function and use the same register
1906 * (D6) for len and as a temporary, with predictable results. The
1907 * following sledgehammer prevents this.
1914 ssh1_log_outgoing_packet(ssh, pkt);
1916 if (ssh->v1_compressing) {
1917 unsigned char *compblk;
1919 zlib_compress_block(ssh->cs_comp_ctx,
1920 pkt->data + 12, pkt->length - 12,
1921 &compblk, &complen);
1922 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1923 memcpy(pkt->data + 12, compblk, complen);
1925 pkt->length = complen + 12;
1928 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1930 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1931 pad = 8 - (len % 8);
1933 biglen = len + pad; /* len(padding+type+data+CRC) */
1935 for (i = pktoffs; i < 4+8; i++)
1936 pkt->data[i] = random_byte();
1937 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1938 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1939 PUT_32BIT(pkt->data + pktoffs, len);
1942 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1943 pkt->data + pktoffs + 4, biglen);
1945 if (offset_p) *offset_p = pktoffs;
1946 return biglen + 4; /* len(length+padding+type+data+CRC) */
1949 static int s_write(Ssh ssh, void *data, int len)
1952 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1953 0, NULL, NULL, 0, NULL);
1956 return sk_write(ssh->s, (char *)data, len);
1959 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1961 int len, backlog, offset;
1962 len = s_wrpkt_prepare(ssh, pkt, &offset);
1963 backlog = s_write(ssh, pkt->data + offset, len);
1964 if (backlog > SSH_MAX_BACKLOG)
1965 ssh_throttle_all(ssh, 1, backlog);
1966 ssh_free_packet(pkt);
1969 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1972 len = s_wrpkt_prepare(ssh, pkt, &offset);
1973 if (ssh->deferred_len + len > ssh->deferred_size) {
1974 ssh->deferred_size = ssh->deferred_len + len + 128;
1975 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1979 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1980 pkt->data + offset, len);
1981 ssh->deferred_len += len;
1982 ssh_free_packet(pkt);
1986 * Construct a SSH-1 packet with the specified contents.
1987 * (This all-at-once interface used to be the only one, but now SSH-1
1988 * packets can also be constructed incrementally.)
1990 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1996 pkt = ssh1_pkt_init(pkttype);
1998 while ((argtype = va_arg(ap, int)) != PKT_END) {
1999 unsigned char *argp, argchar;
2001 unsigned long argint;
2004 /* Actual fields in the packet */
2006 argint = va_arg(ap, int);
2007 ssh_pkt_adduint32(pkt, argint);
2010 argchar = (unsigned char) va_arg(ap, int);
2011 ssh_pkt_addbyte(pkt, argchar);
2014 argp = va_arg(ap, unsigned char *);
2015 arglen = va_arg(ap, int);
2016 ssh_pkt_adddata(pkt, argp, arglen);
2019 sargp = va_arg(ap, char *);
2020 ssh_pkt_addstring(pkt, sargp);
2023 bn = va_arg(ap, Bignum);
2024 ssh1_pkt_addmp(pkt, bn);
2032 static void send_packet(Ssh ssh, int pkttype, ...)
2036 va_start(ap, pkttype);
2037 pkt = construct_packet(ssh, pkttype, ap);
2042 static void defer_packet(Ssh ssh, int pkttype, ...)
2046 va_start(ap, pkttype);
2047 pkt = construct_packet(ssh, pkttype, ap);
2049 s_wrpkt_defer(ssh, pkt);
2052 static int ssh_versioncmp(char *a, char *b)
2055 unsigned long av, bv;
2057 av = strtoul(a, &ae, 10);
2058 bv = strtoul(b, &be, 10);
2060 return (av < bv ? -1 : +1);
2065 av = strtoul(ae, &ae, 10);
2066 bv = strtoul(be, &be, 10);
2068 return (av < bv ? -1 : +1);
2073 * Utility routines for putting an SSH-protocol `string' and
2074 * `uint32' into a hash state.
2076 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2078 unsigned char lenblk[4];
2079 PUT_32BIT(lenblk, len);
2080 h->bytes(s, lenblk, 4);
2081 h->bytes(s, str, len);
2084 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2086 unsigned char intblk[4];
2087 PUT_32BIT(intblk, i);
2088 h->bytes(s, intblk, 4);
2092 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2094 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2096 if (pkt->maxlen < length) {
2097 unsigned char *body = pkt->body;
2098 int offset = body ? body - pkt->data : 0;
2099 pkt->maxlen = length + 256;
2100 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2101 if (body) pkt->body = pkt->data + offset;
2104 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2107 ssh_pkt_ensure(pkt, pkt->length);
2108 memcpy(pkt->data + pkt->length - len, data, len);
2110 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2112 ssh_pkt_adddata(pkt, &byte, 1);
2114 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2116 ssh_pkt_adddata(pkt, &value, 1);
2118 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2121 PUT_32BIT(x, value);
2122 ssh_pkt_adddata(pkt, x, 4);
2124 static void ssh_pkt_addstring_start(struct Packet *pkt)
2126 ssh_pkt_adduint32(pkt, 0);
2127 pkt->savedpos = pkt->length;
2129 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2131 ssh_pkt_adddata(pkt, data, strlen(data));
2132 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2134 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2137 ssh_pkt_adddata(pkt, data, len);
2138 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2140 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2142 ssh_pkt_addstring_start(pkt);
2143 ssh_pkt_addstring_str(pkt, data);
2145 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2147 int len = ssh1_bignum_length(b);
2148 unsigned char *data = snewn(len, unsigned char);
2149 (void) ssh1_write_bignum(data, b);
2150 ssh_pkt_adddata(pkt, data, len);
2153 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2156 int i, n = (bignum_bitcount(b) + 7) / 8;
2157 p = snewn(n + 1, unsigned char);
2159 for (i = 1; i <= n; i++)
2160 p[i] = bignum_byte(b, n - i);
2162 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2164 memmove(p, p + i, n + 1 - i);
2168 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2172 p = ssh2_mpint_fmt(b, &len);
2173 ssh_pkt_addstring_start(pkt);
2174 ssh_pkt_addstring_data(pkt, (char *)p, len);
2178 static struct Packet *ssh1_pkt_init(int pkt_type)
2180 struct Packet *pkt = ssh_new_packet();
2181 pkt->length = 4 + 8; /* space for length + max padding */
2182 ssh_pkt_addbyte(pkt, pkt_type);
2183 pkt->body = pkt->data + pkt->length;
2184 pkt->type = pkt_type;
2185 pkt->downstream_id = 0;
2186 pkt->additional_log_text = NULL;
2190 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2191 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2192 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2193 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2194 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2195 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2196 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2197 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2198 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2200 static struct Packet *ssh2_pkt_init(int pkt_type)
2202 struct Packet *pkt = ssh_new_packet();
2203 pkt->length = 5; /* space for packet length + padding length */
2205 pkt->type = pkt_type;
2206 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2207 pkt->body = pkt->data + pkt->length; /* after packet type */
2208 pkt->downstream_id = 0;
2209 pkt->additional_log_text = NULL;
2214 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2215 * put the MAC on it. Final packet, ready to be sent, is stored in
2216 * pkt->data. Total length is returned.
2218 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2220 int cipherblk, maclen, padding, unencrypted_prefix, i;
2223 ssh2_log_outgoing_packet(ssh, pkt);
2225 if (ssh->bare_connection) {
2227 * Trivial packet construction for the bare connection
2230 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2231 pkt->body = pkt->data + 1;
2232 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2233 return pkt->length - 1;
2237 * Compress packet payload.
2240 unsigned char *newpayload;
2243 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2245 &newpayload, &newlen)) {
2247 ssh2_pkt_adddata(pkt, newpayload, newlen);
2253 * Add padding. At least four bytes, and must also bring total
2254 * length (minus MAC) up to a multiple of the block size.
2255 * If pkt->forcepad is set, make sure the packet is at least that size
2258 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2259 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2261 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2262 if (pkt->length + padding < pkt->forcepad)
2263 padding = pkt->forcepad - pkt->length;
2265 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2267 assert(padding <= 255);
2268 maclen = ssh->csmac ? ssh->csmac->len : 0;
2269 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2270 pkt->data[4] = padding;
2271 for (i = 0; i < padding; i++)
2272 pkt->data[pkt->length + i] = random_byte();
2273 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2274 if (ssh->csmac && ssh->csmac_etm) {
2276 * OpenSSH-defined encrypt-then-MAC protocol.
2279 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2280 pkt->data + 4, pkt->length + padding - 4);
2281 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2282 pkt->length + padding,
2283 ssh->v2_outgoing_sequence);
2286 * SSH-2 standard protocol.
2289 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2290 pkt->length + padding,
2291 ssh->v2_outgoing_sequence);
2293 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2294 pkt->data, pkt->length + padding);
2297 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2298 pkt->encrypted_len = pkt->length + padding;
2300 /* Ready-to-send packet starts at pkt->data. We return length. */
2301 pkt->body = pkt->data;
2302 return pkt->length + padding + maclen;
2306 * Routines called from the main SSH code to send packets. There
2307 * are quite a few of these, because we have two separate
2308 * mechanisms for delaying the sending of packets:
2310 * - In order to send an IGNORE message and a password message in
2311 * a single fixed-length blob, we require the ability to
2312 * concatenate the encrypted forms of those two packets _into_ a
2313 * single blob and then pass it to our <network.h> transport
2314 * layer in one go. Hence, there's a deferment mechanism which
2315 * works after packet encryption.
2317 * - In order to avoid sending any connection-layer messages
2318 * during repeat key exchange, we have to queue up any such
2319 * outgoing messages _before_ they are encrypted (and in
2320 * particular before they're allocated sequence numbers), and
2321 * then send them once we've finished.
2323 * I call these mechanisms `defer' and `queue' respectively, so as
2324 * to distinguish them reasonably easily.
2326 * The functions send_noqueue() and defer_noqueue() free the packet
2327 * structure they are passed. Every outgoing packet goes through
2328 * precisely one of these functions in its life; packets passed to
2329 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2330 * these or get queued, and then when the queue is later emptied
2331 * the packets are all passed to defer_noqueue().
2333 * When using a CBC-mode cipher, it's necessary to ensure that an
2334 * attacker can't provide data to be encrypted using an IV that they
2335 * know. We ensure this by prefixing each packet that might contain
2336 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2337 * mechanism, so in this case send_noqueue() ends up redirecting to
2338 * defer_noqueue(). If you don't like this inefficiency, don't use
2342 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2343 static void ssh_pkt_defersend(Ssh);
2346 * Send an SSH-2 packet immediately, without queuing or deferring.
2348 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2352 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2353 /* We need to send two packets, so use the deferral mechanism. */
2354 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2355 ssh_pkt_defersend(ssh);
2358 len = ssh2_pkt_construct(ssh, pkt);
2359 backlog = s_write(ssh, pkt->body, len);
2360 if (backlog > SSH_MAX_BACKLOG)
2361 ssh_throttle_all(ssh, 1, backlog);
2363 ssh->outgoing_data_size += pkt->encrypted_len;
2364 if (!ssh->kex_in_progress &&
2365 !ssh->bare_connection &&
2366 ssh->max_data_size != 0 &&
2367 ssh->outgoing_data_size > ssh->max_data_size)
2368 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2370 ssh_free_packet(pkt);
2374 * Defer an SSH-2 packet.
2376 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2379 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2380 ssh->deferred_len == 0 && !noignore &&
2381 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2383 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2384 * get encrypted with a known IV.
2386 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2387 ssh2_pkt_addstring_start(ipkt);
2388 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2390 len = ssh2_pkt_construct(ssh, pkt);
2391 if (ssh->deferred_len + len > ssh->deferred_size) {
2392 ssh->deferred_size = ssh->deferred_len + len + 128;
2393 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2397 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2398 ssh->deferred_len += len;
2399 ssh->deferred_data_size += pkt->encrypted_len;
2400 ssh_free_packet(pkt);
2404 * Queue an SSH-2 packet.
2406 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2408 assert(ssh->queueing);
2410 if (ssh->queuelen >= ssh->queuesize) {
2411 ssh->queuesize = ssh->queuelen + 32;
2412 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2415 ssh->queue[ssh->queuelen++] = pkt;
2419 * Either queue or send a packet, depending on whether queueing is
2422 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2425 ssh2_pkt_queue(ssh, pkt);
2427 ssh2_pkt_send_noqueue(ssh, pkt);
2431 * Either queue or defer a packet, depending on whether queueing is
2434 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2437 ssh2_pkt_queue(ssh, pkt);
2439 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2443 * Send the whole deferred data block constructed by
2444 * ssh2_pkt_defer() or SSH-1's defer_packet().
2446 * The expected use of the defer mechanism is that you call
2447 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2448 * not currently queueing, this simply sets up deferred_send_data
2449 * and then sends it. If we _are_ currently queueing, the calls to
2450 * ssh2_pkt_defer() put the deferred packets on to the queue
2451 * instead, and therefore ssh_pkt_defersend() has no deferred data
2452 * to send. Hence, there's no need to make it conditional on
2455 static void ssh_pkt_defersend(Ssh ssh)
2458 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2459 ssh->deferred_len = ssh->deferred_size = 0;
2460 sfree(ssh->deferred_send_data);
2461 ssh->deferred_send_data = NULL;
2462 if (backlog > SSH_MAX_BACKLOG)
2463 ssh_throttle_all(ssh, 1, backlog);
2465 ssh->outgoing_data_size += ssh->deferred_data_size;
2466 if (!ssh->kex_in_progress &&
2467 !ssh->bare_connection &&
2468 ssh->max_data_size != 0 &&
2469 ssh->outgoing_data_size > ssh->max_data_size)
2470 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2471 ssh->deferred_data_size = 0;
2475 * Send a packet whose length needs to be disguised (typically
2476 * passwords or keyboard-interactive responses).
2478 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2484 * The simplest way to do this is to adjust the
2485 * variable-length padding field in the outgoing packet.
2487 * Currently compiled out, because some Cisco SSH servers
2488 * don't like excessively padded packets (bah, why's it
2491 pkt->forcepad = padsize;
2492 ssh2_pkt_send(ssh, pkt);
2497 * If we can't do that, however, an alternative approach is
2498 * to use the pkt_defer mechanism to bundle the packet
2499 * tightly together with an SSH_MSG_IGNORE such that their
2500 * combined length is a constant. So first we construct the
2501 * final form of this packet and defer its sending.
2503 ssh2_pkt_defer(ssh, pkt);
2506 * Now construct an SSH_MSG_IGNORE which includes a string
2507 * that's an exact multiple of the cipher block size. (If
2508 * the cipher is NULL so that the block size is
2509 * unavailable, we don't do this trick at all, because we
2510 * gain nothing by it.)
2512 if (ssh->cscipher &&
2513 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2516 stringlen = (256 - ssh->deferred_len);
2517 stringlen += ssh->cscipher->blksize - 1;
2518 stringlen -= (stringlen % ssh->cscipher->blksize);
2521 * Temporarily disable actual compression, so we
2522 * can guarantee to get this string exactly the
2523 * length we want it. The compression-disabling
2524 * routine should return an integer indicating how
2525 * many bytes we should adjust our string length
2529 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2531 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2532 ssh2_pkt_addstring_start(pkt);
2533 for (i = 0; i < stringlen; i++) {
2534 char c = (char) random_byte();
2535 ssh2_pkt_addstring_data(pkt, &c, 1);
2537 ssh2_pkt_defer(ssh, pkt);
2539 ssh_pkt_defersend(ssh);
2544 * Send all queued SSH-2 packets. We send them by means of
2545 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2546 * packets that needed to be lumped together.
2548 static void ssh2_pkt_queuesend(Ssh ssh)
2552 assert(!ssh->queueing);
2554 for (i = 0; i < ssh->queuelen; i++)
2555 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2558 ssh_pkt_defersend(ssh);
2562 void bndebug(char *string, Bignum b)
2566 p = ssh2_mpint_fmt(b, &len);
2567 debug(("%s", string));
2568 for (i = 0; i < len; i++)
2569 debug((" %02x", p[i]));
2575 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2579 p = ssh2_mpint_fmt(b, &len);
2580 hash_string(h, s, p, len);
2585 * Packet decode functions for both SSH-1 and SSH-2.
2587 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2589 unsigned long value;
2590 if (pkt->length - pkt->savedpos < 4)
2591 return 0; /* arrgh, no way to decline (FIXME?) */
2592 value = GET_32BIT(pkt->body + pkt->savedpos);
2596 static int ssh2_pkt_getbool(struct Packet *pkt)
2598 unsigned long value;
2599 if (pkt->length - pkt->savedpos < 1)
2600 return 0; /* arrgh, no way to decline (FIXME?) */
2601 value = pkt->body[pkt->savedpos] != 0;
2605 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2610 if (pkt->length - pkt->savedpos < 4)
2612 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2617 if (pkt->length - pkt->savedpos < *length)
2619 *p = (char *)(pkt->body + pkt->savedpos);
2620 pkt->savedpos += *length;
2622 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2624 if (pkt->length - pkt->savedpos < length)
2626 pkt->savedpos += length;
2627 return pkt->body + (pkt->savedpos - length);
2629 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2630 unsigned char **keystr)
2634 j = makekey(pkt->body + pkt->savedpos,
2635 pkt->length - pkt->savedpos,
2642 assert(pkt->savedpos < pkt->length);
2646 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2651 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2652 pkt->length - pkt->savedpos, &b);
2660 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2666 ssh_pkt_getstring(pkt, &p, &length);
2671 b = bignum_from_bytes((unsigned char *)p, length);
2676 * Helper function to add an SSH-2 signature blob to a packet.
2677 * Expects to be shown the public key blob as well as the signature
2678 * blob. Normally works just like ssh2_pkt_addstring, but will
2679 * fiddle with the signature packet if necessary for
2680 * BUG_SSH2_RSA_PADDING.
2682 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2683 void *pkblob_v, int pkblob_len,
2684 void *sigblob_v, int sigblob_len)
2686 unsigned char *pkblob = (unsigned char *)pkblob_v;
2687 unsigned char *sigblob = (unsigned char *)sigblob_v;
2689 /* dmemdump(pkblob, pkblob_len); */
2690 /* dmemdump(sigblob, sigblob_len); */
2693 * See if this is in fact an ssh-rsa signature and a buggy
2694 * server; otherwise we can just do this the easy way.
2696 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2697 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2698 int pos, len, siglen;
2701 * Find the byte length of the modulus.
2704 pos = 4+7; /* skip over "ssh-rsa" */
2705 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2706 if (len < 0 || len > pkblob_len - pos - 4)
2708 pos += 4 + len; /* skip over exponent */
2709 if (pkblob_len - pos < 4)
2711 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2712 if (len < 0 || len > pkblob_len - pos - 4)
2714 pos += 4; /* find modulus itself */
2715 while (len > 0 && pkblob[pos] == 0)
2717 /* debug(("modulus length is %d\n", len)); */
2720 * Now find the signature integer.
2722 pos = 4+7; /* skip over "ssh-rsa" */
2723 if (sigblob_len < pos+4)
2725 siglen = toint(GET_32BIT(sigblob+pos));
2726 if (siglen != sigblob_len - pos - 4)
2728 /* debug(("signature length is %d\n", siglen)); */
2730 if (len != siglen) {
2731 unsigned char newlen[4];
2732 ssh2_pkt_addstring_start(pkt);
2733 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2734 /* dmemdump(sigblob, pos); */
2735 pos += 4; /* point to start of actual sig */
2736 PUT_32BIT(newlen, len);
2737 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2738 /* dmemdump(newlen, 4); */
2740 while (len-- > siglen) {
2741 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2742 /* dmemdump(newlen, 1); */
2744 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2745 /* dmemdump(sigblob+pos, siglen); */
2749 /* Otherwise fall through and do it the easy way. We also come
2750 * here as a fallback if we discover above that the key blob
2751 * is misformatted in some way. */
2755 ssh2_pkt_addstring_start(pkt);
2756 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2760 * Examine the remote side's version string and compare it against
2761 * a list of known buggy implementations.
2763 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2765 char *imp; /* pointer to implementation part */
2767 imp += strcspn(imp, "-");
2769 imp += strcspn(imp, "-");
2772 ssh->remote_bugs = 0;
2775 * General notes on server version strings:
2776 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2777 * here -- in particular, we've heard of one that's perfectly happy
2778 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2779 * so we can't distinguish them.
2781 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2782 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2783 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2784 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2785 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2786 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2788 * These versions don't support SSH1_MSG_IGNORE, so we have
2789 * to use a different defence against password length
2792 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2793 logevent("We believe remote version has SSH-1 ignore bug");
2796 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2797 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2798 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2800 * These versions need a plain password sent; they can't
2801 * handle having a null and a random length of data after
2804 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2805 logevent("We believe remote version needs a plain SSH-1 password");
2808 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2809 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2810 (!strcmp(imp, "Cisco-1.25")))) {
2812 * These versions apparently have no clue whatever about
2813 * RSA authentication and will panic and die if they see
2814 * an AUTH_RSA message.
2816 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2817 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2820 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2821 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2822 !wc_match("* VShell", imp) &&
2823 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2824 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2825 wc_match("2.1 *", imp)))) {
2827 * These versions have the HMAC bug.
2829 ssh->remote_bugs |= BUG_SSH2_HMAC;
2830 logevent("We believe remote version has SSH-2 HMAC bug");
2833 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2834 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2835 !wc_match("* VShell", imp) &&
2836 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2838 * These versions have the key-derivation bug (failing to
2839 * include the literal shared secret in the hashes that
2840 * generate the keys).
2842 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2843 logevent("We believe remote version has SSH-2 key-derivation bug");
2846 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2847 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2848 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2849 wc_match("OpenSSH_3.[0-2]*", imp) ||
2850 wc_match("mod_sftp/0.[0-8]*", imp) ||
2851 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2853 * These versions have the SSH-2 RSA padding bug.
2855 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2856 logevent("We believe remote version has SSH-2 RSA padding bug");
2859 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2860 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2861 wc_match("OpenSSH_2.[0-2]*", imp))) {
2863 * These versions have the SSH-2 session-ID bug in
2864 * public-key authentication.
2866 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2867 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2870 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2871 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2872 (wc_match("DigiSSH_2.0", imp) ||
2873 wc_match("OpenSSH_2.[0-4]*", imp) ||
2874 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2875 wc_match("Sun_SSH_1.0", imp) ||
2876 wc_match("Sun_SSH_1.0.1", imp) ||
2877 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2878 wc_match("WeOnlyDo-*", imp)))) {
2880 * These versions have the SSH-2 rekey bug.
2882 ssh->remote_bugs |= BUG_SSH2_REKEY;
2883 logevent("We believe remote version has SSH-2 rekey bug");
2886 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2887 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2888 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2889 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2891 * This version ignores our makpkt and needs to be throttled.
2893 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2894 logevent("We believe remote version ignores SSH-2 maximum packet size");
2897 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2899 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2900 * none detected automatically.
2902 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2903 logevent("We believe remote version has SSH-2 ignore bug");
2906 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2907 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2908 (wc_match("OpenSSH_2.[235]*", imp)))) {
2910 * These versions only support the original (pre-RFC4419)
2911 * SSH-2 GEX request.
2913 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2914 logevent("We believe remote version has outdated SSH-2 GEX");
2917 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2919 * Servers that don't support our winadj request for one
2920 * reason or another. Currently, none detected automatically.
2922 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2923 logevent("We believe remote version has winadj bug");
2926 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
2927 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
2928 (wc_match("OpenSSH_[2-5].*", imp) ||
2929 wc_match("OpenSSH_6.[0-6]*", imp) ||
2930 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
2931 wc_match("dropbear_0.5[01]*", imp)))) {
2933 * These versions have the SSH-2 channel request bug.
2934 * OpenSSH 6.7 and above do not:
2935 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
2936 * dropbear_0.52 and above do not:
2937 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
2939 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
2940 logevent("We believe remote version has SSH-2 channel request bug");
2945 * The `software version' part of an SSH version string is required
2946 * to contain no spaces or minus signs.
2948 static void ssh_fix_verstring(char *str)
2950 /* Eat "<protoversion>-". */
2951 while (*str && *str != '-') str++;
2952 assert(*str == '-'); str++;
2954 /* Convert minus signs and spaces in the remaining string into
2957 if (*str == '-' || *str == ' ')
2964 * Send an appropriate SSH version string.
2966 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
2970 if (ssh->version == 2) {
2972 * Construct a v2 version string.
2974 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
2977 * Construct a v1 version string.
2979 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
2980 verstring = dupprintf("SSH-%s-%s\012",
2981 (ssh_versioncmp(svers, "1.5") <= 0 ?
2986 ssh_fix_verstring(verstring + strlen(protoname));
2988 if (ssh->version == 2) {
2991 * Record our version string.
2993 len = strcspn(verstring, "\015\012");
2994 ssh->v_c = snewn(len + 1, char);
2995 memcpy(ssh->v_c, verstring, len);
2999 logeventf(ssh, "We claim version: %.*s",
3000 strcspn(verstring, "\015\012"), verstring);
3001 s_write(ssh, verstring, strlen(verstring));
3005 static int do_ssh_init(Ssh ssh, unsigned char c)
3007 static const char protoname[] = "SSH-";
3009 struct do_ssh_init_state {
3018 crState(do_ssh_init_state);
3022 /* Search for a line beginning with the protocol name prefix in
3025 for (s->i = 0; protoname[s->i]; s->i++) {
3026 if ((char)c != protoname[s->i]) goto no;
3036 s->vstrsize = sizeof(protoname) + 16;
3037 s->vstring = snewn(s->vstrsize, char);
3038 strcpy(s->vstring, protoname);
3039 s->vslen = strlen(protoname);
3042 if (s->vslen >= s->vstrsize - 1) {
3044 s->vstring = sresize(s->vstring, s->vstrsize, char);
3046 s->vstring[s->vslen++] = c;
3049 s->version[s->i] = '\0';
3051 } else if (s->i < sizeof(s->version) - 1)
3052 s->version[s->i++] = c;
3053 } else if (c == '\012')
3055 crReturn(1); /* get another char */
3058 ssh->agentfwd_enabled = FALSE;
3059 ssh->rdpkt2_state.incoming_sequence = 0;
3061 s->vstring[s->vslen] = 0;
3062 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3063 logeventf(ssh, "Server version: %s", s->vstring);
3064 ssh_detect_bugs(ssh, s->vstring);
3067 * Decide which SSH protocol version to support.
3070 /* Anything strictly below "2.0" means protocol 1 is supported. */
3071 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3072 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3073 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3075 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
3076 bombout(("SSH protocol version 1 required by configuration but "
3077 "not provided by server"));
3080 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
3081 bombout(("SSH protocol version 2 required by configuration but "
3082 "not provided by server"));
3086 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3091 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3093 /* Send the version string, if we haven't already */
3094 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3095 ssh_send_verstring(ssh, protoname, s->version);
3097 if (ssh->version == 2) {
3100 * Record their version string.
3102 len = strcspn(s->vstring, "\015\012");
3103 ssh->v_s = snewn(len + 1, char);
3104 memcpy(ssh->v_s, s->vstring, len);
3108 * Initialise SSH-2 protocol.
3110 ssh->protocol = ssh2_protocol;
3111 ssh2_protocol_setup(ssh);
3112 ssh->s_rdpkt = ssh2_rdpkt;
3115 * Initialise SSH-1 protocol.
3117 ssh->protocol = ssh1_protocol;
3118 ssh1_protocol_setup(ssh);
3119 ssh->s_rdpkt = ssh1_rdpkt;
3121 if (ssh->version == 2)
3122 do_ssh2_transport(ssh, NULL, -1, NULL);
3124 update_specials_menu(ssh->frontend);
3125 ssh->state = SSH_STATE_BEFORE_SIZE;
3126 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3133 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3136 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3137 * the ssh-connection part, extracted and given a trivial binary
3138 * packet protocol, so we replace 'SSH-' at the start with a new
3139 * name. In proper SSH style (though of course this part of the
3140 * proper SSH protocol _isn't_ subject to this kind of
3141 * DNS-domain-based extension), we define the new name in our
3144 static const char protoname[] =
3145 "SSHCONNECTION@putty.projects.tartarus.org-";
3147 struct do_ssh_connection_init_state {
3155 crState(do_ssh_connection_init_state);
3159 /* Search for a line beginning with the protocol name prefix in
3162 for (s->i = 0; protoname[s->i]; s->i++) {
3163 if ((char)c != protoname[s->i]) goto no;
3173 s->vstrsize = sizeof(protoname) + 16;
3174 s->vstring = snewn(s->vstrsize, char);
3175 strcpy(s->vstring, protoname);
3176 s->vslen = strlen(protoname);
3179 if (s->vslen >= s->vstrsize - 1) {
3181 s->vstring = sresize(s->vstring, s->vstrsize, char);
3183 s->vstring[s->vslen++] = c;
3186 s->version[s->i] = '\0';
3188 } else if (s->i < sizeof(s->version) - 1)
3189 s->version[s->i++] = c;
3190 } else if (c == '\012')
3192 crReturn(1); /* get another char */
3195 ssh->agentfwd_enabled = FALSE;
3196 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3198 s->vstring[s->vslen] = 0;
3199 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3200 logeventf(ssh, "Server version: %s", s->vstring);
3201 ssh_detect_bugs(ssh, s->vstring);
3204 * Decide which SSH protocol version to support. This is easy in
3205 * bare ssh-connection mode: only 2.0 is legal.
3207 if (ssh_versioncmp(s->version, "2.0") < 0) {
3208 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3211 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3212 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3218 logeventf(ssh, "Using bare ssh-connection protocol");
3220 /* Send the version string, if we haven't already */
3221 ssh_send_verstring(ssh, protoname, s->version);
3224 * Initialise bare connection protocol.
3226 ssh->protocol = ssh2_bare_connection_protocol;
3227 ssh2_bare_connection_protocol_setup(ssh);
3228 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3230 update_specials_menu(ssh->frontend);
3231 ssh->state = SSH_STATE_BEFORE_SIZE;
3232 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3235 * Get authconn (really just conn) under way.
3237 do_ssh2_authconn(ssh, NULL, 0, NULL);
3244 static void ssh_process_incoming_data(Ssh ssh,
3245 unsigned char **data, int *datalen)
3247 struct Packet *pktin;
3249 pktin = ssh->s_rdpkt(ssh, data, datalen);
3251 ssh->protocol(ssh, NULL, 0, pktin);
3252 ssh_free_packet(pktin);
3256 static void ssh_queue_incoming_data(Ssh ssh,
3257 unsigned char **data, int *datalen)
3259 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3264 static void ssh_process_queued_incoming_data(Ssh ssh)
3267 unsigned char *data;
3270 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3271 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3275 while (!ssh->frozen && len > 0)
3276 ssh_process_incoming_data(ssh, &data, &len);
3279 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3283 static void ssh_set_frozen(Ssh ssh, int frozen)
3286 sk_set_frozen(ssh->s, frozen);
3287 ssh->frozen = frozen;
3290 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
3292 /* Log raw data, if we're in that mode. */
3294 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3295 0, NULL, NULL, 0, NULL);
3297 crBegin(ssh->ssh_gotdata_crstate);
3300 * To begin with, feed the characters one by one to the
3301 * protocol initialisation / selection function do_ssh_init().
3302 * When that returns 0, we're done with the initial greeting
3303 * exchange and can move on to packet discipline.
3306 int ret; /* need not be kept across crReturn */
3308 crReturnV; /* more data please */
3309 ret = ssh->do_ssh_init(ssh, *data);
3317 * We emerge from that loop when the initial negotiation is
3318 * over and we have selected an s_rdpkt function. Now pass
3319 * everything to s_rdpkt, and then pass the resulting packets
3320 * to the proper protocol handler.
3324 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3326 ssh_queue_incoming_data(ssh, &data, &datalen);
3327 /* This uses up all data and cannot cause anything interesting
3328 * to happen; indeed, for anything to happen at all, we must
3329 * return, so break out. */
3331 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3332 /* This uses up some or all data, and may freeze the
3334 ssh_process_queued_incoming_data(ssh);
3336 /* This uses up some or all data, and may freeze the
3338 ssh_process_incoming_data(ssh, &data, &datalen);
3340 /* FIXME this is probably EBW. */
3341 if (ssh->state == SSH_STATE_CLOSED)
3344 /* We're out of data. Go and get some more. */
3350 static int ssh_do_close(Ssh ssh, int notify_exit)
3353 struct ssh_channel *c;
3355 ssh->state = SSH_STATE_CLOSED;
3356 expire_timer_context(ssh);
3361 notify_remote_exit(ssh->frontend);
3366 * Now we must shut down any port- and X-forwarded channels going
3367 * through this connection.
3369 if (ssh->channels) {
3370 while (NULL != (c = index234(ssh->channels, 0))) {
3373 x11_close(c->u.x11.xconn);
3376 case CHAN_SOCKDATA_DORMANT:
3377 pfd_close(c->u.pfd.pf);
3380 del234(ssh->channels, c); /* moving next one to index 0 */
3381 if (ssh->version == 2)
3382 bufchain_clear(&c->v.v2.outbuffer);
3387 * Go through port-forwardings, and close any associated
3388 * listening sockets.
3390 if (ssh->portfwds) {
3391 struct ssh_portfwd *pf;
3392 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3393 /* Dispose of any listening socket. */
3395 pfl_terminate(pf->local);
3396 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3399 freetree234(ssh->portfwds);
3400 ssh->portfwds = NULL;
3404 * Also stop attempting to connection-share.
3406 if (ssh->connshare) {
3407 sharestate_free(ssh->connshare);
3408 ssh->connshare = NULL;
3414 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3415 const char *error_msg, int error_code)
3417 Ssh ssh = (Ssh) plug;
3418 char addrbuf[256], *msg;
3420 if (ssh->attempting_connshare) {
3422 * While we're attempting connection sharing, don't loudly log
3423 * everything that happens. Real TCP connections need to be
3424 * logged when we _start_ trying to connect, because it might
3425 * be ages before they respond if something goes wrong; but
3426 * connection sharing is local and quick to respond, and it's
3427 * sufficient to simply wait and see whether it worked
3431 sk_getaddr(addr, addrbuf, lenof(addrbuf));
3434 if (sk_addr_needs_port(addr)) {
3435 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
3437 msg = dupprintf("Connecting to %s", addrbuf);
3440 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
3448 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3449 const char *ds_err, const char *us_err)
3451 if (event == SHARE_NONE) {
3452 /* In this case, 'logtext' is an error message indicating a
3453 * reason why connection sharing couldn't be set up _at all_.
3454 * Failing that, ds_err and us_err indicate why we couldn't be
3455 * a downstream and an upstream respectively. */
3457 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3460 logeventf(ssh, "Could not set up connection sharing"
3461 " as downstream: %s", ds_err);
3463 logeventf(ssh, "Could not set up connection sharing"
3464 " as upstream: %s", us_err);
3466 } else if (event == SHARE_DOWNSTREAM) {
3467 /* In this case, 'logtext' is a local endpoint address */
3468 logeventf(ssh, "Using existing shared connection at %s", logtext);
3469 /* Also we should mention this in the console window to avoid
3470 * confusing users as to why this window doesn't behave the
3472 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3473 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3475 } else if (event == SHARE_UPSTREAM) {
3476 /* In this case, 'logtext' is a local endpoint address too */
3477 logeventf(ssh, "Sharing this connection at %s", logtext);
3481 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3484 Ssh ssh = (Ssh) plug;
3485 int need_notify = ssh_do_close(ssh, FALSE);
3488 if (!ssh->close_expected)
3489 error_msg = "Server unexpectedly closed network connection";
3491 error_msg = "Server closed network connection";
3494 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3498 notify_remote_exit(ssh->frontend);
3501 logevent(error_msg);
3502 if (!ssh->close_expected || !ssh->clean_exit)
3503 connection_fatal(ssh->frontend, "%s", error_msg);
3507 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3509 Ssh ssh = (Ssh) plug;
3510 ssh_gotdata(ssh, (unsigned char *)data, len);
3511 if (ssh->state == SSH_STATE_CLOSED) {
3512 ssh_do_close(ssh, TRUE);
3518 static void ssh_sent(Plug plug, int bufsize)
3520 Ssh ssh = (Ssh) plug;
3522 * If the send backlog on the SSH socket itself clears, we
3523 * should unthrottle the whole world if it was throttled.
3525 if (bufsize < SSH_MAX_BACKLOG)
3526 ssh_throttle_all(ssh, 0, bufsize);
3530 * Connect to specified host and port.
3531 * Returns an error message, or NULL on success.
3532 * Also places the canonical host name into `realhost'. It must be
3533 * freed by the caller.
3535 static const char *connect_to_host(Ssh ssh, char *host, int port,
3536 char **realhost, int nodelay, int keepalive)
3538 static const struct plug_function_table fn_table = {
3549 int addressfamily, sshprot;
3551 loghost = conf_get_str(ssh->conf, CONF_loghost);
3556 tmphost = dupstr(loghost);
3557 ssh->savedport = 22; /* default ssh port */
3560 * A colon suffix on the hostname string also lets us affect
3561 * savedport. (Unless there are multiple colons, in which case
3562 * we assume this is an unbracketed IPv6 literal.)
3564 colon = host_strrchr(tmphost, ':');
3565 if (colon && colon == host_strchr(tmphost, ':')) {
3568 ssh->savedport = atoi(colon);
3571 ssh->savedhost = host_strduptrim(tmphost);
3574 ssh->savedhost = host_strduptrim(host);
3576 port = 22; /* default ssh port */
3577 ssh->savedport = port;
3580 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3583 * Try connection-sharing, in case that means we don't open a
3584 * socket after all. ssh_connection_sharing_init will connect to a
3585 * previously established upstream if it can, and failing that,
3586 * establish a listening socket for _us_ to be the upstream. In
3587 * the latter case it will return NULL just as if it had done
3588 * nothing, because here we only need to care if we're a
3589 * downstream and need to do our connection setup differently.
3591 ssh->connshare = NULL;
3592 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3593 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3594 ssh->conf, ssh, &ssh->connshare);
3595 ssh->attempting_connshare = FALSE;
3596 if (ssh->s != NULL) {
3598 * We are a downstream.
3600 ssh->bare_connection = TRUE;
3601 ssh->do_ssh_init = do_ssh_connection_init;
3602 ssh->fullhostname = NULL;
3603 *realhost = dupstr(host); /* best we can do */
3606 * We're not a downstream, so open a normal socket.
3608 ssh->do_ssh_init = do_ssh_init;
3613 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3614 logeventf(ssh, "Looking up host \"%s\"%s", host,
3615 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3616 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3617 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3618 if ((err = sk_addr_error(addr)) != NULL) {
3622 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3624 ssh->s = new_connection(addr, *realhost, port,
3625 0, 1, nodelay, keepalive,
3626 (Plug) ssh, ssh->conf);
3627 if ((err = sk_socket_error(ssh->s)) != NULL) {
3629 notify_remote_exit(ssh->frontend);
3635 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3636 * send the version string too.
3638 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3641 if (sshprot == 3 && !ssh->bare_connection) {
3643 ssh_send_verstring(ssh, "SSH-", NULL);
3647 * loghost, if configured, overrides realhost.
3651 *realhost = dupstr(loghost);
3658 * Throttle or unthrottle the SSH connection.
3660 static void ssh_throttle_conn(Ssh ssh, int adjust)
3662 int old_count = ssh->conn_throttle_count;
3663 ssh->conn_throttle_count += adjust;
3664 assert(ssh->conn_throttle_count >= 0);
3665 if (ssh->conn_throttle_count && !old_count) {
3666 ssh_set_frozen(ssh, 1);
3667 } else if (!ssh->conn_throttle_count && old_count) {
3668 ssh_set_frozen(ssh, 0);
3673 * Throttle or unthrottle _all_ local data streams (for when sends
3674 * on the SSH connection itself back up).
3676 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3679 struct ssh_channel *c;
3681 if (enable == ssh->throttled_all)
3683 ssh->throttled_all = enable;
3684 ssh->overall_bufsize = bufsize;
3687 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3689 case CHAN_MAINSESSION:
3691 * This is treated separately, outside the switch.
3695 x11_override_throttle(c->u.x11.xconn, enable);
3698 /* Agent channels require no buffer management. */
3701 pfd_override_throttle(c->u.pfd.pf, enable);
3707 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3709 Ssh ssh = (Ssh) sshv;
3711 ssh->agent_response = reply;
3712 ssh->agent_response_len = replylen;
3714 if (ssh->version == 1)
3715 do_ssh1_login(ssh, NULL, -1, NULL);
3717 do_ssh2_authconn(ssh, NULL, -1, NULL);
3720 static void ssh_dialog_callback(void *sshv, int ret)
3722 Ssh ssh = (Ssh) sshv;
3724 ssh->user_response = ret;
3726 if (ssh->version == 1)
3727 do_ssh1_login(ssh, NULL, -1, NULL);
3729 do_ssh2_transport(ssh, NULL, -1, NULL);
3732 * This may have unfrozen the SSH connection, so do a
3735 ssh_process_queued_incoming_data(ssh);
3738 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3740 struct ssh_channel *c = (struct ssh_channel *)cv;
3742 void *sentreply = reply;
3744 c->u.a.outstanding_requests--;
3746 /* Fake SSH_AGENT_FAILURE. */
3747 sentreply = "\0\0\0\1\5";
3750 if (ssh->version == 2) {
3751 ssh2_add_channel_data(c, sentreply, replylen);
3754 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3755 PKT_INT, c->remoteid,
3757 PKT_DATA, sentreply, replylen,
3763 * If we've already seen an incoming EOF but haven't sent an
3764 * outgoing one, this may be the moment to send it.
3766 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3767 sshfwd_write_eof(c);
3771 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3772 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3773 * => log `wire_reason'.
3775 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3776 int code, int clean_exit)
3780 client_reason = wire_reason;
3782 error = dupprintf("Disconnected: %s", client_reason);
3784 error = dupstr("Disconnected");
3786 if (ssh->version == 1) {
3787 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3789 } else if (ssh->version == 2) {
3790 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3791 ssh2_pkt_adduint32(pktout, code);
3792 ssh2_pkt_addstring(pktout, wire_reason);
3793 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3794 ssh2_pkt_send_noqueue(ssh, pktout);
3797 ssh->close_expected = TRUE;
3798 ssh->clean_exit = clean_exit;
3799 ssh_closing((Plug)ssh, error, 0, 0);
3803 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3804 const struct ssh_signkey *ssh2keytype,
3807 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3808 return -1; /* no manual keys configured */
3813 * The fingerprint string we've been given will have things
3814 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3815 * narrow down to just the colon-separated hex block at the
3816 * end of the string.
3818 const char *p = strrchr(fingerprint, ' ');
3819 fingerprint = p ? p+1 : fingerprint;
3820 /* Quick sanity checks, including making sure it's in lowercase */
3821 assert(strlen(fingerprint) == 16*3 - 1);
3822 assert(fingerprint[2] == ':');
3823 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3825 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3827 return 1; /* success */
3832 * Construct the base64-encoded public key blob and see if
3835 unsigned char *binblob;
3837 int binlen, atoms, i;
3838 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3839 atoms = (binlen + 2) / 3;
3840 base64blob = snewn(atoms * 4 + 1, char);
3841 for (i = 0; i < atoms; i++)
3842 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3843 base64blob[atoms * 4] = '\0';
3845 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3848 return 1; /* success */
3857 * Handle the key exchange and user authentication phases.
3859 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3860 struct Packet *pktin)
3863 unsigned char cookie[8], *ptr;
3864 struct MD5Context md5c;
3865 struct do_ssh1_login_state {
3868 unsigned char *rsabuf, *keystr1, *keystr2;
3869 unsigned long supported_ciphers_mask, supported_auths_mask;
3870 int tried_publickey, tried_agent;
3871 int tis_auth_refused, ccard_auth_refused;
3872 unsigned char session_id[16];
3874 void *publickey_blob;
3875 int publickey_bloblen;
3876 char *publickey_comment;
3877 int publickey_encrypted;
3878 prompts_t *cur_prompt;
3881 unsigned char request[5], *response, *p;
3891 struct RSAKey servkey, hostkey;
3893 crState(do_ssh1_login_state);
3900 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3901 bombout(("Public key packet not received"));
3905 logevent("Received public keys");
3907 ptr = ssh_pkt_getdata(pktin, 8);
3909 bombout(("SSH-1 public key packet stopped before random cookie"));
3912 memcpy(cookie, ptr, 8);
3914 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3915 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3916 bombout(("Failed to read SSH-1 public keys from public key packet"));
3921 * Log the host key fingerprint.
3925 logevent("Host key fingerprint is:");
3926 strcpy(logmsg, " ");
3927 s->hostkey.comment = NULL;
3928 rsa_fingerprint(logmsg + strlen(logmsg),
3929 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3933 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3934 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3935 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3936 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3937 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3939 ssh->v1_local_protoflags =
3940 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3941 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3944 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3945 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3946 MD5Update(&md5c, cookie, 8);
3947 MD5Final(s->session_id, &md5c);
3949 for (i = 0; i < 32; i++)
3950 ssh->session_key[i] = random_byte();
3953 * Verify that the `bits' and `bytes' parameters match.
3955 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3956 s->servkey.bits > s->servkey.bytes * 8) {
3957 bombout(("SSH-1 public keys were badly formatted"));
3961 s->len = (s->hostkey.bytes > s->servkey.bytes ?
3962 s->hostkey.bytes : s->servkey.bytes);
3964 s->rsabuf = snewn(s->len, unsigned char);
3967 * Verify the host key.
3971 * First format the key into a string.
3973 int len = rsastr_len(&s->hostkey);
3974 char fingerprint[100];
3975 char *keystr = snewn(len, char);
3976 rsastr_fmt(keystr, &s->hostkey);
3977 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
3979 /* First check against manually configured host keys. */
3980 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
3981 if (s->dlgret == 0) { /* did not match */
3982 bombout(("Host key did not appear in manually configured list"));
3985 } else if (s->dlgret < 0) { /* none configured; use standard handling */
3986 ssh_set_frozen(ssh, 1);
3987 s->dlgret = verify_ssh_host_key(ssh->frontend,
3988 ssh->savedhost, ssh->savedport,
3989 "rsa", keystr, fingerprint,
3990 ssh_dialog_callback, ssh);
3992 if (s->dlgret < 0) {
3996 bombout(("Unexpected data from server while waiting"
3997 " for user host key response"));
4000 } while (pktin || inlen > 0);
4001 s->dlgret = ssh->user_response;
4003 ssh_set_frozen(ssh, 0);
4005 if (s->dlgret == 0) {
4006 ssh_disconnect(ssh, "User aborted at host key verification",
4015 for (i = 0; i < 32; i++) {
4016 s->rsabuf[i] = ssh->session_key[i];
4018 s->rsabuf[i] ^= s->session_id[i];
4021 if (s->hostkey.bytes > s->servkey.bytes) {
4022 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4024 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4026 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4028 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4031 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4035 logevent("Encrypted session key");
4038 int cipher_chosen = 0, warn = 0;
4039 char *cipher_string = NULL;
4041 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4042 int next_cipher = conf_get_int_int(ssh->conf,
4043 CONF_ssh_cipherlist, i);
4044 if (next_cipher == CIPHER_WARN) {
4045 /* If/when we choose a cipher, warn about it */
4047 } else if (next_cipher == CIPHER_AES) {
4048 /* XXX Probably don't need to mention this. */
4049 logevent("AES not supported in SSH-1, skipping");
4051 switch (next_cipher) {
4052 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4053 cipher_string = "3DES"; break;
4054 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4055 cipher_string = "Blowfish"; break;
4056 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4057 cipher_string = "single-DES"; break;
4059 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4063 if (!cipher_chosen) {
4064 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4065 bombout(("Server violates SSH-1 protocol by not "
4066 "supporting 3DES encryption"));
4068 /* shouldn't happen */
4069 bombout(("No supported ciphers found"));
4073 /* Warn about chosen cipher if necessary. */
4075 ssh_set_frozen(ssh, 1);
4076 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4077 ssh_dialog_callback, ssh);
4078 if (s->dlgret < 0) {
4082 bombout(("Unexpected data from server while waiting"
4083 " for user response"));
4086 } while (pktin || inlen > 0);
4087 s->dlgret = ssh->user_response;
4089 ssh_set_frozen(ssh, 0);
4090 if (s->dlgret == 0) {
4091 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4098 switch (s->cipher_type) {
4099 case SSH_CIPHER_3DES:
4100 logevent("Using 3DES encryption");
4102 case SSH_CIPHER_DES:
4103 logevent("Using single-DES encryption");
4105 case SSH_CIPHER_BLOWFISH:
4106 logevent("Using Blowfish encryption");
4110 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4111 PKT_CHAR, s->cipher_type,
4112 PKT_DATA, cookie, 8,
4113 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4114 PKT_DATA, s->rsabuf, s->len,
4115 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4117 logevent("Trying to enable encryption...");
4121 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4122 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4124 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4125 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4126 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4128 ssh->crcda_ctx = crcda_make_context();
4129 logevent("Installing CRC compensation attack detector");
4131 if (s->servkey.modulus) {
4132 sfree(s->servkey.modulus);
4133 s->servkey.modulus = NULL;
4135 if (s->servkey.exponent) {
4136 sfree(s->servkey.exponent);
4137 s->servkey.exponent = NULL;
4139 if (s->hostkey.modulus) {
4140 sfree(s->hostkey.modulus);
4141 s->hostkey.modulus = NULL;
4143 if (s->hostkey.exponent) {
4144 sfree(s->hostkey.exponent);
4145 s->hostkey.exponent = NULL;
4149 if (pktin->type != SSH1_SMSG_SUCCESS) {
4150 bombout(("Encryption not successfully enabled"));
4154 logevent("Successfully started encryption");
4156 fflush(stdout); /* FIXME eh? */
4158 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4159 int ret; /* need not be kept over crReturn */
4160 s->cur_prompt = new_prompts(ssh->frontend);
4161 s->cur_prompt->to_server = TRUE;
4162 s->cur_prompt->name = dupstr("SSH login name");
4163 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4164 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4167 crWaitUntil(!pktin);
4168 ret = get_userpass_input(s->cur_prompt, in, inlen);
4173 * Failed to get a username. Terminate.
4175 free_prompts(s->cur_prompt);
4176 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4179 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4180 free_prompts(s->cur_prompt);
4183 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4185 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4187 if (flags & FLAG_INTERACTIVE &&
4188 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4189 c_write_str(ssh, userlog);
4190 c_write_str(ssh, "\r\n");
4198 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4199 /* We must not attempt PK auth. Pretend we've already tried it. */
4200 s->tried_publickey = s->tried_agent = 1;
4202 s->tried_publickey = s->tried_agent = 0;
4204 s->tis_auth_refused = s->ccard_auth_refused = 0;
4206 * Load the public half of any configured keyfile for later use.
4208 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4209 if (!filename_is_null(s->keyfile)) {
4211 logeventf(ssh, "Reading private key file \"%.150s\"",
4212 filename_to_str(s->keyfile));
4213 keytype = key_type(s->keyfile);
4214 if (keytype == SSH_KEYTYPE_SSH1) {
4216 if (rsakey_pubblob(s->keyfile,
4217 &s->publickey_blob, &s->publickey_bloblen,
4218 &s->publickey_comment, &error)) {
4219 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
4223 logeventf(ssh, "Unable to load private key (%s)", error);
4224 msgbuf = dupprintf("Unable to load private key file "
4225 "\"%.150s\" (%s)\r\n",
4226 filename_to_str(s->keyfile),
4228 c_write_str(ssh, msgbuf);
4230 s->publickey_blob = NULL;
4234 logeventf(ssh, "Unable to use this key file (%s)",
4235 key_type_to_str(keytype));
4236 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4238 filename_to_str(s->keyfile),
4239 key_type_to_str(keytype));
4240 c_write_str(ssh, msgbuf);
4242 s->publickey_blob = NULL;
4245 s->publickey_blob = NULL;
4247 while (pktin->type == SSH1_SMSG_FAILURE) {
4248 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4250 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4252 * Attempt RSA authentication using Pageant.
4258 logevent("Pageant is running. Requesting keys.");
4260 /* Request the keys held by the agent. */
4261 PUT_32BIT(s->request, 1);
4262 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4263 if (!agent_query(s->request, 5, &r, &s->responselen,
4264 ssh_agent_callback, ssh)) {
4268 bombout(("Unexpected data from server while waiting"
4269 " for agent response"));
4272 } while (pktin || inlen > 0);
4273 r = ssh->agent_response;
4274 s->responselen = ssh->agent_response_len;
4276 s->response = (unsigned char *) r;
4277 if (s->response && s->responselen >= 5 &&
4278 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4279 s->p = s->response + 5;
4280 s->nkeys = toint(GET_32BIT(s->p));
4282 logeventf(ssh, "Pageant reported negative key count %d",
4287 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4288 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4289 unsigned char *pkblob = s->p;
4293 do { /* do while (0) to make breaking easy */
4294 n = ssh1_read_bignum
4295 (s->p, toint(s->responselen-(s->p-s->response)),
4300 n = ssh1_read_bignum
4301 (s->p, toint(s->responselen-(s->p-s->response)),
4306 if (s->responselen - (s->p-s->response) < 4)
4308 s->commentlen = toint(GET_32BIT(s->p));
4310 if (s->commentlen < 0 ||
4311 toint(s->responselen - (s->p-s->response)) <
4314 s->commentp = (char *)s->p;
4315 s->p += s->commentlen;
4319 logevent("Pageant key list packet was truncated");
4323 if (s->publickey_blob) {
4324 if (!memcmp(pkblob, s->publickey_blob,
4325 s->publickey_bloblen)) {
4326 logeventf(ssh, "Pageant key #%d matches "
4327 "configured key file", s->keyi);
4328 s->tried_publickey = 1;
4330 /* Skip non-configured key */
4333 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4334 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4335 PKT_BIGNUM, s->key.modulus, PKT_END);
4337 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4338 logevent("Key refused");
4341 logevent("Received RSA challenge");
4342 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4343 bombout(("Server's RSA challenge was badly formatted"));
4348 char *agentreq, *q, *ret;
4351 len = 1 + 4; /* message type, bit count */
4352 len += ssh1_bignum_length(s->key.exponent);
4353 len += ssh1_bignum_length(s->key.modulus);
4354 len += ssh1_bignum_length(s->challenge);
4355 len += 16; /* session id */
4356 len += 4; /* response format */
4357 agentreq = snewn(4 + len, char);
4358 PUT_32BIT(agentreq, len);
4360 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4361 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4363 q += ssh1_write_bignum(q, s->key.exponent);
4364 q += ssh1_write_bignum(q, s->key.modulus);
4365 q += ssh1_write_bignum(q, s->challenge);
4366 memcpy(q, s->session_id, 16);
4368 PUT_32BIT(q, 1); /* response format */
4369 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4370 ssh_agent_callback, ssh)) {
4375 bombout(("Unexpected data from server"
4376 " while waiting for agent"
4380 } while (pktin || inlen > 0);
4381 vret = ssh->agent_response;
4382 retlen = ssh->agent_response_len;
4387 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4388 logevent("Sending Pageant's response");
4389 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4390 PKT_DATA, ret + 5, 16,
4394 if (pktin->type == SSH1_SMSG_SUCCESS) {
4396 ("Pageant's response accepted");
4397 if (flags & FLAG_VERBOSE) {
4398 c_write_str(ssh, "Authenticated using"
4400 c_write(ssh, s->commentp,
4402 c_write_str(ssh, "\" from agent\r\n");
4407 ("Pageant's response not accepted");
4410 ("Pageant failed to answer challenge");
4414 logevent("No reply received from Pageant");
4417 freebn(s->key.exponent);
4418 freebn(s->key.modulus);
4419 freebn(s->challenge);
4424 if (s->publickey_blob && !s->tried_publickey)
4425 logevent("Configured key file not in Pageant");
4427 logevent("Failed to get reply from Pageant");
4432 if (s->publickey_blob && !s->tried_publickey) {
4434 * Try public key authentication with the specified
4437 int got_passphrase; /* need not be kept over crReturn */
4438 if (flags & FLAG_VERBOSE)
4439 c_write_str(ssh, "Trying public key authentication.\r\n");
4440 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4441 logeventf(ssh, "Trying public key \"%s\"",
4442 filename_to_str(s->keyfile));
4443 s->tried_publickey = 1;
4444 got_passphrase = FALSE;
4445 while (!got_passphrase) {
4447 * Get a passphrase, if necessary.
4449 char *passphrase = NULL; /* only written after crReturn */
4451 if (!s->publickey_encrypted) {
4452 if (flags & FLAG_VERBOSE)
4453 c_write_str(ssh, "No passphrase required.\r\n");
4456 int ret; /* need not be kept over crReturn */
4457 s->cur_prompt = new_prompts(ssh->frontend);
4458 s->cur_prompt->to_server = FALSE;
4459 s->cur_prompt->name = dupstr("SSH key passphrase");
4460 add_prompt(s->cur_prompt,
4461 dupprintf("Passphrase for key \"%.100s\": ",
4462 s->publickey_comment), FALSE);
4463 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4466 crWaitUntil(!pktin);
4467 ret = get_userpass_input(s->cur_prompt, in, inlen);
4471 /* Failed to get a passphrase. Terminate. */
4472 free_prompts(s->cur_prompt);
4473 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4477 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4478 free_prompts(s->cur_prompt);
4481 * Try decrypting key with passphrase.
4483 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4484 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4487 smemclr(passphrase, strlen(passphrase));
4491 /* Correct passphrase. */
4492 got_passphrase = TRUE;
4493 } else if (ret == 0) {
4494 c_write_str(ssh, "Couldn't load private key from ");
4495 c_write_str(ssh, filename_to_str(s->keyfile));
4496 c_write_str(ssh, " (");
4497 c_write_str(ssh, error);
4498 c_write_str(ssh, ").\r\n");
4499 got_passphrase = FALSE;
4500 break; /* go and try something else */
4501 } else if (ret == -1) {
4502 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4503 got_passphrase = FALSE;
4506 assert(0 && "unexpected return from loadrsakey()");
4507 got_passphrase = FALSE; /* placate optimisers */
4511 if (got_passphrase) {
4514 * Send a public key attempt.
4516 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4517 PKT_BIGNUM, s->key.modulus, PKT_END);
4520 if (pktin->type == SSH1_SMSG_FAILURE) {
4521 c_write_str(ssh, "Server refused our public key.\r\n");
4522 continue; /* go and try something else */
4524 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4525 bombout(("Bizarre response to offer of public key"));
4531 unsigned char buffer[32];
4532 Bignum challenge, response;
4534 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4535 bombout(("Server's RSA challenge was badly formatted"));
4538 response = rsadecrypt(challenge, &s->key);
4539 freebn(s->key.private_exponent);/* burn the evidence */
4541 for (i = 0; i < 32; i++) {
4542 buffer[i] = bignum_byte(response, 31 - i);
4546 MD5Update(&md5c, buffer, 32);
4547 MD5Update(&md5c, s->session_id, 16);
4548 MD5Final(buffer, &md5c);
4550 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4551 PKT_DATA, buffer, 16, PKT_END);
4558 if (pktin->type == SSH1_SMSG_FAILURE) {
4559 if (flags & FLAG_VERBOSE)
4560 c_write_str(ssh, "Failed to authenticate with"
4561 " our public key.\r\n");
4562 continue; /* go and try something else */
4563 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4564 bombout(("Bizarre response to RSA authentication response"));
4568 break; /* we're through! */
4574 * Otherwise, try various forms of password-like authentication.
4576 s->cur_prompt = new_prompts(ssh->frontend);
4578 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4579 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4580 !s->tis_auth_refused) {
4581 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4582 logevent("Requested TIS authentication");
4583 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4585 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4586 logevent("TIS authentication declined");
4587 if (flags & FLAG_INTERACTIVE)
4588 c_write_str(ssh, "TIS authentication refused.\r\n");
4589 s->tis_auth_refused = 1;
4594 char *instr_suf, *prompt;
4596 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4598 bombout(("TIS challenge packet was badly formed"));
4601 logevent("Received TIS challenge");
4602 s->cur_prompt->to_server = TRUE;
4603 s->cur_prompt->name = dupstr("SSH TIS authentication");
4604 /* Prompt heuristic comes from OpenSSH */
4605 if (memchr(challenge, '\n', challengelen)) {
4606 instr_suf = dupstr("");
4607 prompt = dupprintf("%.*s", challengelen, challenge);
4609 instr_suf = dupprintf("%.*s", challengelen, challenge);
4610 prompt = dupstr("Response: ");
4612 s->cur_prompt->instruction =
4613 dupprintf("Using TIS authentication.%s%s",
4614 (*instr_suf) ? "\n" : "",
4616 s->cur_prompt->instr_reqd = TRUE;
4617 add_prompt(s->cur_prompt, prompt, FALSE);
4621 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4622 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4623 !s->ccard_auth_refused) {
4624 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4625 logevent("Requested CryptoCard authentication");
4626 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4628 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4629 logevent("CryptoCard authentication declined");
4630 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4631 s->ccard_auth_refused = 1;
4636 char *instr_suf, *prompt;
4638 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4640 bombout(("CryptoCard challenge packet was badly formed"));
4643 logevent("Received CryptoCard challenge");
4644 s->cur_prompt->to_server = TRUE;
4645 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4646 s->cur_prompt->name_reqd = FALSE;
4647 /* Prompt heuristic comes from OpenSSH */
4648 if (memchr(challenge, '\n', challengelen)) {
4649 instr_suf = dupstr("");
4650 prompt = dupprintf("%.*s", challengelen, challenge);
4652 instr_suf = dupprintf("%.*s", challengelen, challenge);
4653 prompt = dupstr("Response: ");
4655 s->cur_prompt->instruction =
4656 dupprintf("Using CryptoCard authentication.%s%s",
4657 (*instr_suf) ? "\n" : "",
4659 s->cur_prompt->instr_reqd = TRUE;
4660 add_prompt(s->cur_prompt, prompt, FALSE);
4664 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4665 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4666 bombout(("No supported authentication methods available"));
4669 s->cur_prompt->to_server = TRUE;
4670 s->cur_prompt->name = dupstr("SSH password");
4671 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4672 ssh->username, ssh->savedhost),
4677 * Show password prompt, having first obtained it via a TIS
4678 * or CryptoCard exchange if we're doing TIS or CryptoCard
4682 int ret; /* need not be kept over crReturn */
4683 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4686 crWaitUntil(!pktin);
4687 ret = get_userpass_input(s->cur_prompt, in, inlen);
4692 * Failed to get a password (for example
4693 * because one was supplied on the command line
4694 * which has already failed to work). Terminate.
4696 free_prompts(s->cur_prompt);
4697 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4702 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4704 * Defence against traffic analysis: we send a
4705 * whole bunch of packets containing strings of
4706 * different lengths. One of these strings is the
4707 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4708 * The others are all random data in
4709 * SSH1_MSG_IGNORE packets. This way a passive
4710 * listener can't tell which is the password, and
4711 * hence can't deduce the password length.
4713 * Anybody with a password length greater than 16
4714 * bytes is going to have enough entropy in their
4715 * password that a listener won't find it _that_
4716 * much help to know how long it is. So what we'll
4719 * - if password length < 16, we send 15 packets
4720 * containing string lengths 1 through 15
4722 * - otherwise, we let N be the nearest multiple
4723 * of 8 below the password length, and send 8
4724 * packets containing string lengths N through
4725 * N+7. This won't obscure the order of
4726 * magnitude of the password length, but it will
4727 * introduce a bit of extra uncertainty.
4729 * A few servers can't deal with SSH1_MSG_IGNORE, at
4730 * least in this context. For these servers, we need
4731 * an alternative defence. We make use of the fact
4732 * that the password is interpreted as a C string:
4733 * so we can append a NUL, then some random data.
4735 * A few servers can deal with neither SSH1_MSG_IGNORE
4736 * here _nor_ a padded password string.
4737 * For these servers we are left with no defences
4738 * against password length sniffing.
4740 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4741 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4743 * The server can deal with SSH1_MSG_IGNORE, so
4744 * we can use the primary defence.
4746 int bottom, top, pwlen, i;
4749 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4751 bottom = 0; /* zero length passwords are OK! :-) */
4754 bottom = pwlen & ~7;
4758 assert(pwlen >= bottom && pwlen <= top);
4760 randomstr = snewn(top + 1, char);
4762 for (i = bottom; i <= top; i++) {
4764 defer_packet(ssh, s->pwpkt_type,
4765 PKT_STR,s->cur_prompt->prompts[0]->result,
4768 for (j = 0; j < i; j++) {
4770 randomstr[j] = random_byte();
4771 } while (randomstr[j] == '\0');
4773 randomstr[i] = '\0';
4774 defer_packet(ssh, SSH1_MSG_IGNORE,
4775 PKT_STR, randomstr, PKT_END);
4778 logevent("Sending password with camouflage packets");
4779 ssh_pkt_defersend(ssh);
4782 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4784 * The server can't deal with SSH1_MSG_IGNORE
4785 * but can deal with padded passwords, so we
4786 * can use the secondary defence.
4792 len = strlen(s->cur_prompt->prompts[0]->result);
4793 if (len < sizeof(string)) {
4795 strcpy(string, s->cur_prompt->prompts[0]->result);
4796 len++; /* cover the zero byte */
4797 while (len < sizeof(string)) {
4798 string[len++] = (char) random_byte();
4801 ss = s->cur_prompt->prompts[0]->result;
4803 logevent("Sending length-padded password");
4804 send_packet(ssh, s->pwpkt_type,
4805 PKT_INT, len, PKT_DATA, ss, len,
4809 * The server is believed unable to cope with
4810 * any of our password camouflage methods.
4813 len = strlen(s->cur_prompt->prompts[0]->result);
4814 logevent("Sending unpadded password");
4815 send_packet(ssh, s->pwpkt_type,
4817 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4821 send_packet(ssh, s->pwpkt_type,
4822 PKT_STR, s->cur_prompt->prompts[0]->result,
4825 logevent("Sent password");
4826 free_prompts(s->cur_prompt);
4828 if (pktin->type == SSH1_SMSG_FAILURE) {
4829 if (flags & FLAG_VERBOSE)
4830 c_write_str(ssh, "Access denied\r\n");
4831 logevent("Authentication refused");
4832 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4833 bombout(("Strange packet received, type %d", pktin->type));
4839 if (s->publickey_blob) {
4840 sfree(s->publickey_blob);
4841 sfree(s->publickey_comment);
4844 logevent("Authentication successful");
4849 static void ssh_channel_try_eof(struct ssh_channel *c)
4852 assert(c->pending_eof); /* precondition for calling us */
4854 return; /* can't close: not even opened yet */
4855 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4856 return; /* can't send EOF: pending outgoing data */
4858 c->pending_eof = FALSE; /* we're about to send it */
4859 if (ssh->version == 1) {
4860 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4862 c->closes |= CLOSES_SENT_EOF;
4864 struct Packet *pktout;
4865 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4866 ssh2_pkt_adduint32(pktout, c->remoteid);
4867 ssh2_pkt_send(ssh, pktout);
4868 c->closes |= CLOSES_SENT_EOF;
4869 ssh2_channel_check_close(c);
4873 Conf *sshfwd_get_conf(struct ssh_channel *c)
4879 void sshfwd_write_eof(struct ssh_channel *c)
4883 if (ssh->state == SSH_STATE_CLOSED)
4886 if (c->closes & CLOSES_SENT_EOF)
4889 c->pending_eof = TRUE;
4890 ssh_channel_try_eof(c);
4893 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4897 if (ssh->state == SSH_STATE_CLOSED)
4902 x11_close(c->u.x11.xconn);
4903 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4907 case CHAN_SOCKDATA_DORMANT:
4908 pfd_close(c->u.pfd.pf);
4909 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4912 c->type = CHAN_ZOMBIE;
4913 c->pending_eof = FALSE; /* this will confuse a zombie channel */
4915 ssh2_channel_check_close(c);
4918 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4922 if (ssh->state == SSH_STATE_CLOSED)
4925 if (ssh->version == 1) {
4926 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4927 PKT_INT, c->remoteid,
4928 PKT_INT, len, PKT_DATA, buf, len,
4931 * In SSH-1 we can return 0 here - implying that forwarded
4932 * connections are never individually throttled - because
4933 * the only circumstance that can cause throttling will be
4934 * the whole SSH connection backing up, in which case
4935 * _everything_ will be throttled as a whole.
4939 ssh2_add_channel_data(c, buf, len);
4940 return ssh2_try_send(c);
4944 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4949 if (ssh->state == SSH_STATE_CLOSED)
4952 if (ssh->version == 1) {
4953 buflimit = SSH1_BUFFER_LIMIT;
4955 buflimit = c->v.v2.locmaxwin;
4956 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4958 if (c->throttling_conn && bufsize <= buflimit) {
4959 c->throttling_conn = 0;
4960 ssh_throttle_conn(ssh, -1);
4964 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4966 struct queued_handler *qh = ssh->qhead;
4970 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4973 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4974 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4977 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4978 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4982 ssh->qhead = qh->next;
4984 if (ssh->qhead->msg1 > 0) {
4985 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4986 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4988 if (ssh->qhead->msg2 > 0) {
4989 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4990 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4993 ssh->qhead = ssh->qtail = NULL;
4996 qh->handler(ssh, pktin, qh->ctx);
5001 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5002 chandler_fn_t handler, void *ctx)
5004 struct queued_handler *qh;
5006 qh = snew(struct queued_handler);
5009 qh->handler = handler;
5013 if (ssh->qtail == NULL) {
5017 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5018 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5021 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5022 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5025 ssh->qtail->next = qh;
5030 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5032 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5034 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5035 SSH2_MSG_REQUEST_SUCCESS)) {
5036 logeventf(ssh, "Remote port forwarding from %s enabled",
5039 logeventf(ssh, "Remote port forwarding from %s refused",
5042 rpf = del234(ssh->rportfwds, pf);
5044 pf->pfrec->remote = NULL;
5049 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5052 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5055 pf->share_ctx = share_ctx;
5056 pf->shost = dupstr(shost);
5058 pf->sportdesc = NULL;
5059 if (!ssh->rportfwds) {
5060 assert(ssh->version == 2);
5061 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5063 if (add234(ssh->rportfwds, pf) != pf) {
5071 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5074 share_got_pkt_from_server(ctx, pktin->type,
5075 pktin->body, pktin->length);
5078 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5080 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5081 ssh_sharing_global_request_response, share_ctx);
5084 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5086 struct ssh_portfwd *epf;
5090 if (!ssh->portfwds) {
5091 ssh->portfwds = newtree234(ssh_portcmp);
5094 * Go through the existing port forwardings and tag them
5095 * with status==DESTROY. Any that we want to keep will be
5096 * re-enabled (status==KEEP) as we go through the
5097 * configuration and find out which bits are the same as
5100 struct ssh_portfwd *epf;
5102 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5103 epf->status = DESTROY;
5106 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5108 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5109 char *kp, *kp2, *vp, *vp2;
5110 char address_family, type;
5111 int sport,dport,sserv,dserv;
5112 char *sports, *dports, *saddr, *host;
5116 address_family = 'A';
5118 if (*kp == 'A' || *kp == '4' || *kp == '6')
5119 address_family = *kp++;
5120 if (*kp == 'L' || *kp == 'R')
5123 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5125 * There's a colon in the middle of the source port
5126 * string, which means that the part before it is
5127 * actually a source address.
5129 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5130 saddr = host_strduptrim(saddr_tmp);
5137 sport = atoi(sports);
5141 sport = net_service_lookup(sports);
5143 logeventf(ssh, "Service lookup failed for source"
5144 " port \"%s\"", sports);
5148 if (type == 'L' && !strcmp(val, "D")) {
5149 /* dynamic forwarding */
5156 /* ordinary forwarding */
5158 vp2 = vp + host_strcspn(vp, ":");
5159 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5163 dport = atoi(dports);
5167 dport = net_service_lookup(dports);
5169 logeventf(ssh, "Service lookup failed for destination"
5170 " port \"%s\"", dports);
5175 if (sport && dport) {
5176 /* Set up a description of the source port. */
5177 struct ssh_portfwd *pfrec, *epfrec;
5179 pfrec = snew(struct ssh_portfwd);
5181 pfrec->saddr = saddr;
5182 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5183 pfrec->sport = sport;
5184 pfrec->daddr = host;
5185 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5186 pfrec->dport = dport;
5187 pfrec->local = NULL;
5188 pfrec->remote = NULL;
5189 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5190 address_family == '6' ? ADDRTYPE_IPV6 :
5193 epfrec = add234(ssh->portfwds, pfrec);
5194 if (epfrec != pfrec) {
5195 if (epfrec->status == DESTROY) {
5197 * We already have a port forwarding up and running
5198 * with precisely these parameters. Hence, no need
5199 * to do anything; simply re-tag the existing one
5202 epfrec->status = KEEP;
5205 * Anything else indicates that there was a duplicate
5206 * in our input, which we'll silently ignore.
5208 free_portfwd(pfrec);
5210 pfrec->status = CREATE;
5219 * Now go through and destroy any port forwardings which were
5222 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5223 if (epf->status == DESTROY) {
5226 message = dupprintf("%s port forwarding from %s%s%d",
5227 epf->type == 'L' ? "local" :
5228 epf->type == 'R' ? "remote" : "dynamic",
5229 epf->saddr ? epf->saddr : "",
5230 epf->saddr ? ":" : "",
5233 if (epf->type != 'D') {
5234 char *msg2 = dupprintf("%s to %s:%d", message,
5235 epf->daddr, epf->dport);
5240 logeventf(ssh, "Cancelling %s", message);
5243 /* epf->remote or epf->local may be NULL if setting up a
5244 * forwarding failed. */
5246 struct ssh_rportfwd *rpf = epf->remote;
5247 struct Packet *pktout;
5250 * Cancel the port forwarding at the server
5253 if (ssh->version == 1) {
5255 * We cannot cancel listening ports on the
5256 * server side in SSH-1! There's no message
5257 * to support it. Instead, we simply remove
5258 * the rportfwd record from the local end
5259 * so that any connections the server tries
5260 * to make on it are rejected.
5263 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5264 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5265 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5267 ssh2_pkt_addstring(pktout, epf->saddr);
5268 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5269 /* XXX: rport_acceptall may not represent
5270 * what was used to open the original connection,
5271 * since it's reconfigurable. */
5272 ssh2_pkt_addstring(pktout, "");
5274 ssh2_pkt_addstring(pktout, "localhost");
5276 ssh2_pkt_adduint32(pktout, epf->sport);
5277 ssh2_pkt_send(ssh, pktout);
5280 del234(ssh->rportfwds, rpf);
5282 } else if (epf->local) {
5283 pfl_terminate(epf->local);
5286 delpos234(ssh->portfwds, i);
5288 i--; /* so we don't skip one in the list */
5292 * And finally, set up any new port forwardings (status==CREATE).
5294 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5295 if (epf->status == CREATE) {
5296 char *sportdesc, *dportdesc;
5297 sportdesc = dupprintf("%s%s%s%s%d%s",
5298 epf->saddr ? epf->saddr : "",
5299 epf->saddr ? ":" : "",
5300 epf->sserv ? epf->sserv : "",
5301 epf->sserv ? "(" : "",
5303 epf->sserv ? ")" : "");
5304 if (epf->type == 'D') {
5307 dportdesc = dupprintf("%s:%s%s%d%s",
5309 epf->dserv ? epf->dserv : "",
5310 epf->dserv ? "(" : "",
5312 epf->dserv ? ")" : "");
5315 if (epf->type == 'L') {
5316 char *err = pfl_listen(epf->daddr, epf->dport,
5317 epf->saddr, epf->sport,
5318 ssh, conf, &epf->local,
5319 epf->addressfamily);
5321 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5322 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5323 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5324 sportdesc, dportdesc,
5325 err ? " failed: " : "", err ? err : "");
5328 } else if (epf->type == 'D') {
5329 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5330 ssh, conf, &epf->local,
5331 epf->addressfamily);
5333 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5334 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5335 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5337 err ? " failed: " : "", err ? err : "");
5342 struct ssh_rportfwd *pf;
5345 * Ensure the remote port forwardings tree exists.
5347 if (!ssh->rportfwds) {
5348 if (ssh->version == 1)
5349 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5351 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5354 pf = snew(struct ssh_rportfwd);
5355 pf->share_ctx = NULL;
5356 pf->dhost = dupstr(epf->daddr);
5357 pf->dport = epf->dport;
5359 pf->shost = dupstr(epf->saddr);
5360 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5361 pf->shost = dupstr("");
5363 pf->shost = dupstr("localhost");
5365 pf->sport = epf->sport;
5366 if (add234(ssh->rportfwds, pf) != pf) {
5367 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5368 epf->daddr, epf->dport);
5371 logeventf(ssh, "Requesting remote port %s"
5372 " forward to %s", sportdesc, dportdesc);
5374 pf->sportdesc = sportdesc;
5379 if (ssh->version == 1) {
5380 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5381 PKT_INT, epf->sport,
5382 PKT_STR, epf->daddr,
5383 PKT_INT, epf->dport,
5385 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5387 ssh_rportfwd_succfail, pf);
5389 struct Packet *pktout;
5390 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5391 ssh2_pkt_addstring(pktout, "tcpip-forward");
5392 ssh2_pkt_addbool(pktout, 1);/* want reply */
5393 ssh2_pkt_addstring(pktout, pf->shost);
5394 ssh2_pkt_adduint32(pktout, pf->sport);
5395 ssh2_pkt_send(ssh, pktout);
5397 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5398 SSH2_MSG_REQUEST_FAILURE,
5399 ssh_rportfwd_succfail, pf);
5408 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5411 int stringlen, bufsize;
5413 ssh_pkt_getstring(pktin, &string, &stringlen);
5414 if (string == NULL) {
5415 bombout(("Incoming terminal data packet was badly formed"));
5419 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5421 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5422 ssh->v1_stdout_throttling = 1;
5423 ssh_throttle_conn(ssh, +1);
5427 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5429 /* Remote side is trying to open a channel to talk to our
5430 * X-Server. Give them back a local channel number. */
5431 struct ssh_channel *c;
5432 int remoteid = ssh_pkt_getuint32(pktin);
5434 logevent("Received X11 connect request");
5435 /* Refuse if X11 forwarding is disabled. */
5436 if (!ssh->X11_fwd_enabled) {
5437 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5438 PKT_INT, remoteid, PKT_END);
5439 logevent("Rejected X11 connect request");
5441 c = snew(struct ssh_channel);
5444 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5445 c->remoteid = remoteid;
5446 c->halfopen = FALSE;
5447 c->localid = alloc_channel_id(ssh);
5449 c->pending_eof = FALSE;
5450 c->throttling_conn = 0;
5451 c->type = CHAN_X11; /* identify channel type */
5452 add234(ssh->channels, c);
5453 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5454 PKT_INT, c->remoteid, PKT_INT,
5455 c->localid, PKT_END);
5456 logevent("Opened X11 forward channel");
5460 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5462 /* Remote side is trying to open a channel to talk to our
5463 * agent. Give them back a local channel number. */
5464 struct ssh_channel *c;
5465 int remoteid = ssh_pkt_getuint32(pktin);
5467 /* Refuse if agent forwarding is disabled. */
5468 if (!ssh->agentfwd_enabled) {
5469 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5470 PKT_INT, remoteid, PKT_END);
5472 c = snew(struct ssh_channel);
5474 c->remoteid = remoteid;
5475 c->halfopen = FALSE;
5476 c->localid = alloc_channel_id(ssh);
5478 c->pending_eof = FALSE;
5479 c->throttling_conn = 0;
5480 c->type = CHAN_AGENT; /* identify channel type */
5481 c->u.a.lensofar = 0;
5482 c->u.a.message = NULL;
5483 c->u.a.outstanding_requests = 0;
5484 add234(ssh->channels, c);
5485 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5486 PKT_INT, c->remoteid, PKT_INT, c->localid,
5491 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5493 /* Remote side is trying to open a channel to talk to a
5494 * forwarded port. Give them back a local channel number. */
5495 struct ssh_rportfwd pf, *pfp;
5501 remoteid = ssh_pkt_getuint32(pktin);
5502 ssh_pkt_getstring(pktin, &host, &hostsize);
5503 port = ssh_pkt_getuint32(pktin);
5505 pf.dhost = dupprintf("%.*s", hostsize, host);
5507 pfp = find234(ssh->rportfwds, &pf, NULL);
5510 logeventf(ssh, "Rejected remote port open request for %s:%d",
5512 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5513 PKT_INT, remoteid, PKT_END);
5515 struct ssh_channel *c = snew(struct ssh_channel);
5518 logeventf(ssh, "Received remote port open request for %s:%d",
5520 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5521 c, ssh->conf, pfp->pfrec->addressfamily);
5523 logeventf(ssh, "Port open failed: %s", err);
5526 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5527 PKT_INT, remoteid, PKT_END);
5529 c->remoteid = remoteid;
5530 c->halfopen = FALSE;
5531 c->localid = alloc_channel_id(ssh);
5533 c->pending_eof = FALSE;
5534 c->throttling_conn = 0;
5535 c->type = CHAN_SOCKDATA; /* identify channel type */
5536 add234(ssh->channels, c);
5537 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5538 PKT_INT, c->remoteid, PKT_INT,
5539 c->localid, PKT_END);
5540 logevent("Forwarded port opened successfully");
5547 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5549 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5550 unsigned int localid = ssh_pkt_getuint32(pktin);
5551 struct ssh_channel *c;
5553 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5554 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5555 c->remoteid = localid;
5556 c->halfopen = FALSE;
5557 c->type = CHAN_SOCKDATA;
5558 c->throttling_conn = 0;
5559 pfd_confirm(c->u.pfd.pf);
5562 if (c && c->pending_eof) {
5564 * We have a pending close on this channel,
5565 * which we decided on before the server acked
5566 * the channel open. So now we know the
5567 * remoteid, we can close it again.
5569 ssh_channel_try_eof(c);
5573 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5575 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5576 struct ssh_channel *c;
5578 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5579 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5580 logevent("Forwarded connection refused by server");
5581 pfd_close(c->u.pfd.pf);
5582 del234(ssh->channels, c);
5587 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5589 /* Remote side closes a channel. */
5590 unsigned i = ssh_pkt_getuint32(pktin);
5591 struct ssh_channel *c;
5592 c = find234(ssh->channels, &i, ssh_channelfind);
5593 if (c && !c->halfopen) {
5595 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5596 !(c->closes & CLOSES_RCVD_EOF)) {
5598 * Received CHANNEL_CLOSE, which we translate into
5601 int send_close = FALSE;
5603 c->closes |= CLOSES_RCVD_EOF;
5608 x11_send_eof(c->u.x11.xconn);
5614 pfd_send_eof(c->u.pfd.pf);
5623 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5624 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5626 c->closes |= CLOSES_SENT_EOF;
5630 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5631 !(c->closes & CLOSES_RCVD_CLOSE)) {
5633 if (!(c->closes & CLOSES_SENT_EOF)) {
5634 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5635 " for which we never sent CHANNEL_CLOSE\n", i));
5638 c->closes |= CLOSES_RCVD_CLOSE;
5641 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5642 !(c->closes & CLOSES_SENT_CLOSE)) {
5643 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5644 PKT_INT, c->remoteid, PKT_END);
5645 c->closes |= CLOSES_SENT_CLOSE;
5648 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5649 ssh_channel_destroy(c);
5651 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5652 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5653 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5658 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5660 /* Data sent down one of our channels. */
5661 int i = ssh_pkt_getuint32(pktin);
5664 struct ssh_channel *c;
5666 ssh_pkt_getstring(pktin, &p, &len);
5668 c = find234(ssh->channels, &i, ssh_channelfind);
5673 bufsize = x11_send(c->u.x11.xconn, p, len);
5676 bufsize = pfd_send(c->u.pfd.pf, p, len);
5679 /* Data for an agent message. Buffer it. */
5681 if (c->u.a.lensofar < 4) {
5682 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5683 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5687 c->u.a.lensofar += l;
5689 if (c->u.a.lensofar == 4) {
5691 4 + GET_32BIT(c->u.a.msglen);
5692 c->u.a.message = snewn(c->u.a.totallen,
5694 memcpy(c->u.a.message, c->u.a.msglen, 4);
5696 if (c->u.a.lensofar >= 4 && len > 0) {
5698 min(c->u.a.totallen - c->u.a.lensofar,
5700 memcpy(c->u.a.message + c->u.a.lensofar, p,
5704 c->u.a.lensofar += l;
5706 if (c->u.a.lensofar == c->u.a.totallen) {
5709 c->u.a.outstanding_requests++;
5710 if (agent_query(c->u.a.message,
5713 ssh_agentf_callback, c))
5714 ssh_agentf_callback(c, reply, replylen);
5715 sfree(c->u.a.message);
5716 c->u.a.lensofar = 0;
5719 bufsize = 0; /* agent channels never back up */
5722 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5723 c->throttling_conn = 1;
5724 ssh_throttle_conn(ssh, +1);
5729 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5731 ssh->exitcode = ssh_pkt_getuint32(pktin);
5732 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5733 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5735 * In case `helpful' firewalls or proxies tack
5736 * extra human-readable text on the end of the
5737 * session which we might mistake for another
5738 * encrypted packet, we close the session once
5739 * we've sent EXIT_CONFIRMATION.
5741 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5744 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5745 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5747 struct Packet *pktout = (struct Packet *)data;
5749 unsigned int arg = 0;
5750 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5751 if (i == lenof(ssh_ttymodes)) return;
5752 switch (ssh_ttymodes[i].type) {
5754 arg = ssh_tty_parse_specchar(val);
5757 arg = ssh_tty_parse_boolean(val);
5760 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5761 ssh2_pkt_addbyte(pktout, arg);
5764 int ssh_agent_forwarding_permitted(Ssh ssh)
5766 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5769 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5770 struct Packet *pktin)
5772 crBegin(ssh->do_ssh1_connection_crstate);
5774 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5775 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5776 ssh1_smsg_stdout_stderr_data;
5778 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5779 ssh1_msg_channel_open_confirmation;
5780 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5781 ssh1_msg_channel_open_failure;
5782 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5783 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5784 ssh1_msg_channel_close;
5785 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5786 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5788 if (ssh_agent_forwarding_permitted(ssh)) {
5789 logevent("Requesting agent forwarding");
5790 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5794 if (pktin->type != SSH1_SMSG_SUCCESS
5795 && pktin->type != SSH1_SMSG_FAILURE) {
5796 bombout(("Protocol confusion"));
5798 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5799 logevent("Agent forwarding refused");
5801 logevent("Agent forwarding enabled");
5802 ssh->agentfwd_enabled = TRUE;
5803 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5807 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5809 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5811 if (!ssh->x11disp) {
5812 /* FIXME: return an error message from x11_setup_display */
5813 logevent("X11 forwarding not enabled: unable to"
5814 " initialise X display");
5816 ssh->x11auth = x11_invent_fake_auth
5817 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5818 ssh->x11auth->disp = ssh->x11disp;
5820 logevent("Requesting X11 forwarding");
5821 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5822 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5823 PKT_STR, ssh->x11auth->protoname,
5824 PKT_STR, ssh->x11auth->datastring,
5825 PKT_INT, ssh->x11disp->screennum,
5828 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5829 PKT_STR, ssh->x11auth->protoname,
5830 PKT_STR, ssh->x11auth->datastring,
5836 if (pktin->type != SSH1_SMSG_SUCCESS
5837 && pktin->type != SSH1_SMSG_FAILURE) {
5838 bombout(("Protocol confusion"));
5840 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5841 logevent("X11 forwarding refused");
5843 logevent("X11 forwarding enabled");
5844 ssh->X11_fwd_enabled = TRUE;
5845 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5850 ssh_setup_portfwd(ssh, ssh->conf);
5851 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5853 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5855 /* Unpick the terminal-speed string. */
5856 /* XXX perhaps we should allow no speeds to be sent. */
5857 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5858 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5859 /* Send the pty request. */
5860 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5861 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5862 ssh_pkt_adduint32(pkt, ssh->term_height);
5863 ssh_pkt_adduint32(pkt, ssh->term_width);
5864 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5865 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5866 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5867 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5868 ssh_pkt_adduint32(pkt, ssh->ispeed);
5869 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5870 ssh_pkt_adduint32(pkt, ssh->ospeed);
5871 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5873 ssh->state = SSH_STATE_INTERMED;
5877 if (pktin->type != SSH1_SMSG_SUCCESS
5878 && pktin->type != SSH1_SMSG_FAILURE) {
5879 bombout(("Protocol confusion"));
5881 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5882 c_write_str(ssh, "Server refused to allocate pty\r\n");
5883 ssh->editing = ssh->echoing = 1;
5885 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5886 ssh->ospeed, ssh->ispeed);
5887 ssh->got_pty = TRUE;
5890 ssh->editing = ssh->echoing = 1;
5893 if (conf_get_int(ssh->conf, CONF_compression)) {
5894 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5898 if (pktin->type != SSH1_SMSG_SUCCESS
5899 && pktin->type != SSH1_SMSG_FAILURE) {
5900 bombout(("Protocol confusion"));
5902 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5903 c_write_str(ssh, "Server refused to compress\r\n");
5905 logevent("Started compression");
5906 ssh->v1_compressing = TRUE;
5907 ssh->cs_comp_ctx = zlib_compress_init();
5908 logevent("Initialised zlib (RFC1950) compression");
5909 ssh->sc_comp_ctx = zlib_decompress_init();
5910 logevent("Initialised zlib (RFC1950) decompression");
5914 * Start the shell or command.
5916 * Special case: if the first-choice command is an SSH-2
5917 * subsystem (hence not usable here) and the second choice
5918 * exists, we fall straight back to that.
5921 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5923 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5924 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5925 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5926 ssh->fallback_cmd = TRUE;
5929 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5931 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5932 logevent("Started session");
5935 ssh->state = SSH_STATE_SESSION;
5936 if (ssh->size_needed)
5937 ssh_size(ssh, ssh->term_width, ssh->term_height);
5938 if (ssh->eof_needed)
5939 ssh_special(ssh, TS_EOF);
5942 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
5944 ssh->channels = newtree234(ssh_channelcmp);
5948 * By this point, most incoming packets are already being
5949 * handled by the dispatch table, and we need only pay
5950 * attention to the unusual ones.
5955 if (pktin->type == SSH1_SMSG_SUCCESS) {
5956 /* may be from EXEC_SHELL on some servers */
5957 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5958 /* may be from EXEC_SHELL on some servers
5959 * if no pty is available or in other odd cases. Ignore */
5961 bombout(("Strange packet received: type %d", pktin->type));
5966 int len = min(inlen, 512);
5967 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5968 PKT_INT, len, PKT_DATA, in, len,
5980 * Handle the top-level SSH-2 protocol.
5982 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5987 ssh_pkt_getstring(pktin, &msg, &msglen);
5988 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5991 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5993 /* log reason code in disconnect message */
5997 ssh_pkt_getstring(pktin, &msg, &msglen);
5998 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
6001 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6003 /* Do nothing, because we're ignoring it! Duhh. */
6006 static void ssh1_protocol_setup(Ssh ssh)
6011 * Most messages are handled by the coroutines.
6013 for (i = 0; i < 256; i++)
6014 ssh->packet_dispatch[i] = NULL;
6017 * These special message types we install handlers for.
6019 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6020 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6021 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6024 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
6025 struct Packet *pktin)
6027 unsigned char *in=(unsigned char*)vin;
6028 if (ssh->state == SSH_STATE_CLOSED)
6031 if (pktin && ssh->packet_dispatch[pktin->type]) {
6032 ssh->packet_dispatch[pktin->type](ssh, pktin);
6036 if (!ssh->protocol_initial_phase_done) {
6037 if (do_ssh1_login(ssh, in, inlen, pktin))
6038 ssh->protocol_initial_phase_done = TRUE;
6043 do_ssh1_connection(ssh, in, inlen, pktin);
6047 * Utility routine for decoding comma-separated strings in KEXINIT.
6049 static int in_commasep_string(char const *needle, char const *haystack,
6053 if (!needle || !haystack) /* protect against null pointers */
6055 needlen = strlen(needle);
6058 * Is it at the start of the string?
6060 if (haylen >= needlen && /* haystack is long enough */
6061 !memcmp(needle, haystack, needlen) && /* initial match */
6062 (haylen == needlen || haystack[needlen] == ',')
6063 /* either , or EOS follows */
6067 * If not, search for the next comma and resume after that.
6068 * If no comma found, terminate.
6070 while (haylen > 0 && *haystack != ',')
6071 haylen--, haystack++;
6074 haylen--, haystack++; /* skip over comma itself */
6079 * Similar routine for checking whether we have the first string in a list.
6081 static int first_in_commasep_string(char const *needle, char const *haystack,
6085 if (!needle || !haystack) /* protect against null pointers */
6087 needlen = strlen(needle);
6089 * Is it at the start of the string?
6091 if (haylen >= needlen && /* haystack is long enough */
6092 !memcmp(needle, haystack, needlen) && /* initial match */
6093 (haylen == needlen || haystack[needlen] == ',')
6094 /* either , or EOS follows */
6101 * Add a value to the comma-separated string at the end of the packet.
6102 * If the value is already in the string, don't bother adding it again.
6104 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6106 if (in_commasep_string(data, (char *)pkt->data + pkt->savedpos,
6107 pkt->length - pkt->savedpos)) return;
6108 if (pkt->length - pkt->savedpos > 0)
6109 ssh_pkt_addstring_str(pkt, ",");
6110 ssh_pkt_addstring_str(pkt, data);
6115 * SSH-2 key creation method.
6116 * (Currently assumes 2 lots of any hash are sufficient to generate
6117 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
6119 #define SSH2_MKKEY_ITERS (2)
6120 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
6121 unsigned char *keyspace)
6123 const struct ssh_hash *h = ssh->kex->hash;
6125 /* First hlen bytes. */
6127 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6128 hash_mpint(h, s, K);
6129 h->bytes(s, H, h->hlen);
6130 h->bytes(s, &chr, 1);
6131 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6132 h->final(s, keyspace);
6133 /* Next hlen bytes. */
6135 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6136 hash_mpint(h, s, K);
6137 h->bytes(s, H, h->hlen);
6138 h->bytes(s, keyspace, h->hlen);
6139 h->final(s, keyspace + h->hlen);
6143 * Handle the SSH-2 transport layer.
6145 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
6146 struct Packet *pktin)
6148 unsigned char *in = (unsigned char *)vin;
6149 struct do_ssh2_transport_state {
6151 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
6152 Bignum p, g, e, f, K;
6155 int kex_init_value, kex_reply_value;
6156 const struct ssh_mac **maclist;
6158 const struct ssh2_cipher *cscipher_tobe;
6159 const struct ssh2_cipher *sccipher_tobe;
6160 const struct ssh_mac *csmac_tobe;
6161 const struct ssh_mac *scmac_tobe;
6162 int csmac_etm_tobe, scmac_etm_tobe;
6163 const struct ssh_compress *cscomp_tobe;
6164 const struct ssh_compress *sccomp_tobe;
6165 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6166 int hostkeylen, siglen, rsakeylen;
6167 void *hkey; /* actual host key */
6168 void *rsakey; /* for RSA kex */
6169 void *eckey; /* for ECDH kex */
6170 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6171 int n_preferred_kex;
6172 const struct ssh_kexes *preferred_kex[KEX_MAX];
6173 int n_preferred_ciphers;
6174 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6175 const struct ssh_compress *preferred_comp;
6176 int userauth_succeeded; /* for delayed compression */
6177 int pending_compression;
6178 int got_session_id, activated_authconn;
6179 struct Packet *pktout;
6184 crState(do_ssh2_transport_state);
6186 assert(!ssh->bare_connection);
6190 s->cscipher_tobe = s->sccipher_tobe = NULL;
6191 s->csmac_tobe = s->scmac_tobe = NULL;
6192 s->cscomp_tobe = s->sccomp_tobe = NULL;
6194 s->got_session_id = s->activated_authconn = FALSE;
6195 s->userauth_succeeded = FALSE;
6196 s->pending_compression = FALSE;
6199 * Be prepared to work around the buggy MAC problem.
6201 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6202 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6204 s->maclist = macs, s->nmacs = lenof(macs);
6207 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6212 * Set up the preferred key exchange. (NULL => warn below here)
6214 s->n_preferred_kex = 0;
6215 for (i = 0; i < KEX_MAX; i++) {
6216 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6218 s->preferred_kex[s->n_preferred_kex++] =
6219 &ssh_diffiehellman_gex;
6222 s->preferred_kex[s->n_preferred_kex++] =
6223 &ssh_diffiehellman_group14;
6226 s->preferred_kex[s->n_preferred_kex++] =
6227 &ssh_diffiehellman_group1;
6230 s->preferred_kex[s->n_preferred_kex++] =
6234 s->preferred_kex[s->n_preferred_kex++] =
6238 /* Flag for later. Don't bother if it's the last in
6240 if (i < KEX_MAX - 1) {
6241 s->preferred_kex[s->n_preferred_kex++] = NULL;
6248 * Set up the preferred ciphers. (NULL => warn below here)
6250 s->n_preferred_ciphers = 0;
6251 for (i = 0; i < CIPHER_MAX; i++) {
6252 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6253 case CIPHER_BLOWFISH:
6254 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6257 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6258 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6262 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6265 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6267 case CIPHER_ARCFOUR:
6268 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6271 /* Flag for later. Don't bother if it's the last in
6273 if (i < CIPHER_MAX - 1) {
6274 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6281 * Set up preferred compression.
6283 if (conf_get_int(ssh->conf, CONF_compression))
6284 s->preferred_comp = &ssh_zlib;
6286 s->preferred_comp = &ssh_comp_none;
6289 * Enable queueing of outgoing auth- or connection-layer
6290 * packets while we are in the middle of a key exchange.
6292 ssh->queueing = TRUE;
6295 * Flag that KEX is in progress.
6297 ssh->kex_in_progress = TRUE;
6300 * Construct and send our key exchange packet.
6302 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6303 for (i = 0; i < 16; i++)
6304 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6305 /* List key exchange algorithms. */
6306 ssh2_pkt_addstring_start(s->pktout);
6307 for (i = 0; i < s->n_preferred_kex; i++) {
6308 const struct ssh_kexes *k = s->preferred_kex[i];
6309 if (!k) continue; /* warning flag */
6310 for (j = 0; j < k->nkexes; j++)
6311 ssh2_pkt_addstring_commasep(s->pktout, k->list[j]->name);
6313 /* List server host key algorithms. */
6314 if (!s->got_session_id) {
6316 * In the first key exchange, we list all the algorithms
6317 * we're prepared to cope with.
6319 ssh2_pkt_addstring_start(s->pktout);
6320 for (i = 0; i < lenof(hostkey_algs); i++)
6321 ssh2_pkt_addstring_commasep(s->pktout, hostkey_algs[i]->name);
6324 * In subsequent key exchanges, we list only the kex
6325 * algorithm that was selected in the first key exchange,
6326 * so that we keep getting the same host key and hence
6327 * don't have to interrupt the user's session to ask for
6331 ssh2_pkt_addstring(s->pktout, ssh->hostkey->name);
6333 /* List encryption algorithms (client->server then server->client). */
6334 for (k = 0; k < 2; k++) {
6335 ssh2_pkt_addstring_start(s->pktout);
6336 for (i = 0; i < s->n_preferred_ciphers; i++) {
6337 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6338 if (!c) continue; /* warning flag */
6339 for (j = 0; j < c->nciphers; j++)
6340 ssh2_pkt_addstring_commasep(s->pktout, c->list[j]->name);
6343 /* List MAC algorithms (client->server then server->client). */
6344 for (j = 0; j < 2; j++) {
6345 ssh2_pkt_addstring_start(s->pktout);
6346 for (i = 0; i < s->nmacs; i++) {
6347 ssh2_pkt_addstring_commasep(s->pktout, s->maclist[i]->name);
6349 for (i = 0; i < s->nmacs; i++) {
6350 /* For each MAC, there may also be an ETM version,
6351 * which we list second. */
6352 if (s->maclist[i]->etm_name)
6353 ssh2_pkt_addstring_commasep(s->pktout, s->maclist[i]->etm_name);
6356 /* List client->server compression algorithms,
6357 * then server->client compression algorithms. (We use the
6358 * same set twice.) */
6359 for (j = 0; j < 2; j++) {
6360 ssh2_pkt_addstring_start(s->pktout);
6361 assert(lenof(compressions) > 1);
6362 /* Prefer non-delayed versions */
6363 ssh2_pkt_addstring_commasep(s->pktout, s->preferred_comp->name);
6364 /* We don't even list delayed versions of algorithms until
6365 * they're allowed to be used, to avoid a race. See the end of
6367 if (s->userauth_succeeded && s->preferred_comp->delayed_name)
6368 ssh2_pkt_addstring_commasep(s->pktout,
6369 s->preferred_comp->delayed_name);
6370 for (i = 0; i < lenof(compressions); i++) {
6371 const struct ssh_compress *c = compressions[i];
6372 ssh2_pkt_addstring_commasep(s->pktout, c->name);
6373 if (s->userauth_succeeded && c->delayed_name)
6374 ssh2_pkt_addstring_commasep(s->pktout, c->delayed_name);
6377 /* List client->server languages. Empty list. */
6378 ssh2_pkt_addstring_start(s->pktout);
6379 /* List server->client languages. Empty list. */
6380 ssh2_pkt_addstring_start(s->pktout);
6381 /* First KEX packet does _not_ follow, because we're not that brave. */
6382 ssh2_pkt_addbool(s->pktout, FALSE);
6384 ssh2_pkt_adduint32(s->pktout, 0);
6387 s->our_kexinitlen = s->pktout->length - 5;
6388 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6389 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6391 ssh2_pkt_send_noqueue(ssh, s->pktout);
6394 crWaitUntilV(pktin);
6397 * Now examine the other side's KEXINIT to see what we're up
6401 char *str, *preferred;
6404 if (pktin->type != SSH2_MSG_KEXINIT) {
6405 bombout(("expected key exchange packet from server"));
6409 ssh->hostkey = NULL;
6410 s->cscipher_tobe = NULL;
6411 s->sccipher_tobe = NULL;
6412 s->csmac_tobe = NULL;
6413 s->scmac_tobe = NULL;
6414 s->cscomp_tobe = NULL;
6415 s->sccomp_tobe = NULL;
6416 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
6418 pktin->savedpos += 16; /* skip garbage cookie */
6419 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
6421 bombout(("KEXINIT packet was incomplete"));
6426 for (i = 0; i < s->n_preferred_kex; i++) {
6427 const struct ssh_kexes *k = s->preferred_kex[i];
6431 for (j = 0; j < k->nkexes; j++) {
6432 if (!preferred) preferred = k->list[j]->name;
6433 if (in_commasep_string(k->list[j]->name, str, len)) {
6434 ssh->kex = k->list[j];
6443 bombout(("Couldn't agree a key exchange algorithm"
6444 " (available: %.*s)", len, str));
6448 * Note that the server's guess is considered wrong if it doesn't match
6449 * the first algorithm in our list, even if it's still the algorithm
6452 s->guessok = first_in_commasep_string(preferred, str, len);
6453 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
6455 bombout(("KEXINIT packet was incomplete"));
6458 for (i = 0; i < lenof(hostkey_algs); i++) {
6459 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
6460 ssh->hostkey = hostkey_algs[i];
6464 if (!ssh->hostkey) {
6465 bombout(("Couldn't agree a host key algorithm"
6466 " (available: %.*s)", len, str));
6470 s->guessok = s->guessok &&
6471 first_in_commasep_string(hostkey_algs[0]->name, str, len);
6472 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
6474 bombout(("KEXINIT packet was incomplete"));
6477 for (i = 0; i < s->n_preferred_ciphers; i++) {
6478 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6480 s->warn_cscipher = TRUE;
6482 for (j = 0; j < c->nciphers; j++) {
6483 if (in_commasep_string(c->list[j]->name, str, len)) {
6484 s->cscipher_tobe = c->list[j];
6489 if (s->cscipher_tobe)
6492 if (!s->cscipher_tobe) {
6493 bombout(("Couldn't agree a client-to-server cipher"
6494 " (available: %.*s)", len, str));
6498 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
6500 bombout(("KEXINIT packet was incomplete"));
6503 for (i = 0; i < s->n_preferred_ciphers; i++) {
6504 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6506 s->warn_sccipher = TRUE;
6508 for (j = 0; j < c->nciphers; j++) {
6509 if (in_commasep_string(c->list[j]->name, str, len)) {
6510 s->sccipher_tobe = c->list[j];
6515 if (s->sccipher_tobe)
6518 if (!s->sccipher_tobe) {
6519 bombout(("Couldn't agree a server-to-client cipher"
6520 " (available: %.*s)", len, str));
6524 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
6526 bombout(("KEXINIT packet was incomplete"));
6529 for (i = 0; i < s->nmacs; i++) {
6530 if (in_commasep_string(s->maclist[i]->name, str, len)) {
6531 s->csmac_tobe = s->maclist[i];
6532 s->csmac_etm_tobe = FALSE;
6536 if (!s->csmac_tobe) {
6537 for (i = 0; i < s->nmacs; i++) {
6538 if (s->maclist[i]->etm_name &&
6539 in_commasep_string(s->maclist[i]->etm_name, str, len)) {
6540 s->csmac_tobe = s->maclist[i];
6541 s->csmac_etm_tobe = TRUE;
6546 if (!s->csmac_tobe) {
6547 bombout(("Couldn't agree a client-to-server MAC"
6548 " (available: %.*s)", len, str));
6551 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
6553 bombout(("KEXINIT packet was incomplete"));
6556 for (i = 0; i < s->nmacs; i++) {
6557 if (in_commasep_string(s->maclist[i]->name, str, len)) {
6558 s->scmac_tobe = s->maclist[i];
6559 s->scmac_etm_tobe = FALSE;
6563 if (!s->scmac_tobe) {
6564 for (i = 0; i < s->nmacs; i++) {
6565 if (s->maclist[i]->etm_name &&
6566 in_commasep_string(s->maclist[i]->etm_name, str, len)) {
6567 s->scmac_tobe = s->maclist[i];
6568 s->scmac_etm_tobe = TRUE;
6573 if (!s->scmac_tobe) {
6574 bombout(("Couldn't agree a server-to-client MAC"
6575 " (available: %.*s)", len, str));
6578 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
6580 bombout(("KEXINIT packet was incomplete"));
6583 for (i = 0; i < lenof(compressions) + 1; i++) {
6584 const struct ssh_compress *c =
6585 i == 0 ? s->preferred_comp : compressions[i - 1];
6586 if (in_commasep_string(c->name, str, len)) {
6589 } else if (in_commasep_string(c->delayed_name, str, len)) {
6590 if (s->userauth_succeeded) {
6594 s->pending_compression = TRUE; /* try this later */
6598 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
6600 bombout(("KEXINIT packet was incomplete"));
6603 for (i = 0; i < lenof(compressions) + 1; i++) {
6604 const struct ssh_compress *c =
6605 i == 0 ? s->preferred_comp : compressions[i - 1];
6606 if (in_commasep_string(c->name, str, len)) {
6609 } else if (in_commasep_string(c->delayed_name, str, len)) {
6610 if (s->userauth_succeeded) {
6614 s->pending_compression = TRUE; /* try this later */
6618 if (s->pending_compression) {
6619 logevent("Server supports delayed compression; "
6620 "will try this later");
6622 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6623 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6624 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6626 ssh->exhash = ssh->kex->hash->init();
6627 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6628 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6629 hash_string(ssh->kex->hash, ssh->exhash,
6630 s->our_kexinit, s->our_kexinitlen);
6631 sfree(s->our_kexinit);
6632 /* Include the type byte in the hash of server's KEXINIT */
6633 hash_string(ssh->kex->hash, ssh->exhash,
6634 pktin->body - 1, pktin->length + 1);
6637 ssh_set_frozen(ssh, 1);
6638 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6640 ssh_dialog_callback, ssh);
6641 if (s->dlgret < 0) {
6645 bombout(("Unexpected data from server while"
6646 " waiting for user response"));
6649 } while (pktin || inlen > 0);
6650 s->dlgret = ssh->user_response;
6652 ssh_set_frozen(ssh, 0);
6653 if (s->dlgret == 0) {
6654 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6660 if (s->warn_cscipher) {
6661 ssh_set_frozen(ssh, 1);
6662 s->dlgret = askalg(ssh->frontend,
6663 "client-to-server cipher",
6664 s->cscipher_tobe->name,
6665 ssh_dialog_callback, ssh);
6666 if (s->dlgret < 0) {
6670 bombout(("Unexpected data from server while"
6671 " waiting for user response"));
6674 } while (pktin || inlen > 0);
6675 s->dlgret = ssh->user_response;
6677 ssh_set_frozen(ssh, 0);
6678 if (s->dlgret == 0) {
6679 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6685 if (s->warn_sccipher) {
6686 ssh_set_frozen(ssh, 1);
6687 s->dlgret = askalg(ssh->frontend,
6688 "server-to-client cipher",
6689 s->sccipher_tobe->name,
6690 ssh_dialog_callback, ssh);
6691 if (s->dlgret < 0) {
6695 bombout(("Unexpected data from server while"
6696 " waiting for user response"));
6699 } while (pktin || inlen > 0);
6700 s->dlgret = ssh->user_response;
6702 ssh_set_frozen(ssh, 0);
6703 if (s->dlgret == 0) {
6704 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6710 if (s->ignorepkt) /* first_kex_packet_follows */
6711 crWaitUntilV(pktin); /* Ignore packet */
6714 if (ssh->kex->main_type == KEXTYPE_DH) {
6716 * Work out the number of bits of key we will need from the
6717 * key exchange. We start with the maximum key length of
6723 csbits = s->cscipher_tobe->keylen;
6724 scbits = s->sccipher_tobe->keylen;
6725 s->nbits = (csbits > scbits ? csbits : scbits);
6727 /* The keys only have hlen-bit entropy, since they're based on
6728 * a hash. So cap the key size at hlen bits. */
6729 if (s->nbits > ssh->kex->hash->hlen * 8)
6730 s->nbits = ssh->kex->hash->hlen * 8;
6733 * If we're doing Diffie-Hellman group exchange, start by
6734 * requesting a group.
6736 if (!ssh->kex->pdata) {
6737 logevent("Doing Diffie-Hellman group exchange");
6738 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6740 * Work out how big a DH group we will need to allow that
6743 s->pbits = 512 << ((s->nbits - 1) / 64);
6744 if (s->pbits < DH_MIN_SIZE)
6745 s->pbits = DH_MIN_SIZE;
6746 if (s->pbits > DH_MAX_SIZE)
6747 s->pbits = DH_MAX_SIZE;
6748 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6749 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6750 ssh2_pkt_adduint32(s->pktout, s->pbits);
6752 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6753 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6754 ssh2_pkt_adduint32(s->pktout, s->pbits);
6755 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6757 ssh2_pkt_send_noqueue(ssh, s->pktout);
6759 crWaitUntilV(pktin);
6760 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6761 bombout(("expected key exchange group packet from server"));
6764 s->p = ssh2_pkt_getmp(pktin);
6765 s->g = ssh2_pkt_getmp(pktin);
6766 if (!s->p || !s->g) {
6767 bombout(("unable to read mp-ints from incoming group packet"));
6770 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6771 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6772 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6774 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6775 ssh->kex_ctx = dh_setup_group(ssh->kex);
6776 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6777 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6778 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6779 ssh->kex->groupname);
6782 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6783 ssh->kex->hash->text_name);
6785 * Now generate and send e for Diffie-Hellman.
6787 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6788 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6789 s->pktout = ssh2_pkt_init(s->kex_init_value);
6790 ssh2_pkt_addmp(s->pktout, s->e);
6791 ssh2_pkt_send_noqueue(ssh, s->pktout);
6793 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6794 crWaitUntilV(pktin);
6795 if (pktin->type != s->kex_reply_value) {
6796 bombout(("expected key exchange reply packet from server"));
6799 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6800 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6801 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6802 s->f = ssh2_pkt_getmp(pktin);
6804 bombout(("unable to parse key exchange reply packet"));
6807 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6810 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
6812 bombout(("key exchange reply failed validation: %s", err));
6816 s->K = dh_find_K(ssh->kex_ctx, s->f);
6818 /* We assume everything from now on will be quick, and it might
6819 * involve user interaction. */
6820 set_busy_status(ssh->frontend, BUSY_NOT);
6822 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6823 if (!ssh->kex->pdata) {
6824 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6825 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
6826 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6827 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6828 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
6829 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6830 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6832 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6833 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6835 dh_cleanup(ssh->kex_ctx);
6837 if (!ssh->kex->pdata) {
6841 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
6843 logeventf(ssh, "Doing ECDH key exchange with hash %s",
6844 ssh->kex->hash->text_name);
6845 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
6848 if (!strcmp(ssh->kex->name, "ecdh-sha2-nistp256")) {
6849 s->eckey = ssh_ecdhkex_newkey(ec_p256());
6850 } else if (!strcmp(ssh->kex->name, "ecdh-sha2-nistp384")) {
6851 s->eckey = ssh_ecdhkex_newkey(ec_p384());
6852 } else if (!strcmp(ssh->kex->name, "ecdh-sha2-nistp521")) {
6853 s->eckey = ssh_ecdhkex_newkey(ec_p521());
6856 bombout(("Unable to generate key for ECDH"));
6862 int publicPointLength;
6863 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6865 ssh_ecdhkex_freekey(s->eckey);
6866 bombout(("Unable to encode public key for ECDH"));
6869 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
6870 ssh2_pkt_addstring_start(s->pktout);
6871 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
6875 ssh2_pkt_send_noqueue(ssh, s->pktout);
6877 crWaitUntilV(pktin);
6878 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
6879 ssh_ecdhkex_freekey(s->eckey);
6880 bombout(("expected ECDH reply packet from server"));
6884 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6885 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6886 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6890 int publicPointLength;
6891 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6893 ssh_ecdhkex_freekey(s->eckey);
6894 bombout(("Unable to encode public key for ECDH hash"));
6897 hash_string(ssh->kex->hash, ssh->exhash,
6898 publicPoint, publicPointLength);
6905 ssh_pkt_getstring(pktin, &keydata, &keylen);
6906 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
6907 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
6909 ssh_ecdhkex_freekey(s->eckey);
6910 bombout(("point received in ECDH was not valid"));
6915 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6917 ssh_ecdhkex_freekey(s->eckey);
6919 logeventf(ssh, "Doing RSA key exchange with hash %s",
6920 ssh->kex->hash->text_name);
6921 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6923 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6926 crWaitUntilV(pktin);
6927 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6928 bombout(("expected RSA public key packet from server"));
6932 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6933 hash_string(ssh->kex->hash, ssh->exhash,
6934 s->hostkeydata, s->hostkeylen);
6935 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6939 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6940 s->rsakeydata = snewn(s->rsakeylen, char);
6941 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6944 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6946 sfree(s->rsakeydata);
6947 bombout(("unable to parse RSA public key from server"));
6951 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6954 * Next, set up a shared secret K, of precisely KLEN -
6955 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6956 * RSA key modulus and HLEN is the bit length of the hash
6960 int klen = ssh_rsakex_klen(s->rsakey);
6961 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6963 unsigned char *kstr1, *kstr2, *outstr;
6964 int kstr1len, kstr2len, outstrlen;
6966 s->K = bn_power_2(nbits - 1);
6968 for (i = 0; i < nbits; i++) {
6970 byte = random_byte();
6972 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6976 * Encode this as an mpint.
6978 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6979 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6980 PUT_32BIT(kstr2, kstr1len);
6981 memcpy(kstr2 + 4, kstr1, kstr1len);
6984 * Encrypt it with the given RSA key.
6986 outstrlen = (klen + 7) / 8;
6987 outstr = snewn(outstrlen, unsigned char);
6988 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6989 outstr, outstrlen, s->rsakey);
6992 * And send it off in a return packet.
6994 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6995 ssh2_pkt_addstring_start(s->pktout);
6996 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6997 ssh2_pkt_send_noqueue(ssh, s->pktout);
6999 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7006 ssh_rsakex_freekey(s->rsakey);
7008 crWaitUntilV(pktin);
7009 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7010 sfree(s->rsakeydata);
7011 bombout(("expected signature packet from server"));
7015 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7017 sfree(s->rsakeydata);
7020 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7021 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7022 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7024 ssh->kex_ctx = NULL;
7027 debug(("Exchange hash is:\n"));
7028 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7032 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7033 (char *)s->exchange_hash,
7034 ssh->kex->hash->hlen)) {
7035 bombout(("Server's host key did not match the signature supplied"));
7039 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7040 if (!s->got_session_id) {
7042 * Authenticate remote host: verify host key. (We've already
7043 * checked the signature of the exchange hash.)
7045 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
7046 logevent("Host key fingerprint is:");
7047 logevent(s->fingerprint);
7048 /* First check against manually configured host keys. */
7049 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7050 ssh->hostkey, s->hkey);
7051 if (s->dlgret == 0) { /* did not match */
7052 bombout(("Host key did not appear in manually configured list"));
7054 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7055 ssh_set_frozen(ssh, 1);
7056 s->dlgret = verify_ssh_host_key(ssh->frontend,
7057 ssh->savedhost, ssh->savedport,
7058 ssh->hostkey->keytype, s->keystr,
7060 ssh_dialog_callback, ssh);
7061 if (s->dlgret < 0) {
7065 bombout(("Unexpected data from server while waiting"
7066 " for user host key response"));
7069 } while (pktin || inlen > 0);
7070 s->dlgret = ssh->user_response;
7072 ssh_set_frozen(ssh, 0);
7073 if (s->dlgret == 0) {
7074 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7079 sfree(s->fingerprint);
7081 * Save this host key, to check against the one presented in
7082 * subsequent rekeys.
7084 ssh->hostkey_str = s->keystr;
7087 * In a rekey, we never present an interactive host key
7088 * verification request to the user. Instead, we simply
7089 * enforce that the key we're seeing this time is identical to
7090 * the one we saw before.
7092 if (strcmp(ssh->hostkey_str, s->keystr)) {
7093 bombout(("Host key was different in repeat key exchange"));
7098 ssh->hostkey->freekey(s->hkey);
7101 * The exchange hash from the very first key exchange is also
7102 * the session id, used in session key construction and
7105 if (!s->got_session_id) {
7106 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7107 memcpy(ssh->v2_session_id, s->exchange_hash,
7108 sizeof(s->exchange_hash));
7109 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7110 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7111 s->got_session_id = TRUE;
7115 * Send SSH2_MSG_NEWKEYS.
7117 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7118 ssh2_pkt_send_noqueue(ssh, s->pktout);
7119 ssh->outgoing_data_size = 0; /* start counting from here */
7122 * We've sent client NEWKEYS, so create and initialise
7123 * client-to-server session keys.
7125 if (ssh->cs_cipher_ctx)
7126 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7127 ssh->cscipher = s->cscipher_tobe;
7128 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7130 if (ssh->cs_mac_ctx)
7131 ssh->csmac->free_context(ssh->cs_mac_ctx);
7132 ssh->csmac = s->csmac_tobe;
7133 ssh->csmac_etm = s->csmac_etm_tobe;
7134 ssh->cs_mac_ctx = ssh->csmac->make_context();
7136 if (ssh->cs_comp_ctx)
7137 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7138 ssh->cscomp = s->cscomp_tobe;
7139 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7142 * Set IVs on client-to-server keys. Here we use the exchange
7143 * hash from the _first_ key exchange.
7146 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
7147 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7148 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
7149 assert((ssh->cscipher->keylen+7) / 8 <=
7150 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7151 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
7152 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
7153 assert(ssh->cscipher->blksize <=
7154 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7155 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
7156 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
7157 assert(ssh->csmac->len <=
7158 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7159 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
7160 smemclr(keyspace, sizeof(keyspace));
7163 logeventf(ssh, "Initialised %.200s client->server encryption",
7164 ssh->cscipher->text_name);
7165 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s",
7166 ssh->csmac->text_name,
7167 ssh->csmac_etm ? " (in ETM mode)" : "");
7168 if (ssh->cscomp->text_name)
7169 logeventf(ssh, "Initialised %s compression",
7170 ssh->cscomp->text_name);
7173 * Now our end of the key exchange is complete, we can send all
7174 * our queued higher-layer packets.
7176 ssh->queueing = FALSE;
7177 ssh2_pkt_queuesend(ssh);
7180 * Expect SSH2_MSG_NEWKEYS from server.
7182 crWaitUntilV(pktin);
7183 if (pktin->type != SSH2_MSG_NEWKEYS) {
7184 bombout(("expected new-keys packet from server"));
7187 ssh->incoming_data_size = 0; /* start counting from here */
7190 * We've seen server NEWKEYS, so create and initialise
7191 * server-to-client session keys.
7193 if (ssh->sc_cipher_ctx)
7194 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7195 ssh->sccipher = s->sccipher_tobe;
7196 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7198 if (ssh->sc_mac_ctx)
7199 ssh->scmac->free_context(ssh->sc_mac_ctx);
7200 ssh->scmac = s->scmac_tobe;
7201 ssh->scmac_etm = s->scmac_etm_tobe;
7202 ssh->sc_mac_ctx = ssh->scmac->make_context();
7204 if (ssh->sc_comp_ctx)
7205 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7206 ssh->sccomp = s->sccomp_tobe;
7207 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7210 * Set IVs on server-to-client keys. Here we use the exchange
7211 * hash from the _first_ key exchange.
7214 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
7215 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7216 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
7217 assert((ssh->sccipher->keylen+7) / 8 <=
7218 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7219 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
7220 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
7221 assert(ssh->sccipher->blksize <=
7222 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7223 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
7224 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
7225 assert(ssh->scmac->len <=
7226 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7227 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
7228 smemclr(keyspace, sizeof(keyspace));
7230 logeventf(ssh, "Initialised %.200s server->client encryption",
7231 ssh->sccipher->text_name);
7232 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s",
7233 ssh->scmac->text_name,
7234 ssh->scmac_etm ? " (in ETM mode)" : "");
7235 if (ssh->sccomp->text_name)
7236 logeventf(ssh, "Initialised %s decompression",
7237 ssh->sccomp->text_name);
7240 * Free shared secret.
7245 * Key exchange is over. Loop straight back round if we have a
7246 * deferred rekey reason.
7248 if (ssh->deferred_rekey_reason) {
7249 logevent(ssh->deferred_rekey_reason);
7251 ssh->deferred_rekey_reason = NULL;
7252 goto begin_key_exchange;
7256 * Otherwise, schedule a timer for our next rekey.
7258 ssh->kex_in_progress = FALSE;
7259 ssh->last_rekey = GETTICKCOUNT();
7260 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7261 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7265 * Now we're encrypting. Begin returning 1 to the protocol main
7266 * function so that other things can run on top of the
7267 * transport. If we ever see a KEXINIT, we must go back to the
7270 * We _also_ go back to the start if we see pktin==NULL and
7271 * inlen negative, because this is a special signal meaning
7272 * `initiate client-driven rekey', and `in' contains a message
7273 * giving the reason for the rekey.
7275 * inlen==-1 means always initiate a rekey;
7276 * inlen==-2 means that userauth has completed successfully and
7277 * we should consider rekeying (for delayed compression).
7279 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7280 (!pktin && inlen < 0))) {
7282 if (!ssh->protocol_initial_phase_done) {
7283 ssh->protocol_initial_phase_done = TRUE;
7285 * Allow authconn to initialise itself.
7287 do_ssh2_authconn(ssh, NULL, 0, NULL);
7292 logevent("Server initiated key re-exchange");
7296 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7297 * delayed compression, if it's available.
7299 * draft-miller-secsh-compression-delayed-00 says that you
7300 * negotiate delayed compression in the first key exchange, and
7301 * both sides start compressing when the server has sent
7302 * USERAUTH_SUCCESS. This has a race condition -- the server
7303 * can't know when the client has seen it, and thus which incoming
7304 * packets it should treat as compressed.
7306 * Instead, we do the initial key exchange without offering the
7307 * delayed methods, but note if the server offers them; when we
7308 * get here, if a delayed method was available that was higher
7309 * on our list than what we got, we initiate a rekey in which we
7310 * _do_ list the delayed methods (and hopefully get it as a
7311 * result). Subsequent rekeys will do the same.
7313 assert(!s->userauth_succeeded); /* should only happen once */
7314 s->userauth_succeeded = TRUE;
7315 if (!s->pending_compression)
7316 /* Can't see any point rekeying. */
7317 goto wait_for_rekey; /* this is utterly horrid */
7318 /* else fall through to rekey... */
7319 s->pending_compression = FALSE;
7322 * Now we've decided to rekey.
7324 * Special case: if the server bug is set that doesn't
7325 * allow rekeying, we give a different log message and
7326 * continue waiting. (If such a server _initiates_ a rekey,
7327 * we process it anyway!)
7329 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7330 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7332 /* Reset the counters, so that at least this message doesn't
7333 * hit the event log _too_ often. */
7334 ssh->outgoing_data_size = 0;
7335 ssh->incoming_data_size = 0;
7336 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7338 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7341 goto wait_for_rekey; /* this is still utterly horrid */
7343 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7346 goto begin_key_exchange;
7352 * Add data to an SSH-2 channel output buffer.
7354 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
7357 bufchain_add(&c->v.v2.outbuffer, buf, len);
7361 * Attempt to send data on an SSH-2 channel.
7363 static int ssh2_try_send(struct ssh_channel *c)
7366 struct Packet *pktout;
7369 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7372 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7373 if ((unsigned)len > c->v.v2.remwindow)
7374 len = c->v.v2.remwindow;
7375 if ((unsigned)len > c->v.v2.remmaxpkt)
7376 len = c->v.v2.remmaxpkt;
7377 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7378 ssh2_pkt_adduint32(pktout, c->remoteid);
7379 ssh2_pkt_addstring_start(pktout);
7380 ssh2_pkt_addstring_data(pktout, data, len);
7381 ssh2_pkt_send(ssh, pktout);
7382 bufchain_consume(&c->v.v2.outbuffer, len);
7383 c->v.v2.remwindow -= len;
7387 * After having sent as much data as we can, return the amount
7390 ret = bufchain_size(&c->v.v2.outbuffer);
7393 * And if there's no data pending but we need to send an EOF, send
7396 if (!ret && c->pending_eof)
7397 ssh_channel_try_eof(c);
7402 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7405 if (c->closes & CLOSES_SENT_EOF)
7406 return; /* don't send on channels we've EOFed */
7407 bufsize = ssh2_try_send(c);
7410 case CHAN_MAINSESSION:
7411 /* stdin need not receive an unthrottle
7412 * notification since it will be polled */
7415 x11_unthrottle(c->u.x11.xconn);
7418 /* agent sockets are request/response and need no
7419 * buffer management */
7422 pfd_unthrottle(c->u.pfd.pf);
7428 static int ssh_is_simple(Ssh ssh)
7431 * We use the 'simple' variant of the SSH protocol if we're asked
7432 * to, except not if we're also doing connection-sharing (either
7433 * tunnelling our packets over an upstream or expecting to be
7434 * tunnelled over ourselves), since then the assumption that we
7435 * have only one channel to worry about is not true after all.
7437 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7438 !ssh->bare_connection && !ssh->connshare);
7442 * Set up most of a new ssh_channel for SSH-2.
7444 static void ssh2_channel_init(struct ssh_channel *c)
7447 c->localid = alloc_channel_id(ssh);
7449 c->pending_eof = FALSE;
7450 c->throttling_conn = FALSE;
7451 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7452 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7453 c->v.v2.chanreq_head = NULL;
7454 c->v.v2.throttle_state = UNTHROTTLED;
7455 bufchain_init(&c->v.v2.outbuffer);
7459 * Construct the common parts of a CHANNEL_OPEN.
7461 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c, char *type)
7463 struct Packet *pktout;
7465 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7466 ssh2_pkt_addstring(pktout, type);
7467 ssh2_pkt_adduint32(pktout, c->localid);
7468 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7469 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7474 * CHANNEL_FAILURE doesn't come with any indication of what message
7475 * caused it, so we have to keep track of the outstanding
7476 * CHANNEL_REQUESTs ourselves.
7478 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7479 cchandler_fn_t handler, void *ctx)
7481 struct outstanding_channel_request *ocr =
7482 snew(struct outstanding_channel_request);
7484 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7485 ocr->handler = handler;
7488 if (!c->v.v2.chanreq_head)
7489 c->v.v2.chanreq_head = ocr;
7491 c->v.v2.chanreq_tail->next = ocr;
7492 c->v.v2.chanreq_tail = ocr;
7496 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7497 * NULL then a reply will be requested and the handler will be called
7498 * when it arrives. The returned packet is ready to have any
7499 * request-specific data added and be sent. Note that if a handler is
7500 * provided, it's essential that the request actually be sent.
7502 * The handler will usually be passed the response packet in pktin. If
7503 * pktin is NULL, this means that no reply will ever be forthcoming
7504 * (e.g. because the entire connection is being destroyed, or because
7505 * the server initiated channel closure before we saw the response)
7506 * and the handler should free any storage it's holding.
7508 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c, char *type,
7509 cchandler_fn_t handler, void *ctx)
7511 struct Packet *pktout;
7513 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7514 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7515 ssh2_pkt_adduint32(pktout, c->remoteid);
7516 ssh2_pkt_addstring(pktout, type);
7517 ssh2_pkt_addbool(pktout, handler != NULL);
7518 if (handler != NULL)
7519 ssh2_queue_chanreq_handler(c, handler, ctx);
7524 * Potentially enlarge the window on an SSH-2 channel.
7526 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7528 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7533 * Never send WINDOW_ADJUST for a channel that the remote side has
7534 * already sent EOF on; there's no point, since it won't be
7535 * sending any more data anyway. Ditto if _we've_ already sent
7538 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7542 * Also, never widen the window for an X11 channel when we're
7543 * still waiting to see its initial auth and may yet hand it off
7546 if (c->type == CHAN_X11 && c->u.x11.initial)
7550 * If the remote end has a habit of ignoring maxpkt, limit the
7551 * window so that it has no choice (assuming it doesn't ignore the
7554 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7555 newwin = OUR_V2_MAXPKT;
7558 * Only send a WINDOW_ADJUST if there's significantly more window
7559 * available than the other end thinks there is. This saves us
7560 * sending a WINDOW_ADJUST for every character in a shell session.
7562 * "Significant" is arbitrarily defined as half the window size.
7564 if (newwin / 2 >= c->v.v2.locwindow) {
7565 struct Packet *pktout;
7569 * In order to keep track of how much window the client
7570 * actually has available, we'd like it to acknowledge each
7571 * WINDOW_ADJUST. We can't do that directly, so we accompany
7572 * it with a CHANNEL_REQUEST that has to be acknowledged.
7574 * This is only necessary if we're opening the window wide.
7575 * If we're not, then throughput is being constrained by
7576 * something other than the maximum window size anyway.
7578 if (newwin == c->v.v2.locmaxwin &&
7579 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7580 up = snew(unsigned);
7581 *up = newwin - c->v.v2.locwindow;
7582 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7583 ssh2_handle_winadj_response, up);
7584 ssh2_pkt_send(ssh, pktout);
7586 if (c->v.v2.throttle_state != UNTHROTTLED)
7587 c->v.v2.throttle_state = UNTHROTTLING;
7589 /* Pretend the WINDOW_ADJUST was acked immediately. */
7590 c->v.v2.remlocwin = newwin;
7591 c->v.v2.throttle_state = THROTTLED;
7593 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7594 ssh2_pkt_adduint32(pktout, c->remoteid);
7595 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7596 ssh2_pkt_send(ssh, pktout);
7597 c->v.v2.locwindow = newwin;
7602 * Find the channel associated with a message. If there's no channel,
7603 * or it's not properly open, make a noise about it and return NULL.
7605 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7607 unsigned localid = ssh_pkt_getuint32(pktin);
7608 struct ssh_channel *c;
7610 c = find234(ssh->channels, &localid, ssh_channelfind);
7612 (c->type != CHAN_SHARING && c->halfopen &&
7613 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7614 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7615 char *buf = dupprintf("Received %s for %s channel %u",
7616 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7618 c ? "half-open" : "nonexistent", localid);
7619 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7626 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7627 struct Packet *pktin, void *ctx)
7629 unsigned *sizep = ctx;
7632 * Winadj responses should always be failures. However, at least
7633 * one server ("boks_sshd") is known to return SUCCESS for channel
7634 * requests it's never heard of, such as "winadj@putty". Raised
7635 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7636 * life, we don't worry about what kind of response we got.
7639 c->v.v2.remlocwin += *sizep;
7642 * winadj messages are only sent when the window is fully open, so
7643 * if we get an ack of one, we know any pending unthrottle is
7646 if (c->v.v2.throttle_state == UNTHROTTLING)
7647 c->v.v2.throttle_state = UNTHROTTLED;
7650 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
7652 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
7653 struct outstanding_channel_request *ocr;
7656 if (c->type == CHAN_SHARING) {
7657 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7658 pktin->body, pktin->length);
7661 ocr = c->v.v2.chanreq_head;
7663 ssh2_msg_unexpected(ssh, pktin);
7666 ocr->handler(c, pktin, ocr->ctx);
7667 c->v.v2.chanreq_head = ocr->next;
7670 * We may now initiate channel-closing procedures, if that
7671 * CHANNEL_REQUEST was the last thing outstanding before we send
7674 ssh2_channel_check_close(c);
7677 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
7679 struct ssh_channel *c;
7680 c = ssh2_channel_msg(ssh, pktin);
7683 if (c->type == CHAN_SHARING) {
7684 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7685 pktin->body, pktin->length);
7688 if (!(c->closes & CLOSES_SENT_EOF)) {
7689 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
7690 ssh2_try_send_and_unthrottle(ssh, c);
7694 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
7698 struct ssh_channel *c;
7699 c = ssh2_channel_msg(ssh, pktin);
7702 if (c->type == CHAN_SHARING) {
7703 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7704 pktin->body, pktin->length);
7707 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
7708 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
7709 return; /* extended but not stderr */
7710 ssh_pkt_getstring(pktin, &data, &length);
7713 c->v.v2.locwindow -= length;
7714 c->v.v2.remlocwin -= length;
7716 case CHAN_MAINSESSION:
7718 from_backend(ssh->frontend, pktin->type ==
7719 SSH2_MSG_CHANNEL_EXTENDED_DATA,
7723 bufsize = x11_send(c->u.x11.xconn, data, length);
7726 bufsize = pfd_send(c->u.pfd.pf, data, length);
7729 while (length > 0) {
7730 if (c->u.a.lensofar < 4) {
7731 unsigned int l = min(4 - c->u.a.lensofar,
7733 memcpy(c->u.a.msglen + c->u.a.lensofar,
7737 c->u.a.lensofar += l;
7739 if (c->u.a.lensofar == 4) {
7741 4 + GET_32BIT(c->u.a.msglen);
7742 c->u.a.message = snewn(c->u.a.totallen,
7744 memcpy(c->u.a.message, c->u.a.msglen, 4);
7746 if (c->u.a.lensofar >= 4 && length > 0) {
7748 min(c->u.a.totallen - c->u.a.lensofar,
7750 memcpy(c->u.a.message + c->u.a.lensofar,
7754 c->u.a.lensofar += l;
7756 if (c->u.a.lensofar == c->u.a.totallen) {
7759 c->u.a.outstanding_requests++;
7760 if (agent_query(c->u.a.message,
7763 ssh_agentf_callback, c))
7764 ssh_agentf_callback(c, reply, replylen);
7765 sfree(c->u.a.message);
7766 c->u.a.message = NULL;
7767 c->u.a.lensofar = 0;
7774 * If it looks like the remote end hit the end of its window,
7775 * and we didn't want it to do that, think about using a
7778 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
7779 c->v.v2.locmaxwin < 0x40000000)
7780 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
7782 * If we are not buffering too much data,
7783 * enlarge the window again at the remote side.
7784 * If we are buffering too much, we may still
7785 * need to adjust the window if the server's
7788 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7789 c->v.v2.locmaxwin - bufsize : 0);
7791 * If we're either buffering way too much data, or if we're
7792 * buffering anything at all and we're in "simple" mode,
7793 * throttle the whole channel.
7795 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
7796 && !c->throttling_conn) {
7797 c->throttling_conn = 1;
7798 ssh_throttle_conn(ssh, +1);
7803 static void ssh_check_termination(Ssh ssh)
7805 if (ssh->version == 2 &&
7806 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7807 count234(ssh->channels) == 0 &&
7808 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
7810 * We used to send SSH_MSG_DISCONNECT here, because I'd
7811 * believed that _every_ conforming SSH-2 connection had to
7812 * end with a disconnect being sent by at least one side;
7813 * apparently I was wrong and it's perfectly OK to
7814 * unceremoniously slam the connection shut when you're done,
7815 * and indeed OpenSSH feels this is more polite than sending a
7816 * DISCONNECT. So now we don't.
7818 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7822 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id)
7824 logeventf(ssh, "Connection sharing downstream #%u connected", id);
7827 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
7829 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
7830 ssh_check_termination(ssh);
7833 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
7838 va_start(ap, logfmt);
7839 buf = dupvprintf(logfmt, ap);
7842 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
7844 logeventf(ssh, "Connection sharing: %s", buf);
7848 static void ssh_channel_destroy(struct ssh_channel *c)
7853 case CHAN_MAINSESSION:
7854 ssh->mainchan = NULL;
7855 update_specials_menu(ssh->frontend);
7858 if (c->u.x11.xconn != NULL)
7859 x11_close(c->u.x11.xconn);
7860 logevent("Forwarded X11 connection terminated");
7863 sfree(c->u.a.message);
7866 if (c->u.pfd.pf != NULL)
7867 pfd_close(c->u.pfd.pf);
7868 logevent("Forwarded port closed");
7872 del234(ssh->channels, c);
7873 if (ssh->version == 2) {
7874 bufchain_clear(&c->v.v2.outbuffer);
7875 assert(c->v.v2.chanreq_head == NULL);
7880 * If that was the last channel left open, we might need to
7883 ssh_check_termination(ssh);
7886 static void ssh2_channel_check_close(struct ssh_channel *c)
7889 struct Packet *pktout;
7893 * If we've sent out our own CHANNEL_OPEN but not yet seen
7894 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
7895 * it's too early to be sending close messages of any kind.
7900 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
7901 c->type == CHAN_ZOMBIE) &&
7902 !c->v.v2.chanreq_head &&
7903 !(c->closes & CLOSES_SENT_CLOSE)) {
7905 * We have both sent and received EOF (or the channel is a
7906 * zombie), and we have no outstanding channel requests, which
7907 * means the channel is in final wind-up. But we haven't sent
7908 * CLOSE, so let's do so now.
7910 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
7911 ssh2_pkt_adduint32(pktout, c->remoteid);
7912 ssh2_pkt_send(ssh, pktout);
7913 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
7916 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
7917 assert(c->v.v2.chanreq_head == NULL);
7919 * We have both sent and received CLOSE, which means we're
7920 * completely done with the channel.
7922 ssh_channel_destroy(c);
7926 static void ssh2_channel_got_eof(struct ssh_channel *c)
7928 if (c->closes & CLOSES_RCVD_EOF)
7929 return; /* already seen EOF */
7930 c->closes |= CLOSES_RCVD_EOF;
7932 if (c->type == CHAN_X11) {
7933 x11_send_eof(c->u.x11.xconn);
7934 } else if (c->type == CHAN_AGENT) {
7935 if (c->u.a.outstanding_requests == 0) {
7936 /* Manufacture an outgoing EOF in response to the incoming one. */
7937 sshfwd_write_eof(c);
7939 } else if (c->type == CHAN_SOCKDATA) {
7940 pfd_send_eof(c->u.pfd.pf);
7941 } else if (c->type == CHAN_MAINSESSION) {
7944 if (!ssh->sent_console_eof &&
7945 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
7947 * Either from_backend_eof told us that the front end
7948 * wants us to close the outgoing side of the connection
7949 * as soon as we see EOF from the far end, or else we've
7950 * unilaterally decided to do that because we've allocated
7951 * a remote pty and hence EOF isn't a particularly
7952 * meaningful concept.
7954 sshfwd_write_eof(c);
7956 ssh->sent_console_eof = TRUE;
7959 ssh2_channel_check_close(c);
7962 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
7964 struct ssh_channel *c;
7966 c = ssh2_channel_msg(ssh, pktin);
7969 if (c->type == CHAN_SHARING) {
7970 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7971 pktin->body, pktin->length);
7974 ssh2_channel_got_eof(c);
7977 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7979 struct ssh_channel *c;
7981 c = ssh2_channel_msg(ssh, pktin);
7984 if (c->type == CHAN_SHARING) {
7985 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7986 pktin->body, pktin->length);
7991 * When we receive CLOSE on a channel, we assume it comes with an
7992 * implied EOF if we haven't seen EOF yet.
7994 ssh2_channel_got_eof(c);
7996 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
7998 * It also means we stop expecting to see replies to any
7999 * outstanding channel requests, so clean those up too.
8000 * (ssh_chanreq_init will enforce by assertion that we don't
8001 * subsequently put anything back on this list.)
8003 while (c->v.v2.chanreq_head) {
8004 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8005 ocr->handler(c, NULL, ocr->ctx);
8006 c->v.v2.chanreq_head = ocr->next;
8012 * And we also send an outgoing EOF, if we haven't already, on the
8013 * assumption that CLOSE is a pretty forceful announcement that
8014 * the remote side is doing away with the entire channel. (If it
8015 * had wanted to send us EOF and continue receiving data from us,
8016 * it would have just sent CHANNEL_EOF.)
8018 if (!(c->closes & CLOSES_SENT_EOF)) {
8020 * Make sure we don't read any more from whatever our local
8021 * data source is for this channel.
8024 case CHAN_MAINSESSION:
8025 ssh->send_ok = 0; /* stop trying to read from stdin */
8028 x11_override_throttle(c->u.x11.xconn, 1);
8031 pfd_override_throttle(c->u.pfd.pf, 1);
8036 * Abandon any buffered data we still wanted to send to this
8037 * channel. Receiving a CHANNEL_CLOSE is an indication that
8038 * the server really wants to get on and _destroy_ this
8039 * channel, and it isn't going to send us any further
8040 * WINDOW_ADJUSTs to permit us to send pending stuff.
8042 bufchain_clear(&c->v.v2.outbuffer);
8045 * Send outgoing EOF.
8047 sshfwd_write_eof(c);
8051 * Now process the actual close.
8053 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8054 c->closes |= CLOSES_RCVD_CLOSE;
8055 ssh2_channel_check_close(c);
8059 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8061 struct ssh_channel *c;
8063 c = ssh2_channel_msg(ssh, pktin);
8066 if (c->type == CHAN_SHARING) {
8067 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8068 pktin->body, pktin->length);
8071 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8072 c->remoteid = ssh_pkt_getuint32(pktin);
8073 c->halfopen = FALSE;
8074 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8075 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8077 if (c->type == CHAN_SOCKDATA_DORMANT) {
8078 c->type = CHAN_SOCKDATA;
8080 pfd_confirm(c->u.pfd.pf);
8081 } else if (c->type == CHAN_ZOMBIE) {
8083 * This case can occur if a local socket error occurred
8084 * between us sending out CHANNEL_OPEN and receiving
8085 * OPEN_CONFIRMATION. In this case, all we can do is
8086 * immediately initiate close proceedings now that we know the
8087 * server's id to put in the close message.
8089 ssh2_channel_check_close(c);
8092 * We never expect to receive OPEN_CONFIRMATION for any
8093 * *other* channel type (since only local-to-remote port
8094 * forwardings cause us to send CHANNEL_OPEN after the main
8095 * channel is live - all other auxiliary channel types are
8096 * initiated from the server end). It's safe to enforce this
8097 * by assertion rather than by ssh_disconnect, because the
8098 * real point is that we never constructed a half-open channel
8099 * structure in the first place with any type other than the
8102 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8106 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8109 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8111 static const char *const reasons[] = {
8112 "<unknown reason code>",
8113 "Administratively prohibited",
8115 "Unknown channel type",
8116 "Resource shortage",
8118 unsigned reason_code;
8119 char *reason_string;
8121 struct ssh_channel *c;
8123 c = ssh2_channel_msg(ssh, pktin);
8126 if (c->type == CHAN_SHARING) {
8127 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8128 pktin->body, pktin->length);
8131 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8133 if (c->type == CHAN_SOCKDATA_DORMANT) {
8134 reason_code = ssh_pkt_getuint32(pktin);
8135 if (reason_code >= lenof(reasons))
8136 reason_code = 0; /* ensure reasons[reason_code] in range */
8137 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8138 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8139 reasons[reason_code], reason_length, reason_string);
8141 pfd_close(c->u.pfd.pf);
8142 } else if (c->type == CHAN_ZOMBIE) {
8144 * This case can occur if a local socket error occurred
8145 * between us sending out CHANNEL_OPEN and receiving
8146 * OPEN_FAILURE. In this case, we need do nothing except allow
8147 * the code below to throw the half-open channel away.
8151 * We never expect to receive OPEN_FAILURE for any *other*
8152 * channel type (since only local-to-remote port forwardings
8153 * cause us to send CHANNEL_OPEN after the main channel is
8154 * live - all other auxiliary channel types are initiated from
8155 * the server end). It's safe to enforce this by assertion
8156 * rather than by ssh_disconnect, because the real point is
8157 * that we never constructed a half-open channel structure in
8158 * the first place with any type other than the above.
8160 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8163 del234(ssh->channels, c);
8167 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8170 int typelen, want_reply;
8171 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8172 struct ssh_channel *c;
8173 struct Packet *pktout;
8175 c = ssh2_channel_msg(ssh, pktin);
8178 if (c->type == CHAN_SHARING) {
8179 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8180 pktin->body, pktin->length);
8183 ssh_pkt_getstring(pktin, &type, &typelen);
8184 want_reply = ssh2_pkt_getbool(pktin);
8186 if (c->closes & CLOSES_SENT_CLOSE) {
8188 * We don't reply to channel requests after we've sent
8189 * CHANNEL_CLOSE for the channel, because our reply might
8190 * cross in the network with the other side's CHANNEL_CLOSE
8191 * and arrive after they have wound the channel up completely.
8197 * Having got the channel number, we now look at
8198 * the request type string to see if it's something
8201 if (c == ssh->mainchan) {
8203 * We recognise "exit-status" and "exit-signal" on
8204 * the primary channel.
8206 if (typelen == 11 &&
8207 !memcmp(type, "exit-status", 11)) {
8209 ssh->exitcode = ssh_pkt_getuint32(pktin);
8210 logeventf(ssh, "Server sent command exit status %d",
8212 reply = SSH2_MSG_CHANNEL_SUCCESS;
8214 } else if (typelen == 11 &&
8215 !memcmp(type, "exit-signal", 11)) {
8217 int is_plausible = TRUE, is_int = FALSE;
8218 char *fmt_sig = "", *fmt_msg = "";
8220 int msglen = 0, core = FALSE;
8221 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8222 * provide an `int' for the signal, despite its
8223 * having been a `string' in the drafts of RFC 4254 since at
8224 * least 2001. (Fixed in session.c 1.147.) Try to
8225 * infer which we can safely parse it as. */
8227 unsigned char *p = pktin->body +
8229 long len = pktin->length - pktin->savedpos;
8230 unsigned long num = GET_32BIT(p); /* what is it? */
8231 /* If it's 0, it hardly matters; assume string */
8235 int maybe_int = FALSE, maybe_str = FALSE;
8236 #define CHECK_HYPOTHESIS(offset, result) \
8239 int q = toint(offset); \
8240 if (q >= 0 && q+4 <= len) { \
8241 q = toint(q + 4 + GET_32BIT(p+q)); \
8242 if (q >= 0 && q+4 <= len && \
8243 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8248 CHECK_HYPOTHESIS(4+1, maybe_int);
8249 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8250 #undef CHECK_HYPOTHESIS
8251 if (maybe_int && !maybe_str)
8253 else if (!maybe_int && maybe_str)
8256 /* Crikey. Either or neither. Panic. */
8257 is_plausible = FALSE;
8260 ssh->exitcode = 128; /* means `unknown signal' */
8263 /* Old non-standard OpenSSH. */
8264 int signum = ssh_pkt_getuint32(pktin);
8265 fmt_sig = dupprintf(" %d", signum);
8266 ssh->exitcode = 128 + signum;
8268 /* As per RFC 4254. */
8271 ssh_pkt_getstring(pktin, &sig, &siglen);
8272 /* Signal name isn't supposed to be blank, but
8273 * let's cope gracefully if it is. */
8275 fmt_sig = dupprintf(" \"%.*s\"",
8280 * Really hideous method of translating the
8281 * signal description back into a locally
8282 * meaningful number.
8287 #define TRANSLATE_SIGNAL(s) \
8288 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8289 ssh->exitcode = 128 + SIG ## s
8291 TRANSLATE_SIGNAL(ABRT);
8294 TRANSLATE_SIGNAL(ALRM);
8297 TRANSLATE_SIGNAL(FPE);
8300 TRANSLATE_SIGNAL(HUP);
8303 TRANSLATE_SIGNAL(ILL);
8306 TRANSLATE_SIGNAL(INT);
8309 TRANSLATE_SIGNAL(KILL);
8312 TRANSLATE_SIGNAL(PIPE);
8315 TRANSLATE_SIGNAL(QUIT);
8318 TRANSLATE_SIGNAL(SEGV);
8321 TRANSLATE_SIGNAL(TERM);
8324 TRANSLATE_SIGNAL(USR1);
8327 TRANSLATE_SIGNAL(USR2);
8329 #undef TRANSLATE_SIGNAL
8331 ssh->exitcode = 128;
8333 core = ssh2_pkt_getbool(pktin);
8334 ssh_pkt_getstring(pktin, &msg, &msglen);
8336 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8338 /* ignore lang tag */
8339 } /* else don't attempt to parse */
8340 logeventf(ssh, "Server exited on signal%s%s%s",
8341 fmt_sig, core ? " (core dumped)" : "",
8343 if (*fmt_sig) sfree(fmt_sig);
8344 if (*fmt_msg) sfree(fmt_msg);
8345 reply = SSH2_MSG_CHANNEL_SUCCESS;
8350 * This is a channel request we don't know
8351 * about, so we now either ignore the request
8352 * or respond with CHANNEL_FAILURE, depending
8355 reply = SSH2_MSG_CHANNEL_FAILURE;
8358 pktout = ssh2_pkt_init(reply);
8359 ssh2_pkt_adduint32(pktout, c->remoteid);
8360 ssh2_pkt_send(ssh, pktout);
8364 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8367 int typelen, want_reply;
8368 struct Packet *pktout;
8370 ssh_pkt_getstring(pktin, &type, &typelen);
8371 want_reply = ssh2_pkt_getbool(pktin);
8374 * We currently don't support any global requests
8375 * at all, so we either ignore the request or
8376 * respond with REQUEST_FAILURE, depending on
8380 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8381 ssh2_pkt_send(ssh, pktout);
8385 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8389 struct X11FakeAuth *auth;
8392 * Make up a new set of fake X11 auth data, and add it to the tree
8393 * of currently valid ones with an indication of the sharing
8394 * context that it's relevant to.
8396 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8397 auth->share_cs = share_cs;
8398 auth->share_chan = share_chan;
8403 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8405 del234(ssh->x11authtree, auth);
8406 x11_free_fake_auth(auth);
8409 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8417 struct ssh_channel *c;
8418 unsigned remid, winsize, pktsize;
8419 unsigned our_winsize_override = 0;
8420 struct Packet *pktout;
8422 ssh_pkt_getstring(pktin, &type, &typelen);
8423 c = snew(struct ssh_channel);
8426 remid = ssh_pkt_getuint32(pktin);
8427 winsize = ssh_pkt_getuint32(pktin);
8428 pktsize = ssh_pkt_getuint32(pktin);
8430 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8433 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8434 addrstr = snewn(peeraddrlen+1, char);
8435 memcpy(addrstr, peeraddr, peeraddrlen);
8436 addrstr[peeraddrlen] = '\0';
8437 peerport = ssh_pkt_getuint32(pktin);
8439 logeventf(ssh, "Received X11 connect request from %s:%d",
8442 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8443 error = "X11 forwarding is not enabled";
8445 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8448 c->u.x11.initial = TRUE;
8451 * If we are a connection-sharing upstream, then we should
8452 * initially present a very small window, adequate to take
8453 * the X11 initial authorisation packet but not much more.
8454 * Downstream will then present us a larger window (by
8455 * fiat of the connection-sharing protocol) and we can
8456 * guarantee to send a positive-valued WINDOW_ADJUST.
8459 our_winsize_override = 128;
8461 logevent("Opened X11 forward channel");
8465 } else if (typelen == 15 &&
8466 !memcmp(type, "forwarded-tcpip", 15)) {
8467 struct ssh_rportfwd pf, *realpf;
8470 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8471 pf.shost = dupprintf("%.*s", shostlen, shost);
8472 pf.sport = ssh_pkt_getuint32(pktin);
8473 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8474 peerport = ssh_pkt_getuint32(pktin);
8475 realpf = find234(ssh->rportfwds, &pf, NULL);
8476 logeventf(ssh, "Received remote port %s:%d open request "
8477 "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
8480 if (realpf == NULL) {
8481 error = "Remote port is not recognised";
8485 if (realpf->share_ctx) {
8487 * This port forwarding is on behalf of a
8488 * connection-sharing downstream, so abandon our own
8489 * channel-open procedure and just pass the message on
8492 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8493 pktin->body, pktin->length);
8498 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8499 c, ssh->conf, realpf->pfrec->addressfamily);
8500 logeventf(ssh, "Attempting to forward remote port to "
8501 "%s:%d", realpf->dhost, realpf->dport);
8503 logeventf(ssh, "Port open failed: %s", err);
8505 error = "Port open failed";
8507 logevent("Forwarded port opened successfully");
8508 c->type = CHAN_SOCKDATA;
8511 } else if (typelen == 22 &&
8512 !memcmp(type, "auth-agent@openssh.com", 22)) {
8513 if (!ssh->agentfwd_enabled)
8514 error = "Agent forwarding is not enabled";
8516 c->type = CHAN_AGENT; /* identify channel type */
8517 c->u.a.lensofar = 0;
8518 c->u.a.message = NULL;
8519 c->u.a.outstanding_requests = 0;
8522 error = "Unsupported channel type requested";
8525 c->remoteid = remid;
8526 c->halfopen = FALSE;
8528 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8529 ssh2_pkt_adduint32(pktout, c->remoteid);
8530 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8531 ssh2_pkt_addstring(pktout, error);
8532 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8533 ssh2_pkt_send(ssh, pktout);
8534 logeventf(ssh, "Rejected channel open: %s", error);
8537 ssh2_channel_init(c);
8538 c->v.v2.remwindow = winsize;
8539 c->v.v2.remmaxpkt = pktsize;
8540 if (our_winsize_override) {
8541 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8542 our_winsize_override;
8544 add234(ssh->channels, c);
8545 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8546 ssh2_pkt_adduint32(pktout, c->remoteid);
8547 ssh2_pkt_adduint32(pktout, c->localid);
8548 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8549 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8550 ssh2_pkt_send(ssh, pktout);
8554 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8555 void *share_cs, void *share_chan,
8556 const char *peer_addr, int peer_port,
8557 int endian, int protomajor, int protominor,
8558 const void *initial_data, int initial_len)
8561 * This function is called when we've just discovered that an X
8562 * forwarding channel on which we'd been handling the initial auth
8563 * ourselves turns out to be destined for a connection-sharing
8564 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8565 * that we completely stop tracking windows and buffering data and
8566 * just pass more or less unmodified SSH messages back and forth.
8568 c->type = CHAN_SHARING;
8569 c->u.sharing.ctx = share_cs;
8570 share_setup_x11_channel(share_cs, share_chan,
8571 c->localid, c->remoteid, c->v.v2.remwindow,
8572 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8573 peer_addr, peer_port, endian,
8574 protomajor, protominor,
8575 initial_data, initial_len);
8578 void sshfwd_x11_is_local(struct ssh_channel *c)
8581 * This function is called when we've just discovered that an X
8582 * forwarding channel is _not_ destined for a connection-sharing
8583 * downstream but we're going to handle it ourselves. We stop
8584 * presenting a cautiously small window and go into ordinary data
8587 c->u.x11.initial = FALSE;
8588 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8592 * Buffer banner messages for later display at some convenient point,
8593 * if we're going to display them.
8595 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8597 /* Arbitrary limit to prevent unbounded inflation of buffer */
8598 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8599 bufchain_size(&ssh->banner) <= 131072) {
8600 char *banner = NULL;
8602 ssh_pkt_getstring(pktin, &banner, &size);
8604 bufchain_add(&ssh->banner, banner, size);
8608 /* Helper function to deal with sending tty modes for "pty-req" */
8609 static void ssh2_send_ttymode(void *data, char *mode, char *val)
8611 struct Packet *pktout = (struct Packet *)data;
8613 unsigned int arg = 0;
8614 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
8615 if (i == lenof(ssh_ttymodes)) return;
8616 switch (ssh_ttymodes[i].type) {
8618 arg = ssh_tty_parse_specchar(val);
8621 arg = ssh_tty_parse_boolean(val);
8624 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
8625 ssh2_pkt_adduint32(pktout, arg);
8628 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8631 struct ssh2_setup_x11_state {
8635 struct Packet *pktout;
8636 crStateP(ssh2_setup_x11_state, ctx);
8640 logevent("Requesting X11 forwarding");
8641 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8643 ssh2_pkt_addbool(pktout, 0); /* many connections */
8644 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8645 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8646 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8647 ssh2_pkt_send(ssh, pktout);
8649 /* Wait to be called back with either a response packet, or NULL
8650 * meaning clean up and free our data */
8654 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8655 logevent("X11 forwarding enabled");
8656 ssh->X11_fwd_enabled = TRUE;
8658 logevent("X11 forwarding refused");
8664 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8667 struct ssh2_setup_agent_state {
8671 struct Packet *pktout;
8672 crStateP(ssh2_setup_agent_state, ctx);
8676 logevent("Requesting OpenSSH-style agent forwarding");
8677 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8678 ssh2_setup_agent, s);
8679 ssh2_pkt_send(ssh, pktout);
8681 /* Wait to be called back with either a response packet, or NULL
8682 * meaning clean up and free our data */
8686 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8687 logevent("Agent forwarding enabled");
8688 ssh->agentfwd_enabled = TRUE;
8690 logevent("Agent forwarding refused");
8696 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8699 struct ssh2_setup_pty_state {
8703 struct Packet *pktout;
8704 crStateP(ssh2_setup_pty_state, ctx);
8708 /* Unpick the terminal-speed string. */
8709 /* XXX perhaps we should allow no speeds to be sent. */
8710 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8711 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8712 /* Build the pty request. */
8713 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
8715 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
8716 ssh2_pkt_adduint32(pktout, ssh->term_width);
8717 ssh2_pkt_adduint32(pktout, ssh->term_height);
8718 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
8719 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
8720 ssh2_pkt_addstring_start(pktout);
8721 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
8722 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
8723 ssh2_pkt_adduint32(pktout, ssh->ispeed);
8724 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
8725 ssh2_pkt_adduint32(pktout, ssh->ospeed);
8726 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
8727 ssh2_pkt_send(ssh, pktout);
8728 ssh->state = SSH_STATE_INTERMED;
8730 /* Wait to be called back with either a response packet, or NULL
8731 * meaning clean up and free our data */
8735 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8736 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8737 ssh->ospeed, ssh->ispeed);
8738 ssh->got_pty = TRUE;
8740 c_write_str(ssh, "Server refused to allocate pty\r\n");
8741 ssh->editing = ssh->echoing = 1;
8748 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
8751 struct ssh2_setup_env_state {
8753 int num_env, env_left, env_ok;
8756 struct Packet *pktout;
8757 crStateP(ssh2_setup_env_state, ctx);
8762 * Send environment variables.
8764 * Simplest thing here is to send all the requests at once, and
8765 * then wait for a whole bunch of successes or failures.
8771 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
8773 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
8774 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
8775 ssh2_pkt_addstring(pktout, key);
8776 ssh2_pkt_addstring(pktout, val);
8777 ssh2_pkt_send(ssh, pktout);
8782 logeventf(ssh, "Sent %d environment variables", s->num_env);
8787 s->env_left = s->num_env;
8789 while (s->env_left > 0) {
8790 /* Wait to be called back with either a response packet,
8791 * or NULL meaning clean up and free our data */
8793 if (!pktin) goto out;
8794 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
8799 if (s->env_ok == s->num_env) {
8800 logevent("All environment variables successfully set");
8801 } else if (s->env_ok == 0) {
8802 logevent("All environment variables refused");
8803 c_write_str(ssh, "Server refused to set environment variables\r\n");
8805 logeventf(ssh, "%d environment variables refused",
8806 s->num_env - s->env_ok);
8807 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8815 * Handle the SSH-2 userauth and connection layers.
8817 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
8819 do_ssh2_authconn(ssh, NULL, 0, pktin);
8822 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
8826 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
8829 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
8830 struct Packet *pktin)
8832 struct do_ssh2_authconn_state {
8836 AUTH_TYPE_PUBLICKEY,
8837 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
8838 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
8840 AUTH_TYPE_GSSAPI, /* always QUIET */
8841 AUTH_TYPE_KEYBOARD_INTERACTIVE,
8842 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
8844 int done_service_req;
8845 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
8846 int tried_pubkey_config, done_agent;
8851 int kbd_inter_refused;
8852 int we_are_in, userauth_success;
8853 prompts_t *cur_prompt;
8858 void *publickey_blob;
8859 int publickey_bloblen;
8860 int publickey_encrypted;
8861 char *publickey_algorithm;
8862 char *publickey_comment;
8863 unsigned char agent_request[5], *agent_response, *agentp;
8864 int agent_responselen;
8865 unsigned char *pkblob_in_agent;
8867 char *pkblob, *alg, *commentp;
8868 int pklen, alglen, commentlen;
8869 int siglen, retlen, len;
8870 char *q, *agentreq, *ret;
8872 struct Packet *pktout;
8875 struct ssh_gss_library *gsslib;
8876 Ssh_gss_ctx gss_ctx;
8877 Ssh_gss_buf gss_buf;
8878 Ssh_gss_buf gss_rcvtok, gss_sndtok;
8879 Ssh_gss_name gss_srv_name;
8880 Ssh_gss_stat gss_stat;
8883 crState(do_ssh2_authconn_state);
8887 /* Register as a handler for all the messages this coroutine handles. */
8888 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
8889 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
8890 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
8891 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
8892 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
8893 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
8894 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
8895 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
8896 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
8897 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
8898 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
8899 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
8900 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
8901 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
8902 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
8903 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
8904 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
8905 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
8906 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
8907 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
8909 s->done_service_req = FALSE;
8910 s->we_are_in = s->userauth_success = FALSE;
8911 s->agent_response = NULL;
8913 s->tried_gssapi = FALSE;
8916 if (!ssh->bare_connection) {
8917 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
8919 * Request userauth protocol, and await a response to it.
8921 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8922 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
8923 ssh2_pkt_send(ssh, s->pktout);
8924 crWaitUntilV(pktin);
8925 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
8926 s->done_service_req = TRUE;
8928 if (!s->done_service_req) {
8930 * Request connection protocol directly, without authentication.
8932 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8933 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8934 ssh2_pkt_send(ssh, s->pktout);
8935 crWaitUntilV(pktin);
8936 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
8937 s->we_are_in = TRUE; /* no auth required */
8939 bombout(("Server refused service request"));
8944 s->we_are_in = TRUE;
8947 /* Arrange to be able to deal with any BANNERs that come in.
8948 * (We do this now as packets may come in during the next bit.) */
8949 bufchain_init(&ssh->banner);
8950 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
8951 ssh2_msg_userauth_banner;
8954 * Misc one-time setup for authentication.
8956 s->publickey_blob = NULL;
8957 if (!s->we_are_in) {
8960 * Load the public half of any configured public key file
8963 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8964 if (!filename_is_null(s->keyfile)) {
8966 logeventf(ssh, "Reading private key file \"%.150s\"",
8967 filename_to_str(s->keyfile));
8968 keytype = key_type(s->keyfile);
8969 if (keytype == SSH_KEYTYPE_SSH2) {
8972 ssh2_userkey_loadpub(s->keyfile,
8973 &s->publickey_algorithm,
8974 &s->publickey_bloblen,
8975 &s->publickey_comment, &error);
8976 if (s->publickey_blob) {
8977 s->publickey_encrypted =
8978 ssh2_userkey_encrypted(s->keyfile, NULL);
8981 logeventf(ssh, "Unable to load private key (%s)",
8983 msgbuf = dupprintf("Unable to load private key file "
8984 "\"%.150s\" (%s)\r\n",
8985 filename_to_str(s->keyfile),
8987 c_write_str(ssh, msgbuf);
8992 logeventf(ssh, "Unable to use this key file (%s)",
8993 key_type_to_str(keytype));
8994 msgbuf = dupprintf("Unable to use key file \"%.150s\""
8996 filename_to_str(s->keyfile),
8997 key_type_to_str(keytype));
8998 c_write_str(ssh, msgbuf);
9000 s->publickey_blob = NULL;
9005 * Find out about any keys Pageant has (but if there's a
9006 * public key configured, filter out all others).
9009 s->agent_response = NULL;
9010 s->pkblob_in_agent = NULL;
9011 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9015 logevent("Pageant is running. Requesting keys.");
9017 /* Request the keys held by the agent. */
9018 PUT_32BIT(s->agent_request, 1);
9019 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9020 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9021 ssh_agent_callback, ssh)) {
9025 bombout(("Unexpected data from server while"
9026 " waiting for agent response"));
9029 } while (pktin || inlen > 0);
9030 r = ssh->agent_response;
9031 s->agent_responselen = ssh->agent_response_len;
9033 s->agent_response = (unsigned char *) r;
9034 if (s->agent_response && s->agent_responselen >= 5 &&
9035 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9038 p = s->agent_response + 5;
9039 s->nkeys = toint(GET_32BIT(p));
9042 * Vet the Pageant response to ensure that the key
9043 * count and blob lengths make sense.
9046 logeventf(ssh, "Pageant response contained a negative"
9047 " key count %d", s->nkeys);
9049 goto done_agent_query;
9051 unsigned char *q = p + 4;
9052 int lenleft = s->agent_responselen - 5 - 4;
9054 for (keyi = 0; keyi < s->nkeys; keyi++) {
9055 int bloblen, commentlen;
9057 logeventf(ssh, "Pageant response was truncated");
9059 goto done_agent_query;
9061 bloblen = toint(GET_32BIT(q));
9062 if (bloblen < 0 || bloblen > lenleft) {
9063 logeventf(ssh, "Pageant response was truncated");
9065 goto done_agent_query;
9067 lenleft -= 4 + bloblen;
9069 commentlen = toint(GET_32BIT(q));
9070 if (commentlen < 0 || commentlen > lenleft) {
9071 logeventf(ssh, "Pageant response was truncated");
9073 goto done_agent_query;
9075 lenleft -= 4 + commentlen;
9076 q += 4 + commentlen;
9081 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9082 if (s->publickey_blob) {
9083 /* See if configured key is in agent. */
9084 for (keyi = 0; keyi < s->nkeys; keyi++) {
9085 s->pklen = toint(GET_32BIT(p));
9086 if (s->pklen == s->publickey_bloblen &&
9087 !memcmp(p+4, s->publickey_blob,
9088 s->publickey_bloblen)) {
9089 logeventf(ssh, "Pageant key #%d matches "
9090 "configured key file", keyi);
9092 s->pkblob_in_agent = p;
9096 p += toint(GET_32BIT(p)) + 4; /* comment */
9098 if (!s->pkblob_in_agent) {
9099 logevent("Configured key file not in Pageant");
9104 logevent("Failed to get reply from Pageant");
9112 * We repeat this whole loop, including the username prompt,
9113 * until we manage a successful authentication. If the user
9114 * types the wrong _password_, they can be sent back to the
9115 * beginning to try another username, if this is configured on.
9116 * (If they specify a username in the config, they are never
9117 * asked, even if they do give a wrong password.)
9119 * I think this best serves the needs of
9121 * - the people who have no configuration, no keys, and just
9122 * want to try repeated (username,password) pairs until they
9123 * type both correctly
9125 * - people who have keys and configuration but occasionally
9126 * need to fall back to passwords
9128 * - people with a key held in Pageant, who might not have
9129 * logged in to a particular machine before; so they want to
9130 * type a username, and then _either_ their key will be
9131 * accepted, _or_ they will type a password. If they mistype
9132 * the username they will want to be able to get back and
9135 s->got_username = FALSE;
9136 while (!s->we_are_in) {
9140 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9142 * We got a username last time round this loop, and
9143 * with change_username turned off we don't try to get
9146 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9147 int ret; /* need not be kept over crReturn */
9148 s->cur_prompt = new_prompts(ssh->frontend);
9149 s->cur_prompt->to_server = TRUE;
9150 s->cur_prompt->name = dupstr("SSH login name");
9151 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9152 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9155 crWaitUntilV(!pktin);
9156 ret = get_userpass_input(s->cur_prompt, in, inlen);
9161 * get_userpass_input() failed to get a username.
9164 free_prompts(s->cur_prompt);
9165 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9168 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9169 free_prompts(s->cur_prompt);
9172 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9173 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9174 c_write_str(ssh, stuff);
9178 s->got_username = TRUE;
9181 * Send an authentication request using method "none": (a)
9182 * just in case it succeeds, and (b) so that we know what
9183 * authentication methods we can usefully try next.
9185 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9187 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9188 ssh2_pkt_addstring(s->pktout, ssh->username);
9189 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9190 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9191 ssh2_pkt_send(ssh, s->pktout);
9192 s->type = AUTH_TYPE_NONE;
9194 s->we_are_in = FALSE;
9196 s->tried_pubkey_config = FALSE;
9197 s->kbd_inter_refused = FALSE;
9199 /* Reset agent request state. */
9200 s->done_agent = FALSE;
9201 if (s->agent_response) {
9202 if (s->pkblob_in_agent) {
9203 s->agentp = s->pkblob_in_agent;
9205 s->agentp = s->agent_response + 5 + 4;
9211 char *methods = NULL;
9215 * Wait for the result of the last authentication request.
9218 crWaitUntilV(pktin);
9220 * Now is a convenient point to spew any banner material
9221 * that we've accumulated. (This should ensure that when
9222 * we exit the auth loop, we haven't any left to deal
9226 int size = bufchain_size(&ssh->banner);
9228 * Don't show the banner if we're operating in
9229 * non-verbose non-interactive mode. (It's probably
9230 * a script, which means nobody will read the
9231 * banner _anyway_, and moreover the printing of
9232 * the banner will screw up processing on the
9233 * output of (say) plink.)
9235 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9236 char *banner = snewn(size, char);
9237 bufchain_fetch(&ssh->banner, banner, size);
9238 c_write_untrusted(ssh, banner, size);
9241 bufchain_clear(&ssh->banner);
9243 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9244 logevent("Access granted");
9245 s->we_are_in = s->userauth_success = TRUE;
9249 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9250 bombout(("Strange packet received during authentication: "
9251 "type %d", pktin->type));
9258 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9259 * we can look at the string in it and know what we can
9260 * helpfully try next.
9262 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9263 ssh_pkt_getstring(pktin, &methods, &methlen);
9264 if (!ssh2_pkt_getbool(pktin)) {
9266 * We have received an unequivocal Access
9267 * Denied. This can translate to a variety of
9268 * messages, or no message at all.
9270 * For forms of authentication which are attempted
9271 * implicitly, by which I mean without printing
9272 * anything in the window indicating that we're
9273 * trying them, we should never print 'Access
9276 * If we do print a message saying that we're
9277 * attempting some kind of authentication, it's OK
9278 * to print a followup message saying it failed -
9279 * but the message may sometimes be more specific
9280 * than simply 'Access denied'.
9282 * Additionally, if we'd just tried password
9283 * authentication, we should break out of this
9284 * whole loop so as to go back to the username
9285 * prompt (iff we're configured to allow
9286 * username change attempts).
9288 if (s->type == AUTH_TYPE_NONE) {
9290 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9291 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9292 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9293 c_write_str(ssh, "Server refused our key\r\n");
9294 logevent("Server refused our key");
9295 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9296 /* This _shouldn't_ happen except by a
9297 * protocol bug causing client and server to
9298 * disagree on what is a correct signature. */
9299 c_write_str(ssh, "Server refused public-key signature"
9300 " despite accepting key!\r\n");
9301 logevent("Server refused public-key signature"
9302 " despite accepting key!");
9303 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9304 /* quiet, so no c_write */
9305 logevent("Server refused keyboard-interactive authentication");
9306 } else if (s->type==AUTH_TYPE_GSSAPI) {
9307 /* always quiet, so no c_write */
9308 /* also, the code down in the GSSAPI block has
9309 * already logged this in the Event Log */
9310 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9311 logevent("Keyboard-interactive authentication failed");
9312 c_write_str(ssh, "Access denied\r\n");
9314 assert(s->type == AUTH_TYPE_PASSWORD);
9315 logevent("Password authentication failed");
9316 c_write_str(ssh, "Access denied\r\n");
9318 if (conf_get_int(ssh->conf, CONF_change_username)) {
9319 /* XXX perhaps we should allow
9320 * keyboard-interactive to do this too? */
9321 s->we_are_in = FALSE;
9326 c_write_str(ssh, "Further authentication required\r\n");
9327 logevent("Further authentication required");
9331 in_commasep_string("publickey", methods, methlen);
9333 in_commasep_string("password", methods, methlen);
9334 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9335 in_commasep_string("keyboard-interactive", methods, methlen);
9338 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9339 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9340 in_commasep_string("gssapi-with-mic", methods, methlen) &&
9341 ssh->gsslibs->nlibraries > 0;
9345 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9347 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9350 * Attempt public-key authentication using a key from Pageant.
9353 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9355 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9357 /* Unpack key from agent response */
9358 s->pklen = toint(GET_32BIT(s->agentp));
9360 s->pkblob = (char *)s->agentp;
9361 s->agentp += s->pklen;
9362 s->alglen = toint(GET_32BIT(s->pkblob));
9363 s->alg = s->pkblob + 4;
9364 s->commentlen = toint(GET_32BIT(s->agentp));
9366 s->commentp = (char *)s->agentp;
9367 s->agentp += s->commentlen;
9368 /* s->agentp now points at next key, if any */
9370 /* See if server will accept it */
9371 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9372 ssh2_pkt_addstring(s->pktout, ssh->username);
9373 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9374 /* service requested */
9375 ssh2_pkt_addstring(s->pktout, "publickey");
9377 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9378 ssh2_pkt_addstring_start(s->pktout);
9379 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9380 ssh2_pkt_addstring_start(s->pktout);
9381 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9382 ssh2_pkt_send(ssh, s->pktout);
9383 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9385 crWaitUntilV(pktin);
9386 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9388 /* Offer of key refused. */
9395 if (flags & FLAG_VERBOSE) {
9396 c_write_str(ssh, "Authenticating with "
9398 c_write(ssh, s->commentp, s->commentlen);
9399 c_write_str(ssh, "\" from agent\r\n");
9403 * Server is willing to accept the key.
9404 * Construct a SIGN_REQUEST.
9406 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9407 ssh2_pkt_addstring(s->pktout, ssh->username);
9408 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9409 /* service requested */
9410 ssh2_pkt_addstring(s->pktout, "publickey");
9412 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9413 ssh2_pkt_addstring_start(s->pktout);
9414 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9415 ssh2_pkt_addstring_start(s->pktout);
9416 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9418 /* Ask agent for signature. */
9419 s->siglen = s->pktout->length - 5 + 4 +
9420 ssh->v2_session_id_len;
9421 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9423 s->len = 1; /* message type */
9424 s->len += 4 + s->pklen; /* key blob */
9425 s->len += 4 + s->siglen; /* data to sign */
9426 s->len += 4; /* flags */
9427 s->agentreq = snewn(4 + s->len, char);
9428 PUT_32BIT(s->agentreq, s->len);
9429 s->q = s->agentreq + 4;
9430 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9431 PUT_32BIT(s->q, s->pklen);
9433 memcpy(s->q, s->pkblob, s->pklen);
9435 PUT_32BIT(s->q, s->siglen);
9437 /* Now the data to be signed... */
9438 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9439 PUT_32BIT(s->q, ssh->v2_session_id_len);
9442 memcpy(s->q, ssh->v2_session_id,
9443 ssh->v2_session_id_len);
9444 s->q += ssh->v2_session_id_len;
9445 memcpy(s->q, s->pktout->data + 5,
9446 s->pktout->length - 5);
9447 s->q += s->pktout->length - 5;
9448 /* And finally the (zero) flags word. */
9450 if (!agent_query(s->agentreq, s->len + 4,
9452 ssh_agent_callback, ssh)) {
9456 bombout(("Unexpected data from server"
9457 " while waiting for agent"
9461 } while (pktin || inlen > 0);
9462 vret = ssh->agent_response;
9463 s->retlen = ssh->agent_response_len;
9468 if (s->retlen >= 9 &&
9469 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9470 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9471 logevent("Sending Pageant's response");
9472 ssh2_add_sigblob(ssh, s->pktout,
9473 s->pkblob, s->pklen,
9475 GET_32BIT(s->ret + 5));
9476 ssh2_pkt_send(ssh, s->pktout);
9477 s->type = AUTH_TYPE_PUBLICKEY;
9479 /* FIXME: less drastic response */
9480 bombout(("Pageant failed to answer challenge"));
9486 /* Do we have any keys left to try? */
9487 if (s->pkblob_in_agent) {
9488 s->done_agent = TRUE;
9489 s->tried_pubkey_config = TRUE;
9492 if (s->keyi >= s->nkeys)
9493 s->done_agent = TRUE;
9496 } else if (s->can_pubkey && s->publickey_blob &&
9497 !s->tried_pubkey_config) {
9499 struct ssh2_userkey *key; /* not live over crReturn */
9500 char *passphrase; /* not live over crReturn */
9502 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9504 s->tried_pubkey_config = TRUE;
9507 * Try the public key supplied in the configuration.
9509 * First, offer the public blob to see if the server is
9510 * willing to accept it.
9512 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9513 ssh2_pkt_addstring(s->pktout, ssh->username);
9514 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9515 /* service requested */
9516 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9517 ssh2_pkt_addbool(s->pktout, FALSE);
9518 /* no signature included */
9519 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9520 ssh2_pkt_addstring_start(s->pktout);
9521 ssh2_pkt_addstring_data(s->pktout,
9522 (char *)s->publickey_blob,
9523 s->publickey_bloblen);
9524 ssh2_pkt_send(ssh, s->pktout);
9525 logevent("Offered public key");
9527 crWaitUntilV(pktin);
9528 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9529 /* Key refused. Give up. */
9530 s->gotit = TRUE; /* reconsider message next loop */
9531 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9532 continue; /* process this new message */
9534 logevent("Offer of public key accepted");
9537 * Actually attempt a serious authentication using
9540 if (flags & FLAG_VERBOSE) {
9541 c_write_str(ssh, "Authenticating with public key \"");
9542 c_write_str(ssh, s->publickey_comment);
9543 c_write_str(ssh, "\"\r\n");
9547 const char *error; /* not live over crReturn */
9548 if (s->publickey_encrypted) {
9550 * Get a passphrase from the user.
9552 int ret; /* need not be kept over crReturn */
9553 s->cur_prompt = new_prompts(ssh->frontend);
9554 s->cur_prompt->to_server = FALSE;
9555 s->cur_prompt->name = dupstr("SSH key passphrase");
9556 add_prompt(s->cur_prompt,
9557 dupprintf("Passphrase for key \"%.100s\": ",
9558 s->publickey_comment),
9560 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9563 crWaitUntilV(!pktin);
9564 ret = get_userpass_input(s->cur_prompt,
9569 /* Failed to get a passphrase. Terminate. */
9570 free_prompts(s->cur_prompt);
9571 ssh_disconnect(ssh, NULL,
9572 "Unable to authenticate",
9573 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9578 dupstr(s->cur_prompt->prompts[0]->result);
9579 free_prompts(s->cur_prompt);
9581 passphrase = NULL; /* no passphrase needed */
9585 * Try decrypting the key.
9587 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9588 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9590 /* burn the evidence */
9591 smemclr(passphrase, strlen(passphrase));
9594 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9596 (key == SSH2_WRONG_PASSPHRASE)) {
9597 c_write_str(ssh, "Wrong passphrase\r\n");
9599 /* and loop again */
9601 c_write_str(ssh, "Unable to load private key (");
9602 c_write_str(ssh, error);
9603 c_write_str(ssh, ")\r\n");
9605 break; /* try something else */
9611 unsigned char *pkblob, *sigblob, *sigdata;
9612 int pkblob_len, sigblob_len, sigdata_len;
9616 * We have loaded the private key and the server
9617 * has announced that it's willing to accept it.
9618 * Hallelujah. Generate a signature and send it.
9620 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9621 ssh2_pkt_addstring(s->pktout, ssh->username);
9622 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9623 /* service requested */
9624 ssh2_pkt_addstring(s->pktout, "publickey");
9626 ssh2_pkt_addbool(s->pktout, TRUE);
9627 /* signature follows */
9628 ssh2_pkt_addstring(s->pktout, key->alg->name);
9629 pkblob = key->alg->public_blob(key->data,
9631 ssh2_pkt_addstring_start(s->pktout);
9632 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9636 * The data to be signed is:
9640 * followed by everything so far placed in the
9643 sigdata_len = s->pktout->length - 5 + 4 +
9644 ssh->v2_session_id_len;
9645 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9647 sigdata = snewn(sigdata_len, unsigned char);
9649 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9650 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9653 memcpy(sigdata+p, ssh->v2_session_id,
9654 ssh->v2_session_id_len);
9655 p += ssh->v2_session_id_len;
9656 memcpy(sigdata+p, s->pktout->data + 5,
9657 s->pktout->length - 5);
9658 p += s->pktout->length - 5;
9659 assert(p == sigdata_len);
9660 sigblob = key->alg->sign(key->data, (char *)sigdata,
9661 sigdata_len, &sigblob_len);
9662 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9663 sigblob, sigblob_len);
9668 ssh2_pkt_send(ssh, s->pktout);
9669 logevent("Sent public key signature");
9670 s->type = AUTH_TYPE_PUBLICKEY;
9671 key->alg->freekey(key->data);
9672 sfree(key->comment);
9677 } else if (s->can_gssapi && !s->tried_gssapi) {
9679 /* GSSAPI Authentication */
9684 s->type = AUTH_TYPE_GSSAPI;
9685 s->tried_gssapi = TRUE;
9687 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9690 * Pick the highest GSS library on the preference
9696 for (i = 0; i < ngsslibs; i++) {
9697 int want_id = conf_get_int_int(ssh->conf,
9698 CONF_ssh_gsslist, i);
9699 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
9700 if (ssh->gsslibs->libraries[j].id == want_id) {
9701 s->gsslib = &ssh->gsslibs->libraries[j];
9702 goto got_gsslib; /* double break */
9707 * We always expect to have found something in
9708 * the above loop: we only came here if there
9709 * was at least one viable GSS library, and the
9710 * preference list should always mention
9711 * everything and only change the order.
9716 if (s->gsslib->gsslogmsg)
9717 logevent(s->gsslib->gsslogmsg);
9719 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
9720 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9721 ssh2_pkt_addstring(s->pktout, ssh->username);
9722 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9723 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
9724 logevent("Attempting GSSAPI authentication");
9726 /* add mechanism info */
9727 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
9729 /* number of GSSAPI mechanisms */
9730 ssh2_pkt_adduint32(s->pktout,1);
9732 /* length of OID + 2 */
9733 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
9734 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
9737 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
9739 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
9741 ssh2_pkt_send(ssh, s->pktout);
9742 crWaitUntilV(pktin);
9743 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
9744 logevent("GSSAPI authentication request refused");
9748 /* check returned packet ... */
9750 ssh_pkt_getstring(pktin, &data, &len);
9751 s->gss_rcvtok.value = data;
9752 s->gss_rcvtok.length = len;
9753 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
9754 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
9755 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
9756 memcmp((char *)s->gss_rcvtok.value + 2,
9757 s->gss_buf.value,s->gss_buf.length) ) {
9758 logevent("GSSAPI authentication - wrong response from server");
9762 /* now start running */
9763 s->gss_stat = s->gsslib->import_name(s->gsslib,
9766 if (s->gss_stat != SSH_GSS_OK) {
9767 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
9768 logevent("GSSAPI import name failed - Bad service name");
9770 logevent("GSSAPI import name failed");
9774 /* fetch TGT into GSS engine */
9775 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
9777 if (s->gss_stat != SSH_GSS_OK) {
9778 logevent("GSSAPI authentication failed to get credentials");
9779 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9783 /* initial tokens are empty */
9784 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
9785 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
9787 /* now enter the loop */
9789 s->gss_stat = s->gsslib->init_sec_context
9793 conf_get_int(ssh->conf, CONF_gssapifwd),
9797 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
9798 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
9799 logevent("GSSAPI authentication initialisation failed");
9801 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
9802 &s->gss_buf) == SSH_GSS_OK) {
9803 logevent(s->gss_buf.value);
9804 sfree(s->gss_buf.value);
9809 logevent("GSSAPI authentication initialised");
9811 /* Client and server now exchange tokens until GSSAPI
9812 * no longer says CONTINUE_NEEDED */
9814 if (s->gss_sndtok.length != 0) {
9815 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
9816 ssh_pkt_addstring_start(s->pktout);
9817 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
9818 ssh2_pkt_send(ssh, s->pktout);
9819 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
9822 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
9823 crWaitUntilV(pktin);
9824 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
9825 logevent("GSSAPI authentication - bad server response");
9826 s->gss_stat = SSH_GSS_FAILURE;
9829 ssh_pkt_getstring(pktin, &data, &len);
9830 s->gss_rcvtok.value = data;
9831 s->gss_rcvtok.length = len;
9833 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
9835 if (s->gss_stat != SSH_GSS_OK) {
9836 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9837 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9840 logevent("GSSAPI authentication loop finished OK");
9842 /* Now send the MIC */
9844 s->pktout = ssh2_pkt_init(0);
9845 micoffset = s->pktout->length;
9846 ssh_pkt_addstring_start(s->pktout);
9847 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
9848 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
9849 ssh_pkt_addstring(s->pktout, ssh->username);
9850 ssh_pkt_addstring(s->pktout, "ssh-connection");
9851 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
9853 s->gss_buf.value = (char *)s->pktout->data + micoffset;
9854 s->gss_buf.length = s->pktout->length - micoffset;
9856 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
9857 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
9858 ssh_pkt_addstring_start(s->pktout);
9859 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
9860 ssh2_pkt_send(ssh, s->pktout);
9861 s->gsslib->free_mic(s->gsslib, &mic);
9865 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9866 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9869 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
9872 * Keyboard-interactive authentication.
9875 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
9877 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
9879 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9880 ssh2_pkt_addstring(s->pktout, ssh->username);
9881 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9882 /* service requested */
9883 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
9885 ssh2_pkt_addstring(s->pktout, ""); /* lang */
9886 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
9887 ssh2_pkt_send(ssh, s->pktout);
9889 logevent("Attempting keyboard-interactive authentication");
9891 crWaitUntilV(pktin);
9892 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
9893 /* Server is not willing to do keyboard-interactive
9894 * at all (or, bizarrely but legally, accepts the
9895 * user without actually issuing any prompts).
9896 * Give up on it entirely. */
9898 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
9899 s->kbd_inter_refused = TRUE; /* don't try it again */
9904 * Loop while the server continues to send INFO_REQUESTs.
9906 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
9908 char *name, *inst, *lang;
9909 int name_len, inst_len, lang_len;
9913 * We've got a fresh USERAUTH_INFO_REQUEST.
9914 * Get the preamble and start building a prompt.
9916 ssh_pkt_getstring(pktin, &name, &name_len);
9917 ssh_pkt_getstring(pktin, &inst, &inst_len);
9918 ssh_pkt_getstring(pktin, &lang, &lang_len);
9919 s->cur_prompt = new_prompts(ssh->frontend);
9920 s->cur_prompt->to_server = TRUE;
9923 * Get any prompt(s) from the packet.
9925 s->num_prompts = ssh_pkt_getuint32(pktin);
9926 for (i = 0; i < s->num_prompts; i++) {
9930 static char noprompt[] =
9931 "<server failed to send prompt>: ";
9933 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9934 echo = ssh2_pkt_getbool(pktin);
9937 prompt_len = lenof(noprompt)-1;
9939 add_prompt(s->cur_prompt,
9940 dupprintf("%.*s", prompt_len, prompt),
9945 /* FIXME: better prefix to distinguish from
9947 s->cur_prompt->name =
9948 dupprintf("SSH server: %.*s", name_len, name);
9949 s->cur_prompt->name_reqd = TRUE;
9951 s->cur_prompt->name =
9952 dupstr("SSH server authentication");
9953 s->cur_prompt->name_reqd = FALSE;
9955 /* We add a prefix to try to make it clear that a prompt
9956 * has come from the server.
9957 * FIXME: ugly to print "Using..." in prompt _every_
9958 * time round. Can this be done more subtly? */
9959 /* Special case: for reasons best known to themselves,
9960 * some servers send k-i requests with no prompts and
9961 * nothing to display. Keep quiet in this case. */
9962 if (s->num_prompts || name_len || inst_len) {
9963 s->cur_prompt->instruction =
9964 dupprintf("Using keyboard-interactive authentication.%s%.*s",
9965 inst_len ? "\n" : "", inst_len, inst);
9966 s->cur_prompt->instr_reqd = TRUE;
9968 s->cur_prompt->instr_reqd = FALSE;
9972 * Display any instructions, and get the user's
9976 int ret; /* not live over crReturn */
9977 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9980 crWaitUntilV(!pktin);
9981 ret = get_userpass_input(s->cur_prompt, in, inlen);
9986 * Failed to get responses. Terminate.
9988 free_prompts(s->cur_prompt);
9989 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9990 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9997 * Send the response(s) to the server.
9999 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10000 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10001 for (i=0; i < s->num_prompts; i++) {
10002 ssh2_pkt_addstring(s->pktout,
10003 s->cur_prompt->prompts[i]->result);
10005 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10008 * Free the prompts structure from this iteration.
10009 * If there's another, a new one will be allocated
10010 * when we return to the top of this while loop.
10012 free_prompts(s->cur_prompt);
10015 * Get the next packet in case it's another
10018 crWaitUntilV(pktin);
10023 * We should have SUCCESS or FAILURE now.
10027 } else if (s->can_passwd) {
10030 * Plain old password authentication.
10032 int ret; /* not live over crReturn */
10033 int changereq_first_time; /* not live over crReturn */
10035 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10037 s->cur_prompt = new_prompts(ssh->frontend);
10038 s->cur_prompt->to_server = TRUE;
10039 s->cur_prompt->name = dupstr("SSH password");
10040 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10045 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10048 crWaitUntilV(!pktin);
10049 ret = get_userpass_input(s->cur_prompt, in, inlen);
10054 * Failed to get responses. Terminate.
10056 free_prompts(s->cur_prompt);
10057 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10058 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10063 * Squirrel away the password. (We may need it later if
10064 * asked to change it.)
10066 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10067 free_prompts(s->cur_prompt);
10070 * Send the password packet.
10072 * We pad out the password packet to 256 bytes to make
10073 * it harder for an attacker to find the length of the
10076 * Anyone using a password longer than 256 bytes
10077 * probably doesn't have much to worry about from
10078 * people who find out how long their password is!
10080 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10081 ssh2_pkt_addstring(s->pktout, ssh->username);
10082 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10083 /* service requested */
10084 ssh2_pkt_addstring(s->pktout, "password");
10085 ssh2_pkt_addbool(s->pktout, FALSE);
10086 ssh2_pkt_addstring(s->pktout, s->password);
10087 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10088 logevent("Sent password");
10089 s->type = AUTH_TYPE_PASSWORD;
10092 * Wait for next packet, in case it's a password change
10095 crWaitUntilV(pktin);
10096 changereq_first_time = TRUE;
10098 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10101 * We're being asked for a new password
10102 * (perhaps not for the first time).
10103 * Loop until the server accepts it.
10106 int got_new = FALSE; /* not live over crReturn */
10107 char *prompt; /* not live over crReturn */
10108 int prompt_len; /* not live over crReturn */
10112 if (changereq_first_time)
10113 msg = "Server requested password change";
10115 msg = "Server rejected new password";
10117 c_write_str(ssh, msg);
10118 c_write_str(ssh, "\r\n");
10121 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10123 s->cur_prompt = new_prompts(ssh->frontend);
10124 s->cur_prompt->to_server = TRUE;
10125 s->cur_prompt->name = dupstr("New SSH password");
10126 s->cur_prompt->instruction =
10127 dupprintf("%.*s", prompt_len, prompt);
10128 s->cur_prompt->instr_reqd = TRUE;
10130 * There's no explicit requirement in the protocol
10131 * for the "old" passwords in the original and
10132 * password-change messages to be the same, and
10133 * apparently some Cisco kit supports password change
10134 * by the user entering a blank password originally
10135 * and the real password subsequently, so,
10136 * reluctantly, we prompt for the old password again.
10138 * (On the other hand, some servers don't even bother
10139 * to check this field.)
10141 add_prompt(s->cur_prompt,
10142 dupstr("Current password (blank for previously entered password): "),
10144 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10146 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10150 * Loop until the user manages to enter the same
10155 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10158 crWaitUntilV(!pktin);
10159 ret = get_userpass_input(s->cur_prompt, in, inlen);
10164 * Failed to get responses. Terminate.
10166 /* burn the evidence */
10167 free_prompts(s->cur_prompt);
10168 smemclr(s->password, strlen(s->password));
10169 sfree(s->password);
10170 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10171 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10177 * If the user specified a new original password
10178 * (IYSWIM), overwrite any previously specified
10180 * (A side effect is that the user doesn't have to
10181 * re-enter it if they louse up the new password.)
10183 if (s->cur_prompt->prompts[0]->result[0]) {
10184 smemclr(s->password, strlen(s->password));
10185 /* burn the evidence */
10186 sfree(s->password);
10188 dupstr(s->cur_prompt->prompts[0]->result);
10192 * Check the two new passwords match.
10194 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10195 s->cur_prompt->prompts[2]->result)
10198 /* They don't. Silly user. */
10199 c_write_str(ssh, "Passwords do not match\r\n");
10204 * Send the new password (along with the old one).
10205 * (see above for padding rationale)
10207 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10208 ssh2_pkt_addstring(s->pktout, ssh->username);
10209 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10210 /* service requested */
10211 ssh2_pkt_addstring(s->pktout, "password");
10212 ssh2_pkt_addbool(s->pktout, TRUE);
10213 ssh2_pkt_addstring(s->pktout, s->password);
10214 ssh2_pkt_addstring(s->pktout,
10215 s->cur_prompt->prompts[1]->result);
10216 free_prompts(s->cur_prompt);
10217 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10218 logevent("Sent new password");
10221 * Now see what the server has to say about it.
10222 * (If it's CHANGEREQ again, it's not happy with the
10225 crWaitUntilV(pktin);
10226 changereq_first_time = FALSE;
10231 * We need to reexamine the current pktin at the top
10232 * of the loop. Either:
10233 * - we weren't asked to change password at all, in
10234 * which case it's a SUCCESS or FAILURE with the
10236 * - we sent a new password, and the server was
10237 * either OK with it (SUCCESS or FAILURE w/partial
10238 * success) or unhappy with the _old_ password
10239 * (FAILURE w/o partial success)
10240 * In any of these cases, we go back to the top of
10241 * the loop and start again.
10246 * We don't need the old password any more, in any
10247 * case. Burn the evidence.
10249 smemclr(s->password, strlen(s->password));
10250 sfree(s->password);
10253 char *str = dupprintf("No supported authentication methods available"
10254 " (server sent: %.*s)",
10257 ssh_disconnect(ssh, str,
10258 "No supported authentication methods available",
10259 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10269 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10271 /* Clear up various bits and pieces from authentication. */
10272 if (s->publickey_blob) {
10273 sfree(s->publickey_blob);
10274 sfree(s->publickey_comment);
10276 if (s->agent_response)
10277 sfree(s->agent_response);
10279 if (s->userauth_success && !ssh->bare_connection) {
10281 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10282 * packets since. Signal the transport layer to consider enacting
10283 * delayed compression.
10285 * (Relying on we_are_in is not sufficient, as
10286 * draft-miller-secsh-compression-delayed is quite clear that it
10287 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10288 * become set for other reasons.)
10290 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10293 ssh->channels = newtree234(ssh_channelcmp);
10296 * Set up handlers for some connection protocol messages, so we
10297 * don't have to handle them repeatedly in this coroutine.
10299 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10300 ssh2_msg_channel_window_adjust;
10301 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10302 ssh2_msg_global_request;
10305 * Create the main session channel.
10307 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10308 ssh->mainchan = NULL;
10310 ssh->mainchan = snew(struct ssh_channel);
10311 ssh->mainchan->ssh = ssh;
10312 ssh2_channel_init(ssh->mainchan);
10314 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10316 * Just start a direct-tcpip channel and use it as the main
10319 ssh_send_port_open(ssh->mainchan,
10320 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10321 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10323 ssh->ncmode = TRUE;
10325 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10326 logevent("Opening session as main channel");
10327 ssh2_pkt_send(ssh, s->pktout);
10328 ssh->ncmode = FALSE;
10330 crWaitUntilV(pktin);
10331 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10332 bombout(("Server refused to open channel"));
10334 /* FIXME: error data comes back in FAILURE packet */
10336 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10337 bombout(("Server's channel confirmation cited wrong channel"));
10340 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10341 ssh->mainchan->halfopen = FALSE;
10342 ssh->mainchan->type = CHAN_MAINSESSION;
10343 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10344 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10345 add234(ssh->channels, ssh->mainchan);
10346 update_specials_menu(ssh->frontend);
10347 logevent("Opened main channel");
10351 * Now we have a channel, make dispatch table entries for
10352 * general channel-based messages.
10354 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10355 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10356 ssh2_msg_channel_data;
10357 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10358 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10359 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10360 ssh2_msg_channel_open_confirmation;
10361 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10362 ssh2_msg_channel_open_failure;
10363 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10364 ssh2_msg_channel_request;
10365 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10366 ssh2_msg_channel_open;
10367 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10368 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10371 * Now the connection protocol is properly up and running, with
10372 * all those dispatch table entries, so it's safe to let
10373 * downstreams start trying to open extra channels through us.
10375 if (ssh->connshare)
10376 share_activate(ssh->connshare, ssh->v_s);
10378 if (ssh->mainchan && ssh_is_simple(ssh)) {
10380 * This message indicates to the server that we promise
10381 * not to try to run any other channel in parallel with
10382 * this one, so it's safe for it to advertise a very large
10383 * window and leave the flow control to TCP.
10385 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10386 "simple@putty.projects.tartarus.org",
10388 ssh2_pkt_send(ssh, s->pktout);
10392 * Enable port forwardings.
10394 ssh_setup_portfwd(ssh, ssh->conf);
10396 if (ssh->mainchan && !ssh->ncmode) {
10398 * Send the CHANNEL_REQUESTS for the main session channel.
10399 * Each one is handled by its own little asynchronous
10403 /* Potentially enable X11 forwarding. */
10404 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10406 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10408 if (!ssh->x11disp) {
10409 /* FIXME: return an error message from x11_setup_display */
10410 logevent("X11 forwarding not enabled: unable to"
10411 " initialise X display");
10413 ssh->x11auth = x11_invent_fake_auth
10414 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10415 ssh->x11auth->disp = ssh->x11disp;
10417 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10421 /* Potentially enable agent forwarding. */
10422 if (ssh_agent_forwarding_permitted(ssh))
10423 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10425 /* Now allocate a pty for the session. */
10426 if (!conf_get_int(ssh->conf, CONF_nopty))
10427 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10429 /* Send environment variables. */
10430 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10433 * Start a shell or a remote command. We may have to attempt
10434 * this twice if the config data has provided a second choice
10441 if (ssh->fallback_cmd) {
10442 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10443 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10445 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10446 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10450 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10451 ssh2_response_authconn, NULL);
10452 ssh2_pkt_addstring(s->pktout, cmd);
10454 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10455 ssh2_response_authconn, NULL);
10456 ssh2_pkt_addstring(s->pktout, cmd);
10458 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10459 ssh2_response_authconn, NULL);
10461 ssh2_pkt_send(ssh, s->pktout);
10463 crWaitUntilV(pktin);
10465 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10466 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10467 bombout(("Unexpected response to shell/command request:"
10468 " packet type %d", pktin->type));
10472 * We failed to start the command. If this is the
10473 * fallback command, we really are finished; if it's
10474 * not, and if the fallback command exists, try falling
10475 * back to it before complaining.
10477 if (!ssh->fallback_cmd &&
10478 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10479 logevent("Primary command failed; attempting fallback");
10480 ssh->fallback_cmd = TRUE;
10483 bombout(("Server refused to start a shell/command"));
10486 logevent("Started a shell/command");
10491 ssh->editing = ssh->echoing = TRUE;
10494 ssh->state = SSH_STATE_SESSION;
10495 if (ssh->size_needed)
10496 ssh_size(ssh, ssh->term_width, ssh->term_height);
10497 if (ssh->eof_needed)
10498 ssh_special(ssh, TS_EOF);
10504 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10509 s->try_send = FALSE;
10513 * _All_ the connection-layer packets we expect to
10514 * receive are now handled by the dispatch table.
10515 * Anything that reaches here must be bogus.
10518 bombout(("Strange packet received: type %d", pktin->type));
10520 } else if (ssh->mainchan) {
10522 * We have spare data. Add it to the channel buffer.
10524 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
10525 s->try_send = TRUE;
10529 struct ssh_channel *c;
10531 * Try to send data on all channels if we can.
10533 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
10534 ssh2_try_send_and_unthrottle(ssh, c);
10542 * Handlers for SSH-2 messages that might arrive at any moment.
10544 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10546 /* log reason code in disconnect message */
10548 int reason, msglen;
10550 reason = ssh_pkt_getuint32(pktin);
10551 ssh_pkt_getstring(pktin, &msg, &msglen);
10553 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10554 buf = dupprintf("Received disconnect message (%s)",
10555 ssh2_disconnect_reasons[reason]);
10557 buf = dupprintf("Received disconnect message (unknown"
10558 " type %d)", reason);
10562 buf = dupprintf("Disconnection message text: %.*s",
10565 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10567 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10568 ssh2_disconnect_reasons[reason] : "unknown",
10573 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10575 /* log the debug message */
10579 /* XXX maybe we should actually take notice of the return value */
10580 ssh2_pkt_getbool(pktin);
10581 ssh_pkt_getstring(pktin, &msg, &msglen);
10583 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
10586 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10588 do_ssh2_transport(ssh, NULL, 0, pktin);
10592 * Called if we receive a packet that isn't allowed by the protocol.
10593 * This only applies to packets whose meaning PuTTY understands.
10594 * Entirely unknown packets are handled below.
10596 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10598 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10599 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10601 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10605 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10607 struct Packet *pktout;
10608 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10609 ssh2_pkt_adduint32(pktout, pktin->sequence);
10611 * UNIMPLEMENTED messages MUST appear in the same order as the
10612 * messages they respond to. Hence, never queue them.
10614 ssh2_pkt_send_noqueue(ssh, pktout);
10618 * Handle the top-level SSH-2 protocol.
10620 static void ssh2_protocol_setup(Ssh ssh)
10625 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10627 for (i = 0; i < 256; i++)
10628 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10631 * Initially, we only accept transport messages (and a few generic
10632 * ones). do_ssh2_authconn will add more when it starts.
10633 * Messages that are understood but not currently acceptable go to
10634 * ssh2_msg_unexpected.
10636 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10637 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10638 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10639 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10640 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10641 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10642 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10643 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10644 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10645 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10646 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10647 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10648 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10649 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10650 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10651 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10652 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10653 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10654 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10655 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10656 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10657 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10658 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10659 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10660 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10661 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10662 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10663 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10664 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10665 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10666 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10667 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10668 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10671 * These messages have a special handler from the start.
10673 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10674 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10675 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10678 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10683 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10685 for (i = 0; i < 256; i++)
10686 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10689 * Initially, we set all ssh-connection messages to 'unexpected';
10690 * do_ssh2_authconn will fill things in properly. We also handle a
10691 * couple of messages from the transport protocol which aren't
10692 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10695 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10696 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10697 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10698 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10699 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10700 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10701 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10702 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10703 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10704 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10705 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10706 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10707 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10708 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10710 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10713 * These messages have a special handler from the start.
10715 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10716 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
10717 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10720 static void ssh2_timer(void *ctx, unsigned long now)
10722 Ssh ssh = (Ssh)ctx;
10724 if (ssh->state == SSH_STATE_CLOSED)
10727 if (!ssh->kex_in_progress && !ssh->bare_connection &&
10728 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
10729 now == ssh->next_rekey) {
10730 do_ssh2_transport(ssh, "timeout", -1, NULL);
10734 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
10735 struct Packet *pktin)
10737 unsigned char *in = (unsigned char *)vin;
10738 if (ssh->state == SSH_STATE_CLOSED)
10742 ssh->incoming_data_size += pktin->encrypted_len;
10743 if (!ssh->kex_in_progress &&
10744 ssh->max_data_size != 0 &&
10745 ssh->incoming_data_size > ssh->max_data_size)
10746 do_ssh2_transport(ssh, "too much data received", -1, NULL);
10750 ssh->packet_dispatch[pktin->type](ssh, pktin);
10751 else if (!ssh->protocol_initial_phase_done)
10752 do_ssh2_transport(ssh, in, inlen, pktin);
10754 do_ssh2_authconn(ssh, in, inlen, pktin);
10757 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
10758 struct Packet *pktin)
10760 unsigned char *in = (unsigned char *)vin;
10761 if (ssh->state == SSH_STATE_CLOSED)
10765 ssh->packet_dispatch[pktin->type](ssh, pktin);
10767 do_ssh2_authconn(ssh, in, inlen, pktin);
10770 static void ssh_cache_conf_values(Ssh ssh)
10772 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
10776 * Called to set up the connection.
10778 * Returns an error message, or NULL on success.
10780 static const char *ssh_init(void *frontend_handle, void **backend_handle,
10781 Conf *conf, char *host, int port, char **realhost,
10782 int nodelay, int keepalive)
10787 ssh = snew(struct ssh_tag);
10788 ssh->conf = conf_copy(conf);
10789 ssh_cache_conf_values(ssh);
10790 ssh->version = 0; /* when not ready yet */
10792 ssh->cipher = NULL;
10793 ssh->v1_cipher_ctx = NULL;
10794 ssh->crcda_ctx = NULL;
10795 ssh->cscipher = NULL;
10796 ssh->cs_cipher_ctx = NULL;
10797 ssh->sccipher = NULL;
10798 ssh->sc_cipher_ctx = NULL;
10800 ssh->cs_mac_ctx = NULL;
10802 ssh->sc_mac_ctx = NULL;
10803 ssh->cscomp = NULL;
10804 ssh->cs_comp_ctx = NULL;
10805 ssh->sccomp = NULL;
10806 ssh->sc_comp_ctx = NULL;
10808 ssh->kex_ctx = NULL;
10809 ssh->hostkey = NULL;
10810 ssh->hostkey_str = NULL;
10811 ssh->exitcode = -1;
10812 ssh->close_expected = FALSE;
10813 ssh->clean_exit = FALSE;
10814 ssh->state = SSH_STATE_PREPACKET;
10815 ssh->size_needed = FALSE;
10816 ssh->eof_needed = FALSE;
10818 ssh->logctx = NULL;
10819 ssh->deferred_send_data = NULL;
10820 ssh->deferred_len = 0;
10821 ssh->deferred_size = 0;
10822 ssh->fallback_cmd = 0;
10823 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
10824 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
10825 ssh->x11disp = NULL;
10826 ssh->x11auth = NULL;
10827 ssh->x11authtree = newtree234(x11_authcmp);
10828 ssh->v1_compressing = FALSE;
10829 ssh->v2_outgoing_sequence = 0;
10830 ssh->ssh1_rdpkt_crstate = 0;
10831 ssh->ssh2_rdpkt_crstate = 0;
10832 ssh->ssh2_bare_rdpkt_crstate = 0;
10833 ssh->ssh_gotdata_crstate = 0;
10834 ssh->do_ssh1_connection_crstate = 0;
10835 ssh->do_ssh_init_state = NULL;
10836 ssh->do_ssh_connection_init_state = NULL;
10837 ssh->do_ssh1_login_state = NULL;
10838 ssh->do_ssh2_transport_state = NULL;
10839 ssh->do_ssh2_authconn_state = NULL;
10842 ssh->mainchan = NULL;
10843 ssh->throttled_all = 0;
10844 ssh->v1_stdout_throttling = 0;
10846 ssh->queuelen = ssh->queuesize = 0;
10847 ssh->queueing = FALSE;
10848 ssh->qhead = ssh->qtail = NULL;
10849 ssh->deferred_rekey_reason = NULL;
10850 bufchain_init(&ssh->queued_incoming_data);
10851 ssh->frozen = FALSE;
10852 ssh->username = NULL;
10853 ssh->sent_console_eof = FALSE;
10854 ssh->got_pty = FALSE;
10855 ssh->bare_connection = FALSE;
10856 ssh->X11_fwd_enabled = FALSE;
10857 ssh->connshare = NULL;
10858 ssh->attempting_connshare = FALSE;
10860 *backend_handle = ssh;
10863 if (crypto_startup() == 0)
10864 return "Microsoft high encryption pack not installed!";
10867 ssh->frontend = frontend_handle;
10868 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
10869 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
10871 ssh->channels = NULL;
10872 ssh->rportfwds = NULL;
10873 ssh->portfwds = NULL;
10878 ssh->conn_throttle_count = 0;
10879 ssh->overall_bufsize = 0;
10880 ssh->fallback_cmd = 0;
10882 ssh->protocol = NULL;
10884 ssh->protocol_initial_phase_done = FALSE;
10886 ssh->pinger = NULL;
10888 ssh->incoming_data_size = ssh->outgoing_data_size =
10889 ssh->deferred_data_size = 0L;
10890 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10891 CONF_ssh_rekey_data));
10892 ssh->kex_in_progress = FALSE;
10895 ssh->gsslibs = NULL;
10898 random_ref(); /* do this now - may be needed by sharing setup code */
10900 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
10909 static void ssh_free(void *handle)
10911 Ssh ssh = (Ssh) handle;
10912 struct ssh_channel *c;
10913 struct ssh_rportfwd *pf;
10914 struct X11FakeAuth *auth;
10916 if (ssh->v1_cipher_ctx)
10917 ssh->cipher->free_context(ssh->v1_cipher_ctx);
10918 if (ssh->cs_cipher_ctx)
10919 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
10920 if (ssh->sc_cipher_ctx)
10921 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
10922 if (ssh->cs_mac_ctx)
10923 ssh->csmac->free_context(ssh->cs_mac_ctx);
10924 if (ssh->sc_mac_ctx)
10925 ssh->scmac->free_context(ssh->sc_mac_ctx);
10926 if (ssh->cs_comp_ctx) {
10928 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
10930 zlib_compress_cleanup(ssh->cs_comp_ctx);
10932 if (ssh->sc_comp_ctx) {
10934 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
10936 zlib_decompress_cleanup(ssh->sc_comp_ctx);
10939 dh_cleanup(ssh->kex_ctx);
10940 sfree(ssh->savedhost);
10942 while (ssh->queuelen-- > 0)
10943 ssh_free_packet(ssh->queue[ssh->queuelen]);
10946 while (ssh->qhead) {
10947 struct queued_handler *qh = ssh->qhead;
10948 ssh->qhead = qh->next;
10951 ssh->qhead = ssh->qtail = NULL;
10953 if (ssh->channels) {
10954 while ((c = delpos234(ssh->channels, 0)) != NULL) {
10957 if (c->u.x11.xconn != NULL)
10958 x11_close(c->u.x11.xconn);
10960 case CHAN_SOCKDATA:
10961 case CHAN_SOCKDATA_DORMANT:
10962 if (c->u.pfd.pf != NULL)
10963 pfd_close(c->u.pfd.pf);
10966 if (ssh->version == 2) {
10967 struct outstanding_channel_request *ocr, *nocr;
10968 ocr = c->v.v2.chanreq_head;
10970 ocr->handler(c, NULL, ocr->ctx);
10975 bufchain_clear(&c->v.v2.outbuffer);
10979 freetree234(ssh->channels);
10980 ssh->channels = NULL;
10983 if (ssh->connshare)
10984 sharestate_free(ssh->connshare);
10986 if (ssh->rportfwds) {
10987 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
10989 freetree234(ssh->rportfwds);
10990 ssh->rportfwds = NULL;
10992 sfree(ssh->deferred_send_data);
10994 x11_free_display(ssh->x11disp);
10995 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
10996 x11_free_fake_auth(auth);
10997 freetree234(ssh->x11authtree);
10998 sfree(ssh->do_ssh_init_state);
10999 sfree(ssh->do_ssh1_login_state);
11000 sfree(ssh->do_ssh2_transport_state);
11001 sfree(ssh->do_ssh2_authconn_state);
11004 sfree(ssh->fullhostname);
11005 sfree(ssh->hostkey_str);
11006 if (ssh->crcda_ctx) {
11007 crcda_free_context(ssh->crcda_ctx);
11008 ssh->crcda_ctx = NULL;
11011 ssh_do_close(ssh, TRUE);
11012 expire_timer_context(ssh);
11014 pinger_free(ssh->pinger);
11015 bufchain_clear(&ssh->queued_incoming_data);
11016 sfree(ssh->username);
11017 conf_free(ssh->conf);
11020 ssh_gss_cleanup(ssh->gsslibs);
11028 * Reconfigure the SSH backend.
11030 static void ssh_reconfig(void *handle, Conf *conf)
11032 Ssh ssh = (Ssh) handle;
11033 char *rekeying = NULL, rekey_mandatory = FALSE;
11034 unsigned long old_max_data_size;
11037 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11039 ssh_setup_portfwd(ssh, conf);
11041 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11042 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11044 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11045 unsigned long now = GETTICKCOUNT();
11047 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11048 rekeying = "timeout shortened";
11050 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11054 old_max_data_size = ssh->max_data_size;
11055 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11056 CONF_ssh_rekey_data));
11057 if (old_max_data_size != ssh->max_data_size &&
11058 ssh->max_data_size != 0) {
11059 if (ssh->outgoing_data_size > ssh->max_data_size ||
11060 ssh->incoming_data_size > ssh->max_data_size)
11061 rekeying = "data limit lowered";
11064 if (conf_get_int(ssh->conf, CONF_compression) !=
11065 conf_get_int(conf, CONF_compression)) {
11066 rekeying = "compression setting changed";
11067 rekey_mandatory = TRUE;
11070 for (i = 0; i < CIPHER_MAX; i++)
11071 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11072 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11073 rekeying = "cipher settings changed";
11074 rekey_mandatory = TRUE;
11076 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11077 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11078 rekeying = "cipher settings changed";
11079 rekey_mandatory = TRUE;
11082 conf_free(ssh->conf);
11083 ssh->conf = conf_copy(conf);
11084 ssh_cache_conf_values(ssh);
11086 if (!ssh->bare_connection && rekeying) {
11087 if (!ssh->kex_in_progress) {
11088 do_ssh2_transport(ssh, rekeying, -1, NULL);
11089 } else if (rekey_mandatory) {
11090 ssh->deferred_rekey_reason = rekeying;
11096 * Called to send data down the SSH connection.
11098 static int ssh_send(void *handle, char *buf, int len)
11100 Ssh ssh = (Ssh) handle;
11102 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11105 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
11107 return ssh_sendbuffer(ssh);
11111 * Called to query the current amount of buffered stdin data.
11113 static int ssh_sendbuffer(void *handle)
11115 Ssh ssh = (Ssh) handle;
11116 int override_value;
11118 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11122 * If the SSH socket itself has backed up, add the total backup
11123 * size on that to any individual buffer on the stdin channel.
11125 override_value = 0;
11126 if (ssh->throttled_all)
11127 override_value = ssh->overall_bufsize;
11129 if (ssh->version == 1) {
11130 return override_value;
11131 } else if (ssh->version == 2) {
11132 if (!ssh->mainchan)
11133 return override_value;
11135 return (override_value +
11136 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11143 * Called to set the size of the window from SSH's POV.
11145 static void ssh_size(void *handle, int width, int height)
11147 Ssh ssh = (Ssh) handle;
11148 struct Packet *pktout;
11150 ssh->term_width = width;
11151 ssh->term_height = height;
11153 switch (ssh->state) {
11154 case SSH_STATE_BEFORE_SIZE:
11155 case SSH_STATE_PREPACKET:
11156 case SSH_STATE_CLOSED:
11157 break; /* do nothing */
11158 case SSH_STATE_INTERMED:
11159 ssh->size_needed = TRUE; /* buffer for later */
11161 case SSH_STATE_SESSION:
11162 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11163 if (ssh->version == 1) {
11164 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11165 PKT_INT, ssh->term_height,
11166 PKT_INT, ssh->term_width,
11167 PKT_INT, 0, PKT_INT, 0, PKT_END);
11168 } else if (ssh->mainchan) {
11169 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11171 ssh2_pkt_adduint32(pktout, ssh->term_width);
11172 ssh2_pkt_adduint32(pktout, ssh->term_height);
11173 ssh2_pkt_adduint32(pktout, 0);
11174 ssh2_pkt_adduint32(pktout, 0);
11175 ssh2_pkt_send(ssh, pktout);
11183 * Return a list of the special codes that make sense in this
11186 static const struct telnet_special *ssh_get_specials(void *handle)
11188 static const struct telnet_special ssh1_ignore_special[] = {
11189 {"IGNORE message", TS_NOP}
11191 static const struct telnet_special ssh2_ignore_special[] = {
11192 {"IGNORE message", TS_NOP},
11194 static const struct telnet_special ssh2_rekey_special[] = {
11195 {"Repeat key exchange", TS_REKEY},
11197 static const struct telnet_special ssh2_session_specials[] = {
11200 /* These are the signal names defined by RFC 4254.
11201 * They include all the ISO C signals, but are a subset of the POSIX
11202 * required signals. */
11203 {"SIGINT (Interrupt)", TS_SIGINT},
11204 {"SIGTERM (Terminate)", TS_SIGTERM},
11205 {"SIGKILL (Kill)", TS_SIGKILL},
11206 {"SIGQUIT (Quit)", TS_SIGQUIT},
11207 {"SIGHUP (Hangup)", TS_SIGHUP},
11208 {"More signals", TS_SUBMENU},
11209 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11210 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11211 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11212 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11213 {NULL, TS_EXITMENU}
11215 static const struct telnet_special specials_end[] = {
11216 {NULL, TS_EXITMENU}
11218 /* XXX review this length for any changes: */
11219 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
11220 lenof(ssh2_rekey_special) +
11221 lenof(ssh2_session_specials) +
11222 lenof(specials_end)];
11223 Ssh ssh = (Ssh) handle;
11225 #define ADD_SPECIALS(name) \
11227 assert((i + lenof(name)) <= lenof(ssh_specials)); \
11228 memcpy(&ssh_specials[i], name, sizeof name); \
11229 i += lenof(name); \
11232 if (ssh->version == 1) {
11233 /* Don't bother offering IGNORE if we've decided the remote
11234 * won't cope with it, since we wouldn't bother sending it if
11236 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11237 ADD_SPECIALS(ssh1_ignore_special);
11238 } else if (ssh->version == 2) {
11239 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11240 ADD_SPECIALS(ssh2_ignore_special);
11241 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11242 ADD_SPECIALS(ssh2_rekey_special);
11244 ADD_SPECIALS(ssh2_session_specials);
11245 } /* else we're not ready yet */
11248 ADD_SPECIALS(specials_end);
11249 return ssh_specials;
11253 #undef ADD_SPECIALS
11257 * Send special codes. TS_EOF is useful for `plink', so you
11258 * can send an EOF and collect resulting output (e.g. `plink
11261 static void ssh_special(void *handle, Telnet_Special code)
11263 Ssh ssh = (Ssh) handle;
11264 struct Packet *pktout;
11266 if (code == TS_EOF) {
11267 if (ssh->state != SSH_STATE_SESSION) {
11269 * Buffer the EOF in case we are pre-SESSION, so we can
11270 * send it as soon as we reach SESSION.
11272 if (code == TS_EOF)
11273 ssh->eof_needed = TRUE;
11276 if (ssh->version == 1) {
11277 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11278 } else if (ssh->mainchan) {
11279 sshfwd_write_eof(ssh->mainchan);
11280 ssh->send_ok = 0; /* now stop trying to read from stdin */
11282 logevent("Sent EOF message");
11283 } else if (code == TS_PING || code == TS_NOP) {
11284 if (ssh->state == SSH_STATE_CLOSED
11285 || ssh->state == SSH_STATE_PREPACKET) return;
11286 if (ssh->version == 1) {
11287 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11288 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11290 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11291 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11292 ssh2_pkt_addstring_start(pktout);
11293 ssh2_pkt_send_noqueue(ssh, pktout);
11296 } else if (code == TS_REKEY) {
11297 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11298 ssh->version == 2) {
11299 do_ssh2_transport(ssh, "at user request", -1, NULL);
11301 } else if (code == TS_BRK) {
11302 if (ssh->state == SSH_STATE_CLOSED
11303 || ssh->state == SSH_STATE_PREPACKET) return;
11304 if (ssh->version == 1) {
11305 logevent("Unable to send BREAK signal in SSH-1");
11306 } else if (ssh->mainchan) {
11307 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11308 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11309 ssh2_pkt_send(ssh, pktout);
11312 /* Is is a POSIX signal? */
11313 char *signame = NULL;
11314 if (code == TS_SIGABRT) signame = "ABRT";
11315 if (code == TS_SIGALRM) signame = "ALRM";
11316 if (code == TS_SIGFPE) signame = "FPE";
11317 if (code == TS_SIGHUP) signame = "HUP";
11318 if (code == TS_SIGILL) signame = "ILL";
11319 if (code == TS_SIGINT) signame = "INT";
11320 if (code == TS_SIGKILL) signame = "KILL";
11321 if (code == TS_SIGPIPE) signame = "PIPE";
11322 if (code == TS_SIGQUIT) signame = "QUIT";
11323 if (code == TS_SIGSEGV) signame = "SEGV";
11324 if (code == TS_SIGTERM) signame = "TERM";
11325 if (code == TS_SIGUSR1) signame = "USR1";
11326 if (code == TS_SIGUSR2) signame = "USR2";
11327 /* The SSH-2 protocol does in principle support arbitrary named
11328 * signals, including signame@domain, but we don't support those. */
11330 /* It's a signal. */
11331 if (ssh->version == 2 && ssh->mainchan) {
11332 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11333 ssh2_pkt_addstring(pktout, signame);
11334 ssh2_pkt_send(ssh, pktout);
11335 logeventf(ssh, "Sent signal SIG%s", signame);
11338 /* Never heard of it. Do nothing */
11343 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11345 Ssh ssh = (Ssh) handle;
11346 struct ssh_channel *c;
11347 c = snew(struct ssh_channel);
11350 ssh2_channel_init(c);
11351 c->halfopen = TRUE;
11352 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11354 add234(ssh->channels, c);
11358 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11360 struct ssh_channel *c;
11361 c = snew(struct ssh_channel);
11364 ssh2_channel_init(c);
11365 c->type = CHAN_SHARING;
11366 c->u.sharing.ctx = sharing_ctx;
11367 add234(ssh->channels, c);
11371 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11373 struct ssh_channel *c;
11375 c = find234(ssh->channels, &localid, ssh_channelfind);
11377 ssh_channel_destroy(c);
11380 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11381 const void *data, int datalen,
11382 const char *additional_log_text)
11384 struct Packet *pkt;
11386 pkt = ssh2_pkt_init(type);
11387 pkt->downstream_id = id;
11388 pkt->additional_log_text = additional_log_text;
11389 ssh2_pkt_adddata(pkt, data, datalen);
11390 ssh2_pkt_send(ssh, pkt);
11394 * This is called when stdout/stderr (the entity to which
11395 * from_backend sends data) manages to clear some backlog.
11397 static void ssh_unthrottle(void *handle, int bufsize)
11399 Ssh ssh = (Ssh) handle;
11402 if (ssh->version == 1) {
11403 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11404 ssh->v1_stdout_throttling = 0;
11405 ssh_throttle_conn(ssh, -1);
11408 if (ssh->mainchan) {
11409 ssh2_set_window(ssh->mainchan,
11410 bufsize < ssh->mainchan->v.v2.locmaxwin ?
11411 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11412 if (ssh_is_simple(ssh))
11415 buflimit = ssh->mainchan->v.v2.locmaxwin;
11416 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11417 ssh->mainchan->throttling_conn = 0;
11418 ssh_throttle_conn(ssh, -1);
11424 * Now process any SSH connection data that was stashed in our
11425 * queue while we were frozen.
11427 ssh_process_queued_incoming_data(ssh);
11430 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
11432 struct ssh_channel *c = (struct ssh_channel *)channel;
11434 struct Packet *pktout;
11436 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11438 if (ssh->version == 1) {
11439 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11440 PKT_INT, c->localid,
11443 /* PKT_STR, <org:orgport>, */
11446 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11448 char *trimmed_host = host_strduptrim(hostname);
11449 ssh2_pkt_addstring(pktout, trimmed_host);
11450 sfree(trimmed_host);
11452 ssh2_pkt_adduint32(pktout, port);
11454 * We make up values for the originator data; partly it's
11455 * too much hassle to keep track, and partly I'm not
11456 * convinced the server should be told details like that
11457 * about my local network configuration.
11458 * The "originator IP address" is syntactically a numeric
11459 * IP address, and some servers (e.g., Tectia) get upset
11460 * if it doesn't match this syntax.
11462 ssh2_pkt_addstring(pktout, "0.0.0.0");
11463 ssh2_pkt_adduint32(pktout, 0);
11464 ssh2_pkt_send(ssh, pktout);
11468 static int ssh_connected(void *handle)
11470 Ssh ssh = (Ssh) handle;
11471 return ssh->s != NULL;
11474 static int ssh_sendok(void *handle)
11476 Ssh ssh = (Ssh) handle;
11477 return ssh->send_ok;
11480 static int ssh_ldisc(void *handle, int option)
11482 Ssh ssh = (Ssh) handle;
11483 if (option == LD_ECHO)
11484 return ssh->echoing;
11485 if (option == LD_EDIT)
11486 return ssh->editing;
11490 static void ssh_provide_ldisc(void *handle, void *ldisc)
11492 Ssh ssh = (Ssh) handle;
11493 ssh->ldisc = ldisc;
11496 static void ssh_provide_logctx(void *handle, void *logctx)
11498 Ssh ssh = (Ssh) handle;
11499 ssh->logctx = logctx;
11502 static int ssh_return_exitcode(void *handle)
11504 Ssh ssh = (Ssh) handle;
11505 if (ssh->s != NULL)
11508 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11512 * cfg_info for SSH is the protocol running in this session.
11513 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11514 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11516 static int ssh_cfg_info(void *handle)
11518 Ssh ssh = (Ssh) handle;
11519 if (ssh->version == 0)
11520 return 0; /* don't know yet */
11521 else if (ssh->bare_connection)
11524 return ssh->version;
11528 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11529 * that fails. This variable is the means by which scp.c can reach
11530 * into the SSH code and find out which one it got.
11532 extern int ssh_fallback_cmd(void *handle)
11534 Ssh ssh = (Ssh) handle;
11535 return ssh->fallback_cmd;
11538 Backend ssh_backend = {
11548 ssh_return_exitcode,
11552 ssh_provide_logctx,