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 const 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 const char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx,
240 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
241 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
242 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
243 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
244 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
245 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
246 translate(SSH2_MSG_DISCONNECT);
247 translate(SSH2_MSG_IGNORE);
248 translate(SSH2_MSG_UNIMPLEMENTED);
249 translate(SSH2_MSG_DEBUG);
250 translate(SSH2_MSG_SERVICE_REQUEST);
251 translate(SSH2_MSG_SERVICE_ACCEPT);
252 translate(SSH2_MSG_KEXINIT);
253 translate(SSH2_MSG_NEWKEYS);
254 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
255 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
256 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD, SSH2_PKTCTX_DHGEX);
257 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
258 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
259 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
260 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
261 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
262 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
263 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
264 translatek(SSH2_MSG_KEX_ECDH_INIT, SSH2_PKTCTX_ECDHKEX);
265 translatek(SSH2_MSG_KEX_ECDH_REPLY, SSH2_PKTCTX_ECDHKEX);
266 translate(SSH2_MSG_USERAUTH_REQUEST);
267 translate(SSH2_MSG_USERAUTH_FAILURE);
268 translate(SSH2_MSG_USERAUTH_SUCCESS);
269 translate(SSH2_MSG_USERAUTH_BANNER);
270 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
271 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
272 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
273 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
274 translate(SSH2_MSG_GLOBAL_REQUEST);
275 translate(SSH2_MSG_REQUEST_SUCCESS);
276 translate(SSH2_MSG_REQUEST_FAILURE);
277 translate(SSH2_MSG_CHANNEL_OPEN);
278 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
279 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
280 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
281 translate(SSH2_MSG_CHANNEL_DATA);
282 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
283 translate(SSH2_MSG_CHANNEL_EOF);
284 translate(SSH2_MSG_CHANNEL_CLOSE);
285 translate(SSH2_MSG_CHANNEL_REQUEST);
286 translate(SSH2_MSG_CHANNEL_SUCCESS);
287 translate(SSH2_MSG_CHANNEL_FAILURE);
293 /* Enumeration values for fields in SSH-1 packets */
295 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
299 * Coroutine mechanics for the sillier bits of the code. If these
300 * macros look impenetrable to you, you might find it helpful to
303 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
305 * which explains the theory behind these macros.
307 * In particular, if you are getting `case expression not constant'
308 * errors when building with MS Visual Studio, this is because MS's
309 * Edit and Continue debugging feature causes their compiler to
310 * violate ANSI C. To disable Edit and Continue debugging:
312 * - right-click ssh.c in the FileView
314 * - select the C/C++ tab and the General category
315 * - under `Debug info:', select anything _other_ than `Program
316 * Database for Edit and Continue'.
318 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
319 #define crBeginState crBegin(s->crLine)
320 #define crStateP(t, v) \
322 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
324 #define crState(t) crStateP(t, ssh->t)
325 #define crFinish(z) } *crLine = 0; return (z); }
326 #define crFinishV } *crLine = 0; return; }
327 #define crFinishFree(z) } sfree(s); return (z); }
328 #define crFinishFreeV } sfree(s); return; }
329 #define crReturn(z) \
331 *crLine =__LINE__; return (z); case __LINE__:;\
335 *crLine=__LINE__; return; case __LINE__:;\
337 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
338 #define crStopV do{ *crLine = 0; return; }while(0)
339 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
340 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
344 static struct Packet *ssh1_pkt_init(int pkt_type);
345 static struct Packet *ssh2_pkt_init(int pkt_type);
346 static void ssh_pkt_ensure(struct Packet *, int length);
347 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
348 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
349 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
350 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
351 static void ssh_pkt_addstring_start(struct Packet *);
352 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
353 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
354 static void ssh_pkt_addstring(struct Packet *, const char *data);
355 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
356 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
357 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
358 static int ssh2_pkt_construct(Ssh, struct Packet *);
359 static void ssh2_pkt_send(Ssh, struct Packet *);
360 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
361 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
362 struct Packet *pktin);
363 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
364 struct Packet *pktin);
365 static void ssh2_channel_check_close(struct ssh_channel *c);
366 static void ssh_channel_destroy(struct ssh_channel *c);
369 * Buffer management constants. There are several of these for
370 * various different purposes:
372 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
373 * on a local data stream before we throttle the whole SSH
374 * connection (in SSH-1 only). Throttling the whole connection is
375 * pretty drastic so we set this high in the hope it won't
378 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
379 * on the SSH connection itself before we defensively throttle
380 * _all_ local data streams. This is pretty drastic too (though
381 * thankfully unlikely in SSH-2 since the window mechanism should
382 * ensure that the server never has any need to throttle its end
383 * of the connection), so we set this high as well.
385 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
388 * - OUR_V2_BIGWIN is the window size we advertise for the only
389 * channel in a simple connection. It must be <= INT_MAX.
391 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
392 * to the remote side. This actually has nothing to do with the
393 * size of the _packet_, but is instead a limit on the amount
394 * of data we're willing to receive in a single SSH2 channel
397 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
398 * _packet_ we're prepared to cope with. It must be a multiple
399 * of the cipher block size, and must be at least 35000.
402 #define SSH1_BUFFER_LIMIT 32768
403 #define SSH_MAX_BACKLOG 32768
404 #define OUR_V2_WINSIZE 16384
405 #define OUR_V2_BIGWIN 0x7fffffff
406 #define OUR_V2_MAXPKT 0x4000UL
407 #define OUR_V2_PACKETLIMIT 0x9000UL
409 const static struct ssh_signkey *hostkey_algs[] = {
411 &ssh_ecdsa_nistp256, &ssh_ecdsa_nistp384, &ssh_ecdsa_nistp521,
415 const static struct ssh_mac *macs[] = {
416 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
418 const static struct ssh_mac *buggymacs[] = {
419 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
422 static void *ssh_comp_none_init(void)
426 static void ssh_comp_none_cleanup(void *handle)
429 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
430 unsigned char **outblock, int *outlen)
434 static int ssh_comp_none_disable(void *handle)
438 const static struct ssh_compress ssh_comp_none = {
440 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
441 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
442 ssh_comp_none_disable, NULL
444 extern const struct ssh_compress ssh_zlib;
445 const static struct ssh_compress *compressions[] = {
446 &ssh_zlib, &ssh_comp_none
449 enum { /* channel types */
454 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
456 * CHAN_SHARING indicates a channel which is tracked here on
457 * behalf of a connection-sharing downstream. We do almost nothing
458 * with these channels ourselves: all messages relating to them
459 * get thrown straight to sshshare.c and passed on almost
460 * unmodified to downstream.
464 * CHAN_ZOMBIE is used to indicate a channel for which we've
465 * already destroyed the local data source: for instance, if a
466 * forwarded port experiences a socket error on the local side, we
467 * immediately destroy its local socket and turn the SSH channel
473 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
474 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
475 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
478 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
481 struct outstanding_channel_request {
482 cchandler_fn_t handler;
484 struct outstanding_channel_request *next;
488 * 2-3-4 tree storing channels.
491 Ssh ssh; /* pointer back to main context */
492 unsigned remoteid, localid;
494 /* True if we opened this channel but server hasn't confirmed. */
497 * In SSH-1, this value contains four bits:
499 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
500 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
501 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
502 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
504 * A channel is completely finished with when all four bits are set.
506 * In SSH-2, the four bits mean:
508 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
509 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
510 * 4 We have received SSH2_MSG_CHANNEL_EOF.
511 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
513 * A channel is completely finished with when we have both sent
514 * and received CLOSE.
516 * The symbolic constants below use the SSH-2 terminology, which
517 * is a bit confusing in SSH-1, but we have to use _something_.
519 #define CLOSES_SENT_EOF 1
520 #define CLOSES_SENT_CLOSE 2
521 #define CLOSES_RCVD_EOF 4
522 #define CLOSES_RCVD_CLOSE 8
526 * This flag indicates that an EOF is pending on the outgoing side
527 * of the channel: that is, wherever we're getting the data for
528 * this channel has sent us some data followed by EOF. We can't
529 * actually send the EOF until we've finished sending the data, so
530 * we set this flag instead to remind us to do so once our buffer
536 * True if this channel is causing the underlying connection to be
541 struct ssh2_data_channel {
543 unsigned remwindow, remmaxpkt;
544 /* locwindow is signed so we can cope with excess data. */
545 int locwindow, locmaxwin;
547 * remlocwin is the amount of local window that we think
548 * the remote end had available to it after it sent the
549 * last data packet or window adjust ack.
553 * These store the list of channel requests that haven't
556 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
557 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
561 struct ssh_agent_channel {
562 unsigned char *message;
563 unsigned char msglen[4];
564 unsigned lensofar, totallen;
565 int outstanding_requests;
567 struct ssh_x11_channel {
568 struct X11Connection *xconn;
571 struct ssh_pfd_channel {
572 struct PortForwarding *pf;
574 struct ssh_sharing_channel {
581 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
582 * use this structure in different ways, reflecting SSH-2's
583 * altogether saner approach to port forwarding.
585 * In SSH-1, you arrange a remote forwarding by sending the server
586 * the remote port number, and the local destination host:port.
587 * When a connection comes in, the server sends you back that
588 * host:port pair, and you connect to it. This is a ready-made
589 * security hole if you're not on the ball: a malicious server
590 * could send you back _any_ host:port pair, so if you trustingly
591 * connect to the address it gives you then you've just opened the
592 * entire inside of your corporate network just by connecting
593 * through it to a dodgy SSH server. Hence, we must store a list of
594 * host:port pairs we _are_ trying to forward to, and reject a
595 * connection request from the server if it's not in the list.
597 * In SSH-2, each side of the connection minds its own business and
598 * doesn't send unnecessary information to the other. You arrange a
599 * remote forwarding by sending the server just the remote port
600 * number. When a connection comes in, the server tells you which
601 * of its ports was connected to; and _you_ have to remember what
602 * local host:port pair went with that port number.
604 * Hence, in SSH-1 this structure is indexed by destination
605 * host:port pair, whereas in SSH-2 it is indexed by source port.
607 struct ssh_portfwd; /* forward declaration */
609 struct ssh_rportfwd {
610 unsigned sport, dport;
614 struct ssh_portfwd *pfrec;
617 static void free_rportfwd(struct ssh_rportfwd *pf)
620 sfree(pf->sportdesc);
628 * Separately to the rportfwd tree (which is for looking up port
629 * open requests from the server), a tree of _these_ structures is
630 * used to keep track of all the currently open port forwardings,
631 * so that we can reconfigure in mid-session if the user requests
635 enum { DESTROY, KEEP, CREATE } status;
637 unsigned sport, dport;
640 struct ssh_rportfwd *remote;
642 struct PortListener *local;
644 #define free_portfwd(pf) ( \
645 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
646 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
649 long length; /* length of packet: see below */
650 long forcepad; /* SSH-2: force padding to at least this length */
651 int type; /* only used for incoming packets */
652 unsigned long sequence; /* SSH-2 incoming sequence number */
653 unsigned char *data; /* allocated storage */
654 unsigned char *body; /* offset of payload within `data' */
655 long savedpos; /* dual-purpose saved packet position: see below */
656 long maxlen; /* amount of storage allocated for `data' */
657 long encrypted_len; /* for SSH-2 total-size counting */
660 * A note on the 'length' and 'savedpos' fields above.
662 * Incoming packets are set up so that pkt->length is measured
663 * relative to pkt->body, which itself points to a few bytes after
664 * pkt->data (skipping some uninteresting header fields including
665 * the packet type code). The ssh_pkt_get* functions all expect
666 * this setup, and they also use pkt->savedpos to indicate how far
667 * through the packet being decoded they've got - and that, too,
668 * is an offset from pkt->body rather than pkt->data.
670 * During construction of an outgoing packet, however, pkt->length
671 * is measured relative to the base pointer pkt->data, and
672 * pkt->body is not really used for anything until the packet is
673 * ready for sending. In this mode, pkt->savedpos is reused as a
674 * temporary variable by the addstring functions, which write out
675 * a string length field and then keep going back and updating it
676 * as more data is appended to the subsequent string data field;
677 * pkt->savedpos stores the offset (again relative to pkt->data)
678 * of the start of the string data field.
681 /* Extra metadata used in SSH packet logging mode, allowing us to
682 * log in the packet header line that the packet came from a
683 * connection-sharing downstream and what if anything unusual was
684 * done to it. The additional_log_text field is expected to be a
685 * static string - it will not be freed. */
686 unsigned downstream_id;
687 const char *additional_log_text;
690 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
691 struct Packet *pktin);
692 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
693 struct Packet *pktin);
694 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
695 struct Packet *pktin);
696 static void ssh1_protocol_setup(Ssh ssh);
697 static void ssh2_protocol_setup(Ssh ssh);
698 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
699 static void ssh_size(void *handle, int width, int height);
700 static void ssh_special(void *handle, Telnet_Special);
701 static int ssh2_try_send(struct ssh_channel *c);
702 static void ssh2_add_channel_data(struct ssh_channel *c,
703 const char *buf, int len);
704 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
705 static void ssh2_set_window(struct ssh_channel *c, int newwin);
706 static int ssh_sendbuffer(void *handle);
707 static int ssh_do_close(Ssh ssh, int notify_exit);
708 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
709 static int ssh2_pkt_getbool(struct Packet *pkt);
710 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
711 static void ssh2_timer(void *ctx, unsigned long now);
712 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
713 struct Packet *pktin);
714 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
716 struct rdpkt1_state_tag {
717 long len, pad, biglen, to_read;
718 unsigned long realcrc, gotcrc;
722 struct Packet *pktin;
725 struct rdpkt2_state_tag {
726 long len, pad, payload, packetlen, maclen;
729 unsigned long incoming_sequence;
730 struct Packet *pktin;
733 struct rdpkt2_bare_state_tag {
737 unsigned long incoming_sequence;
738 struct Packet *pktin;
741 struct queued_handler;
742 struct queued_handler {
744 chandler_fn_t handler;
746 struct queued_handler *next;
750 const struct plug_function_table *fn;
751 /* the above field _must_ be first in the structure */
761 unsigned char session_key[32];
763 int v1_remote_protoflags;
764 int v1_local_protoflags;
765 int agentfwd_enabled;
768 const struct ssh_cipher *cipher;
771 const struct ssh2_cipher *cscipher, *sccipher;
772 void *cs_cipher_ctx, *sc_cipher_ctx;
773 const struct ssh_mac *csmac, *scmac;
774 int csmac_etm, scmac_etm;
775 void *cs_mac_ctx, *sc_mac_ctx;
776 const struct ssh_compress *cscomp, *sccomp;
777 void *cs_comp_ctx, *sc_comp_ctx;
778 const struct ssh_kex *kex;
779 const struct ssh_signkey *hostkey;
780 char *hostkey_str; /* string representation, for easy checking in rekeys */
781 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
782 int v2_session_id_len;
786 int attempting_connshare;
792 int echoing, editing;
796 int ospeed, ispeed; /* temporaries */
797 int term_width, term_height;
799 tree234 *channels; /* indexed by local id */
800 struct ssh_channel *mainchan; /* primary session channel */
801 int ncmode; /* is primary channel direct-tcpip? */
806 tree234 *rportfwds, *portfwds;
810 SSH_STATE_BEFORE_SIZE,
816 int size_needed, eof_needed;
817 int sent_console_eof;
818 int got_pty; /* affects EOF behaviour on main channel */
820 struct Packet **queue;
821 int queuelen, queuesize;
823 unsigned char *deferred_send_data;
824 int deferred_len, deferred_size;
827 * Gross hack: pscp will try to start SFTP but fall back to
828 * scp1 if that fails. This variable is the means by which
829 * scp.c can reach into the SSH code and find out which one it
834 bufchain banner; /* accumulates banners during do_ssh2_authconn */
839 struct X11Display *x11disp;
840 struct X11FakeAuth *x11auth;
841 tree234 *x11authtree;
844 int conn_throttle_count;
847 int v1_stdout_throttling;
848 unsigned long v2_outgoing_sequence;
850 int ssh1_rdpkt_crstate;
851 int ssh2_rdpkt_crstate;
852 int ssh2_bare_rdpkt_crstate;
853 int ssh_gotdata_crstate;
854 int do_ssh1_connection_crstate;
856 void *do_ssh_init_state;
857 void *do_ssh1_login_state;
858 void *do_ssh2_transport_state;
859 void *do_ssh2_authconn_state;
860 void *do_ssh_connection_init_state;
862 struct rdpkt1_state_tag rdpkt1_state;
863 struct rdpkt2_state_tag rdpkt2_state;
864 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
866 /* SSH-1 and SSH-2 use this for different things, but both use it */
867 int protocol_initial_phase_done;
869 void (*protocol) (Ssh ssh, const void *vin, int inlen,
871 struct Packet *(*s_rdpkt) (Ssh ssh, const unsigned char **data,
873 int (*do_ssh_init)(Ssh ssh, unsigned char c);
876 * We maintain our own copy of a Conf structure here. That way,
877 * when we're passed a new one for reconfiguration, we can check
878 * the differences and potentially reconfigure port forwardings
879 * etc in mid-session.
884 * Values cached out of conf so as to avoid the tree234 lookup
885 * cost every time they're used.
890 * Dynamically allocated username string created during SSH
891 * login. Stored in here rather than in the coroutine state so
892 * that it'll be reliably freed if we shut down the SSH session
893 * at some unexpected moment.
898 * Used to transfer data back from async callbacks.
900 void *agent_response;
901 int agent_response_len;
905 * The SSH connection can be set as `frozen', meaning we are
906 * not currently accepting incoming data from the network. This
907 * is slightly more serious than setting the _socket_ as
908 * frozen, because we may already have had data passed to us
909 * from the network which we need to delay processing until
910 * after the freeze is lifted, so we also need a bufchain to
914 bufchain queued_incoming_data;
917 * Dispatch table for packet types that we may have to deal
920 handler_fn_t packet_dispatch[256];
923 * Queues of one-off handler functions for success/failure
924 * indications from a request.
926 struct queued_handler *qhead, *qtail;
927 handler_fn_t q_saved_handler1, q_saved_handler2;
930 * This module deals with sending keepalives.
935 * Track incoming and outgoing data sizes and time, for
938 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
939 unsigned long max_data_size;
941 unsigned long next_rekey, last_rekey;
942 const char *deferred_rekey_reason;
945 * Fully qualified host name, which we need if doing GSSAPI.
951 * GSSAPI libraries for this session.
953 struct ssh_gss_liblist *gsslibs;
957 #define logevent(s) logevent(ssh->frontend, s)
959 /* logevent, only printf-formatted. */
960 static void logeventf(Ssh ssh, const char *fmt, ...)
966 buf = dupvprintf(fmt, ap);
972 static void bomb_out(Ssh ssh, char *text)
974 ssh_do_close(ssh, FALSE);
976 connection_fatal(ssh->frontend, "%s", text);
980 #define bombout(msg) bomb_out(ssh, dupprintf msg)
982 /* Helper function for common bits of parsing ttymodes. */
983 static void parse_ttymodes(Ssh ssh,
984 void (*do_mode)(void *data, char *mode, char *val),
989 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
991 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
993 * val[0] is either 'V', indicating that an explicit value
994 * follows it, or 'A' indicating that we should pass the
995 * value through from the local environment via get_ttymode.
998 val = get_ttymode(ssh->frontend, key);
1000 do_mode(data, key, val);
1004 do_mode(data, key, val + 1); /* skip the 'V' */
1008 static int ssh_channelcmp(void *av, void *bv)
1010 struct ssh_channel *a = (struct ssh_channel *) av;
1011 struct ssh_channel *b = (struct ssh_channel *) bv;
1012 if (a->localid < b->localid)
1014 if (a->localid > b->localid)
1018 static int ssh_channelfind(void *av, void *bv)
1020 unsigned *a = (unsigned *) av;
1021 struct ssh_channel *b = (struct ssh_channel *) bv;
1022 if (*a < b->localid)
1024 if (*a > b->localid)
1029 static int ssh_rportcmp_ssh1(void *av, void *bv)
1031 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1032 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1034 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1035 return i < 0 ? -1 : +1;
1036 if (a->dport > b->dport)
1038 if (a->dport < b->dport)
1043 static int ssh_rportcmp_ssh2(void *av, void *bv)
1045 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1046 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1048 if ( (i = strcmp(a->shost, b->shost)) != 0)
1049 return i < 0 ? -1 : +1;
1050 if (a->sport > b->sport)
1052 if (a->sport < b->sport)
1058 * Special form of strcmp which can cope with NULL inputs. NULL is
1059 * defined to sort before even the empty string.
1061 static int nullstrcmp(const char *a, const char *b)
1063 if (a == NULL && b == NULL)
1069 return strcmp(a, b);
1072 static int ssh_portcmp(void *av, void *bv)
1074 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1075 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1077 if (a->type > b->type)
1079 if (a->type < b->type)
1081 if (a->addressfamily > b->addressfamily)
1083 if (a->addressfamily < b->addressfamily)
1085 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1086 return i < 0 ? -1 : +1;
1087 if (a->sport > b->sport)
1089 if (a->sport < b->sport)
1091 if (a->type != 'D') {
1092 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1093 return i < 0 ? -1 : +1;
1094 if (a->dport > b->dport)
1096 if (a->dport < b->dport)
1102 static int alloc_channel_id(Ssh ssh)
1104 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1105 unsigned low, high, mid;
1107 struct ssh_channel *c;
1110 * First-fit allocation of channel numbers: always pick the
1111 * lowest unused one. To do this, binary-search using the
1112 * counted B-tree to find the largest channel ID which is in a
1113 * contiguous sequence from the beginning. (Precisely
1114 * everything in that sequence must have ID equal to its tree
1115 * index plus CHANNEL_NUMBER_OFFSET.)
1117 tsize = count234(ssh->channels);
1121 while (high - low > 1) {
1122 mid = (high + low) / 2;
1123 c = index234(ssh->channels, mid);
1124 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1125 low = mid; /* this one is fine */
1127 high = mid; /* this one is past it */
1130 * Now low points to either -1, or the tree index of the
1131 * largest ID in the initial sequence.
1134 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1135 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1137 return low + 1 + CHANNEL_NUMBER_OFFSET;
1140 static void c_write_stderr(int trusted, const char *buf, int len)
1143 for (i = 0; i < len; i++)
1144 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1145 fputc(buf[i], stderr);
1148 static void c_write(Ssh ssh, const char *buf, int len)
1150 if (flags & FLAG_STDERR)
1151 c_write_stderr(1, buf, len);
1153 from_backend(ssh->frontend, 1, buf, len);
1156 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1158 if (flags & FLAG_STDERR)
1159 c_write_stderr(0, buf, len);
1161 from_backend_untrusted(ssh->frontend, buf, len);
1164 static void c_write_str(Ssh ssh, const char *buf)
1166 c_write(ssh, buf, strlen(buf));
1169 static void ssh_free_packet(struct Packet *pkt)
1174 static struct Packet *ssh_new_packet(void)
1176 struct Packet *pkt = snew(struct Packet);
1178 pkt->body = pkt->data = NULL;
1184 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1187 struct logblank_t blanks[4];
1193 if (ssh->logomitdata &&
1194 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1195 pkt->type == SSH1_SMSG_STDERR_DATA ||
1196 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1197 /* "Session data" packets - omit the data string. */
1198 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1199 ssh_pkt_getuint32(pkt); /* skip channel id */
1200 blanks[nblanks].offset = pkt->savedpos + 4;
1201 blanks[nblanks].type = PKTLOG_OMIT;
1202 ssh_pkt_getstring(pkt, &str, &slen);
1204 blanks[nblanks].len = slen;
1208 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1209 ssh1_pkt_type(pkt->type),
1210 pkt->body, pkt->length, nblanks, blanks, NULL,
1214 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1217 struct logblank_t blanks[4];
1222 * For outgoing packets, pkt->length represents the length of the
1223 * whole packet starting at pkt->data (including some header), and
1224 * pkt->body refers to the point within that where the log-worthy
1225 * payload begins. However, incoming packets expect pkt->length to
1226 * represent only the payload length (that is, it's measured from
1227 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1228 * packet to conform to the incoming-packet semantics, so that we
1229 * can analyse it with the ssh_pkt_get functions.
1231 pkt->length -= (pkt->body - pkt->data);
1234 if (ssh->logomitdata &&
1235 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1236 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1237 /* "Session data" packets - omit the data string. */
1238 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1239 ssh_pkt_getuint32(pkt); /* skip channel id */
1240 blanks[nblanks].offset = pkt->savedpos + 4;
1241 blanks[nblanks].type = PKTLOG_OMIT;
1242 ssh_pkt_getstring(pkt, &str, &slen);
1244 blanks[nblanks].len = slen;
1249 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1250 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1251 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1252 conf_get_int(ssh->conf, CONF_logomitpass)) {
1253 /* If this is a password or similar packet, blank the password(s). */
1254 blanks[nblanks].offset = 0;
1255 blanks[nblanks].len = pkt->length;
1256 blanks[nblanks].type = PKTLOG_BLANK;
1258 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1259 conf_get_int(ssh->conf, CONF_logomitpass)) {
1261 * If this is an X forwarding request packet, blank the fake
1264 * Note that while we blank the X authentication data here, we
1265 * don't take any special action to blank the start of an X11
1266 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1267 * an X connection without having session blanking enabled is
1268 * likely to leak your cookie into the log.
1271 ssh_pkt_getstring(pkt, &str, &slen);
1272 blanks[nblanks].offset = pkt->savedpos;
1273 blanks[nblanks].type = PKTLOG_BLANK;
1274 ssh_pkt_getstring(pkt, &str, &slen);
1276 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1281 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1282 ssh1_pkt_type(pkt->data[12]),
1283 pkt->body, pkt->length,
1284 nblanks, blanks, NULL, 0, NULL);
1287 * Undo the above adjustment of pkt->length, to put the packet
1288 * back in the state we found it.
1290 pkt->length += (pkt->body - pkt->data);
1294 * Collect incoming data in the incoming packet buffer.
1295 * Decipher and verify the packet when it is completely read.
1296 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1297 * Update the *data and *datalen variables.
1298 * Return a Packet structure when a packet is completed.
1300 static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
1303 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1305 crBegin(ssh->ssh1_rdpkt_crstate);
1307 st->pktin = ssh_new_packet();
1309 st->pktin->type = 0;
1310 st->pktin->length = 0;
1312 for (st->i = st->len = 0; st->i < 4; st->i++) {
1313 while ((*datalen) == 0)
1315 st->len = (st->len << 8) + **data;
1316 (*data)++, (*datalen)--;
1319 st->pad = 8 - (st->len % 8);
1320 st->biglen = st->len + st->pad;
1321 st->pktin->length = st->len - 5;
1323 if (st->biglen < 0) {
1324 bombout(("Extremely large packet length from server suggests"
1325 " data stream corruption"));
1326 ssh_free_packet(st->pktin);
1330 st->pktin->maxlen = st->biglen;
1331 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1333 st->to_read = st->biglen;
1334 st->p = st->pktin->data;
1335 while (st->to_read > 0) {
1336 st->chunk = st->to_read;
1337 while ((*datalen) == 0)
1339 if (st->chunk > (*datalen))
1340 st->chunk = (*datalen);
1341 memcpy(st->p, *data, st->chunk);
1343 *datalen -= st->chunk;
1345 st->to_read -= st->chunk;
1348 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1349 st->biglen, NULL)) {
1350 bombout(("Network attack (CRC compensation) detected!"));
1351 ssh_free_packet(st->pktin);
1356 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1358 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1359 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1360 if (st->gotcrc != st->realcrc) {
1361 bombout(("Incorrect CRC received on packet"));
1362 ssh_free_packet(st->pktin);
1366 st->pktin->body = st->pktin->data + st->pad + 1;
1368 if (ssh->v1_compressing) {
1369 unsigned char *decompblk;
1371 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1372 st->pktin->body - 1, st->pktin->length + 1,
1373 &decompblk, &decomplen)) {
1374 bombout(("Zlib decompression encountered invalid data"));
1375 ssh_free_packet(st->pktin);
1379 if (st->pktin->maxlen < st->pad + decomplen) {
1380 st->pktin->maxlen = st->pad + decomplen;
1381 st->pktin->data = sresize(st->pktin->data,
1382 st->pktin->maxlen + APIEXTRA,
1384 st->pktin->body = st->pktin->data + st->pad + 1;
1387 memcpy(st->pktin->body - 1, decompblk, decomplen);
1389 st->pktin->length = decomplen - 1;
1392 st->pktin->type = st->pktin->body[-1];
1395 * Now pktin->body and pktin->length identify the semantic content
1396 * of the packet, excluding the initial type byte.
1400 ssh1_log_incoming_packet(ssh, st->pktin);
1402 st->pktin->savedpos = 0;
1404 crFinish(st->pktin);
1407 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1410 struct logblank_t blanks[4];
1416 if (ssh->logomitdata &&
1417 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1418 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1419 /* "Session data" packets - omit the data string. */
1420 ssh_pkt_getuint32(pkt); /* skip channel id */
1421 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1422 ssh_pkt_getuint32(pkt); /* skip extended data type */
1423 blanks[nblanks].offset = pkt->savedpos + 4;
1424 blanks[nblanks].type = PKTLOG_OMIT;
1425 ssh_pkt_getstring(pkt, &str, &slen);
1427 blanks[nblanks].len = slen;
1432 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1433 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1434 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1438 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1441 struct logblank_t blanks[4];
1446 * For outgoing packets, pkt->length represents the length of the
1447 * whole packet starting at pkt->data (including some header), and
1448 * pkt->body refers to the point within that where the log-worthy
1449 * payload begins. However, incoming packets expect pkt->length to
1450 * represent only the payload length (that is, it's measured from
1451 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1452 * packet to conform to the incoming-packet semantics, so that we
1453 * can analyse it with the ssh_pkt_get functions.
1455 pkt->length -= (pkt->body - pkt->data);
1458 if (ssh->logomitdata &&
1459 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1460 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1461 /* "Session data" packets - omit the data string. */
1462 ssh_pkt_getuint32(pkt); /* skip channel id */
1463 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1464 ssh_pkt_getuint32(pkt); /* skip extended data type */
1465 blanks[nblanks].offset = pkt->savedpos + 4;
1466 blanks[nblanks].type = PKTLOG_OMIT;
1467 ssh_pkt_getstring(pkt, &str, &slen);
1469 blanks[nblanks].len = slen;
1474 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1475 conf_get_int(ssh->conf, CONF_logomitpass)) {
1476 /* If this is a password packet, blank the password(s). */
1478 ssh_pkt_getstring(pkt, &str, &slen);
1479 ssh_pkt_getstring(pkt, &str, &slen);
1480 ssh_pkt_getstring(pkt, &str, &slen);
1481 if (slen == 8 && !memcmp(str, "password", 8)) {
1482 ssh2_pkt_getbool(pkt);
1483 /* Blank the password field. */
1484 blanks[nblanks].offset = pkt->savedpos;
1485 blanks[nblanks].type = PKTLOG_BLANK;
1486 ssh_pkt_getstring(pkt, &str, &slen);
1488 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1490 /* If there's another password field beyond it (change of
1491 * password), blank that too. */
1492 ssh_pkt_getstring(pkt, &str, &slen);
1494 blanks[nblanks-1].len =
1495 pkt->savedpos - blanks[nblanks].offset;
1498 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1499 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1500 conf_get_int(ssh->conf, CONF_logomitpass)) {
1501 /* If this is a keyboard-interactive response packet, blank
1504 ssh_pkt_getuint32(pkt);
1505 blanks[nblanks].offset = pkt->savedpos;
1506 blanks[nblanks].type = PKTLOG_BLANK;
1508 ssh_pkt_getstring(pkt, &str, &slen);
1512 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1514 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1515 conf_get_int(ssh->conf, CONF_logomitpass)) {
1517 * If this is an X forwarding request packet, blank the fake
1520 * Note that while we blank the X authentication data here, we
1521 * don't take any special action to blank the start of an X11
1522 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1523 * an X connection without having session blanking enabled is
1524 * likely to leak your cookie into the log.
1527 ssh_pkt_getuint32(pkt);
1528 ssh_pkt_getstring(pkt, &str, &slen);
1529 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1530 ssh2_pkt_getbool(pkt);
1531 ssh2_pkt_getbool(pkt);
1532 ssh_pkt_getstring(pkt, &str, &slen);
1533 blanks[nblanks].offset = pkt->savedpos;
1534 blanks[nblanks].type = PKTLOG_BLANK;
1535 ssh_pkt_getstring(pkt, &str, &slen);
1537 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1543 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1544 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1545 pkt->body, pkt->length, nblanks, blanks,
1546 &ssh->v2_outgoing_sequence,
1547 pkt->downstream_id, pkt->additional_log_text);
1550 * Undo the above adjustment of pkt->length, to put the packet
1551 * back in the state we found it.
1553 pkt->length += (pkt->body - pkt->data);
1556 static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
1559 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1561 crBegin(ssh->ssh2_rdpkt_crstate);
1563 st->pktin = ssh_new_packet();
1565 st->pktin->type = 0;
1566 st->pktin->length = 0;
1568 st->cipherblk = ssh->sccipher->blksize;
1571 if (st->cipherblk < 8)
1573 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1575 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1576 ssh->scmac && !ssh->scmac_etm) {
1578 * When dealing with a CBC-mode cipher, we want to avoid the
1579 * possibility of an attacker's tweaking the ciphertext stream
1580 * so as to cause us to feed the same block to the block
1581 * cipher more than once and thus leak information
1582 * (VU#958563). The way we do this is not to take any
1583 * decisions on the basis of anything we've decrypted until
1584 * we've verified it with a MAC. That includes the packet
1585 * length, so we just read data and check the MAC repeatedly,
1586 * and when the MAC passes, see if the length we've got is
1589 * This defence is unnecessary in OpenSSH ETM mode, because
1590 * the whole point of ETM mode is that the attacker can't
1591 * tweak the ciphertext stream at all without the MAC
1592 * detecting it before we decrypt anything.
1595 /* May as well allocate the whole lot now. */
1596 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1599 /* Read an amount corresponding to the MAC. */
1600 for (st->i = 0; st->i < st->maclen; st->i++) {
1601 while ((*datalen) == 0)
1603 st->pktin->data[st->i] = *(*data)++;
1609 unsigned char seq[4];
1610 ssh->scmac->start(ssh->sc_mac_ctx);
1611 PUT_32BIT(seq, st->incoming_sequence);
1612 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1615 for (;;) { /* Once around this loop per cipher block. */
1616 /* Read another cipher-block's worth, and tack it onto the end. */
1617 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1618 while ((*datalen) == 0)
1620 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1623 /* Decrypt one more block (a little further back in the stream). */
1624 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1625 st->pktin->data + st->packetlen,
1627 /* Feed that block to the MAC. */
1628 ssh->scmac->bytes(ssh->sc_mac_ctx,
1629 st->pktin->data + st->packetlen, st->cipherblk);
1630 st->packetlen += st->cipherblk;
1631 /* See if that gives us a valid packet. */
1632 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1633 st->pktin->data + st->packetlen) &&
1634 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1637 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1638 bombout(("No valid incoming packet found"));
1639 ssh_free_packet(st->pktin);
1643 st->pktin->maxlen = st->packetlen + st->maclen;
1644 st->pktin->data = sresize(st->pktin->data,
1645 st->pktin->maxlen + APIEXTRA,
1647 } else if (ssh->scmac && ssh->scmac_etm) {
1648 st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1651 * OpenSSH encrypt-then-MAC mode: the packet length is
1654 for (st->i = st->len = 0; st->i < 4; st->i++) {
1655 while ((*datalen) == 0)
1657 st->pktin->data[st->i] = *(*data)++;
1660 st->len = toint(GET_32BIT(st->pktin->data));
1663 * _Completely_ silly lengths should be stomped on before they
1664 * do us any more damage.
1666 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1667 st->len % st->cipherblk != 0) {
1668 bombout(("Incoming packet length field was garbled"));
1669 ssh_free_packet(st->pktin);
1674 * So now we can work out the total packet length.
1676 st->packetlen = st->len + 4;
1679 * Allocate memory for the rest of the packet.
1681 st->pktin->maxlen = st->packetlen + st->maclen;
1682 st->pktin->data = sresize(st->pktin->data,
1683 st->pktin->maxlen + APIEXTRA,
1687 * Read the remainder of the packet.
1689 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1690 while ((*datalen) == 0)
1692 st->pktin->data[st->i] = *(*data)++;
1700 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1701 st->len + 4, st->incoming_sequence)) {
1702 bombout(("Incorrect MAC received on packet"));
1703 ssh_free_packet(st->pktin);
1707 /* Decrypt everything between the length field and the MAC. */
1709 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1710 st->pktin->data + 4,
1713 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1716 * Acquire and decrypt the first block of the packet. This will
1717 * contain the length and padding details.
1719 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1720 while ((*datalen) == 0)
1722 st->pktin->data[st->i] = *(*data)++;
1727 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1728 st->pktin->data, st->cipherblk);
1731 * Now get the length figure.
1733 st->len = toint(GET_32BIT(st->pktin->data));
1736 * _Completely_ silly lengths should be stomped on before they
1737 * do us any more damage.
1739 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1740 (st->len + 4) % st->cipherblk != 0) {
1741 bombout(("Incoming packet was garbled on decryption"));
1742 ssh_free_packet(st->pktin);
1747 * So now we can work out the total packet length.
1749 st->packetlen = st->len + 4;
1752 * Allocate memory for the rest of the packet.
1754 st->pktin->maxlen = st->packetlen + st->maclen;
1755 st->pktin->data = sresize(st->pktin->data,
1756 st->pktin->maxlen + APIEXTRA,
1760 * Read and decrypt the remainder of the packet.
1762 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1764 while ((*datalen) == 0)
1766 st->pktin->data[st->i] = *(*data)++;
1769 /* Decrypt everything _except_ the MAC. */
1771 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1772 st->pktin->data + st->cipherblk,
1773 st->packetlen - st->cipherblk);
1779 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1780 st->len + 4, st->incoming_sequence)) {
1781 bombout(("Incorrect MAC received on packet"));
1782 ssh_free_packet(st->pktin);
1786 /* Get and sanity-check the amount of random padding. */
1787 st->pad = st->pktin->data[4];
1788 if (st->pad < 4 || st->len - st->pad < 1) {
1789 bombout(("Invalid padding length on received packet"));
1790 ssh_free_packet(st->pktin);
1794 * This enables us to deduce the payload length.
1796 st->payload = st->len - st->pad - 1;
1798 st->pktin->length = st->payload + 5;
1799 st->pktin->encrypted_len = st->packetlen;
1801 st->pktin->sequence = st->incoming_sequence++;
1803 st->pktin->length = st->packetlen - st->pad;
1804 assert(st->pktin->length >= 0);
1807 * Decompress packet payload.
1810 unsigned char *newpayload;
1813 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1814 st->pktin->data + 5, st->pktin->length - 5,
1815 &newpayload, &newlen)) {
1816 if (st->pktin->maxlen < newlen + 5) {
1817 st->pktin->maxlen = newlen + 5;
1818 st->pktin->data = sresize(st->pktin->data,
1819 st->pktin->maxlen + APIEXTRA,
1822 st->pktin->length = 5 + newlen;
1823 memcpy(st->pktin->data + 5, newpayload, newlen);
1829 * pktin->body and pktin->length should identify the semantic
1830 * content of the packet, excluding the initial type byte.
1832 st->pktin->type = st->pktin->data[5];
1833 st->pktin->body = st->pktin->data + 6;
1834 st->pktin->length -= 6;
1835 assert(st->pktin->length >= 0); /* one last double-check */
1838 ssh2_log_incoming_packet(ssh, st->pktin);
1840 st->pktin->savedpos = 0;
1842 crFinish(st->pktin);
1845 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
1846 const unsigned char **data,
1849 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1851 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1854 * Read the packet length field.
1856 for (st->i = 0; st->i < 4; st->i++) {
1857 while ((*datalen) == 0)
1859 st->length[st->i] = *(*data)++;
1863 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1864 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1865 bombout(("Invalid packet length received"));
1869 st->pktin = ssh_new_packet();
1870 st->pktin->data = snewn(st->packetlen, unsigned char);
1872 st->pktin->encrypted_len = st->packetlen;
1874 st->pktin->sequence = st->incoming_sequence++;
1877 * Read the remainder of the packet.
1879 for (st->i = 0; st->i < st->packetlen; st->i++) {
1880 while ((*datalen) == 0)
1882 st->pktin->data[st->i] = *(*data)++;
1887 * pktin->body and pktin->length should identify the semantic
1888 * content of the packet, excluding the initial type byte.
1890 st->pktin->type = st->pktin->data[0];
1891 st->pktin->body = st->pktin->data + 1;
1892 st->pktin->length = st->packetlen - 1;
1895 * Log incoming packet, possibly omitting sensitive fields.
1898 ssh2_log_incoming_packet(ssh, st->pktin);
1900 st->pktin->savedpos = 0;
1902 crFinish(st->pktin);
1905 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1907 int pad, biglen, i, pktoffs;
1911 * XXX various versions of SC (including 8.8.4) screw up the
1912 * register allocation in this function and use the same register
1913 * (D6) for len and as a temporary, with predictable results. The
1914 * following sledgehammer prevents this.
1921 ssh1_log_outgoing_packet(ssh, pkt);
1923 if (ssh->v1_compressing) {
1924 unsigned char *compblk;
1926 zlib_compress_block(ssh->cs_comp_ctx,
1927 pkt->data + 12, pkt->length - 12,
1928 &compblk, &complen);
1929 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1930 memcpy(pkt->data + 12, compblk, complen);
1932 pkt->length = complen + 12;
1935 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1937 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1938 pad = 8 - (len % 8);
1940 biglen = len + pad; /* len(padding+type+data+CRC) */
1942 for (i = pktoffs; i < 4+8; i++)
1943 pkt->data[i] = random_byte();
1944 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1945 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1946 PUT_32BIT(pkt->data + pktoffs, len);
1949 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1950 pkt->data + pktoffs + 4, biglen);
1952 if (offset_p) *offset_p = pktoffs;
1953 return biglen + 4; /* len(length+padding+type+data+CRC) */
1956 static int s_write(Ssh ssh, void *data, int len)
1959 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1960 0, NULL, NULL, 0, NULL);
1963 return sk_write(ssh->s, (char *)data, len);
1966 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1968 int len, backlog, offset;
1969 len = s_wrpkt_prepare(ssh, pkt, &offset);
1970 backlog = s_write(ssh, pkt->data + offset, len);
1971 if (backlog > SSH_MAX_BACKLOG)
1972 ssh_throttle_all(ssh, 1, backlog);
1973 ssh_free_packet(pkt);
1976 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1979 len = s_wrpkt_prepare(ssh, pkt, &offset);
1980 if (ssh->deferred_len + len > ssh->deferred_size) {
1981 ssh->deferred_size = ssh->deferred_len + len + 128;
1982 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1986 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1987 pkt->data + offset, len);
1988 ssh->deferred_len += len;
1989 ssh_free_packet(pkt);
1993 * Construct a SSH-1 packet with the specified contents.
1994 * (This all-at-once interface used to be the only one, but now SSH-1
1995 * packets can also be constructed incrementally.)
1997 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
2003 pkt = ssh1_pkt_init(pkttype);
2005 while ((argtype = va_arg(ap, int)) != PKT_END) {
2006 unsigned char *argp, argchar;
2008 unsigned long argint;
2011 /* Actual fields in the packet */
2013 argint = va_arg(ap, int);
2014 ssh_pkt_adduint32(pkt, argint);
2017 argchar = (unsigned char) va_arg(ap, int);
2018 ssh_pkt_addbyte(pkt, argchar);
2021 argp = va_arg(ap, unsigned char *);
2022 arglen = va_arg(ap, int);
2023 ssh_pkt_adddata(pkt, argp, arglen);
2026 sargp = va_arg(ap, char *);
2027 ssh_pkt_addstring(pkt, sargp);
2030 bn = va_arg(ap, Bignum);
2031 ssh1_pkt_addmp(pkt, bn);
2039 static void send_packet(Ssh ssh, int pkttype, ...)
2043 va_start(ap, pkttype);
2044 pkt = construct_packet(ssh, pkttype, ap);
2049 static void defer_packet(Ssh ssh, int pkttype, ...)
2053 va_start(ap, pkttype);
2054 pkt = construct_packet(ssh, pkttype, ap);
2056 s_wrpkt_defer(ssh, pkt);
2059 static int ssh_versioncmp(const char *a, const char *b)
2062 unsigned long av, bv;
2064 av = strtoul(a, &ae, 10);
2065 bv = strtoul(b, &be, 10);
2067 return (av < bv ? -1 : +1);
2072 av = strtoul(ae, &ae, 10);
2073 bv = strtoul(be, &be, 10);
2075 return (av < bv ? -1 : +1);
2080 * Utility routines for putting an SSH-protocol `string' and
2081 * `uint32' into a hash state.
2083 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2085 unsigned char lenblk[4];
2086 PUT_32BIT(lenblk, len);
2087 h->bytes(s, lenblk, 4);
2088 h->bytes(s, str, len);
2091 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2093 unsigned char intblk[4];
2094 PUT_32BIT(intblk, i);
2095 h->bytes(s, intblk, 4);
2099 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2101 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2103 if (pkt->maxlen < length) {
2104 unsigned char *body = pkt->body;
2105 int offset = body ? body - pkt->data : 0;
2106 pkt->maxlen = length + 256;
2107 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2108 if (body) pkt->body = pkt->data + offset;
2111 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2114 ssh_pkt_ensure(pkt, pkt->length);
2115 memcpy(pkt->data + pkt->length - len, data, len);
2117 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2119 ssh_pkt_adddata(pkt, &byte, 1);
2121 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2123 ssh_pkt_adddata(pkt, &value, 1);
2125 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2128 PUT_32BIT(x, value);
2129 ssh_pkt_adddata(pkt, x, 4);
2131 static void ssh_pkt_addstring_start(struct Packet *pkt)
2133 ssh_pkt_adduint32(pkt, 0);
2134 pkt->savedpos = pkt->length;
2136 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2139 ssh_pkt_adddata(pkt, data, len);
2140 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2142 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2144 ssh_pkt_addstring_data(pkt, data, strlen(data));
2146 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2148 ssh_pkt_addstring_start(pkt);
2149 ssh_pkt_addstring_str(pkt, data);
2151 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2153 int len = ssh1_bignum_length(b);
2154 unsigned char *data = snewn(len, unsigned char);
2155 (void) ssh1_write_bignum(data, b);
2156 ssh_pkt_adddata(pkt, data, len);
2159 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2162 int i, n = (bignum_bitcount(b) + 7) / 8;
2163 p = snewn(n + 1, unsigned char);
2165 for (i = 1; i <= n; i++)
2166 p[i] = bignum_byte(b, n - i);
2168 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2170 memmove(p, p + i, n + 1 - i);
2174 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2178 p = ssh2_mpint_fmt(b, &len);
2179 ssh_pkt_addstring_start(pkt);
2180 ssh_pkt_addstring_data(pkt, (char *)p, len);
2184 static struct Packet *ssh1_pkt_init(int pkt_type)
2186 struct Packet *pkt = ssh_new_packet();
2187 pkt->length = 4 + 8; /* space for length + max padding */
2188 ssh_pkt_addbyte(pkt, pkt_type);
2189 pkt->body = pkt->data + pkt->length;
2190 pkt->type = pkt_type;
2191 pkt->downstream_id = 0;
2192 pkt->additional_log_text = NULL;
2196 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2197 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2198 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2199 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2200 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2201 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2202 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2203 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2204 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2206 static struct Packet *ssh2_pkt_init(int pkt_type)
2208 struct Packet *pkt = ssh_new_packet();
2209 pkt->length = 5; /* space for packet length + padding length */
2211 pkt->type = pkt_type;
2212 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2213 pkt->body = pkt->data + pkt->length; /* after packet type */
2214 pkt->downstream_id = 0;
2215 pkt->additional_log_text = NULL;
2220 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2221 * put the MAC on it. Final packet, ready to be sent, is stored in
2222 * pkt->data. Total length is returned.
2224 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2226 int cipherblk, maclen, padding, unencrypted_prefix, i;
2229 ssh2_log_outgoing_packet(ssh, pkt);
2231 if (ssh->bare_connection) {
2233 * Trivial packet construction for the bare connection
2236 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2237 pkt->body = pkt->data + 1;
2238 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2239 return pkt->length - 1;
2243 * Compress packet payload.
2246 unsigned char *newpayload;
2249 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2251 &newpayload, &newlen)) {
2253 ssh2_pkt_adddata(pkt, newpayload, newlen);
2259 * Add padding. At least four bytes, and must also bring total
2260 * length (minus MAC) up to a multiple of the block size.
2261 * If pkt->forcepad is set, make sure the packet is at least that size
2264 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2265 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2267 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2268 if (pkt->length + padding < pkt->forcepad)
2269 padding = pkt->forcepad - pkt->length;
2271 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2273 assert(padding <= 255);
2274 maclen = ssh->csmac ? ssh->csmac->len : 0;
2275 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2276 pkt->data[4] = padding;
2277 for (i = 0; i < padding; i++)
2278 pkt->data[pkt->length + i] = random_byte();
2279 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2280 if (ssh->csmac && ssh->csmac_etm) {
2282 * OpenSSH-defined encrypt-then-MAC protocol.
2285 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2286 pkt->data + 4, pkt->length + padding - 4);
2287 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2288 pkt->length + padding,
2289 ssh->v2_outgoing_sequence);
2292 * SSH-2 standard protocol.
2295 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2296 pkt->length + padding,
2297 ssh->v2_outgoing_sequence);
2299 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2300 pkt->data, pkt->length + padding);
2303 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2304 pkt->encrypted_len = pkt->length + padding;
2306 /* Ready-to-send packet starts at pkt->data. We return length. */
2307 pkt->body = pkt->data;
2308 return pkt->length + padding + maclen;
2312 * Routines called from the main SSH code to send packets. There
2313 * are quite a few of these, because we have two separate
2314 * mechanisms for delaying the sending of packets:
2316 * - In order to send an IGNORE message and a password message in
2317 * a single fixed-length blob, we require the ability to
2318 * concatenate the encrypted forms of those two packets _into_ a
2319 * single blob and then pass it to our <network.h> transport
2320 * layer in one go. Hence, there's a deferment mechanism which
2321 * works after packet encryption.
2323 * - In order to avoid sending any connection-layer messages
2324 * during repeat key exchange, we have to queue up any such
2325 * outgoing messages _before_ they are encrypted (and in
2326 * particular before they're allocated sequence numbers), and
2327 * then send them once we've finished.
2329 * I call these mechanisms `defer' and `queue' respectively, so as
2330 * to distinguish them reasonably easily.
2332 * The functions send_noqueue() and defer_noqueue() free the packet
2333 * structure they are passed. Every outgoing packet goes through
2334 * precisely one of these functions in its life; packets passed to
2335 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2336 * these or get queued, and then when the queue is later emptied
2337 * the packets are all passed to defer_noqueue().
2339 * When using a CBC-mode cipher, it's necessary to ensure that an
2340 * attacker can't provide data to be encrypted using an IV that they
2341 * know. We ensure this by prefixing each packet that might contain
2342 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2343 * mechanism, so in this case send_noqueue() ends up redirecting to
2344 * defer_noqueue(). If you don't like this inefficiency, don't use
2348 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2349 static void ssh_pkt_defersend(Ssh);
2352 * Send an SSH-2 packet immediately, without queuing or deferring.
2354 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2358 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2359 /* We need to send two packets, so use the deferral mechanism. */
2360 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2361 ssh_pkt_defersend(ssh);
2364 len = ssh2_pkt_construct(ssh, pkt);
2365 backlog = s_write(ssh, pkt->body, len);
2366 if (backlog > SSH_MAX_BACKLOG)
2367 ssh_throttle_all(ssh, 1, backlog);
2369 ssh->outgoing_data_size += pkt->encrypted_len;
2370 if (!ssh->kex_in_progress &&
2371 !ssh->bare_connection &&
2372 ssh->max_data_size != 0 &&
2373 ssh->outgoing_data_size > ssh->max_data_size)
2374 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2376 ssh_free_packet(pkt);
2380 * Defer an SSH-2 packet.
2382 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2385 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2386 ssh->deferred_len == 0 && !noignore &&
2387 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2389 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2390 * get encrypted with a known IV.
2392 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2393 ssh2_pkt_addstring_start(ipkt);
2394 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2396 len = ssh2_pkt_construct(ssh, pkt);
2397 if (ssh->deferred_len + len > ssh->deferred_size) {
2398 ssh->deferred_size = ssh->deferred_len + len + 128;
2399 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2403 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2404 ssh->deferred_len += len;
2405 ssh->deferred_data_size += pkt->encrypted_len;
2406 ssh_free_packet(pkt);
2410 * Queue an SSH-2 packet.
2412 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2414 assert(ssh->queueing);
2416 if (ssh->queuelen >= ssh->queuesize) {
2417 ssh->queuesize = ssh->queuelen + 32;
2418 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2421 ssh->queue[ssh->queuelen++] = pkt;
2425 * Either queue or send a packet, depending on whether queueing is
2428 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2431 ssh2_pkt_queue(ssh, pkt);
2433 ssh2_pkt_send_noqueue(ssh, pkt);
2437 * Either queue or defer a packet, depending on whether queueing is
2440 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2443 ssh2_pkt_queue(ssh, pkt);
2445 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2449 * Send the whole deferred data block constructed by
2450 * ssh2_pkt_defer() or SSH-1's defer_packet().
2452 * The expected use of the defer mechanism is that you call
2453 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2454 * not currently queueing, this simply sets up deferred_send_data
2455 * and then sends it. If we _are_ currently queueing, the calls to
2456 * ssh2_pkt_defer() put the deferred packets on to the queue
2457 * instead, and therefore ssh_pkt_defersend() has no deferred data
2458 * to send. Hence, there's no need to make it conditional on
2461 static void ssh_pkt_defersend(Ssh ssh)
2464 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2465 ssh->deferred_len = ssh->deferred_size = 0;
2466 sfree(ssh->deferred_send_data);
2467 ssh->deferred_send_data = NULL;
2468 if (backlog > SSH_MAX_BACKLOG)
2469 ssh_throttle_all(ssh, 1, backlog);
2471 ssh->outgoing_data_size += ssh->deferred_data_size;
2472 if (!ssh->kex_in_progress &&
2473 !ssh->bare_connection &&
2474 ssh->max_data_size != 0 &&
2475 ssh->outgoing_data_size > ssh->max_data_size)
2476 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2477 ssh->deferred_data_size = 0;
2481 * Send a packet whose length needs to be disguised (typically
2482 * passwords or keyboard-interactive responses).
2484 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2490 * The simplest way to do this is to adjust the
2491 * variable-length padding field in the outgoing packet.
2493 * Currently compiled out, because some Cisco SSH servers
2494 * don't like excessively padded packets (bah, why's it
2497 pkt->forcepad = padsize;
2498 ssh2_pkt_send(ssh, pkt);
2503 * If we can't do that, however, an alternative approach is
2504 * to use the pkt_defer mechanism to bundle the packet
2505 * tightly together with an SSH_MSG_IGNORE such that their
2506 * combined length is a constant. So first we construct the
2507 * final form of this packet and defer its sending.
2509 ssh2_pkt_defer(ssh, pkt);
2512 * Now construct an SSH_MSG_IGNORE which includes a string
2513 * that's an exact multiple of the cipher block size. (If
2514 * the cipher is NULL so that the block size is
2515 * unavailable, we don't do this trick at all, because we
2516 * gain nothing by it.)
2518 if (ssh->cscipher &&
2519 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2522 stringlen = (256 - ssh->deferred_len);
2523 stringlen += ssh->cscipher->blksize - 1;
2524 stringlen -= (stringlen % ssh->cscipher->blksize);
2527 * Temporarily disable actual compression, so we
2528 * can guarantee to get this string exactly the
2529 * length we want it. The compression-disabling
2530 * routine should return an integer indicating how
2531 * many bytes we should adjust our string length
2535 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2537 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2538 ssh2_pkt_addstring_start(pkt);
2539 for (i = 0; i < stringlen; i++) {
2540 char c = (char) random_byte();
2541 ssh2_pkt_addstring_data(pkt, &c, 1);
2543 ssh2_pkt_defer(ssh, pkt);
2545 ssh_pkt_defersend(ssh);
2550 * Send all queued SSH-2 packets. We send them by means of
2551 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2552 * packets that needed to be lumped together.
2554 static void ssh2_pkt_queuesend(Ssh ssh)
2558 assert(!ssh->queueing);
2560 for (i = 0; i < ssh->queuelen; i++)
2561 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2564 ssh_pkt_defersend(ssh);
2568 void bndebug(char *string, Bignum b)
2572 p = ssh2_mpint_fmt(b, &len);
2573 debug(("%s", string));
2574 for (i = 0; i < len; i++)
2575 debug((" %02x", p[i]));
2581 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2585 p = ssh2_mpint_fmt(b, &len);
2586 hash_string(h, s, p, len);
2591 * Packet decode functions for both SSH-1 and SSH-2.
2593 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2595 unsigned long value;
2596 if (pkt->length - pkt->savedpos < 4)
2597 return 0; /* arrgh, no way to decline (FIXME?) */
2598 value = GET_32BIT(pkt->body + pkt->savedpos);
2602 static int ssh2_pkt_getbool(struct Packet *pkt)
2604 unsigned long value;
2605 if (pkt->length - pkt->savedpos < 1)
2606 return 0; /* arrgh, no way to decline (FIXME?) */
2607 value = pkt->body[pkt->savedpos] != 0;
2611 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2616 if (pkt->length - pkt->savedpos < 4)
2618 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2623 if (pkt->length - pkt->savedpos < *length)
2625 *p = (char *)(pkt->body + pkt->savedpos);
2626 pkt->savedpos += *length;
2628 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2630 if (pkt->length - pkt->savedpos < length)
2632 pkt->savedpos += length;
2633 return pkt->body + (pkt->savedpos - length);
2635 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2636 const unsigned char **keystr)
2640 j = makekey(pkt->body + pkt->savedpos,
2641 pkt->length - pkt->savedpos,
2648 assert(pkt->savedpos < pkt->length);
2652 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2657 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2658 pkt->length - pkt->savedpos, &b);
2666 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2672 ssh_pkt_getstring(pkt, &p, &length);
2677 b = bignum_from_bytes((unsigned char *)p, length);
2682 * Helper function to add an SSH-2 signature blob to a packet.
2683 * Expects to be shown the public key blob as well as the signature
2684 * blob. Normally works just like ssh2_pkt_addstring, but will
2685 * fiddle with the signature packet if necessary for
2686 * BUG_SSH2_RSA_PADDING.
2688 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2689 void *pkblob_v, int pkblob_len,
2690 void *sigblob_v, int sigblob_len)
2692 unsigned char *pkblob = (unsigned char *)pkblob_v;
2693 unsigned char *sigblob = (unsigned char *)sigblob_v;
2695 /* dmemdump(pkblob, pkblob_len); */
2696 /* dmemdump(sigblob, sigblob_len); */
2699 * See if this is in fact an ssh-rsa signature and a buggy
2700 * server; otherwise we can just do this the easy way.
2702 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2703 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2704 int pos, len, siglen;
2707 * Find the byte length of the modulus.
2710 pos = 4+7; /* skip over "ssh-rsa" */
2711 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2712 if (len < 0 || len > pkblob_len - pos - 4)
2714 pos += 4 + len; /* skip over exponent */
2715 if (pkblob_len - pos < 4)
2717 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2718 if (len < 0 || len > pkblob_len - pos - 4)
2720 pos += 4; /* find modulus itself */
2721 while (len > 0 && pkblob[pos] == 0)
2723 /* debug(("modulus length is %d\n", len)); */
2726 * Now find the signature integer.
2728 pos = 4+7; /* skip over "ssh-rsa" */
2729 if (sigblob_len < pos+4)
2731 siglen = toint(GET_32BIT(sigblob+pos));
2732 if (siglen != sigblob_len - pos - 4)
2734 /* debug(("signature length is %d\n", siglen)); */
2736 if (len != siglen) {
2737 unsigned char newlen[4];
2738 ssh2_pkt_addstring_start(pkt);
2739 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2740 /* dmemdump(sigblob, pos); */
2741 pos += 4; /* point to start of actual sig */
2742 PUT_32BIT(newlen, len);
2743 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2744 /* dmemdump(newlen, 4); */
2746 while (len-- > siglen) {
2747 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2748 /* dmemdump(newlen, 1); */
2750 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2751 /* dmemdump(sigblob+pos, siglen); */
2755 /* Otherwise fall through and do it the easy way. We also come
2756 * here as a fallback if we discover above that the key blob
2757 * is misformatted in some way. */
2761 ssh2_pkt_addstring_start(pkt);
2762 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2766 * Examine the remote side's version string and compare it against
2767 * a list of known buggy implementations.
2769 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2771 char *imp; /* pointer to implementation part */
2773 imp += strcspn(imp, "-");
2775 imp += strcspn(imp, "-");
2778 ssh->remote_bugs = 0;
2781 * General notes on server version strings:
2782 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2783 * here -- in particular, we've heard of one that's perfectly happy
2784 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2785 * so we can't distinguish them.
2787 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2788 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2789 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2790 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2791 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2792 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2794 * These versions don't support SSH1_MSG_IGNORE, so we have
2795 * to use a different defence against password length
2798 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2799 logevent("We believe remote version has SSH-1 ignore bug");
2802 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2803 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2804 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2806 * These versions need a plain password sent; they can't
2807 * handle having a null and a random length of data after
2810 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2811 logevent("We believe remote version needs a plain SSH-1 password");
2814 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2815 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2816 (!strcmp(imp, "Cisco-1.25")))) {
2818 * These versions apparently have no clue whatever about
2819 * RSA authentication and will panic and die if they see
2820 * an AUTH_RSA message.
2822 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2823 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2826 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2827 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2828 !wc_match("* VShell", imp) &&
2829 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2830 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2831 wc_match("2.1 *", imp)))) {
2833 * These versions have the HMAC bug.
2835 ssh->remote_bugs |= BUG_SSH2_HMAC;
2836 logevent("We believe remote version has SSH-2 HMAC bug");
2839 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2840 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2841 !wc_match("* VShell", imp) &&
2842 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2844 * These versions have the key-derivation bug (failing to
2845 * include the literal shared secret in the hashes that
2846 * generate the keys).
2848 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2849 logevent("We believe remote version has SSH-2 key-derivation bug");
2852 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2853 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2854 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2855 wc_match("OpenSSH_3.[0-2]*", imp) ||
2856 wc_match("mod_sftp/0.[0-8]*", imp) ||
2857 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2859 * These versions have the SSH-2 RSA padding bug.
2861 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2862 logevent("We believe remote version has SSH-2 RSA padding bug");
2865 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2866 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2867 wc_match("OpenSSH_2.[0-2]*", imp))) {
2869 * These versions have the SSH-2 session-ID bug in
2870 * public-key authentication.
2872 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2873 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2876 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2877 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2878 (wc_match("DigiSSH_2.0", imp) ||
2879 wc_match("OpenSSH_2.[0-4]*", imp) ||
2880 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2881 wc_match("Sun_SSH_1.0", imp) ||
2882 wc_match("Sun_SSH_1.0.1", imp) ||
2883 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2884 wc_match("WeOnlyDo-*", imp)))) {
2886 * These versions have the SSH-2 rekey bug.
2888 ssh->remote_bugs |= BUG_SSH2_REKEY;
2889 logevent("We believe remote version has SSH-2 rekey bug");
2892 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2893 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2894 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2895 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2897 * This version ignores our makpkt and needs to be throttled.
2899 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2900 logevent("We believe remote version ignores SSH-2 maximum packet size");
2903 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2905 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2906 * none detected automatically.
2908 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2909 logevent("We believe remote version has SSH-2 ignore bug");
2912 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2913 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2914 (wc_match("OpenSSH_2.[235]*", imp)))) {
2916 * These versions only support the original (pre-RFC4419)
2917 * SSH-2 GEX request, and disconnect with a protocol error if
2918 * we use the newer version.
2920 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2921 logevent("We believe remote version has outdated SSH-2 GEX");
2924 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2926 * Servers that don't support our winadj request for one
2927 * reason or another. Currently, none detected automatically.
2929 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2930 logevent("We believe remote version has winadj bug");
2933 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
2934 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
2935 (wc_match("OpenSSH_[2-5].*", imp) ||
2936 wc_match("OpenSSH_6.[0-6]*", imp) ||
2937 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
2938 wc_match("dropbear_0.5[01]*", imp)))) {
2940 * These versions have the SSH-2 channel request bug.
2941 * OpenSSH 6.7 and above do not:
2942 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
2943 * dropbear_0.52 and above do not:
2944 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
2946 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
2947 logevent("We believe remote version has SSH-2 channel request bug");
2952 * The `software version' part of an SSH version string is required
2953 * to contain no spaces or minus signs.
2955 static void ssh_fix_verstring(char *str)
2957 /* Eat "<protoversion>-". */
2958 while (*str && *str != '-') str++;
2959 assert(*str == '-'); str++;
2961 /* Convert minus signs and spaces in the remaining string into
2964 if (*str == '-' || *str == ' ')
2971 * Send an appropriate SSH version string.
2973 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
2977 if (ssh->version == 2) {
2979 * Construct a v2 version string.
2981 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
2984 * Construct a v1 version string.
2986 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
2987 verstring = dupprintf("SSH-%s-%s\012",
2988 (ssh_versioncmp(svers, "1.5") <= 0 ?
2993 ssh_fix_verstring(verstring + strlen(protoname));
2995 if (ssh->version == 2) {
2998 * Record our version string.
3000 len = strcspn(verstring, "\015\012");
3001 ssh->v_c = snewn(len + 1, char);
3002 memcpy(ssh->v_c, verstring, len);
3006 logeventf(ssh, "We claim version: %.*s",
3007 strcspn(verstring, "\015\012"), verstring);
3008 s_write(ssh, verstring, strlen(verstring));
3012 static int do_ssh_init(Ssh ssh, unsigned char c)
3014 static const char protoname[] = "SSH-";
3016 struct do_ssh_init_state {
3025 crState(do_ssh_init_state);
3029 /* Search for a line beginning with the protocol name prefix in
3032 for (s->i = 0; protoname[s->i]; s->i++) {
3033 if ((char)c != protoname[s->i]) goto no;
3043 s->vstrsize = sizeof(protoname) + 16;
3044 s->vstring = snewn(s->vstrsize, char);
3045 strcpy(s->vstring, protoname);
3046 s->vslen = strlen(protoname);
3049 if (s->vslen >= s->vstrsize - 1) {
3051 s->vstring = sresize(s->vstring, s->vstrsize, char);
3053 s->vstring[s->vslen++] = c;
3056 s->version[s->i] = '\0';
3058 } else if (s->i < sizeof(s->version) - 1)
3059 s->version[s->i++] = c;
3060 } else if (c == '\012')
3062 crReturn(1); /* get another char */
3065 ssh->agentfwd_enabled = FALSE;
3066 ssh->rdpkt2_state.incoming_sequence = 0;
3068 s->vstring[s->vslen] = 0;
3069 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3070 logeventf(ssh, "Server version: %s", s->vstring);
3071 ssh_detect_bugs(ssh, s->vstring);
3074 * Decide which SSH protocol version to support.
3077 /* Anything strictly below "2.0" means protocol 1 is supported. */
3078 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3079 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3080 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3082 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
3083 bombout(("SSH protocol version 1 required by configuration but "
3084 "not provided by server"));
3087 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
3088 bombout(("SSH protocol version 2 required by configuration but "
3089 "not provided by server"));
3093 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3098 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3100 /* Send the version string, if we haven't already */
3101 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3102 ssh_send_verstring(ssh, protoname, s->version);
3104 if (ssh->version == 2) {
3107 * Record their version string.
3109 len = strcspn(s->vstring, "\015\012");
3110 ssh->v_s = snewn(len + 1, char);
3111 memcpy(ssh->v_s, s->vstring, len);
3115 * Initialise SSH-2 protocol.
3117 ssh->protocol = ssh2_protocol;
3118 ssh2_protocol_setup(ssh);
3119 ssh->s_rdpkt = ssh2_rdpkt;
3122 * Initialise SSH-1 protocol.
3124 ssh->protocol = ssh1_protocol;
3125 ssh1_protocol_setup(ssh);
3126 ssh->s_rdpkt = ssh1_rdpkt;
3128 if (ssh->version == 2)
3129 do_ssh2_transport(ssh, NULL, -1, NULL);
3131 update_specials_menu(ssh->frontend);
3132 ssh->state = SSH_STATE_BEFORE_SIZE;
3133 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3140 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3143 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3144 * the ssh-connection part, extracted and given a trivial binary
3145 * packet protocol, so we replace 'SSH-' at the start with a new
3146 * name. In proper SSH style (though of course this part of the
3147 * proper SSH protocol _isn't_ subject to this kind of
3148 * DNS-domain-based extension), we define the new name in our
3151 static const char protoname[] =
3152 "SSHCONNECTION@putty.projects.tartarus.org-";
3154 struct do_ssh_connection_init_state {
3162 crState(do_ssh_connection_init_state);
3166 /* Search for a line beginning with the protocol name prefix in
3169 for (s->i = 0; protoname[s->i]; s->i++) {
3170 if ((char)c != protoname[s->i]) goto no;
3180 s->vstrsize = sizeof(protoname) + 16;
3181 s->vstring = snewn(s->vstrsize, char);
3182 strcpy(s->vstring, protoname);
3183 s->vslen = strlen(protoname);
3186 if (s->vslen >= s->vstrsize - 1) {
3188 s->vstring = sresize(s->vstring, s->vstrsize, char);
3190 s->vstring[s->vslen++] = c;
3193 s->version[s->i] = '\0';
3195 } else if (s->i < sizeof(s->version) - 1)
3196 s->version[s->i++] = c;
3197 } else if (c == '\012')
3199 crReturn(1); /* get another char */
3202 ssh->agentfwd_enabled = FALSE;
3203 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3205 s->vstring[s->vslen] = 0;
3206 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3207 logeventf(ssh, "Server version: %s", s->vstring);
3208 ssh_detect_bugs(ssh, s->vstring);
3211 * Decide which SSH protocol version to support. This is easy in
3212 * bare ssh-connection mode: only 2.0 is legal.
3214 if (ssh_versioncmp(s->version, "2.0") < 0) {
3215 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3218 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3219 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3225 logeventf(ssh, "Using bare ssh-connection protocol");
3227 /* Send the version string, if we haven't already */
3228 ssh_send_verstring(ssh, protoname, s->version);
3231 * Initialise bare connection protocol.
3233 ssh->protocol = ssh2_bare_connection_protocol;
3234 ssh2_bare_connection_protocol_setup(ssh);
3235 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3237 update_specials_menu(ssh->frontend);
3238 ssh->state = SSH_STATE_BEFORE_SIZE;
3239 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3242 * Get authconn (really just conn) under way.
3244 do_ssh2_authconn(ssh, NULL, 0, NULL);
3251 static void ssh_process_incoming_data(Ssh ssh,
3252 const unsigned char **data, int *datalen)
3254 struct Packet *pktin;
3256 pktin = ssh->s_rdpkt(ssh, data, datalen);
3258 ssh->protocol(ssh, NULL, 0, pktin);
3259 ssh_free_packet(pktin);
3263 static void ssh_queue_incoming_data(Ssh ssh,
3264 const unsigned char **data, int *datalen)
3266 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3271 static void ssh_process_queued_incoming_data(Ssh ssh)
3274 const unsigned char *data;
3277 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3278 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3282 while (!ssh->frozen && len > 0)
3283 ssh_process_incoming_data(ssh, &data, &len);
3286 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3290 static void ssh_set_frozen(Ssh ssh, int frozen)
3293 sk_set_frozen(ssh->s, frozen);
3294 ssh->frozen = frozen;
3297 static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
3299 /* Log raw data, if we're in that mode. */
3301 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3302 0, NULL, NULL, 0, NULL);
3304 crBegin(ssh->ssh_gotdata_crstate);
3307 * To begin with, feed the characters one by one to the
3308 * protocol initialisation / selection function do_ssh_init().
3309 * When that returns 0, we're done with the initial greeting
3310 * exchange and can move on to packet discipline.
3313 int ret; /* need not be kept across crReturn */
3315 crReturnV; /* more data please */
3316 ret = ssh->do_ssh_init(ssh, *data);
3324 * We emerge from that loop when the initial negotiation is
3325 * over and we have selected an s_rdpkt function. Now pass
3326 * everything to s_rdpkt, and then pass the resulting packets
3327 * to the proper protocol handler.
3331 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3333 ssh_queue_incoming_data(ssh, &data, &datalen);
3334 /* This uses up all data and cannot cause anything interesting
3335 * to happen; indeed, for anything to happen at all, we must
3336 * return, so break out. */
3338 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3339 /* This uses up some or all data, and may freeze the
3341 ssh_process_queued_incoming_data(ssh);
3343 /* This uses up some or all data, and may freeze the
3345 ssh_process_incoming_data(ssh, &data, &datalen);
3347 /* FIXME this is probably EBW. */
3348 if (ssh->state == SSH_STATE_CLOSED)
3351 /* We're out of data. Go and get some more. */
3357 static int ssh_do_close(Ssh ssh, int notify_exit)
3360 struct ssh_channel *c;
3362 ssh->state = SSH_STATE_CLOSED;
3363 expire_timer_context(ssh);
3368 notify_remote_exit(ssh->frontend);
3373 * Now we must shut down any port- and X-forwarded channels going
3374 * through this connection.
3376 if (ssh->channels) {
3377 while (NULL != (c = index234(ssh->channels, 0))) {
3380 x11_close(c->u.x11.xconn);
3383 case CHAN_SOCKDATA_DORMANT:
3384 pfd_close(c->u.pfd.pf);
3387 del234(ssh->channels, c); /* moving next one to index 0 */
3388 if (ssh->version == 2)
3389 bufchain_clear(&c->v.v2.outbuffer);
3394 * Go through port-forwardings, and close any associated
3395 * listening sockets.
3397 if (ssh->portfwds) {
3398 struct ssh_portfwd *pf;
3399 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3400 /* Dispose of any listening socket. */
3402 pfl_terminate(pf->local);
3403 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3406 freetree234(ssh->portfwds);
3407 ssh->portfwds = NULL;
3411 * Also stop attempting to connection-share.
3413 if (ssh->connshare) {
3414 sharestate_free(ssh->connshare);
3415 ssh->connshare = NULL;
3421 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3422 const char *error_msg, int error_code)
3424 Ssh ssh = (Ssh) plug;
3425 char addrbuf[256], *msg;
3427 if (ssh->attempting_connshare) {
3429 * While we're attempting connection sharing, don't loudly log
3430 * everything that happens. Real TCP connections need to be
3431 * logged when we _start_ trying to connect, because it might
3432 * be ages before they respond if something goes wrong; but
3433 * connection sharing is local and quick to respond, and it's
3434 * sufficient to simply wait and see whether it worked
3438 sk_getaddr(addr, addrbuf, lenof(addrbuf));
3441 if (sk_addr_needs_port(addr)) {
3442 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
3444 msg = dupprintf("Connecting to %s", addrbuf);
3447 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
3455 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3456 const char *ds_err, const char *us_err)
3458 if (event == SHARE_NONE) {
3459 /* In this case, 'logtext' is an error message indicating a
3460 * reason why connection sharing couldn't be set up _at all_.
3461 * Failing that, ds_err and us_err indicate why we couldn't be
3462 * a downstream and an upstream respectively. */
3464 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3467 logeventf(ssh, "Could not set up connection sharing"
3468 " as downstream: %s", ds_err);
3470 logeventf(ssh, "Could not set up connection sharing"
3471 " as upstream: %s", us_err);
3473 } else if (event == SHARE_DOWNSTREAM) {
3474 /* In this case, 'logtext' is a local endpoint address */
3475 logeventf(ssh, "Using existing shared connection at %s", logtext);
3476 /* Also we should mention this in the console window to avoid
3477 * confusing users as to why this window doesn't behave the
3479 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3480 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3482 } else if (event == SHARE_UPSTREAM) {
3483 /* In this case, 'logtext' is a local endpoint address too */
3484 logeventf(ssh, "Sharing this connection at %s", logtext);
3488 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3491 Ssh ssh = (Ssh) plug;
3492 int need_notify = ssh_do_close(ssh, FALSE);
3495 if (!ssh->close_expected)
3496 error_msg = "Server unexpectedly closed network connection";
3498 error_msg = "Server closed network connection";
3501 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3505 notify_remote_exit(ssh->frontend);
3508 logevent(error_msg);
3509 if (!ssh->close_expected || !ssh->clean_exit)
3510 connection_fatal(ssh->frontend, "%s", error_msg);
3514 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3516 Ssh ssh = (Ssh) plug;
3517 ssh_gotdata(ssh, (unsigned char *)data, len);
3518 if (ssh->state == SSH_STATE_CLOSED) {
3519 ssh_do_close(ssh, TRUE);
3525 static void ssh_sent(Plug plug, int bufsize)
3527 Ssh ssh = (Ssh) plug;
3529 * If the send backlog on the SSH socket itself clears, we
3530 * should unthrottle the whole world if it was throttled.
3532 if (bufsize < SSH_MAX_BACKLOG)
3533 ssh_throttle_all(ssh, 0, bufsize);
3537 * Connect to specified host and port.
3538 * Returns an error message, or NULL on success.
3539 * Also places the canonical host name into `realhost'. It must be
3540 * freed by the caller.
3542 static const char *connect_to_host(Ssh ssh, const char *host, int port,
3543 char **realhost, int nodelay, int keepalive)
3545 static const struct plug_function_table fn_table = {
3556 int addressfamily, sshprot;
3558 loghost = conf_get_str(ssh->conf, CONF_loghost);
3563 tmphost = dupstr(loghost);
3564 ssh->savedport = 22; /* default ssh port */
3567 * A colon suffix on the hostname string also lets us affect
3568 * savedport. (Unless there are multiple colons, in which case
3569 * we assume this is an unbracketed IPv6 literal.)
3571 colon = host_strrchr(tmphost, ':');
3572 if (colon && colon == host_strchr(tmphost, ':')) {
3575 ssh->savedport = atoi(colon);
3578 ssh->savedhost = host_strduptrim(tmphost);
3581 ssh->savedhost = host_strduptrim(host);
3583 port = 22; /* default ssh port */
3584 ssh->savedport = port;
3587 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3590 * Try connection-sharing, in case that means we don't open a
3591 * socket after all. ssh_connection_sharing_init will connect to a
3592 * previously established upstream if it can, and failing that,
3593 * establish a listening socket for _us_ to be the upstream. In
3594 * the latter case it will return NULL just as if it had done
3595 * nothing, because here we only need to care if we're a
3596 * downstream and need to do our connection setup differently.
3598 ssh->connshare = NULL;
3599 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3600 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3601 ssh->conf, ssh, &ssh->connshare);
3602 ssh->attempting_connshare = FALSE;
3603 if (ssh->s != NULL) {
3605 * We are a downstream.
3607 ssh->bare_connection = TRUE;
3608 ssh->do_ssh_init = do_ssh_connection_init;
3609 ssh->fullhostname = NULL;
3610 *realhost = dupstr(host); /* best we can do */
3613 * We're not a downstream, so open a normal socket.
3615 ssh->do_ssh_init = do_ssh_init;
3620 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3621 logeventf(ssh, "Looking up host \"%s\"%s", host,
3622 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3623 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3624 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3625 if ((err = sk_addr_error(addr)) != NULL) {
3629 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3631 ssh->s = new_connection(addr, *realhost, port,
3632 0, 1, nodelay, keepalive,
3633 (Plug) ssh, ssh->conf);
3634 if ((err = sk_socket_error(ssh->s)) != NULL) {
3636 notify_remote_exit(ssh->frontend);
3642 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3643 * send the version string too.
3645 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3648 if (sshprot == 3 && !ssh->bare_connection) {
3650 ssh_send_verstring(ssh, "SSH-", NULL);
3654 * loghost, if configured, overrides realhost.
3658 *realhost = dupstr(loghost);
3665 * Throttle or unthrottle the SSH connection.
3667 static void ssh_throttle_conn(Ssh ssh, int adjust)
3669 int old_count = ssh->conn_throttle_count;
3670 ssh->conn_throttle_count += adjust;
3671 assert(ssh->conn_throttle_count >= 0);
3672 if (ssh->conn_throttle_count && !old_count) {
3673 ssh_set_frozen(ssh, 1);
3674 } else if (!ssh->conn_throttle_count && old_count) {
3675 ssh_set_frozen(ssh, 0);
3680 * Throttle or unthrottle _all_ local data streams (for when sends
3681 * on the SSH connection itself back up).
3683 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3686 struct ssh_channel *c;
3688 if (enable == ssh->throttled_all)
3690 ssh->throttled_all = enable;
3691 ssh->overall_bufsize = bufsize;
3694 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3696 case CHAN_MAINSESSION:
3698 * This is treated separately, outside the switch.
3702 x11_override_throttle(c->u.x11.xconn, enable);
3705 /* Agent channels require no buffer management. */
3708 pfd_override_throttle(c->u.pfd.pf, enable);
3714 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3716 Ssh ssh = (Ssh) sshv;
3718 ssh->agent_response = reply;
3719 ssh->agent_response_len = replylen;
3721 if (ssh->version == 1)
3722 do_ssh1_login(ssh, NULL, -1, NULL);
3724 do_ssh2_authconn(ssh, NULL, -1, NULL);
3727 static void ssh_dialog_callback(void *sshv, int ret)
3729 Ssh ssh = (Ssh) sshv;
3731 ssh->user_response = ret;
3733 if (ssh->version == 1)
3734 do_ssh1_login(ssh, NULL, -1, NULL);
3736 do_ssh2_transport(ssh, NULL, -1, NULL);
3739 * This may have unfrozen the SSH connection, so do a
3742 ssh_process_queued_incoming_data(ssh);
3745 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3747 struct ssh_channel *c = (struct ssh_channel *)cv;
3749 const void *sentreply = reply;
3751 c->u.a.outstanding_requests--;
3753 /* Fake SSH_AGENT_FAILURE. */
3754 sentreply = "\0\0\0\1\5";
3757 if (ssh->version == 2) {
3758 ssh2_add_channel_data(c, sentreply, replylen);
3761 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3762 PKT_INT, c->remoteid,
3764 PKT_DATA, sentreply, replylen,
3770 * If we've already seen an incoming EOF but haven't sent an
3771 * outgoing one, this may be the moment to send it.
3773 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3774 sshfwd_write_eof(c);
3778 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3779 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3780 * => log `wire_reason'.
3782 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3783 const char *wire_reason,
3784 int code, int clean_exit)
3788 client_reason = wire_reason;
3790 error = dupprintf("Disconnected: %s", client_reason);
3792 error = dupstr("Disconnected");
3794 if (ssh->version == 1) {
3795 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3797 } else if (ssh->version == 2) {
3798 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3799 ssh2_pkt_adduint32(pktout, code);
3800 ssh2_pkt_addstring(pktout, wire_reason);
3801 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3802 ssh2_pkt_send_noqueue(ssh, pktout);
3805 ssh->close_expected = TRUE;
3806 ssh->clean_exit = clean_exit;
3807 ssh_closing((Plug)ssh, error, 0, 0);
3811 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3812 const struct ssh_signkey *ssh2keytype,
3815 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3816 return -1; /* no manual keys configured */
3821 * The fingerprint string we've been given will have things
3822 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3823 * narrow down to just the colon-separated hex block at the
3824 * end of the string.
3826 const char *p = strrchr(fingerprint, ' ');
3827 fingerprint = p ? p+1 : fingerprint;
3828 /* Quick sanity checks, including making sure it's in lowercase */
3829 assert(strlen(fingerprint) == 16*3 - 1);
3830 assert(fingerprint[2] == ':');
3831 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3833 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3835 return 1; /* success */
3840 * Construct the base64-encoded public key blob and see if
3843 unsigned char *binblob;
3845 int binlen, atoms, i;
3846 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3847 atoms = (binlen + 2) / 3;
3848 base64blob = snewn(atoms * 4 + 1, char);
3849 for (i = 0; i < atoms; i++)
3850 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3851 base64blob[atoms * 4] = '\0';
3853 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3856 return 1; /* success */
3865 * Handle the key exchange and user authentication phases.
3867 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
3868 struct Packet *pktin)
3871 unsigned char cookie[8], *ptr;
3872 struct MD5Context md5c;
3873 struct do_ssh1_login_state {
3876 unsigned char *rsabuf;
3877 const unsigned char *keystr1, *keystr2;
3878 unsigned long supported_ciphers_mask, supported_auths_mask;
3879 int tried_publickey, tried_agent;
3880 int tis_auth_refused, ccard_auth_refused;
3881 unsigned char session_id[16];
3883 void *publickey_blob;
3884 int publickey_bloblen;
3885 char *publickey_comment;
3886 int privatekey_available, privatekey_encrypted;
3887 prompts_t *cur_prompt;
3890 unsigned char request[5], *response, *p;
3900 struct RSAKey servkey, hostkey;
3902 crState(do_ssh1_login_state);
3909 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3910 bombout(("Public key packet not received"));
3914 logevent("Received public keys");
3916 ptr = ssh_pkt_getdata(pktin, 8);
3918 bombout(("SSH-1 public key packet stopped before random cookie"));
3921 memcpy(cookie, ptr, 8);
3923 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3924 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3925 bombout(("Failed to read SSH-1 public keys from public key packet"));
3930 * Log the host key fingerprint.
3934 logevent("Host key fingerprint is:");
3935 strcpy(logmsg, " ");
3936 s->hostkey.comment = NULL;
3937 rsa_fingerprint(logmsg + strlen(logmsg),
3938 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3942 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3943 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3944 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3945 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3946 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3948 ssh->v1_local_protoflags =
3949 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3950 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3953 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3954 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3955 MD5Update(&md5c, cookie, 8);
3956 MD5Final(s->session_id, &md5c);
3958 for (i = 0; i < 32; i++)
3959 ssh->session_key[i] = random_byte();
3962 * Verify that the `bits' and `bytes' parameters match.
3964 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3965 s->servkey.bits > s->servkey.bytes * 8) {
3966 bombout(("SSH-1 public keys were badly formatted"));
3970 s->len = (s->hostkey.bytes > s->servkey.bytes ?
3971 s->hostkey.bytes : s->servkey.bytes);
3973 s->rsabuf = snewn(s->len, unsigned char);
3976 * Verify the host key.
3980 * First format the key into a string.
3982 int len = rsastr_len(&s->hostkey);
3983 char fingerprint[100];
3984 char *keystr = snewn(len, char);
3985 rsastr_fmt(keystr, &s->hostkey);
3986 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
3988 /* First check against manually configured host keys. */
3989 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
3990 if (s->dlgret == 0) { /* did not match */
3991 bombout(("Host key did not appear in manually configured list"));
3994 } else if (s->dlgret < 0) { /* none configured; use standard handling */
3995 ssh_set_frozen(ssh, 1);
3996 s->dlgret = verify_ssh_host_key(ssh->frontend,
3997 ssh->savedhost, ssh->savedport,
3998 "rsa", keystr, fingerprint,
3999 ssh_dialog_callback, ssh);
4001 if (s->dlgret < 0) {
4005 bombout(("Unexpected data from server while waiting"
4006 " for user host key response"));
4009 } while (pktin || inlen > 0);
4010 s->dlgret = ssh->user_response;
4012 ssh_set_frozen(ssh, 0);
4014 if (s->dlgret == 0) {
4015 ssh_disconnect(ssh, "User aborted at host key verification",
4024 for (i = 0; i < 32; i++) {
4025 s->rsabuf[i] = ssh->session_key[i];
4027 s->rsabuf[i] ^= s->session_id[i];
4030 if (s->hostkey.bytes > s->servkey.bytes) {
4031 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4033 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4035 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4037 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4040 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4044 logevent("Encrypted session key");
4047 int cipher_chosen = 0, warn = 0;
4048 const char *cipher_string = NULL;
4050 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4051 int next_cipher = conf_get_int_int(ssh->conf,
4052 CONF_ssh_cipherlist, i);
4053 if (next_cipher == CIPHER_WARN) {
4054 /* If/when we choose a cipher, warn about it */
4056 } else if (next_cipher == CIPHER_AES) {
4057 /* XXX Probably don't need to mention this. */
4058 logevent("AES not supported in SSH-1, skipping");
4060 switch (next_cipher) {
4061 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4062 cipher_string = "3DES"; break;
4063 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4064 cipher_string = "Blowfish"; break;
4065 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4066 cipher_string = "single-DES"; break;
4068 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4072 if (!cipher_chosen) {
4073 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4074 bombout(("Server violates SSH-1 protocol by not "
4075 "supporting 3DES encryption"));
4077 /* shouldn't happen */
4078 bombout(("No supported ciphers found"));
4082 /* Warn about chosen cipher if necessary. */
4084 ssh_set_frozen(ssh, 1);
4085 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4086 ssh_dialog_callback, ssh);
4087 if (s->dlgret < 0) {
4091 bombout(("Unexpected data from server while waiting"
4092 " for user response"));
4095 } while (pktin || inlen > 0);
4096 s->dlgret = ssh->user_response;
4098 ssh_set_frozen(ssh, 0);
4099 if (s->dlgret == 0) {
4100 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4107 switch (s->cipher_type) {
4108 case SSH_CIPHER_3DES:
4109 logevent("Using 3DES encryption");
4111 case SSH_CIPHER_DES:
4112 logevent("Using single-DES encryption");
4114 case SSH_CIPHER_BLOWFISH:
4115 logevent("Using Blowfish encryption");
4119 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4120 PKT_CHAR, s->cipher_type,
4121 PKT_DATA, cookie, 8,
4122 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4123 PKT_DATA, s->rsabuf, s->len,
4124 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4126 logevent("Trying to enable encryption...");
4130 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4131 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4133 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4134 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4135 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4137 ssh->crcda_ctx = crcda_make_context();
4138 logevent("Installing CRC compensation attack detector");
4140 if (s->servkey.modulus) {
4141 sfree(s->servkey.modulus);
4142 s->servkey.modulus = NULL;
4144 if (s->servkey.exponent) {
4145 sfree(s->servkey.exponent);
4146 s->servkey.exponent = NULL;
4148 if (s->hostkey.modulus) {
4149 sfree(s->hostkey.modulus);
4150 s->hostkey.modulus = NULL;
4152 if (s->hostkey.exponent) {
4153 sfree(s->hostkey.exponent);
4154 s->hostkey.exponent = NULL;
4158 if (pktin->type != SSH1_SMSG_SUCCESS) {
4159 bombout(("Encryption not successfully enabled"));
4163 logevent("Successfully started encryption");
4165 fflush(stdout); /* FIXME eh? */
4167 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4168 int ret; /* need not be kept over crReturn */
4169 s->cur_prompt = new_prompts(ssh->frontend);
4170 s->cur_prompt->to_server = TRUE;
4171 s->cur_prompt->name = dupstr("SSH login name");
4172 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4173 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4176 crWaitUntil(!pktin);
4177 ret = get_userpass_input(s->cur_prompt, in, inlen);
4182 * Failed to get a username. Terminate.
4184 free_prompts(s->cur_prompt);
4185 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4188 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4189 free_prompts(s->cur_prompt);
4192 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4194 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4196 if (flags & FLAG_INTERACTIVE &&
4197 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4198 c_write_str(ssh, userlog);
4199 c_write_str(ssh, "\r\n");
4207 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4208 /* We must not attempt PK auth. Pretend we've already tried it. */
4209 s->tried_publickey = s->tried_agent = 1;
4211 s->tried_publickey = s->tried_agent = 0;
4213 s->tis_auth_refused = s->ccard_auth_refused = 0;
4215 * Load the public half of any configured keyfile for later use.
4217 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4218 if (!filename_is_null(s->keyfile)) {
4220 logeventf(ssh, "Reading key file \"%.150s\"",
4221 filename_to_str(s->keyfile));
4222 keytype = key_type(s->keyfile);
4223 if (keytype == SSH_KEYTYPE_SSH1 ||
4224 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4226 if (rsakey_pubblob(s->keyfile,
4227 &s->publickey_blob, &s->publickey_bloblen,
4228 &s->publickey_comment, &error)) {
4229 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4230 if (!s->privatekey_available)
4231 logeventf(ssh, "Key file contains public key only");
4232 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4236 logeventf(ssh, "Unable to load key (%s)", error);
4237 msgbuf = dupprintf("Unable to load key file "
4238 "\"%.150s\" (%s)\r\n",
4239 filename_to_str(s->keyfile),
4241 c_write_str(ssh, msgbuf);
4243 s->publickey_blob = NULL;
4247 logeventf(ssh, "Unable to use this key file (%s)",
4248 key_type_to_str(keytype));
4249 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4251 filename_to_str(s->keyfile),
4252 key_type_to_str(keytype));
4253 c_write_str(ssh, msgbuf);
4255 s->publickey_blob = NULL;
4258 s->publickey_blob = NULL;
4260 while (pktin->type == SSH1_SMSG_FAILURE) {
4261 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4263 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4265 * Attempt RSA authentication using Pageant.
4271 logevent("Pageant is running. Requesting keys.");
4273 /* Request the keys held by the agent. */
4274 PUT_32BIT(s->request, 1);
4275 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4276 if (!agent_query(s->request, 5, &r, &s->responselen,
4277 ssh_agent_callback, ssh)) {
4281 bombout(("Unexpected data from server while waiting"
4282 " for agent response"));
4285 } while (pktin || inlen > 0);
4286 r = ssh->agent_response;
4287 s->responselen = ssh->agent_response_len;
4289 s->response = (unsigned char *) r;
4290 if (s->response && s->responselen >= 5 &&
4291 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4292 s->p = s->response + 5;
4293 s->nkeys = toint(GET_32BIT(s->p));
4295 logeventf(ssh, "Pageant reported negative key count %d",
4300 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4301 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4302 unsigned char *pkblob = s->p;
4306 do { /* do while (0) to make breaking easy */
4307 n = ssh1_read_bignum
4308 (s->p, toint(s->responselen-(s->p-s->response)),
4313 n = ssh1_read_bignum
4314 (s->p, toint(s->responselen-(s->p-s->response)),
4319 if (s->responselen - (s->p-s->response) < 4)
4321 s->commentlen = toint(GET_32BIT(s->p));
4323 if (s->commentlen < 0 ||
4324 toint(s->responselen - (s->p-s->response)) <
4327 s->commentp = (char *)s->p;
4328 s->p += s->commentlen;
4332 logevent("Pageant key list packet was truncated");
4336 if (s->publickey_blob) {
4337 if (!memcmp(pkblob, s->publickey_blob,
4338 s->publickey_bloblen)) {
4339 logeventf(ssh, "Pageant key #%d matches "
4340 "configured key file", s->keyi);
4341 s->tried_publickey = 1;
4343 /* Skip non-configured key */
4346 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4347 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4348 PKT_BIGNUM, s->key.modulus, PKT_END);
4350 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4351 logevent("Key refused");
4354 logevent("Received RSA challenge");
4355 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4356 bombout(("Server's RSA challenge was badly formatted"));
4361 char *agentreq, *q, *ret;
4364 len = 1 + 4; /* message type, bit count */
4365 len += ssh1_bignum_length(s->key.exponent);
4366 len += ssh1_bignum_length(s->key.modulus);
4367 len += ssh1_bignum_length(s->challenge);
4368 len += 16; /* session id */
4369 len += 4; /* response format */
4370 agentreq = snewn(4 + len, char);
4371 PUT_32BIT(agentreq, len);
4373 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4374 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4376 q += ssh1_write_bignum(q, s->key.exponent);
4377 q += ssh1_write_bignum(q, s->key.modulus);
4378 q += ssh1_write_bignum(q, s->challenge);
4379 memcpy(q, s->session_id, 16);
4381 PUT_32BIT(q, 1); /* response format */
4382 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4383 ssh_agent_callback, ssh)) {
4388 bombout(("Unexpected data from server"
4389 " while waiting for agent"
4393 } while (pktin || inlen > 0);
4394 vret = ssh->agent_response;
4395 retlen = ssh->agent_response_len;
4400 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4401 logevent("Sending Pageant's response");
4402 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4403 PKT_DATA, ret + 5, 16,
4407 if (pktin->type == SSH1_SMSG_SUCCESS) {
4409 ("Pageant's response accepted");
4410 if (flags & FLAG_VERBOSE) {
4411 c_write_str(ssh, "Authenticated using"
4413 c_write(ssh, s->commentp,
4415 c_write_str(ssh, "\" from agent\r\n");
4420 ("Pageant's response not accepted");
4423 ("Pageant failed to answer challenge");
4427 logevent("No reply received from Pageant");
4430 freebn(s->key.exponent);
4431 freebn(s->key.modulus);
4432 freebn(s->challenge);
4437 if (s->publickey_blob && !s->tried_publickey)
4438 logevent("Configured key file not in Pageant");
4440 logevent("Failed to get reply from Pageant");
4445 if (s->publickey_blob && s->privatekey_available &&
4446 !s->tried_publickey) {
4448 * Try public key authentication with the specified
4451 int got_passphrase; /* need not be kept over crReturn */
4452 if (flags & FLAG_VERBOSE)
4453 c_write_str(ssh, "Trying public key authentication.\r\n");
4454 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4455 logeventf(ssh, "Trying public key \"%s\"",
4456 filename_to_str(s->keyfile));
4457 s->tried_publickey = 1;
4458 got_passphrase = FALSE;
4459 while (!got_passphrase) {
4461 * Get a passphrase, if necessary.
4463 char *passphrase = NULL; /* only written after crReturn */
4465 if (!s->privatekey_encrypted) {
4466 if (flags & FLAG_VERBOSE)
4467 c_write_str(ssh, "No passphrase required.\r\n");
4470 int ret; /* need not be kept over crReturn */
4471 s->cur_prompt = new_prompts(ssh->frontend);
4472 s->cur_prompt->to_server = FALSE;
4473 s->cur_prompt->name = dupstr("SSH key passphrase");
4474 add_prompt(s->cur_prompt,
4475 dupprintf("Passphrase for key \"%.100s\": ",
4476 s->publickey_comment), FALSE);
4477 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4480 crWaitUntil(!pktin);
4481 ret = get_userpass_input(s->cur_prompt, in, inlen);
4485 /* Failed to get a passphrase. Terminate. */
4486 free_prompts(s->cur_prompt);
4487 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4491 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4492 free_prompts(s->cur_prompt);
4495 * Try decrypting key with passphrase.
4497 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4498 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4501 smemclr(passphrase, strlen(passphrase));
4505 /* Correct passphrase. */
4506 got_passphrase = TRUE;
4507 } else if (ret == 0) {
4508 c_write_str(ssh, "Couldn't load private key from ");
4509 c_write_str(ssh, filename_to_str(s->keyfile));
4510 c_write_str(ssh, " (");
4511 c_write_str(ssh, error);
4512 c_write_str(ssh, ").\r\n");
4513 got_passphrase = FALSE;
4514 break; /* go and try something else */
4515 } else if (ret == -1) {
4516 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4517 got_passphrase = FALSE;
4520 assert(0 && "unexpected return from loadrsakey()");
4521 got_passphrase = FALSE; /* placate optimisers */
4525 if (got_passphrase) {
4528 * Send a public key attempt.
4530 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4531 PKT_BIGNUM, s->key.modulus, PKT_END);
4534 if (pktin->type == SSH1_SMSG_FAILURE) {
4535 c_write_str(ssh, "Server refused our public key.\r\n");
4536 continue; /* go and try something else */
4538 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4539 bombout(("Bizarre response to offer of public key"));
4545 unsigned char buffer[32];
4546 Bignum challenge, response;
4548 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4549 bombout(("Server's RSA challenge was badly formatted"));
4552 response = rsadecrypt(challenge, &s->key);
4553 freebn(s->key.private_exponent);/* burn the evidence */
4555 for (i = 0; i < 32; i++) {
4556 buffer[i] = bignum_byte(response, 31 - i);
4560 MD5Update(&md5c, buffer, 32);
4561 MD5Update(&md5c, s->session_id, 16);
4562 MD5Final(buffer, &md5c);
4564 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4565 PKT_DATA, buffer, 16, PKT_END);
4572 if (pktin->type == SSH1_SMSG_FAILURE) {
4573 if (flags & FLAG_VERBOSE)
4574 c_write_str(ssh, "Failed to authenticate with"
4575 " our public key.\r\n");
4576 continue; /* go and try something else */
4577 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4578 bombout(("Bizarre response to RSA authentication response"));
4582 break; /* we're through! */
4588 * Otherwise, try various forms of password-like authentication.
4590 s->cur_prompt = new_prompts(ssh->frontend);
4592 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4593 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4594 !s->tis_auth_refused) {
4595 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4596 logevent("Requested TIS authentication");
4597 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4599 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4600 logevent("TIS authentication declined");
4601 if (flags & FLAG_INTERACTIVE)
4602 c_write_str(ssh, "TIS authentication refused.\r\n");
4603 s->tis_auth_refused = 1;
4608 char *instr_suf, *prompt;
4610 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4612 bombout(("TIS challenge packet was badly formed"));
4615 logevent("Received TIS challenge");
4616 s->cur_prompt->to_server = TRUE;
4617 s->cur_prompt->name = dupstr("SSH TIS authentication");
4618 /* Prompt heuristic comes from OpenSSH */
4619 if (memchr(challenge, '\n', challengelen)) {
4620 instr_suf = dupstr("");
4621 prompt = dupprintf("%.*s", challengelen, challenge);
4623 instr_suf = dupprintf("%.*s", challengelen, challenge);
4624 prompt = dupstr("Response: ");
4626 s->cur_prompt->instruction =
4627 dupprintf("Using TIS authentication.%s%s",
4628 (*instr_suf) ? "\n" : "",
4630 s->cur_prompt->instr_reqd = TRUE;
4631 add_prompt(s->cur_prompt, prompt, FALSE);
4635 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4636 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4637 !s->ccard_auth_refused) {
4638 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4639 logevent("Requested CryptoCard authentication");
4640 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4642 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4643 logevent("CryptoCard authentication declined");
4644 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4645 s->ccard_auth_refused = 1;
4650 char *instr_suf, *prompt;
4652 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4654 bombout(("CryptoCard challenge packet was badly formed"));
4657 logevent("Received CryptoCard challenge");
4658 s->cur_prompt->to_server = TRUE;
4659 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4660 s->cur_prompt->name_reqd = FALSE;
4661 /* Prompt heuristic comes from OpenSSH */
4662 if (memchr(challenge, '\n', challengelen)) {
4663 instr_suf = dupstr("");
4664 prompt = dupprintf("%.*s", challengelen, challenge);
4666 instr_suf = dupprintf("%.*s", challengelen, challenge);
4667 prompt = dupstr("Response: ");
4669 s->cur_prompt->instruction =
4670 dupprintf("Using CryptoCard authentication.%s%s",
4671 (*instr_suf) ? "\n" : "",
4673 s->cur_prompt->instr_reqd = TRUE;
4674 add_prompt(s->cur_prompt, prompt, FALSE);
4678 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4679 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4680 bombout(("No supported authentication methods available"));
4683 s->cur_prompt->to_server = TRUE;
4684 s->cur_prompt->name = dupstr("SSH password");
4685 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4686 ssh->username, ssh->savedhost),
4691 * Show password prompt, having first obtained it via a TIS
4692 * or CryptoCard exchange if we're doing TIS or CryptoCard
4696 int ret; /* need not be kept over crReturn */
4697 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4700 crWaitUntil(!pktin);
4701 ret = get_userpass_input(s->cur_prompt, in, inlen);
4706 * Failed to get a password (for example
4707 * because one was supplied on the command line
4708 * which has already failed to work). Terminate.
4710 free_prompts(s->cur_prompt);
4711 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4716 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4718 * Defence against traffic analysis: we send a
4719 * whole bunch of packets containing strings of
4720 * different lengths. One of these strings is the
4721 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4722 * The others are all random data in
4723 * SSH1_MSG_IGNORE packets. This way a passive
4724 * listener can't tell which is the password, and
4725 * hence can't deduce the password length.
4727 * Anybody with a password length greater than 16
4728 * bytes is going to have enough entropy in their
4729 * password that a listener won't find it _that_
4730 * much help to know how long it is. So what we'll
4733 * - if password length < 16, we send 15 packets
4734 * containing string lengths 1 through 15
4736 * - otherwise, we let N be the nearest multiple
4737 * of 8 below the password length, and send 8
4738 * packets containing string lengths N through
4739 * N+7. This won't obscure the order of
4740 * magnitude of the password length, but it will
4741 * introduce a bit of extra uncertainty.
4743 * A few servers can't deal with SSH1_MSG_IGNORE, at
4744 * least in this context. For these servers, we need
4745 * an alternative defence. We make use of the fact
4746 * that the password is interpreted as a C string:
4747 * so we can append a NUL, then some random data.
4749 * A few servers can deal with neither SSH1_MSG_IGNORE
4750 * here _nor_ a padded password string.
4751 * For these servers we are left with no defences
4752 * against password length sniffing.
4754 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4755 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4757 * The server can deal with SSH1_MSG_IGNORE, so
4758 * we can use the primary defence.
4760 int bottom, top, pwlen, i;
4763 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4765 bottom = 0; /* zero length passwords are OK! :-) */
4768 bottom = pwlen & ~7;
4772 assert(pwlen >= bottom && pwlen <= top);
4774 randomstr = snewn(top + 1, char);
4776 for (i = bottom; i <= top; i++) {
4778 defer_packet(ssh, s->pwpkt_type,
4779 PKT_STR,s->cur_prompt->prompts[0]->result,
4782 for (j = 0; j < i; j++) {
4784 randomstr[j] = random_byte();
4785 } while (randomstr[j] == '\0');
4787 randomstr[i] = '\0';
4788 defer_packet(ssh, SSH1_MSG_IGNORE,
4789 PKT_STR, randomstr, PKT_END);
4792 logevent("Sending password with camouflage packets");
4793 ssh_pkt_defersend(ssh);
4796 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4798 * The server can't deal with SSH1_MSG_IGNORE
4799 * but can deal with padded passwords, so we
4800 * can use the secondary defence.
4806 len = strlen(s->cur_prompt->prompts[0]->result);
4807 if (len < sizeof(string)) {
4809 strcpy(string, s->cur_prompt->prompts[0]->result);
4810 len++; /* cover the zero byte */
4811 while (len < sizeof(string)) {
4812 string[len++] = (char) random_byte();
4815 ss = s->cur_prompt->prompts[0]->result;
4817 logevent("Sending length-padded password");
4818 send_packet(ssh, s->pwpkt_type,
4819 PKT_INT, len, PKT_DATA, ss, len,
4823 * The server is believed unable to cope with
4824 * any of our password camouflage methods.
4827 len = strlen(s->cur_prompt->prompts[0]->result);
4828 logevent("Sending unpadded password");
4829 send_packet(ssh, s->pwpkt_type,
4831 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4835 send_packet(ssh, s->pwpkt_type,
4836 PKT_STR, s->cur_prompt->prompts[0]->result,
4839 logevent("Sent password");
4840 free_prompts(s->cur_prompt);
4842 if (pktin->type == SSH1_SMSG_FAILURE) {
4843 if (flags & FLAG_VERBOSE)
4844 c_write_str(ssh, "Access denied\r\n");
4845 logevent("Authentication refused");
4846 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4847 bombout(("Strange packet received, type %d", pktin->type));
4853 if (s->publickey_blob) {
4854 sfree(s->publickey_blob);
4855 sfree(s->publickey_comment);
4858 logevent("Authentication successful");
4863 static void ssh_channel_try_eof(struct ssh_channel *c)
4866 assert(c->pending_eof); /* precondition for calling us */
4868 return; /* can't close: not even opened yet */
4869 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4870 return; /* can't send EOF: pending outgoing data */
4872 c->pending_eof = FALSE; /* we're about to send it */
4873 if (ssh->version == 1) {
4874 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4876 c->closes |= CLOSES_SENT_EOF;
4878 struct Packet *pktout;
4879 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4880 ssh2_pkt_adduint32(pktout, c->remoteid);
4881 ssh2_pkt_send(ssh, pktout);
4882 c->closes |= CLOSES_SENT_EOF;
4883 ssh2_channel_check_close(c);
4887 Conf *sshfwd_get_conf(struct ssh_channel *c)
4893 void sshfwd_write_eof(struct ssh_channel *c)
4897 if (ssh->state == SSH_STATE_CLOSED)
4900 if (c->closes & CLOSES_SENT_EOF)
4903 c->pending_eof = TRUE;
4904 ssh_channel_try_eof(c);
4907 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4911 if (ssh->state == SSH_STATE_CLOSED)
4916 x11_close(c->u.x11.xconn);
4917 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4921 case CHAN_SOCKDATA_DORMANT:
4922 pfd_close(c->u.pfd.pf);
4923 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4926 c->type = CHAN_ZOMBIE;
4927 c->pending_eof = FALSE; /* this will confuse a zombie channel */
4929 ssh2_channel_check_close(c);
4932 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4936 if (ssh->state == SSH_STATE_CLOSED)
4939 if (ssh->version == 1) {
4940 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4941 PKT_INT, c->remoteid,
4942 PKT_INT, len, PKT_DATA, buf, len,
4945 * In SSH-1 we can return 0 here - implying that forwarded
4946 * connections are never individually throttled - because
4947 * the only circumstance that can cause throttling will be
4948 * the whole SSH connection backing up, in which case
4949 * _everything_ will be throttled as a whole.
4953 ssh2_add_channel_data(c, buf, len);
4954 return ssh2_try_send(c);
4958 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4963 if (ssh->state == SSH_STATE_CLOSED)
4966 if (ssh->version == 1) {
4967 buflimit = SSH1_BUFFER_LIMIT;
4969 buflimit = c->v.v2.locmaxwin;
4970 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4972 if (c->throttling_conn && bufsize <= buflimit) {
4973 c->throttling_conn = 0;
4974 ssh_throttle_conn(ssh, -1);
4978 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4980 struct queued_handler *qh = ssh->qhead;
4984 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4987 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4988 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4991 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4992 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4996 ssh->qhead = qh->next;
4998 if (ssh->qhead->msg1 > 0) {
4999 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5000 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5002 if (ssh->qhead->msg2 > 0) {
5003 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5004 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5007 ssh->qhead = ssh->qtail = NULL;
5010 qh->handler(ssh, pktin, qh->ctx);
5015 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5016 chandler_fn_t handler, void *ctx)
5018 struct queued_handler *qh;
5020 qh = snew(struct queued_handler);
5023 qh->handler = handler;
5027 if (ssh->qtail == NULL) {
5031 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5032 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5035 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5036 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5039 ssh->qtail->next = qh;
5044 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5046 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5048 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5049 SSH2_MSG_REQUEST_SUCCESS)) {
5050 logeventf(ssh, "Remote port forwarding from %s enabled",
5053 logeventf(ssh, "Remote port forwarding from %s refused",
5056 rpf = del234(ssh->rportfwds, pf);
5058 pf->pfrec->remote = NULL;
5063 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5066 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5069 pf->share_ctx = share_ctx;
5070 pf->shost = dupstr(shost);
5072 pf->sportdesc = NULL;
5073 if (!ssh->rportfwds) {
5074 assert(ssh->version == 2);
5075 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5077 if (add234(ssh->rportfwds, pf) != pf) {
5085 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5088 share_got_pkt_from_server(ctx, pktin->type,
5089 pktin->body, pktin->length);
5092 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5094 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5095 ssh_sharing_global_request_response, share_ctx);
5098 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5100 struct ssh_portfwd *epf;
5104 if (!ssh->portfwds) {
5105 ssh->portfwds = newtree234(ssh_portcmp);
5108 * Go through the existing port forwardings and tag them
5109 * with status==DESTROY. Any that we want to keep will be
5110 * re-enabled (status==KEEP) as we go through the
5111 * configuration and find out which bits are the same as
5114 struct ssh_portfwd *epf;
5116 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5117 epf->status = DESTROY;
5120 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5122 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5123 char *kp, *kp2, *vp, *vp2;
5124 char address_family, type;
5125 int sport,dport,sserv,dserv;
5126 char *sports, *dports, *saddr, *host;
5130 address_family = 'A';
5132 if (*kp == 'A' || *kp == '4' || *kp == '6')
5133 address_family = *kp++;
5134 if (*kp == 'L' || *kp == 'R')
5137 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5139 * There's a colon in the middle of the source port
5140 * string, which means that the part before it is
5141 * actually a source address.
5143 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5144 saddr = host_strduptrim(saddr_tmp);
5151 sport = atoi(sports);
5155 sport = net_service_lookup(sports);
5157 logeventf(ssh, "Service lookup failed for source"
5158 " port \"%s\"", sports);
5162 if (type == 'L' && !strcmp(val, "D")) {
5163 /* dynamic forwarding */
5170 /* ordinary forwarding */
5172 vp2 = vp + host_strcspn(vp, ":");
5173 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5177 dport = atoi(dports);
5181 dport = net_service_lookup(dports);
5183 logeventf(ssh, "Service lookup failed for destination"
5184 " port \"%s\"", dports);
5189 if (sport && dport) {
5190 /* Set up a description of the source port. */
5191 struct ssh_portfwd *pfrec, *epfrec;
5193 pfrec = snew(struct ssh_portfwd);
5195 pfrec->saddr = saddr;
5196 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5197 pfrec->sport = sport;
5198 pfrec->daddr = host;
5199 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5200 pfrec->dport = dport;
5201 pfrec->local = NULL;
5202 pfrec->remote = NULL;
5203 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5204 address_family == '6' ? ADDRTYPE_IPV6 :
5207 epfrec = add234(ssh->portfwds, pfrec);
5208 if (epfrec != pfrec) {
5209 if (epfrec->status == DESTROY) {
5211 * We already have a port forwarding up and running
5212 * with precisely these parameters. Hence, no need
5213 * to do anything; simply re-tag the existing one
5216 epfrec->status = KEEP;
5219 * Anything else indicates that there was a duplicate
5220 * in our input, which we'll silently ignore.
5222 free_portfwd(pfrec);
5224 pfrec->status = CREATE;
5233 * Now go through and destroy any port forwardings which were
5236 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5237 if (epf->status == DESTROY) {
5240 message = dupprintf("%s port forwarding from %s%s%d",
5241 epf->type == 'L' ? "local" :
5242 epf->type == 'R' ? "remote" : "dynamic",
5243 epf->saddr ? epf->saddr : "",
5244 epf->saddr ? ":" : "",
5247 if (epf->type != 'D') {
5248 char *msg2 = dupprintf("%s to %s:%d", message,
5249 epf->daddr, epf->dport);
5254 logeventf(ssh, "Cancelling %s", message);
5257 /* epf->remote or epf->local may be NULL if setting up a
5258 * forwarding failed. */
5260 struct ssh_rportfwd *rpf = epf->remote;
5261 struct Packet *pktout;
5264 * Cancel the port forwarding at the server
5267 if (ssh->version == 1) {
5269 * We cannot cancel listening ports on the
5270 * server side in SSH-1! There's no message
5271 * to support it. Instead, we simply remove
5272 * the rportfwd record from the local end
5273 * so that any connections the server tries
5274 * to make on it are rejected.
5277 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5278 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5279 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5281 ssh2_pkt_addstring(pktout, epf->saddr);
5282 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5283 /* XXX: rport_acceptall may not represent
5284 * what was used to open the original connection,
5285 * since it's reconfigurable. */
5286 ssh2_pkt_addstring(pktout, "");
5288 ssh2_pkt_addstring(pktout, "localhost");
5290 ssh2_pkt_adduint32(pktout, epf->sport);
5291 ssh2_pkt_send(ssh, pktout);
5294 del234(ssh->rportfwds, rpf);
5296 } else if (epf->local) {
5297 pfl_terminate(epf->local);
5300 delpos234(ssh->portfwds, i);
5302 i--; /* so we don't skip one in the list */
5306 * And finally, set up any new port forwardings (status==CREATE).
5308 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5309 if (epf->status == CREATE) {
5310 char *sportdesc, *dportdesc;
5311 sportdesc = dupprintf("%s%s%s%s%d%s",
5312 epf->saddr ? epf->saddr : "",
5313 epf->saddr ? ":" : "",
5314 epf->sserv ? epf->sserv : "",
5315 epf->sserv ? "(" : "",
5317 epf->sserv ? ")" : "");
5318 if (epf->type == 'D') {
5321 dportdesc = dupprintf("%s:%s%s%d%s",
5323 epf->dserv ? epf->dserv : "",
5324 epf->dserv ? "(" : "",
5326 epf->dserv ? ")" : "");
5329 if (epf->type == 'L') {
5330 char *err = pfl_listen(epf->daddr, epf->dport,
5331 epf->saddr, epf->sport,
5332 ssh, conf, &epf->local,
5333 epf->addressfamily);
5335 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5336 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5337 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5338 sportdesc, dportdesc,
5339 err ? " failed: " : "", err ? err : "");
5342 } else if (epf->type == 'D') {
5343 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5344 ssh, conf, &epf->local,
5345 epf->addressfamily);
5347 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5348 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5349 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5351 err ? " failed: " : "", err ? err : "");
5356 struct ssh_rportfwd *pf;
5359 * Ensure the remote port forwardings tree exists.
5361 if (!ssh->rportfwds) {
5362 if (ssh->version == 1)
5363 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5365 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5368 pf = snew(struct ssh_rportfwd);
5369 pf->share_ctx = NULL;
5370 pf->dhost = dupstr(epf->daddr);
5371 pf->dport = epf->dport;
5373 pf->shost = dupstr(epf->saddr);
5374 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5375 pf->shost = dupstr("");
5377 pf->shost = dupstr("localhost");
5379 pf->sport = epf->sport;
5380 if (add234(ssh->rportfwds, pf) != pf) {
5381 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5382 epf->daddr, epf->dport);
5385 logeventf(ssh, "Requesting remote port %s"
5386 " forward to %s", sportdesc, dportdesc);
5388 pf->sportdesc = sportdesc;
5393 if (ssh->version == 1) {
5394 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5395 PKT_INT, epf->sport,
5396 PKT_STR, epf->daddr,
5397 PKT_INT, epf->dport,
5399 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5401 ssh_rportfwd_succfail, pf);
5403 struct Packet *pktout;
5404 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5405 ssh2_pkt_addstring(pktout, "tcpip-forward");
5406 ssh2_pkt_addbool(pktout, 1);/* want reply */
5407 ssh2_pkt_addstring(pktout, pf->shost);
5408 ssh2_pkt_adduint32(pktout, pf->sport);
5409 ssh2_pkt_send(ssh, pktout);
5411 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5412 SSH2_MSG_REQUEST_FAILURE,
5413 ssh_rportfwd_succfail, pf);
5422 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5425 int stringlen, bufsize;
5427 ssh_pkt_getstring(pktin, &string, &stringlen);
5428 if (string == NULL) {
5429 bombout(("Incoming terminal data packet was badly formed"));
5433 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5435 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5436 ssh->v1_stdout_throttling = 1;
5437 ssh_throttle_conn(ssh, +1);
5441 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5443 /* Remote side is trying to open a channel to talk to our
5444 * X-Server. Give them back a local channel number. */
5445 struct ssh_channel *c;
5446 int remoteid = ssh_pkt_getuint32(pktin);
5448 logevent("Received X11 connect request");
5449 /* Refuse if X11 forwarding is disabled. */
5450 if (!ssh->X11_fwd_enabled) {
5451 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5452 PKT_INT, remoteid, PKT_END);
5453 logevent("Rejected X11 connect request");
5455 c = snew(struct ssh_channel);
5458 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5459 c->remoteid = remoteid;
5460 c->halfopen = FALSE;
5461 c->localid = alloc_channel_id(ssh);
5463 c->pending_eof = FALSE;
5464 c->throttling_conn = 0;
5465 c->type = CHAN_X11; /* identify channel type */
5466 add234(ssh->channels, c);
5467 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5468 PKT_INT, c->remoteid, PKT_INT,
5469 c->localid, PKT_END);
5470 logevent("Opened X11 forward channel");
5474 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5476 /* Remote side is trying to open a channel to talk to our
5477 * agent. Give them back a local channel number. */
5478 struct ssh_channel *c;
5479 int remoteid = ssh_pkt_getuint32(pktin);
5481 /* Refuse if agent forwarding is disabled. */
5482 if (!ssh->agentfwd_enabled) {
5483 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5484 PKT_INT, remoteid, PKT_END);
5486 c = snew(struct ssh_channel);
5488 c->remoteid = remoteid;
5489 c->halfopen = FALSE;
5490 c->localid = alloc_channel_id(ssh);
5492 c->pending_eof = FALSE;
5493 c->throttling_conn = 0;
5494 c->type = CHAN_AGENT; /* identify channel type */
5495 c->u.a.lensofar = 0;
5496 c->u.a.message = NULL;
5497 c->u.a.outstanding_requests = 0;
5498 add234(ssh->channels, c);
5499 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5500 PKT_INT, c->remoteid, PKT_INT, c->localid,
5505 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5507 /* Remote side is trying to open a channel to talk to a
5508 * forwarded port. Give them back a local channel number. */
5509 struct ssh_rportfwd pf, *pfp;
5515 remoteid = ssh_pkt_getuint32(pktin);
5516 ssh_pkt_getstring(pktin, &host, &hostsize);
5517 port = ssh_pkt_getuint32(pktin);
5519 pf.dhost = dupprintf("%.*s", hostsize, host);
5521 pfp = find234(ssh->rportfwds, &pf, NULL);
5524 logeventf(ssh, "Rejected remote port open request for %s:%d",
5526 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5527 PKT_INT, remoteid, PKT_END);
5529 struct ssh_channel *c = snew(struct ssh_channel);
5532 logeventf(ssh, "Received remote port open request for %s:%d",
5534 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5535 c, ssh->conf, pfp->pfrec->addressfamily);
5537 logeventf(ssh, "Port open failed: %s", err);
5540 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5541 PKT_INT, remoteid, PKT_END);
5543 c->remoteid = remoteid;
5544 c->halfopen = FALSE;
5545 c->localid = alloc_channel_id(ssh);
5547 c->pending_eof = FALSE;
5548 c->throttling_conn = 0;
5549 c->type = CHAN_SOCKDATA; /* identify channel type */
5550 add234(ssh->channels, c);
5551 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5552 PKT_INT, c->remoteid, PKT_INT,
5553 c->localid, PKT_END);
5554 logevent("Forwarded port opened successfully");
5561 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5563 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5564 unsigned int localid = ssh_pkt_getuint32(pktin);
5565 struct ssh_channel *c;
5567 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5568 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5569 c->remoteid = localid;
5570 c->halfopen = FALSE;
5571 c->type = CHAN_SOCKDATA;
5572 c->throttling_conn = 0;
5573 pfd_confirm(c->u.pfd.pf);
5576 if (c && c->pending_eof) {
5578 * We have a pending close on this channel,
5579 * which we decided on before the server acked
5580 * the channel open. So now we know the
5581 * remoteid, we can close it again.
5583 ssh_channel_try_eof(c);
5587 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5589 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5590 struct ssh_channel *c;
5592 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5593 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5594 logevent("Forwarded connection refused by server");
5595 pfd_close(c->u.pfd.pf);
5596 del234(ssh->channels, c);
5601 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5603 /* Remote side closes a channel. */
5604 unsigned i = ssh_pkt_getuint32(pktin);
5605 struct ssh_channel *c;
5606 c = find234(ssh->channels, &i, ssh_channelfind);
5607 if (c && !c->halfopen) {
5609 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5610 !(c->closes & CLOSES_RCVD_EOF)) {
5612 * Received CHANNEL_CLOSE, which we translate into
5615 int send_close = FALSE;
5617 c->closes |= CLOSES_RCVD_EOF;
5622 x11_send_eof(c->u.x11.xconn);
5628 pfd_send_eof(c->u.pfd.pf);
5637 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5638 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5640 c->closes |= CLOSES_SENT_EOF;
5644 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5645 !(c->closes & CLOSES_RCVD_CLOSE)) {
5647 if (!(c->closes & CLOSES_SENT_EOF)) {
5648 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5649 " for which we never sent CHANNEL_CLOSE\n", i));
5652 c->closes |= CLOSES_RCVD_CLOSE;
5655 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5656 !(c->closes & CLOSES_SENT_CLOSE)) {
5657 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5658 PKT_INT, c->remoteid, PKT_END);
5659 c->closes |= CLOSES_SENT_CLOSE;
5662 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5663 ssh_channel_destroy(c);
5665 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5666 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5667 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5672 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5674 /* Data sent down one of our channels. */
5675 int i = ssh_pkt_getuint32(pktin);
5678 struct ssh_channel *c;
5680 ssh_pkt_getstring(pktin, &p, &len);
5682 c = find234(ssh->channels, &i, ssh_channelfind);
5687 bufsize = x11_send(c->u.x11.xconn, p, len);
5690 bufsize = pfd_send(c->u.pfd.pf, p, len);
5693 /* Data for an agent message. Buffer it. */
5695 if (c->u.a.lensofar < 4) {
5696 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5697 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5701 c->u.a.lensofar += l;
5703 if (c->u.a.lensofar == 4) {
5705 4 + GET_32BIT(c->u.a.msglen);
5706 c->u.a.message = snewn(c->u.a.totallen,
5708 memcpy(c->u.a.message, c->u.a.msglen, 4);
5710 if (c->u.a.lensofar >= 4 && len > 0) {
5712 min(c->u.a.totallen - c->u.a.lensofar,
5714 memcpy(c->u.a.message + c->u.a.lensofar, p,
5718 c->u.a.lensofar += l;
5720 if (c->u.a.lensofar == c->u.a.totallen) {
5723 c->u.a.outstanding_requests++;
5724 if (agent_query(c->u.a.message,
5727 ssh_agentf_callback, c))
5728 ssh_agentf_callback(c, reply, replylen);
5729 sfree(c->u.a.message);
5730 c->u.a.lensofar = 0;
5733 bufsize = 0; /* agent channels never back up */
5736 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5737 c->throttling_conn = 1;
5738 ssh_throttle_conn(ssh, +1);
5743 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5745 ssh->exitcode = ssh_pkt_getuint32(pktin);
5746 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5747 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5749 * In case `helpful' firewalls or proxies tack
5750 * extra human-readable text on the end of the
5751 * session which we might mistake for another
5752 * encrypted packet, we close the session once
5753 * we've sent EXIT_CONFIRMATION.
5755 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5758 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5759 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5761 struct Packet *pktout = (struct Packet *)data;
5763 unsigned int arg = 0;
5764 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5765 if (i == lenof(ssh_ttymodes)) return;
5766 switch (ssh_ttymodes[i].type) {
5768 arg = ssh_tty_parse_specchar(val);
5771 arg = ssh_tty_parse_boolean(val);
5774 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5775 ssh2_pkt_addbyte(pktout, arg);
5778 int ssh_agent_forwarding_permitted(Ssh ssh)
5780 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5783 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5784 struct Packet *pktin)
5786 crBegin(ssh->do_ssh1_connection_crstate);
5788 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5789 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5790 ssh1_smsg_stdout_stderr_data;
5792 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5793 ssh1_msg_channel_open_confirmation;
5794 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5795 ssh1_msg_channel_open_failure;
5796 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5797 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5798 ssh1_msg_channel_close;
5799 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5800 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5802 if (ssh_agent_forwarding_permitted(ssh)) {
5803 logevent("Requesting agent forwarding");
5804 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5808 if (pktin->type != SSH1_SMSG_SUCCESS
5809 && pktin->type != SSH1_SMSG_FAILURE) {
5810 bombout(("Protocol confusion"));
5812 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5813 logevent("Agent forwarding refused");
5815 logevent("Agent forwarding enabled");
5816 ssh->agentfwd_enabled = TRUE;
5817 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5821 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5823 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5825 if (!ssh->x11disp) {
5826 /* FIXME: return an error message from x11_setup_display */
5827 logevent("X11 forwarding not enabled: unable to"
5828 " initialise X display");
5830 ssh->x11auth = x11_invent_fake_auth
5831 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5832 ssh->x11auth->disp = ssh->x11disp;
5834 logevent("Requesting X11 forwarding");
5835 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5836 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5837 PKT_STR, ssh->x11auth->protoname,
5838 PKT_STR, ssh->x11auth->datastring,
5839 PKT_INT, ssh->x11disp->screennum,
5842 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5843 PKT_STR, ssh->x11auth->protoname,
5844 PKT_STR, ssh->x11auth->datastring,
5850 if (pktin->type != SSH1_SMSG_SUCCESS
5851 && pktin->type != SSH1_SMSG_FAILURE) {
5852 bombout(("Protocol confusion"));
5854 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5855 logevent("X11 forwarding refused");
5857 logevent("X11 forwarding enabled");
5858 ssh->X11_fwd_enabled = TRUE;
5859 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5864 ssh_setup_portfwd(ssh, ssh->conf);
5865 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5867 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5869 /* Unpick the terminal-speed string. */
5870 /* XXX perhaps we should allow no speeds to be sent. */
5871 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5872 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5873 /* Send the pty request. */
5874 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5875 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5876 ssh_pkt_adduint32(pkt, ssh->term_height);
5877 ssh_pkt_adduint32(pkt, ssh->term_width);
5878 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5879 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5880 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5881 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5882 ssh_pkt_adduint32(pkt, ssh->ispeed);
5883 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5884 ssh_pkt_adduint32(pkt, ssh->ospeed);
5885 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5887 ssh->state = SSH_STATE_INTERMED;
5891 if (pktin->type != SSH1_SMSG_SUCCESS
5892 && pktin->type != SSH1_SMSG_FAILURE) {
5893 bombout(("Protocol confusion"));
5895 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5896 c_write_str(ssh, "Server refused to allocate pty\r\n");
5897 ssh->editing = ssh->echoing = 1;
5899 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5900 ssh->ospeed, ssh->ispeed);
5901 ssh->got_pty = TRUE;
5904 ssh->editing = ssh->echoing = 1;
5907 if (conf_get_int(ssh->conf, CONF_compression)) {
5908 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5912 if (pktin->type != SSH1_SMSG_SUCCESS
5913 && pktin->type != SSH1_SMSG_FAILURE) {
5914 bombout(("Protocol confusion"));
5916 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5917 c_write_str(ssh, "Server refused to compress\r\n");
5919 logevent("Started compression");
5920 ssh->v1_compressing = TRUE;
5921 ssh->cs_comp_ctx = zlib_compress_init();
5922 logevent("Initialised zlib (RFC1950) compression");
5923 ssh->sc_comp_ctx = zlib_decompress_init();
5924 logevent("Initialised zlib (RFC1950) decompression");
5928 * Start the shell or command.
5930 * Special case: if the first-choice command is an SSH-2
5931 * subsystem (hence not usable here) and the second choice
5932 * exists, we fall straight back to that.
5935 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5937 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5938 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5939 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5940 ssh->fallback_cmd = TRUE;
5943 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5945 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5946 logevent("Started session");
5949 ssh->state = SSH_STATE_SESSION;
5950 if (ssh->size_needed)
5951 ssh_size(ssh, ssh->term_width, ssh->term_height);
5952 if (ssh->eof_needed)
5953 ssh_special(ssh, TS_EOF);
5956 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
5958 ssh->channels = newtree234(ssh_channelcmp);
5962 * By this point, most incoming packets are already being
5963 * handled by the dispatch table, and we need only pay
5964 * attention to the unusual ones.
5969 if (pktin->type == SSH1_SMSG_SUCCESS) {
5970 /* may be from EXEC_SHELL on some servers */
5971 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5972 /* may be from EXEC_SHELL on some servers
5973 * if no pty is available or in other odd cases. Ignore */
5975 bombout(("Strange packet received: type %d", pktin->type));
5980 int len = min(inlen, 512);
5981 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5982 PKT_INT, len, PKT_DATA, in, len,
5994 * Handle the top-level SSH-2 protocol.
5996 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6001 ssh_pkt_getstring(pktin, &msg, &msglen);
6002 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
6005 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6007 /* log reason code in disconnect message */
6011 ssh_pkt_getstring(pktin, &msg, &msglen);
6012 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
6015 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6017 /* Do nothing, because we're ignoring it! Duhh. */
6020 static void ssh1_protocol_setup(Ssh ssh)
6025 * Most messages are handled by the coroutines.
6027 for (i = 0; i < 256; i++)
6028 ssh->packet_dispatch[i] = NULL;
6031 * These special message types we install handlers for.
6033 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6034 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6035 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6038 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6039 struct Packet *pktin)
6041 const unsigned char *in = (const unsigned char *)vin;
6042 if (ssh->state == SSH_STATE_CLOSED)
6045 if (pktin && ssh->packet_dispatch[pktin->type]) {
6046 ssh->packet_dispatch[pktin->type](ssh, pktin);
6050 if (!ssh->protocol_initial_phase_done) {
6051 if (do_ssh1_login(ssh, in, inlen, pktin))
6052 ssh->protocol_initial_phase_done = TRUE;
6057 do_ssh1_connection(ssh, in, inlen, pktin);
6061 * Utility routines for decoding comma-separated strings in KEXINIT.
6063 static int first_in_commasep_string(char const *needle, char const *haystack,
6067 if (!needle || !haystack) /* protect against null pointers */
6069 needlen = strlen(needle);
6071 if (haylen >= needlen && /* haystack is long enough */
6072 !memcmp(needle, haystack, needlen) && /* initial match */
6073 (haylen == needlen || haystack[needlen] == ',')
6074 /* either , or EOS follows */
6080 static int in_commasep_string(char const *needle, char const *haystack,
6085 if (!needle || !haystack) /* protect against null pointers */
6088 * Is it at the start of the string?
6090 if (first_in_commasep_string(needle, haystack, haylen))
6093 * If not, search for the next comma and resume after that.
6094 * If no comma found, terminate.
6096 p = memchr(haystack, ',', haylen);
6098 /* + 1 to skip over comma */
6099 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6103 * Add a value to the comma-separated string at the end of the packet.
6105 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6107 if (pkt->length - pkt->savedpos > 0)
6108 ssh_pkt_addstring_str(pkt, ",");
6109 ssh_pkt_addstring_str(pkt, data);
6114 * SSH-2 key creation method.
6115 * (Currently assumes 2 lots of any hash are sufficient to generate
6116 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
6118 #define SSH2_MKKEY_ITERS (2)
6119 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
6120 unsigned char *keyspace)
6122 const struct ssh_hash *h = ssh->kex->hash;
6124 /* First hlen bytes. */
6126 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6127 hash_mpint(h, s, K);
6128 h->bytes(s, H, h->hlen);
6129 h->bytes(s, &chr, 1);
6130 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6131 h->final(s, keyspace);
6132 /* Next hlen bytes. */
6134 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6135 hash_mpint(h, s, K);
6136 h->bytes(s, H, h->hlen);
6137 h->bytes(s, keyspace, h->hlen);
6138 h->final(s, keyspace + h->hlen);
6142 * Structure for constructing KEXINIT algorithm lists.
6144 #define MAXKEXLIST 16
6145 struct kexinit_algorithm {
6149 const struct ssh_kex *kex;
6152 const struct ssh_signkey *hostkey;
6154 const struct ssh2_cipher *cipher;
6158 const struct ssh_mac *mac;
6161 const struct ssh_compress *comp;
6166 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6167 * If the algorithm is already in the list, return a pointer to its
6168 * entry, otherwise return an entry from the end of the list.
6169 * This assumes that every time a particular name is passed in, it
6170 * comes from the same string constant. If this isn't true, this
6171 * function may need to be rewritten to use strcmp() instead.
6173 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6174 *list, const char *name)
6178 for (i = 0; i < MAXKEXLIST; i++)
6179 if (list[i].name == NULL || list[i].name == name) {
6180 list[i].name = name;
6183 assert(!"No space in KEXINIT list");
6187 * Handle the SSH-2 transport layer.
6189 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6190 struct Packet *pktin)
6192 const unsigned char *in = (const unsigned char *)vin;
6194 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6195 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6198 const char * kexlist_descr[NKEXLIST] = {
6199 "key exchange algorithm", "host key algorithm",
6200 "client-to-server cipher", "server-to-client cipher",
6201 "client-to-server MAC", "server-to-client MAC",
6202 "client-to-server compression method",
6203 "server-to-client compression method" };
6204 struct do_ssh2_transport_state {
6206 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
6207 Bignum p, g, e, f, K;
6210 int kex_init_value, kex_reply_value;
6211 const struct ssh_mac **maclist;
6213 const struct ssh2_cipher *cscipher_tobe;
6214 const struct ssh2_cipher *sccipher_tobe;
6215 const struct ssh_mac *csmac_tobe;
6216 const struct ssh_mac *scmac_tobe;
6217 int csmac_etm_tobe, scmac_etm_tobe;
6218 const struct ssh_compress *cscomp_tobe;
6219 const struct ssh_compress *sccomp_tobe;
6220 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6221 int hostkeylen, siglen, rsakeylen;
6222 void *hkey; /* actual host key */
6223 void *rsakey; /* for RSA kex */
6224 void *eckey; /* for ECDH kex */
6225 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6226 int n_preferred_kex;
6227 const struct ssh_kexes *preferred_kex[KEX_MAX];
6228 int n_preferred_ciphers;
6229 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6230 const struct ssh_compress *preferred_comp;
6231 int userauth_succeeded; /* for delayed compression */
6232 int pending_compression;
6233 int got_session_id, activated_authconn;
6234 struct Packet *pktout;
6238 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6240 crState(do_ssh2_transport_state);
6242 assert(!ssh->bare_connection);
6246 s->cscipher_tobe = s->sccipher_tobe = NULL;
6247 s->csmac_tobe = s->scmac_tobe = NULL;
6248 s->cscomp_tobe = s->sccomp_tobe = NULL;
6250 s->got_session_id = s->activated_authconn = FALSE;
6251 s->userauth_succeeded = FALSE;
6252 s->pending_compression = FALSE;
6255 * Be prepared to work around the buggy MAC problem.
6257 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6258 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6260 s->maclist = macs, s->nmacs = lenof(macs);
6263 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6266 struct kexinit_algorithm *alg;
6269 * Set up the preferred key exchange. (NULL => warn below here)
6271 s->n_preferred_kex = 0;
6272 for (i = 0; i < KEX_MAX; i++) {
6273 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6275 s->preferred_kex[s->n_preferred_kex++] =
6276 &ssh_diffiehellman_gex;
6279 s->preferred_kex[s->n_preferred_kex++] =
6280 &ssh_diffiehellman_group14;
6283 s->preferred_kex[s->n_preferred_kex++] =
6284 &ssh_diffiehellman_group1;
6287 s->preferred_kex[s->n_preferred_kex++] =
6291 s->preferred_kex[s->n_preferred_kex++] =
6295 /* Flag for later. Don't bother if it's the last in
6297 if (i < KEX_MAX - 1) {
6298 s->preferred_kex[s->n_preferred_kex++] = NULL;
6305 * Set up the preferred ciphers. (NULL => warn below here)
6307 s->n_preferred_ciphers = 0;
6308 for (i = 0; i < CIPHER_MAX; i++) {
6309 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6310 case CIPHER_BLOWFISH:
6311 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6314 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6315 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6319 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6322 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6324 case CIPHER_ARCFOUR:
6325 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6328 /* Flag for later. Don't bother if it's the last in
6330 if (i < CIPHER_MAX - 1) {
6331 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6338 * Set up preferred compression.
6340 if (conf_get_int(ssh->conf, CONF_compression))
6341 s->preferred_comp = &ssh_zlib;
6343 s->preferred_comp = &ssh_comp_none;
6346 * Enable queueing of outgoing auth- or connection-layer
6347 * packets while we are in the middle of a key exchange.
6349 ssh->queueing = TRUE;
6352 * Flag that KEX is in progress.
6354 ssh->kex_in_progress = TRUE;
6356 for (i = 0; i < NKEXLIST; i++)
6357 for (j = 0; j < MAXKEXLIST; j++)
6358 s->kexlists[i][j].name = NULL;
6359 /* List key exchange algorithms. */
6361 for (i = 0; i < s->n_preferred_kex; i++) {
6362 const struct ssh_kexes *k = s->preferred_kex[i];
6363 if (!k) warn = TRUE;
6364 else for (j = 0; j < k->nkexes; j++) {
6365 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6367 alg->u.kex.kex = k->list[j];
6368 alg->u.kex.warn = warn;
6371 /* List server host key algorithms. */
6372 if (!s->got_session_id) {
6374 * In the first key exchange, we list all the algorithms
6375 * we're prepared to cope with, but prefer those algorithms
6376 * for which we have a host key for this host.
6378 for (i = 0; i < lenof(hostkey_algs); i++) {
6379 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6380 hostkey_algs[i]->keytype)) {
6381 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6382 hostkey_algs[i]->name);
6383 alg->u.hostkey = hostkey_algs[i];
6386 for (i = 0; i < lenof(hostkey_algs); i++) {
6387 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6388 hostkey_algs[i]->name);
6389 alg->u.hostkey = hostkey_algs[i];
6393 * In subsequent key exchanges, we list only the kex
6394 * algorithm that was selected in the first key exchange,
6395 * so that we keep getting the same host key and hence
6396 * don't have to interrupt the user's session to ask for
6400 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6401 ssh->hostkey->name);
6402 alg->u.hostkey = ssh->hostkey;
6404 /* List encryption algorithms (client->server then server->client). */
6405 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6407 for (i = 0; i < s->n_preferred_ciphers; i++) {
6408 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6409 if (!c) warn = TRUE;
6410 else for (j = 0; j < c->nciphers; j++) {
6411 alg = ssh2_kexinit_addalg(s->kexlists[k],
6413 alg->u.cipher.cipher = c->list[j];
6414 alg->u.cipher.warn = warn;
6418 /* List MAC algorithms (client->server then server->client). */
6419 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6420 for (i = 0; i < s->nmacs; i++) {
6421 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6422 alg->u.mac.mac = s->maclist[i];
6423 alg->u.mac.etm = FALSE;
6425 for (i = 0; i < s->nmacs; i++)
6426 /* For each MAC, there may also be an ETM version,
6427 * which we list second. */
6428 if (s->maclist[i]->etm_name) {
6429 alg = ssh2_kexinit_addalg(s->kexlists[j],
6430 s->maclist[i]->etm_name);
6431 alg->u.mac.mac = s->maclist[i];
6432 alg->u.mac.etm = TRUE;
6435 /* List client->server compression algorithms,
6436 * then server->client compression algorithms. (We use the
6437 * same set twice.) */
6438 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6439 assert(lenof(compressions) > 1);
6440 /* Prefer non-delayed versions */
6441 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6442 alg->u.comp = s->preferred_comp;
6443 /* We don't even list delayed versions of algorithms until
6444 * they're allowed to be used, to avoid a race. See the end of
6446 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6447 alg = ssh2_kexinit_addalg(s->kexlists[j],
6448 s->preferred_comp->delayed_name);
6449 alg->u.comp = s->preferred_comp;
6451 for (i = 0; i < lenof(compressions); i++) {
6452 const struct ssh_compress *c = compressions[i];
6453 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6455 if (s->userauth_succeeded && c->delayed_name) {
6456 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6462 * Construct and send our key exchange packet.
6464 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6465 for (i = 0; i < 16; i++)
6466 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6467 for (i = 0; i < NKEXLIST; i++) {
6468 ssh2_pkt_addstring_start(s->pktout);
6469 for (j = 0; j < MAXKEXLIST; j++) {
6470 if (s->kexlists[i][j].name == NULL) break;
6471 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6474 /* List client->server languages. Empty list. */
6475 ssh2_pkt_addstring_start(s->pktout);
6476 /* List server->client languages. Empty list. */
6477 ssh2_pkt_addstring_start(s->pktout);
6478 /* First KEX packet does _not_ follow, because we're not that brave. */
6479 ssh2_pkt_addbool(s->pktout, FALSE);
6481 ssh2_pkt_adduint32(s->pktout, 0);
6484 s->our_kexinitlen = s->pktout->length - 5;
6485 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6486 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6488 ssh2_pkt_send_noqueue(ssh, s->pktout);
6491 crWaitUntilV(pktin);
6494 * Now examine the other side's KEXINIT to see what we're up
6501 if (pktin->type != SSH2_MSG_KEXINIT) {
6502 bombout(("expected key exchange packet from server"));
6506 ssh->hostkey = NULL;
6507 s->cscipher_tobe = NULL;
6508 s->sccipher_tobe = NULL;
6509 s->csmac_tobe = NULL;
6510 s->scmac_tobe = NULL;
6511 s->cscomp_tobe = NULL;
6512 s->sccomp_tobe = NULL;
6513 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
6515 pktin->savedpos += 16; /* skip garbage cookie */
6518 for (i = 0; i < NKEXLIST; i++) {
6519 ssh_pkt_getstring(pktin, &str, &len);
6521 bombout(("KEXINIT packet was incomplete"));
6524 for (j = 0; j < MAXKEXLIST; j++) {
6525 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6526 if (alg->name == NULL) break;
6527 if (in_commasep_string(alg->name, str, len)) {
6528 /* We've found a matching algorithm. */
6529 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6530 /* Check if we might need to ignore first kex pkt */
6532 !first_in_commasep_string(alg->name, str, len))
6535 if (i == KEXLIST_KEX) {
6536 ssh->kex = alg->u.kex.kex;
6537 s->warn_kex = alg->u.kex.warn;
6538 } else if (i == KEXLIST_HOSTKEY) {
6539 ssh->hostkey = alg->u.hostkey;
6540 } else if (i == KEXLIST_CSCIPHER) {
6541 s->cscipher_tobe = alg->u.cipher.cipher;
6542 s->warn_cscipher = alg->u.cipher.warn;
6543 } else if (i == KEXLIST_SCCIPHER) {
6544 s->sccipher_tobe = alg->u.cipher.cipher;
6545 s->warn_sccipher = alg->u.cipher.warn;
6546 } else if (i == KEXLIST_CSMAC) {
6547 s->csmac_tobe = alg->u.mac.mac;
6548 s->csmac_etm_tobe = alg->u.mac.etm;
6549 } else if (i == KEXLIST_SCMAC) {
6550 s->scmac_tobe = alg->u.mac.mac;
6551 s->scmac_etm_tobe = alg->u.mac.etm;
6552 } else if (i == KEXLIST_CSCOMP) {
6553 s->cscomp_tobe = alg->u.comp;
6554 } else if (i == KEXLIST_SCCOMP) {
6555 s->sccomp_tobe = alg->u.comp;
6559 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6560 in_commasep_string(alg->u.comp->delayed_name, str, len))
6561 s->pending_compression = TRUE; /* try this later */
6563 bombout(("Couldn't agree a %s ((available: %.*s)",
6564 kexlist_descr[i], len, str));
6569 /* If the cipher over-rides the mac, then pick it */
6570 if (s->cscipher_tobe && s->cscipher_tobe->required_mac) {
6571 s->csmac_tobe = s->cscipher_tobe->required_mac;
6572 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6574 if (s->sccipher_tobe && s->sccipher_tobe->required_mac) {
6575 s->scmac_tobe = s->sccipher_tobe->required_mac;
6576 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6579 if (s->pending_compression) {
6580 logevent("Server supports delayed compression; "
6581 "will try this later");
6583 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6584 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6585 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6587 ssh->exhash = ssh->kex->hash->init();
6588 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6589 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6590 hash_string(ssh->kex->hash, ssh->exhash,
6591 s->our_kexinit, s->our_kexinitlen);
6592 sfree(s->our_kexinit);
6593 /* Include the type byte in the hash of server's KEXINIT */
6594 hash_string(ssh->kex->hash, ssh->exhash,
6595 pktin->body - 1, pktin->length + 1);
6598 ssh_set_frozen(ssh, 1);
6599 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6601 ssh_dialog_callback, ssh);
6602 if (s->dlgret < 0) {
6606 bombout(("Unexpected data from server while"
6607 " waiting for user response"));
6610 } while (pktin || inlen > 0);
6611 s->dlgret = ssh->user_response;
6613 ssh_set_frozen(ssh, 0);
6614 if (s->dlgret == 0) {
6615 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6621 if (s->warn_cscipher) {
6622 ssh_set_frozen(ssh, 1);
6623 s->dlgret = askalg(ssh->frontend,
6624 "client-to-server cipher",
6625 s->cscipher_tobe->name,
6626 ssh_dialog_callback, ssh);
6627 if (s->dlgret < 0) {
6631 bombout(("Unexpected data from server while"
6632 " waiting for user response"));
6635 } while (pktin || inlen > 0);
6636 s->dlgret = ssh->user_response;
6638 ssh_set_frozen(ssh, 0);
6639 if (s->dlgret == 0) {
6640 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6646 if (s->warn_sccipher) {
6647 ssh_set_frozen(ssh, 1);
6648 s->dlgret = askalg(ssh->frontend,
6649 "server-to-client cipher",
6650 s->sccipher_tobe->name,
6651 ssh_dialog_callback, ssh);
6652 if (s->dlgret < 0) {
6656 bombout(("Unexpected data from server while"
6657 " waiting for user response"));
6660 } while (pktin || inlen > 0);
6661 s->dlgret = ssh->user_response;
6663 ssh_set_frozen(ssh, 0);
6664 if (s->dlgret == 0) {
6665 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6671 if (s->ignorepkt) /* first_kex_packet_follows */
6672 crWaitUntilV(pktin); /* Ignore packet */
6675 if (ssh->kex->main_type == KEXTYPE_DH) {
6677 * Work out the number of bits of key we will need from the
6678 * key exchange. We start with the maximum key length of
6684 csbits = s->cscipher_tobe->keylen;
6685 scbits = s->sccipher_tobe->keylen;
6686 s->nbits = (csbits > scbits ? csbits : scbits);
6688 /* The keys only have hlen-bit entropy, since they're based on
6689 * a hash. So cap the key size at hlen bits. */
6690 if (s->nbits > ssh->kex->hash->hlen * 8)
6691 s->nbits = ssh->kex->hash->hlen * 8;
6694 * If we're doing Diffie-Hellman group exchange, start by
6695 * requesting a group.
6697 if (dh_is_gex(ssh->kex)) {
6698 logevent("Doing Diffie-Hellman group exchange");
6699 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6701 * Work out how big a DH group we will need to allow that
6704 s->pbits = 512 << ((s->nbits - 1) / 64);
6705 if (s->pbits < DH_MIN_SIZE)
6706 s->pbits = DH_MIN_SIZE;
6707 if (s->pbits > DH_MAX_SIZE)
6708 s->pbits = DH_MAX_SIZE;
6709 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6710 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6711 ssh2_pkt_adduint32(s->pktout, s->pbits);
6713 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6714 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6715 ssh2_pkt_adduint32(s->pktout, s->pbits);
6716 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6718 ssh2_pkt_send_noqueue(ssh, s->pktout);
6720 crWaitUntilV(pktin);
6721 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6722 bombout(("expected key exchange group packet from server"));
6725 s->p = ssh2_pkt_getmp(pktin);
6726 s->g = ssh2_pkt_getmp(pktin);
6727 if (!s->p || !s->g) {
6728 bombout(("unable to read mp-ints from incoming group packet"));
6731 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6732 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6733 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6735 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6736 ssh->kex_ctx = dh_setup_group(ssh->kex);
6737 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6738 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6739 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6740 ssh->kex->groupname);
6743 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6744 ssh->kex->hash->text_name);
6746 * Now generate and send e for Diffie-Hellman.
6748 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6749 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6750 s->pktout = ssh2_pkt_init(s->kex_init_value);
6751 ssh2_pkt_addmp(s->pktout, s->e);
6752 ssh2_pkt_send_noqueue(ssh, s->pktout);
6754 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6755 crWaitUntilV(pktin);
6756 if (pktin->type != s->kex_reply_value) {
6757 bombout(("expected key exchange reply packet from server"));
6760 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6761 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6762 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6763 s->hostkeydata, s->hostkeylen);
6764 s->f = ssh2_pkt_getmp(pktin);
6766 bombout(("unable to parse key exchange reply packet"));
6769 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6772 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
6774 bombout(("key exchange reply failed validation: %s", err));
6778 s->K = dh_find_K(ssh->kex_ctx, s->f);
6780 /* We assume everything from now on will be quick, and it might
6781 * involve user interaction. */
6782 set_busy_status(ssh->frontend, BUSY_NOT);
6784 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6785 if (dh_is_gex(ssh->kex)) {
6786 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6787 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
6788 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6789 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6790 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
6791 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6792 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6794 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6795 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6797 dh_cleanup(ssh->kex_ctx);
6799 if (dh_is_gex(ssh->kex)) {
6803 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
6805 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
6806 ssh_ecdhkex_curve_textname(ssh->kex),
6807 ssh->kex->hash->text_name);
6808 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
6810 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
6812 bombout(("Unable to generate key for ECDH"));
6818 int publicPointLength;
6819 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6821 ssh_ecdhkex_freekey(s->eckey);
6822 bombout(("Unable to encode public key for ECDH"));
6825 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
6826 ssh2_pkt_addstring_start(s->pktout);
6827 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
6831 ssh2_pkt_send_noqueue(ssh, s->pktout);
6833 crWaitUntilV(pktin);
6834 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
6835 ssh_ecdhkex_freekey(s->eckey);
6836 bombout(("expected ECDH reply packet from server"));
6840 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6841 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6842 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6843 s->hostkeydata, s->hostkeylen);
6847 int publicPointLength;
6848 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6850 ssh_ecdhkex_freekey(s->eckey);
6851 bombout(("Unable to encode public key for ECDH hash"));
6854 hash_string(ssh->kex->hash, ssh->exhash,
6855 publicPoint, publicPointLength);
6862 ssh_pkt_getstring(pktin, &keydata, &keylen);
6863 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
6864 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
6866 ssh_ecdhkex_freekey(s->eckey);
6867 bombout(("point received in ECDH was not valid"));
6872 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6874 ssh_ecdhkex_freekey(s->eckey);
6876 logeventf(ssh, "Doing RSA key exchange with hash %s",
6877 ssh->kex->hash->text_name);
6878 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6880 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6883 crWaitUntilV(pktin);
6884 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6885 bombout(("expected RSA public key packet from server"));
6889 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6890 hash_string(ssh->kex->hash, ssh->exhash,
6891 s->hostkeydata, s->hostkeylen);
6892 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6893 s->hostkeydata, s->hostkeylen);
6897 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6898 s->rsakeydata = snewn(s->rsakeylen, char);
6899 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6902 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6904 sfree(s->rsakeydata);
6905 bombout(("unable to parse RSA public key from server"));
6909 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6912 * Next, set up a shared secret K, of precisely KLEN -
6913 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6914 * RSA key modulus and HLEN is the bit length of the hash
6918 int klen = ssh_rsakex_klen(s->rsakey);
6919 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6921 unsigned char *kstr1, *kstr2, *outstr;
6922 int kstr1len, kstr2len, outstrlen;
6924 s->K = bn_power_2(nbits - 1);
6926 for (i = 0; i < nbits; i++) {
6928 byte = random_byte();
6930 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6934 * Encode this as an mpint.
6936 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6937 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6938 PUT_32BIT(kstr2, kstr1len);
6939 memcpy(kstr2 + 4, kstr1, kstr1len);
6942 * Encrypt it with the given RSA key.
6944 outstrlen = (klen + 7) / 8;
6945 outstr = snewn(outstrlen, unsigned char);
6946 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6947 outstr, outstrlen, s->rsakey);
6950 * And send it off in a return packet.
6952 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6953 ssh2_pkt_addstring_start(s->pktout);
6954 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6955 ssh2_pkt_send_noqueue(ssh, s->pktout);
6957 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6964 ssh_rsakex_freekey(s->rsakey);
6966 crWaitUntilV(pktin);
6967 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6968 sfree(s->rsakeydata);
6969 bombout(("expected signature packet from server"));
6973 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6975 sfree(s->rsakeydata);
6978 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6979 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6980 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6982 ssh->kex_ctx = NULL;
6985 debug(("Exchange hash is:\n"));
6986 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6990 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6991 (char *)s->exchange_hash,
6992 ssh->kex->hash->hlen)) {
6993 bombout(("Server's host key did not match the signature supplied"));
6997 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6998 if (!s->got_session_id) {
7000 * Authenticate remote host: verify host key. (We've already
7001 * checked the signature of the exchange hash.)
7003 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7004 logevent("Host key fingerprint is:");
7005 logevent(s->fingerprint);
7006 /* First check against manually configured host keys. */
7007 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7008 ssh->hostkey, s->hkey);
7009 if (s->dlgret == 0) { /* did not match */
7010 bombout(("Host key did not appear in manually configured list"));
7012 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7013 ssh_set_frozen(ssh, 1);
7014 s->dlgret = verify_ssh_host_key(ssh->frontend,
7015 ssh->savedhost, ssh->savedport,
7016 ssh->hostkey->keytype, s->keystr,
7018 ssh_dialog_callback, ssh);
7019 if (s->dlgret < 0) {
7023 bombout(("Unexpected data from server while waiting"
7024 " for user host key response"));
7027 } while (pktin || inlen > 0);
7028 s->dlgret = ssh->user_response;
7030 ssh_set_frozen(ssh, 0);
7031 if (s->dlgret == 0) {
7032 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7037 sfree(s->fingerprint);
7039 * Save this host key, to check against the one presented in
7040 * subsequent rekeys.
7042 ssh->hostkey_str = s->keystr;
7045 * In a rekey, we never present an interactive host key
7046 * verification request to the user. Instead, we simply
7047 * enforce that the key we're seeing this time is identical to
7048 * the one we saw before.
7050 if (strcmp(ssh->hostkey_str, s->keystr)) {
7051 bombout(("Host key was different in repeat key exchange"));
7056 ssh->hostkey->freekey(s->hkey);
7059 * The exchange hash from the very first key exchange is also
7060 * the session id, used in session key construction and
7063 if (!s->got_session_id) {
7064 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7065 memcpy(ssh->v2_session_id, s->exchange_hash,
7066 sizeof(s->exchange_hash));
7067 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7068 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7069 s->got_session_id = TRUE;
7073 * Send SSH2_MSG_NEWKEYS.
7075 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7076 ssh2_pkt_send_noqueue(ssh, s->pktout);
7077 ssh->outgoing_data_size = 0; /* start counting from here */
7080 * We've sent client NEWKEYS, so create and initialise
7081 * client-to-server session keys.
7083 if (ssh->cs_cipher_ctx)
7084 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7085 ssh->cscipher = s->cscipher_tobe;
7086 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7088 if (ssh->cs_mac_ctx)
7089 ssh->csmac->free_context(ssh->cs_mac_ctx);
7090 ssh->csmac = s->csmac_tobe;
7091 ssh->csmac_etm = s->csmac_etm_tobe;
7092 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7094 if (ssh->cs_comp_ctx)
7095 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7096 ssh->cscomp = s->cscomp_tobe;
7097 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7100 * Set IVs on client-to-server keys. Here we use the exchange
7101 * hash from the _first_ key exchange.
7104 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
7105 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7106 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
7107 assert((ssh->cscipher->keylen+7) / 8 <=
7108 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7109 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
7110 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
7111 assert(ssh->cscipher->blksize <=
7112 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7113 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
7114 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
7115 assert(ssh->csmac->len <=
7116 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7117 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
7118 smemclr(keyspace, sizeof(keyspace));
7121 logeventf(ssh, "Initialised %.200s client->server encryption",
7122 ssh->cscipher->text_name);
7123 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s",
7124 ssh->csmac->text_name,
7125 ssh->csmac_etm ? " (in ETM mode)" : "");
7126 if (ssh->cscomp->text_name)
7127 logeventf(ssh, "Initialised %s compression",
7128 ssh->cscomp->text_name);
7131 * Now our end of the key exchange is complete, we can send all
7132 * our queued higher-layer packets.
7134 ssh->queueing = FALSE;
7135 ssh2_pkt_queuesend(ssh);
7138 * Expect SSH2_MSG_NEWKEYS from server.
7140 crWaitUntilV(pktin);
7141 if (pktin->type != SSH2_MSG_NEWKEYS) {
7142 bombout(("expected new-keys packet from server"));
7145 ssh->incoming_data_size = 0; /* start counting from here */
7148 * We've seen server NEWKEYS, so create and initialise
7149 * server-to-client session keys.
7151 if (ssh->sc_cipher_ctx)
7152 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7153 ssh->sccipher = s->sccipher_tobe;
7154 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7156 if (ssh->sc_mac_ctx)
7157 ssh->scmac->free_context(ssh->sc_mac_ctx);
7158 ssh->scmac = s->scmac_tobe;
7159 ssh->scmac_etm = s->scmac_etm_tobe;
7160 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7162 if (ssh->sc_comp_ctx)
7163 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7164 ssh->sccomp = s->sccomp_tobe;
7165 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7168 * Set IVs on server-to-client keys. Here we use the exchange
7169 * hash from the _first_ key exchange.
7172 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
7173 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7174 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
7175 assert((ssh->sccipher->keylen+7) / 8 <=
7176 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7177 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
7178 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
7179 assert(ssh->sccipher->blksize <=
7180 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7181 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
7182 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
7183 assert(ssh->scmac->len <=
7184 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7185 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
7186 smemclr(keyspace, sizeof(keyspace));
7188 logeventf(ssh, "Initialised %.200s server->client encryption",
7189 ssh->sccipher->text_name);
7190 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s",
7191 ssh->scmac->text_name,
7192 ssh->scmac_etm ? " (in ETM mode)" : "");
7193 if (ssh->sccomp->text_name)
7194 logeventf(ssh, "Initialised %s decompression",
7195 ssh->sccomp->text_name);
7198 * Free shared secret.
7203 * Key exchange is over. Loop straight back round if we have a
7204 * deferred rekey reason.
7206 if (ssh->deferred_rekey_reason) {
7207 logevent(ssh->deferred_rekey_reason);
7209 ssh->deferred_rekey_reason = NULL;
7210 goto begin_key_exchange;
7214 * Otherwise, schedule a timer for our next rekey.
7216 ssh->kex_in_progress = FALSE;
7217 ssh->last_rekey = GETTICKCOUNT();
7218 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7219 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7223 * Now we're encrypting. Begin returning 1 to the protocol main
7224 * function so that other things can run on top of the
7225 * transport. If we ever see a KEXINIT, we must go back to the
7228 * We _also_ go back to the start if we see pktin==NULL and
7229 * inlen negative, because this is a special signal meaning
7230 * `initiate client-driven rekey', and `in' contains a message
7231 * giving the reason for the rekey.
7233 * inlen==-1 means always initiate a rekey;
7234 * inlen==-2 means that userauth has completed successfully and
7235 * we should consider rekeying (for delayed compression).
7237 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7238 (!pktin && inlen < 0))) {
7240 if (!ssh->protocol_initial_phase_done) {
7241 ssh->protocol_initial_phase_done = TRUE;
7243 * Allow authconn to initialise itself.
7245 do_ssh2_authconn(ssh, NULL, 0, NULL);
7250 logevent("Server initiated key re-exchange");
7254 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7255 * delayed compression, if it's available.
7257 * draft-miller-secsh-compression-delayed-00 says that you
7258 * negotiate delayed compression in the first key exchange, and
7259 * both sides start compressing when the server has sent
7260 * USERAUTH_SUCCESS. This has a race condition -- the server
7261 * can't know when the client has seen it, and thus which incoming
7262 * packets it should treat as compressed.
7264 * Instead, we do the initial key exchange without offering the
7265 * delayed methods, but note if the server offers them; when we
7266 * get here, if a delayed method was available that was higher
7267 * on our list than what we got, we initiate a rekey in which we
7268 * _do_ list the delayed methods (and hopefully get it as a
7269 * result). Subsequent rekeys will do the same.
7271 assert(!s->userauth_succeeded); /* should only happen once */
7272 s->userauth_succeeded = TRUE;
7273 if (!s->pending_compression)
7274 /* Can't see any point rekeying. */
7275 goto wait_for_rekey; /* this is utterly horrid */
7276 /* else fall through to rekey... */
7277 s->pending_compression = FALSE;
7280 * Now we've decided to rekey.
7282 * Special case: if the server bug is set that doesn't
7283 * allow rekeying, we give a different log message and
7284 * continue waiting. (If such a server _initiates_ a rekey,
7285 * we process it anyway!)
7287 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7288 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7290 /* Reset the counters, so that at least this message doesn't
7291 * hit the event log _too_ often. */
7292 ssh->outgoing_data_size = 0;
7293 ssh->incoming_data_size = 0;
7294 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7296 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7299 goto wait_for_rekey; /* this is still utterly horrid */
7301 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7304 goto begin_key_exchange;
7310 * Add data to an SSH-2 channel output buffer.
7312 static void ssh2_add_channel_data(struct ssh_channel *c, const char *buf,
7315 bufchain_add(&c->v.v2.outbuffer, buf, len);
7319 * Attempt to send data on an SSH-2 channel.
7321 static int ssh2_try_send(struct ssh_channel *c)
7324 struct Packet *pktout;
7327 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7330 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7331 if ((unsigned)len > c->v.v2.remwindow)
7332 len = c->v.v2.remwindow;
7333 if ((unsigned)len > c->v.v2.remmaxpkt)
7334 len = c->v.v2.remmaxpkt;
7335 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7336 ssh2_pkt_adduint32(pktout, c->remoteid);
7337 ssh2_pkt_addstring_start(pktout);
7338 ssh2_pkt_addstring_data(pktout, data, len);
7339 ssh2_pkt_send(ssh, pktout);
7340 bufchain_consume(&c->v.v2.outbuffer, len);
7341 c->v.v2.remwindow -= len;
7345 * After having sent as much data as we can, return the amount
7348 ret = bufchain_size(&c->v.v2.outbuffer);
7351 * And if there's no data pending but we need to send an EOF, send
7354 if (!ret && c->pending_eof)
7355 ssh_channel_try_eof(c);
7360 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7363 if (c->closes & CLOSES_SENT_EOF)
7364 return; /* don't send on channels we've EOFed */
7365 bufsize = ssh2_try_send(c);
7368 case CHAN_MAINSESSION:
7369 /* stdin need not receive an unthrottle
7370 * notification since it will be polled */
7373 x11_unthrottle(c->u.x11.xconn);
7376 /* agent sockets are request/response and need no
7377 * buffer management */
7380 pfd_unthrottle(c->u.pfd.pf);
7386 static int ssh_is_simple(Ssh ssh)
7389 * We use the 'simple' variant of the SSH protocol if we're asked
7390 * to, except not if we're also doing connection-sharing (either
7391 * tunnelling our packets over an upstream or expecting to be
7392 * tunnelled over ourselves), since then the assumption that we
7393 * have only one channel to worry about is not true after all.
7395 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7396 !ssh->bare_connection && !ssh->connshare);
7400 * Set up most of a new ssh_channel for SSH-2.
7402 static void ssh2_channel_init(struct ssh_channel *c)
7405 c->localid = alloc_channel_id(ssh);
7407 c->pending_eof = FALSE;
7408 c->throttling_conn = FALSE;
7409 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7410 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7411 c->v.v2.chanreq_head = NULL;
7412 c->v.v2.throttle_state = UNTHROTTLED;
7413 bufchain_init(&c->v.v2.outbuffer);
7417 * Construct the common parts of a CHANNEL_OPEN.
7419 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7422 struct Packet *pktout;
7424 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7425 ssh2_pkt_addstring(pktout, type);
7426 ssh2_pkt_adduint32(pktout, c->localid);
7427 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7428 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7433 * CHANNEL_FAILURE doesn't come with any indication of what message
7434 * caused it, so we have to keep track of the outstanding
7435 * CHANNEL_REQUESTs ourselves.
7437 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7438 cchandler_fn_t handler, void *ctx)
7440 struct outstanding_channel_request *ocr =
7441 snew(struct outstanding_channel_request);
7443 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7444 ocr->handler = handler;
7447 if (!c->v.v2.chanreq_head)
7448 c->v.v2.chanreq_head = ocr;
7450 c->v.v2.chanreq_tail->next = ocr;
7451 c->v.v2.chanreq_tail = ocr;
7455 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7456 * NULL then a reply will be requested and the handler will be called
7457 * when it arrives. The returned packet is ready to have any
7458 * request-specific data added and be sent. Note that if a handler is
7459 * provided, it's essential that the request actually be sent.
7461 * The handler will usually be passed the response packet in pktin. If
7462 * pktin is NULL, this means that no reply will ever be forthcoming
7463 * (e.g. because the entire connection is being destroyed, or because
7464 * the server initiated channel closure before we saw the response)
7465 * and the handler should free any storage it's holding.
7467 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7469 cchandler_fn_t handler, void *ctx)
7471 struct Packet *pktout;
7473 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7474 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7475 ssh2_pkt_adduint32(pktout, c->remoteid);
7476 ssh2_pkt_addstring(pktout, type);
7477 ssh2_pkt_addbool(pktout, handler != NULL);
7478 if (handler != NULL)
7479 ssh2_queue_chanreq_handler(c, handler, ctx);
7484 * Potentially enlarge the window on an SSH-2 channel.
7486 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7488 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7493 * Never send WINDOW_ADJUST for a channel that the remote side has
7494 * already sent EOF on; there's no point, since it won't be
7495 * sending any more data anyway. Ditto if _we've_ already sent
7498 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7502 * Also, never widen the window for an X11 channel when we're
7503 * still waiting to see its initial auth and may yet hand it off
7506 if (c->type == CHAN_X11 && c->u.x11.initial)
7510 * If the remote end has a habit of ignoring maxpkt, limit the
7511 * window so that it has no choice (assuming it doesn't ignore the
7514 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7515 newwin = OUR_V2_MAXPKT;
7518 * Only send a WINDOW_ADJUST if there's significantly more window
7519 * available than the other end thinks there is. This saves us
7520 * sending a WINDOW_ADJUST for every character in a shell session.
7522 * "Significant" is arbitrarily defined as half the window size.
7524 if (newwin / 2 >= c->v.v2.locwindow) {
7525 struct Packet *pktout;
7529 * In order to keep track of how much window the client
7530 * actually has available, we'd like it to acknowledge each
7531 * WINDOW_ADJUST. We can't do that directly, so we accompany
7532 * it with a CHANNEL_REQUEST that has to be acknowledged.
7534 * This is only necessary if we're opening the window wide.
7535 * If we're not, then throughput is being constrained by
7536 * something other than the maximum window size anyway.
7538 if (newwin == c->v.v2.locmaxwin &&
7539 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7540 up = snew(unsigned);
7541 *up = newwin - c->v.v2.locwindow;
7542 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7543 ssh2_handle_winadj_response, up);
7544 ssh2_pkt_send(ssh, pktout);
7546 if (c->v.v2.throttle_state != UNTHROTTLED)
7547 c->v.v2.throttle_state = UNTHROTTLING;
7549 /* Pretend the WINDOW_ADJUST was acked immediately. */
7550 c->v.v2.remlocwin = newwin;
7551 c->v.v2.throttle_state = THROTTLED;
7553 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7554 ssh2_pkt_adduint32(pktout, c->remoteid);
7555 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7556 ssh2_pkt_send(ssh, pktout);
7557 c->v.v2.locwindow = newwin;
7562 * Find the channel associated with a message. If there's no channel,
7563 * or it's not properly open, make a noise about it and return NULL.
7565 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7567 unsigned localid = ssh_pkt_getuint32(pktin);
7568 struct ssh_channel *c;
7570 c = find234(ssh->channels, &localid, ssh_channelfind);
7572 (c->type != CHAN_SHARING && c->halfopen &&
7573 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7574 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7575 char *buf = dupprintf("Received %s for %s channel %u",
7576 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7578 c ? "half-open" : "nonexistent", localid);
7579 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7586 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7587 struct Packet *pktin, void *ctx)
7589 unsigned *sizep = ctx;
7592 * Winadj responses should always be failures. However, at least
7593 * one server ("boks_sshd") is known to return SUCCESS for channel
7594 * requests it's never heard of, such as "winadj@putty". Raised
7595 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7596 * life, we don't worry about what kind of response we got.
7599 c->v.v2.remlocwin += *sizep;
7602 * winadj messages are only sent when the window is fully open, so
7603 * if we get an ack of one, we know any pending unthrottle is
7606 if (c->v.v2.throttle_state == UNTHROTTLING)
7607 c->v.v2.throttle_state = UNTHROTTLED;
7610 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
7612 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
7613 struct outstanding_channel_request *ocr;
7616 if (c->type == CHAN_SHARING) {
7617 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7618 pktin->body, pktin->length);
7621 ocr = c->v.v2.chanreq_head;
7623 ssh2_msg_unexpected(ssh, pktin);
7626 ocr->handler(c, pktin, ocr->ctx);
7627 c->v.v2.chanreq_head = ocr->next;
7630 * We may now initiate channel-closing procedures, if that
7631 * CHANNEL_REQUEST was the last thing outstanding before we send
7634 ssh2_channel_check_close(c);
7637 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
7639 struct ssh_channel *c;
7640 c = ssh2_channel_msg(ssh, pktin);
7643 if (c->type == CHAN_SHARING) {
7644 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7645 pktin->body, pktin->length);
7648 if (!(c->closes & CLOSES_SENT_EOF)) {
7649 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
7650 ssh2_try_send_and_unthrottle(ssh, c);
7654 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
7658 struct ssh_channel *c;
7659 c = ssh2_channel_msg(ssh, pktin);
7662 if (c->type == CHAN_SHARING) {
7663 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7664 pktin->body, pktin->length);
7667 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
7668 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
7669 return; /* extended but not stderr */
7670 ssh_pkt_getstring(pktin, &data, &length);
7673 c->v.v2.locwindow -= length;
7674 c->v.v2.remlocwin -= length;
7676 case CHAN_MAINSESSION:
7678 from_backend(ssh->frontend, pktin->type ==
7679 SSH2_MSG_CHANNEL_EXTENDED_DATA,
7683 bufsize = x11_send(c->u.x11.xconn, data, length);
7686 bufsize = pfd_send(c->u.pfd.pf, data, length);
7689 while (length > 0) {
7690 if (c->u.a.lensofar < 4) {
7691 unsigned int l = min(4 - c->u.a.lensofar,
7693 memcpy(c->u.a.msglen + c->u.a.lensofar,
7697 c->u.a.lensofar += l;
7699 if (c->u.a.lensofar == 4) {
7701 4 + GET_32BIT(c->u.a.msglen);
7702 c->u.a.message = snewn(c->u.a.totallen,
7704 memcpy(c->u.a.message, c->u.a.msglen, 4);
7706 if (c->u.a.lensofar >= 4 && length > 0) {
7708 min(c->u.a.totallen - c->u.a.lensofar,
7710 memcpy(c->u.a.message + c->u.a.lensofar,
7714 c->u.a.lensofar += l;
7716 if (c->u.a.lensofar == c->u.a.totallen) {
7719 c->u.a.outstanding_requests++;
7720 if (agent_query(c->u.a.message,
7723 ssh_agentf_callback, c))
7724 ssh_agentf_callback(c, reply, replylen);
7725 sfree(c->u.a.message);
7726 c->u.a.message = NULL;
7727 c->u.a.lensofar = 0;
7734 * If it looks like the remote end hit the end of its window,
7735 * and we didn't want it to do that, think about using a
7738 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
7739 c->v.v2.locmaxwin < 0x40000000)
7740 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
7742 * If we are not buffering too much data,
7743 * enlarge the window again at the remote side.
7744 * If we are buffering too much, we may still
7745 * need to adjust the window if the server's
7748 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7749 c->v.v2.locmaxwin - bufsize : 0);
7751 * If we're either buffering way too much data, or if we're
7752 * buffering anything at all and we're in "simple" mode,
7753 * throttle the whole channel.
7755 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
7756 && !c->throttling_conn) {
7757 c->throttling_conn = 1;
7758 ssh_throttle_conn(ssh, +1);
7763 static void ssh_check_termination(Ssh ssh)
7765 if (ssh->version == 2 &&
7766 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7767 count234(ssh->channels) == 0 &&
7768 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
7770 * We used to send SSH_MSG_DISCONNECT here, because I'd
7771 * believed that _every_ conforming SSH-2 connection had to
7772 * end with a disconnect being sent by at least one side;
7773 * apparently I was wrong and it's perfectly OK to
7774 * unceremoniously slam the connection shut when you're done,
7775 * and indeed OpenSSH feels this is more polite than sending a
7776 * DISCONNECT. So now we don't.
7778 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7782 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
7783 const char *peerinfo)
7786 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
7789 logeventf(ssh, "Connection sharing downstream #%u connected", id);
7792 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
7794 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
7795 ssh_check_termination(ssh);
7798 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
7803 va_start(ap, logfmt);
7804 buf = dupvprintf(logfmt, ap);
7807 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
7809 logeventf(ssh, "Connection sharing: %s", buf);
7813 static void ssh_channel_destroy(struct ssh_channel *c)
7818 case CHAN_MAINSESSION:
7819 ssh->mainchan = NULL;
7820 update_specials_menu(ssh->frontend);
7823 if (c->u.x11.xconn != NULL)
7824 x11_close(c->u.x11.xconn);
7825 logevent("Forwarded X11 connection terminated");
7828 sfree(c->u.a.message);
7831 if (c->u.pfd.pf != NULL)
7832 pfd_close(c->u.pfd.pf);
7833 logevent("Forwarded port closed");
7837 del234(ssh->channels, c);
7838 if (ssh->version == 2) {
7839 bufchain_clear(&c->v.v2.outbuffer);
7840 assert(c->v.v2.chanreq_head == NULL);
7845 * If that was the last channel left open, we might need to
7848 ssh_check_termination(ssh);
7851 static void ssh2_channel_check_close(struct ssh_channel *c)
7854 struct Packet *pktout;
7858 * If we've sent out our own CHANNEL_OPEN but not yet seen
7859 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
7860 * it's too early to be sending close messages of any kind.
7865 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
7866 c->type == CHAN_ZOMBIE) &&
7867 !c->v.v2.chanreq_head &&
7868 !(c->closes & CLOSES_SENT_CLOSE)) {
7870 * We have both sent and received EOF (or the channel is a
7871 * zombie), and we have no outstanding channel requests, which
7872 * means the channel is in final wind-up. But we haven't sent
7873 * CLOSE, so let's do so now.
7875 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
7876 ssh2_pkt_adduint32(pktout, c->remoteid);
7877 ssh2_pkt_send(ssh, pktout);
7878 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
7881 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
7882 assert(c->v.v2.chanreq_head == NULL);
7884 * We have both sent and received CLOSE, which means we're
7885 * completely done with the channel.
7887 ssh_channel_destroy(c);
7891 static void ssh2_channel_got_eof(struct ssh_channel *c)
7893 if (c->closes & CLOSES_RCVD_EOF)
7894 return; /* already seen EOF */
7895 c->closes |= CLOSES_RCVD_EOF;
7897 if (c->type == CHAN_X11) {
7898 x11_send_eof(c->u.x11.xconn);
7899 } else if (c->type == CHAN_AGENT) {
7900 if (c->u.a.outstanding_requests == 0) {
7901 /* Manufacture an outgoing EOF in response to the incoming one. */
7902 sshfwd_write_eof(c);
7904 } else if (c->type == CHAN_SOCKDATA) {
7905 pfd_send_eof(c->u.pfd.pf);
7906 } else if (c->type == CHAN_MAINSESSION) {
7909 if (!ssh->sent_console_eof &&
7910 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
7912 * Either from_backend_eof told us that the front end
7913 * wants us to close the outgoing side of the connection
7914 * as soon as we see EOF from the far end, or else we've
7915 * unilaterally decided to do that because we've allocated
7916 * a remote pty and hence EOF isn't a particularly
7917 * meaningful concept.
7919 sshfwd_write_eof(c);
7921 ssh->sent_console_eof = TRUE;
7924 ssh2_channel_check_close(c);
7927 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
7929 struct ssh_channel *c;
7931 c = ssh2_channel_msg(ssh, pktin);
7934 if (c->type == CHAN_SHARING) {
7935 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7936 pktin->body, pktin->length);
7939 ssh2_channel_got_eof(c);
7942 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7944 struct ssh_channel *c;
7946 c = ssh2_channel_msg(ssh, pktin);
7949 if (c->type == CHAN_SHARING) {
7950 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7951 pktin->body, pktin->length);
7956 * When we receive CLOSE on a channel, we assume it comes with an
7957 * implied EOF if we haven't seen EOF yet.
7959 ssh2_channel_got_eof(c);
7961 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
7963 * It also means we stop expecting to see replies to any
7964 * outstanding channel requests, so clean those up too.
7965 * (ssh_chanreq_init will enforce by assertion that we don't
7966 * subsequently put anything back on this list.)
7968 while (c->v.v2.chanreq_head) {
7969 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
7970 ocr->handler(c, NULL, ocr->ctx);
7971 c->v.v2.chanreq_head = ocr->next;
7977 * And we also send an outgoing EOF, if we haven't already, on the
7978 * assumption that CLOSE is a pretty forceful announcement that
7979 * the remote side is doing away with the entire channel. (If it
7980 * had wanted to send us EOF and continue receiving data from us,
7981 * it would have just sent CHANNEL_EOF.)
7983 if (!(c->closes & CLOSES_SENT_EOF)) {
7985 * Make sure we don't read any more from whatever our local
7986 * data source is for this channel.
7989 case CHAN_MAINSESSION:
7990 ssh->send_ok = 0; /* stop trying to read from stdin */
7993 x11_override_throttle(c->u.x11.xconn, 1);
7996 pfd_override_throttle(c->u.pfd.pf, 1);
8001 * Abandon any buffered data we still wanted to send to this
8002 * channel. Receiving a CHANNEL_CLOSE is an indication that
8003 * the server really wants to get on and _destroy_ this
8004 * channel, and it isn't going to send us any further
8005 * WINDOW_ADJUSTs to permit us to send pending stuff.
8007 bufchain_clear(&c->v.v2.outbuffer);
8010 * Send outgoing EOF.
8012 sshfwd_write_eof(c);
8016 * Now process the actual close.
8018 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8019 c->closes |= CLOSES_RCVD_CLOSE;
8020 ssh2_channel_check_close(c);
8024 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8026 struct ssh_channel *c;
8028 c = ssh2_channel_msg(ssh, pktin);
8031 if (c->type == CHAN_SHARING) {
8032 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8033 pktin->body, pktin->length);
8036 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8037 c->remoteid = ssh_pkt_getuint32(pktin);
8038 c->halfopen = FALSE;
8039 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8040 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8042 if (c->type == CHAN_SOCKDATA_DORMANT) {
8043 c->type = CHAN_SOCKDATA;
8045 pfd_confirm(c->u.pfd.pf);
8046 } else if (c->type == CHAN_ZOMBIE) {
8048 * This case can occur if a local socket error occurred
8049 * between us sending out CHANNEL_OPEN and receiving
8050 * OPEN_CONFIRMATION. In this case, all we can do is
8051 * immediately initiate close proceedings now that we know the
8052 * server's id to put in the close message.
8054 ssh2_channel_check_close(c);
8057 * We never expect to receive OPEN_CONFIRMATION for any
8058 * *other* channel type (since only local-to-remote port
8059 * forwardings cause us to send CHANNEL_OPEN after the main
8060 * channel is live - all other auxiliary channel types are
8061 * initiated from the server end). It's safe to enforce this
8062 * by assertion rather than by ssh_disconnect, because the
8063 * real point is that we never constructed a half-open channel
8064 * structure in the first place with any type other than the
8067 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8071 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8074 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8076 static const char *const reasons[] = {
8077 "<unknown reason code>",
8078 "Administratively prohibited",
8080 "Unknown channel type",
8081 "Resource shortage",
8083 unsigned reason_code;
8084 char *reason_string;
8086 struct ssh_channel *c;
8088 c = ssh2_channel_msg(ssh, pktin);
8091 if (c->type == CHAN_SHARING) {
8092 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8093 pktin->body, pktin->length);
8096 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8098 if (c->type == CHAN_SOCKDATA_DORMANT) {
8099 reason_code = ssh_pkt_getuint32(pktin);
8100 if (reason_code >= lenof(reasons))
8101 reason_code = 0; /* ensure reasons[reason_code] in range */
8102 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8103 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8104 reasons[reason_code], reason_length, reason_string);
8106 pfd_close(c->u.pfd.pf);
8107 } else if (c->type == CHAN_ZOMBIE) {
8109 * This case can occur if a local socket error occurred
8110 * between us sending out CHANNEL_OPEN and receiving
8111 * OPEN_FAILURE. In this case, we need do nothing except allow
8112 * the code below to throw the half-open channel away.
8116 * We never expect to receive OPEN_FAILURE for any *other*
8117 * channel type (since only local-to-remote port forwardings
8118 * cause us to send CHANNEL_OPEN after the main channel is
8119 * live - all other auxiliary channel types are initiated from
8120 * the server end). It's safe to enforce this by assertion
8121 * rather than by ssh_disconnect, because the real point is
8122 * that we never constructed a half-open channel structure in
8123 * the first place with any type other than the above.
8125 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8128 del234(ssh->channels, c);
8132 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8135 int typelen, want_reply;
8136 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8137 struct ssh_channel *c;
8138 struct Packet *pktout;
8140 c = ssh2_channel_msg(ssh, pktin);
8143 if (c->type == CHAN_SHARING) {
8144 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8145 pktin->body, pktin->length);
8148 ssh_pkt_getstring(pktin, &type, &typelen);
8149 want_reply = ssh2_pkt_getbool(pktin);
8151 if (c->closes & CLOSES_SENT_CLOSE) {
8153 * We don't reply to channel requests after we've sent
8154 * CHANNEL_CLOSE for the channel, because our reply might
8155 * cross in the network with the other side's CHANNEL_CLOSE
8156 * and arrive after they have wound the channel up completely.
8162 * Having got the channel number, we now look at
8163 * the request type string to see if it's something
8166 if (c == ssh->mainchan) {
8168 * We recognise "exit-status" and "exit-signal" on
8169 * the primary channel.
8171 if (typelen == 11 &&
8172 !memcmp(type, "exit-status", 11)) {
8174 ssh->exitcode = ssh_pkt_getuint32(pktin);
8175 logeventf(ssh, "Server sent command exit status %d",
8177 reply = SSH2_MSG_CHANNEL_SUCCESS;
8179 } else if (typelen == 11 &&
8180 !memcmp(type, "exit-signal", 11)) {
8182 int is_plausible = TRUE, is_int = FALSE;
8183 char *fmt_sig = NULL, *fmt_msg = NULL;
8185 int msglen = 0, core = FALSE;
8186 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8187 * provide an `int' for the signal, despite its
8188 * having been a `string' in the drafts of RFC 4254 since at
8189 * least 2001. (Fixed in session.c 1.147.) Try to
8190 * infer which we can safely parse it as. */
8192 unsigned char *p = pktin->body +
8194 long len = pktin->length - pktin->savedpos;
8195 unsigned long num = GET_32BIT(p); /* what is it? */
8196 /* If it's 0, it hardly matters; assume string */
8200 int maybe_int = FALSE, maybe_str = FALSE;
8201 #define CHECK_HYPOTHESIS(offset, result) \
8204 int q = toint(offset); \
8205 if (q >= 0 && q+4 <= len) { \
8206 q = toint(q + 4 + GET_32BIT(p+q)); \
8207 if (q >= 0 && q+4 <= len && \
8208 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8213 CHECK_HYPOTHESIS(4+1, maybe_int);
8214 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8215 #undef CHECK_HYPOTHESIS
8216 if (maybe_int && !maybe_str)
8218 else if (!maybe_int && maybe_str)
8221 /* Crikey. Either or neither. Panic. */
8222 is_plausible = FALSE;
8225 ssh->exitcode = 128; /* means `unknown signal' */
8228 /* Old non-standard OpenSSH. */
8229 int signum = ssh_pkt_getuint32(pktin);
8230 fmt_sig = dupprintf(" %d", signum);
8231 ssh->exitcode = 128 + signum;
8233 /* As per RFC 4254. */
8236 ssh_pkt_getstring(pktin, &sig, &siglen);
8237 /* Signal name isn't supposed to be blank, but
8238 * let's cope gracefully if it is. */
8240 fmt_sig = dupprintf(" \"%.*s\"",
8245 * Really hideous method of translating the
8246 * signal description back into a locally
8247 * meaningful number.
8252 #define TRANSLATE_SIGNAL(s) \
8253 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8254 ssh->exitcode = 128 + SIG ## s
8256 TRANSLATE_SIGNAL(ABRT);
8259 TRANSLATE_SIGNAL(ALRM);
8262 TRANSLATE_SIGNAL(FPE);
8265 TRANSLATE_SIGNAL(HUP);
8268 TRANSLATE_SIGNAL(ILL);
8271 TRANSLATE_SIGNAL(INT);
8274 TRANSLATE_SIGNAL(KILL);
8277 TRANSLATE_SIGNAL(PIPE);
8280 TRANSLATE_SIGNAL(QUIT);
8283 TRANSLATE_SIGNAL(SEGV);
8286 TRANSLATE_SIGNAL(TERM);
8289 TRANSLATE_SIGNAL(USR1);
8292 TRANSLATE_SIGNAL(USR2);
8294 #undef TRANSLATE_SIGNAL
8296 ssh->exitcode = 128;
8298 core = ssh2_pkt_getbool(pktin);
8299 ssh_pkt_getstring(pktin, &msg, &msglen);
8301 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8303 /* ignore lang tag */
8304 } /* else don't attempt to parse */
8305 logeventf(ssh, "Server exited on signal%s%s%s",
8306 fmt_sig ? fmt_sig : "",
8307 core ? " (core dumped)" : "",
8308 fmt_msg ? fmt_msg : "");
8311 reply = SSH2_MSG_CHANNEL_SUCCESS;
8316 * This is a channel request we don't know
8317 * about, so we now either ignore the request
8318 * or respond with CHANNEL_FAILURE, depending
8321 reply = SSH2_MSG_CHANNEL_FAILURE;
8324 pktout = ssh2_pkt_init(reply);
8325 ssh2_pkt_adduint32(pktout, c->remoteid);
8326 ssh2_pkt_send(ssh, pktout);
8330 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8333 int typelen, want_reply;
8334 struct Packet *pktout;
8336 ssh_pkt_getstring(pktin, &type, &typelen);
8337 want_reply = ssh2_pkt_getbool(pktin);
8340 * We currently don't support any global requests
8341 * at all, so we either ignore the request or
8342 * respond with REQUEST_FAILURE, depending on
8346 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8347 ssh2_pkt_send(ssh, pktout);
8351 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8355 struct X11FakeAuth *auth;
8358 * Make up a new set of fake X11 auth data, and add it to the tree
8359 * of currently valid ones with an indication of the sharing
8360 * context that it's relevant to.
8362 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8363 auth->share_cs = share_cs;
8364 auth->share_chan = share_chan;
8369 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8371 del234(ssh->x11authtree, auth);
8372 x11_free_fake_auth(auth);
8375 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8382 const char *error = NULL;
8383 struct ssh_channel *c;
8384 unsigned remid, winsize, pktsize;
8385 unsigned our_winsize_override = 0;
8386 struct Packet *pktout;
8388 ssh_pkt_getstring(pktin, &type, &typelen);
8389 c = snew(struct ssh_channel);
8392 remid = ssh_pkt_getuint32(pktin);
8393 winsize = ssh_pkt_getuint32(pktin);
8394 pktsize = ssh_pkt_getuint32(pktin);
8396 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8399 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8400 addrstr = snewn(peeraddrlen+1, char);
8401 memcpy(addrstr, peeraddr, peeraddrlen);
8402 addrstr[peeraddrlen] = '\0';
8403 peerport = ssh_pkt_getuint32(pktin);
8405 logeventf(ssh, "Received X11 connect request from %s:%d",
8408 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8409 error = "X11 forwarding is not enabled";
8411 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8414 c->u.x11.initial = TRUE;
8417 * If we are a connection-sharing upstream, then we should
8418 * initially present a very small window, adequate to take
8419 * the X11 initial authorisation packet but not much more.
8420 * Downstream will then present us a larger window (by
8421 * fiat of the connection-sharing protocol) and we can
8422 * guarantee to send a positive-valued WINDOW_ADJUST.
8425 our_winsize_override = 128;
8427 logevent("Opened X11 forward channel");
8431 } else if (typelen == 15 &&
8432 !memcmp(type, "forwarded-tcpip", 15)) {
8433 struct ssh_rportfwd pf, *realpf;
8436 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8437 pf.shost = dupprintf("%.*s", shostlen, shost);
8438 pf.sport = ssh_pkt_getuint32(pktin);
8439 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8440 peerport = ssh_pkt_getuint32(pktin);
8441 realpf = find234(ssh->rportfwds, &pf, NULL);
8442 logeventf(ssh, "Received remote port %s:%d open request "
8443 "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
8446 if (realpf == NULL) {
8447 error = "Remote port is not recognised";
8451 if (realpf->share_ctx) {
8453 * This port forwarding is on behalf of a
8454 * connection-sharing downstream, so abandon our own
8455 * channel-open procedure and just pass the message on
8458 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8459 pktin->body, pktin->length);
8464 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8465 c, ssh->conf, realpf->pfrec->addressfamily);
8466 logeventf(ssh, "Attempting to forward remote port to "
8467 "%s:%d", realpf->dhost, realpf->dport);
8469 logeventf(ssh, "Port open failed: %s", err);
8471 error = "Port open failed";
8473 logevent("Forwarded port opened successfully");
8474 c->type = CHAN_SOCKDATA;
8477 } else if (typelen == 22 &&
8478 !memcmp(type, "auth-agent@openssh.com", 22)) {
8479 if (!ssh->agentfwd_enabled)
8480 error = "Agent forwarding is not enabled";
8482 c->type = CHAN_AGENT; /* identify channel type */
8483 c->u.a.lensofar = 0;
8484 c->u.a.message = NULL;
8485 c->u.a.outstanding_requests = 0;
8488 error = "Unsupported channel type requested";
8491 c->remoteid = remid;
8492 c->halfopen = FALSE;
8494 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8495 ssh2_pkt_adduint32(pktout, c->remoteid);
8496 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8497 ssh2_pkt_addstring(pktout, error);
8498 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8499 ssh2_pkt_send(ssh, pktout);
8500 logeventf(ssh, "Rejected channel open: %s", error);
8503 ssh2_channel_init(c);
8504 c->v.v2.remwindow = winsize;
8505 c->v.v2.remmaxpkt = pktsize;
8506 if (our_winsize_override) {
8507 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8508 our_winsize_override;
8510 add234(ssh->channels, c);
8511 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8512 ssh2_pkt_adduint32(pktout, c->remoteid);
8513 ssh2_pkt_adduint32(pktout, c->localid);
8514 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8515 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8516 ssh2_pkt_send(ssh, pktout);
8520 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8521 void *share_cs, void *share_chan,
8522 const char *peer_addr, int peer_port,
8523 int endian, int protomajor, int protominor,
8524 const void *initial_data, int initial_len)
8527 * This function is called when we've just discovered that an X
8528 * forwarding channel on which we'd been handling the initial auth
8529 * ourselves turns out to be destined for a connection-sharing
8530 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8531 * that we completely stop tracking windows and buffering data and
8532 * just pass more or less unmodified SSH messages back and forth.
8534 c->type = CHAN_SHARING;
8535 c->u.sharing.ctx = share_cs;
8536 share_setup_x11_channel(share_cs, share_chan,
8537 c->localid, c->remoteid, c->v.v2.remwindow,
8538 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8539 peer_addr, peer_port, endian,
8540 protomajor, protominor,
8541 initial_data, initial_len);
8544 void sshfwd_x11_is_local(struct ssh_channel *c)
8547 * This function is called when we've just discovered that an X
8548 * forwarding channel is _not_ destined for a connection-sharing
8549 * downstream but we're going to handle it ourselves. We stop
8550 * presenting a cautiously small window and go into ordinary data
8553 c->u.x11.initial = FALSE;
8554 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8558 * Buffer banner messages for later display at some convenient point,
8559 * if we're going to display them.
8561 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8563 /* Arbitrary limit to prevent unbounded inflation of buffer */
8564 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8565 bufchain_size(&ssh->banner) <= 131072) {
8566 char *banner = NULL;
8568 ssh_pkt_getstring(pktin, &banner, &size);
8570 bufchain_add(&ssh->banner, banner, size);
8574 /* Helper function to deal with sending tty modes for "pty-req" */
8575 static void ssh2_send_ttymode(void *data, char *mode, char *val)
8577 struct Packet *pktout = (struct Packet *)data;
8579 unsigned int arg = 0;
8580 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
8581 if (i == lenof(ssh_ttymodes)) return;
8582 switch (ssh_ttymodes[i].type) {
8584 arg = ssh_tty_parse_specchar(val);
8587 arg = ssh_tty_parse_boolean(val);
8590 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
8591 ssh2_pkt_adduint32(pktout, arg);
8594 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8597 struct ssh2_setup_x11_state {
8601 struct Packet *pktout;
8602 crStateP(ssh2_setup_x11_state, ctx);
8606 logevent("Requesting X11 forwarding");
8607 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8609 ssh2_pkt_addbool(pktout, 0); /* many connections */
8610 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8611 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8612 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8613 ssh2_pkt_send(ssh, pktout);
8615 /* Wait to be called back with either a response packet, or NULL
8616 * meaning clean up and free our data */
8620 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8621 logevent("X11 forwarding enabled");
8622 ssh->X11_fwd_enabled = TRUE;
8624 logevent("X11 forwarding refused");
8630 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8633 struct ssh2_setup_agent_state {
8637 struct Packet *pktout;
8638 crStateP(ssh2_setup_agent_state, ctx);
8642 logevent("Requesting OpenSSH-style agent forwarding");
8643 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8644 ssh2_setup_agent, s);
8645 ssh2_pkt_send(ssh, pktout);
8647 /* Wait to be called back with either a response packet, or NULL
8648 * meaning clean up and free our data */
8652 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8653 logevent("Agent forwarding enabled");
8654 ssh->agentfwd_enabled = TRUE;
8656 logevent("Agent forwarding refused");
8662 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8665 struct ssh2_setup_pty_state {
8669 struct Packet *pktout;
8670 crStateP(ssh2_setup_pty_state, ctx);
8674 /* Unpick the terminal-speed string. */
8675 /* XXX perhaps we should allow no speeds to be sent. */
8676 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8677 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8678 /* Build the pty request. */
8679 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
8681 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
8682 ssh2_pkt_adduint32(pktout, ssh->term_width);
8683 ssh2_pkt_adduint32(pktout, ssh->term_height);
8684 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
8685 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
8686 ssh2_pkt_addstring_start(pktout);
8687 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
8688 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
8689 ssh2_pkt_adduint32(pktout, ssh->ispeed);
8690 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
8691 ssh2_pkt_adduint32(pktout, ssh->ospeed);
8692 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
8693 ssh2_pkt_send(ssh, pktout);
8694 ssh->state = SSH_STATE_INTERMED;
8696 /* Wait to be called back with either a response packet, or NULL
8697 * meaning clean up and free our data */
8701 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8702 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8703 ssh->ospeed, ssh->ispeed);
8704 ssh->got_pty = TRUE;
8706 c_write_str(ssh, "Server refused to allocate pty\r\n");
8707 ssh->editing = ssh->echoing = 1;
8714 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
8717 struct ssh2_setup_env_state {
8719 int num_env, env_left, env_ok;
8722 struct Packet *pktout;
8723 crStateP(ssh2_setup_env_state, ctx);
8728 * Send environment variables.
8730 * Simplest thing here is to send all the requests at once, and
8731 * then wait for a whole bunch of successes or failures.
8737 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
8739 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
8740 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
8741 ssh2_pkt_addstring(pktout, key);
8742 ssh2_pkt_addstring(pktout, val);
8743 ssh2_pkt_send(ssh, pktout);
8748 logeventf(ssh, "Sent %d environment variables", s->num_env);
8753 s->env_left = s->num_env;
8755 while (s->env_left > 0) {
8756 /* Wait to be called back with either a response packet,
8757 * or NULL meaning clean up and free our data */
8759 if (!pktin) goto out;
8760 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
8765 if (s->env_ok == s->num_env) {
8766 logevent("All environment variables successfully set");
8767 } else if (s->env_ok == 0) {
8768 logevent("All environment variables refused");
8769 c_write_str(ssh, "Server refused to set environment variables\r\n");
8771 logeventf(ssh, "%d environment variables refused",
8772 s->num_env - s->env_ok);
8773 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8781 * Handle the SSH-2 userauth and connection layers.
8783 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
8785 do_ssh2_authconn(ssh, NULL, 0, pktin);
8788 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
8792 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
8795 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
8796 struct Packet *pktin)
8798 struct do_ssh2_authconn_state {
8802 AUTH_TYPE_PUBLICKEY,
8803 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
8804 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
8806 AUTH_TYPE_GSSAPI, /* always QUIET */
8807 AUTH_TYPE_KEYBOARD_INTERACTIVE,
8808 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
8810 int done_service_req;
8811 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
8812 int tried_pubkey_config, done_agent;
8817 int kbd_inter_refused;
8818 int we_are_in, userauth_success;
8819 prompts_t *cur_prompt;
8824 void *publickey_blob;
8825 int publickey_bloblen;
8826 int privatekey_available, privatekey_encrypted;
8827 char *publickey_algorithm;
8828 char *publickey_comment;
8829 unsigned char agent_request[5], *agent_response, *agentp;
8830 int agent_responselen;
8831 unsigned char *pkblob_in_agent;
8833 char *pkblob, *alg, *commentp;
8834 int pklen, alglen, commentlen;
8835 int siglen, retlen, len;
8836 char *q, *agentreq, *ret;
8838 struct Packet *pktout;
8841 struct ssh_gss_library *gsslib;
8842 Ssh_gss_ctx gss_ctx;
8843 Ssh_gss_buf gss_buf;
8844 Ssh_gss_buf gss_rcvtok, gss_sndtok;
8845 Ssh_gss_name gss_srv_name;
8846 Ssh_gss_stat gss_stat;
8849 crState(do_ssh2_authconn_state);
8853 /* Register as a handler for all the messages this coroutine handles. */
8854 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
8855 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
8856 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
8857 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
8858 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
8859 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
8860 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
8861 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
8862 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
8863 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
8864 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
8865 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
8866 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
8867 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
8868 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
8869 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
8870 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
8871 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
8872 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
8873 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
8875 s->done_service_req = FALSE;
8876 s->we_are_in = s->userauth_success = FALSE;
8877 s->agent_response = NULL;
8879 s->tried_gssapi = FALSE;
8882 if (!ssh->bare_connection) {
8883 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
8885 * Request userauth protocol, and await a response to it.
8887 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8888 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
8889 ssh2_pkt_send(ssh, s->pktout);
8890 crWaitUntilV(pktin);
8891 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
8892 s->done_service_req = TRUE;
8894 if (!s->done_service_req) {
8896 * Request connection protocol directly, without authentication.
8898 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8899 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8900 ssh2_pkt_send(ssh, s->pktout);
8901 crWaitUntilV(pktin);
8902 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
8903 s->we_are_in = TRUE; /* no auth required */
8905 bombout(("Server refused service request"));
8910 s->we_are_in = TRUE;
8913 /* Arrange to be able to deal with any BANNERs that come in.
8914 * (We do this now as packets may come in during the next bit.) */
8915 bufchain_init(&ssh->banner);
8916 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
8917 ssh2_msg_userauth_banner;
8920 * Misc one-time setup for authentication.
8922 s->publickey_blob = NULL;
8923 if (!s->we_are_in) {
8926 * Load the public half of any configured public key file
8929 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8930 if (!filename_is_null(s->keyfile)) {
8932 logeventf(ssh, "Reading key file \"%.150s\"",
8933 filename_to_str(s->keyfile));
8934 keytype = key_type(s->keyfile);
8935 if (keytype == SSH_KEYTYPE_SSH2 ||
8936 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
8937 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
8940 ssh2_userkey_loadpub(s->keyfile,
8941 &s->publickey_algorithm,
8942 &s->publickey_bloblen,
8943 &s->publickey_comment, &error);
8944 if (s->publickey_blob) {
8945 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
8946 if (!s->privatekey_available)
8947 logeventf(ssh, "Key file contains public key only");
8948 s->privatekey_encrypted =
8949 ssh2_userkey_encrypted(s->keyfile, NULL);
8952 logeventf(ssh, "Unable to load key (%s)",
8954 msgbuf = dupprintf("Unable to load key file "
8955 "\"%.150s\" (%s)\r\n",
8956 filename_to_str(s->keyfile),
8958 c_write_str(ssh, msgbuf);
8963 logeventf(ssh, "Unable to use this key file (%s)",
8964 key_type_to_str(keytype));
8965 msgbuf = dupprintf("Unable to use key file \"%.150s\""
8967 filename_to_str(s->keyfile),
8968 key_type_to_str(keytype));
8969 c_write_str(ssh, msgbuf);
8971 s->publickey_blob = NULL;
8976 * Find out about any keys Pageant has (but if there's a
8977 * public key configured, filter out all others).
8980 s->agent_response = NULL;
8981 s->pkblob_in_agent = NULL;
8982 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
8986 logevent("Pageant is running. Requesting keys.");
8988 /* Request the keys held by the agent. */
8989 PUT_32BIT(s->agent_request, 1);
8990 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
8991 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
8992 ssh_agent_callback, ssh)) {
8996 bombout(("Unexpected data from server while"
8997 " waiting for agent response"));
9000 } while (pktin || inlen > 0);
9001 r = ssh->agent_response;
9002 s->agent_responselen = ssh->agent_response_len;
9004 s->agent_response = (unsigned char *) r;
9005 if (s->agent_response && s->agent_responselen >= 5 &&
9006 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9009 p = s->agent_response + 5;
9010 s->nkeys = toint(GET_32BIT(p));
9013 * Vet the Pageant response to ensure that the key
9014 * count and blob lengths make sense.
9017 logeventf(ssh, "Pageant response contained a negative"
9018 " key count %d", s->nkeys);
9020 goto done_agent_query;
9022 unsigned char *q = p + 4;
9023 int lenleft = s->agent_responselen - 5 - 4;
9025 for (keyi = 0; keyi < s->nkeys; keyi++) {
9026 int bloblen, commentlen;
9028 logeventf(ssh, "Pageant response was truncated");
9030 goto done_agent_query;
9032 bloblen = toint(GET_32BIT(q));
9033 if (bloblen < 0 || bloblen > lenleft) {
9034 logeventf(ssh, "Pageant response was truncated");
9036 goto done_agent_query;
9038 lenleft -= 4 + bloblen;
9040 commentlen = toint(GET_32BIT(q));
9041 if (commentlen < 0 || commentlen > lenleft) {
9042 logeventf(ssh, "Pageant response was truncated");
9044 goto done_agent_query;
9046 lenleft -= 4 + commentlen;
9047 q += 4 + commentlen;
9052 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9053 if (s->publickey_blob) {
9054 /* See if configured key is in agent. */
9055 for (keyi = 0; keyi < s->nkeys; keyi++) {
9056 s->pklen = toint(GET_32BIT(p));
9057 if (s->pklen == s->publickey_bloblen &&
9058 !memcmp(p+4, s->publickey_blob,
9059 s->publickey_bloblen)) {
9060 logeventf(ssh, "Pageant key #%d matches "
9061 "configured key file", keyi);
9063 s->pkblob_in_agent = p;
9067 p += toint(GET_32BIT(p)) + 4; /* comment */
9069 if (!s->pkblob_in_agent) {
9070 logevent("Configured key file not in Pageant");
9075 logevent("Failed to get reply from Pageant");
9083 * We repeat this whole loop, including the username prompt,
9084 * until we manage a successful authentication. If the user
9085 * types the wrong _password_, they can be sent back to the
9086 * beginning to try another username, if this is configured on.
9087 * (If they specify a username in the config, they are never
9088 * asked, even if they do give a wrong password.)
9090 * I think this best serves the needs of
9092 * - the people who have no configuration, no keys, and just
9093 * want to try repeated (username,password) pairs until they
9094 * type both correctly
9096 * - people who have keys and configuration but occasionally
9097 * need to fall back to passwords
9099 * - people with a key held in Pageant, who might not have
9100 * logged in to a particular machine before; so they want to
9101 * type a username, and then _either_ their key will be
9102 * accepted, _or_ they will type a password. If they mistype
9103 * the username they will want to be able to get back and
9106 s->got_username = FALSE;
9107 while (!s->we_are_in) {
9111 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9113 * We got a username last time round this loop, and
9114 * with change_username turned off we don't try to get
9117 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9118 int ret; /* need not be kept over crReturn */
9119 s->cur_prompt = new_prompts(ssh->frontend);
9120 s->cur_prompt->to_server = TRUE;
9121 s->cur_prompt->name = dupstr("SSH login name");
9122 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9123 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9126 crWaitUntilV(!pktin);
9127 ret = get_userpass_input(s->cur_prompt, in, inlen);
9132 * get_userpass_input() failed to get a username.
9135 free_prompts(s->cur_prompt);
9136 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9139 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9140 free_prompts(s->cur_prompt);
9143 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9144 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9145 c_write_str(ssh, stuff);
9149 s->got_username = TRUE;
9152 * Send an authentication request using method "none": (a)
9153 * just in case it succeeds, and (b) so that we know what
9154 * authentication methods we can usefully try next.
9156 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9158 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9159 ssh2_pkt_addstring(s->pktout, ssh->username);
9160 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9161 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9162 ssh2_pkt_send(ssh, s->pktout);
9163 s->type = AUTH_TYPE_NONE;
9165 s->we_are_in = FALSE;
9167 s->tried_pubkey_config = FALSE;
9168 s->kbd_inter_refused = FALSE;
9170 /* Reset agent request state. */
9171 s->done_agent = FALSE;
9172 if (s->agent_response) {
9173 if (s->pkblob_in_agent) {
9174 s->agentp = s->pkblob_in_agent;
9176 s->agentp = s->agent_response + 5 + 4;
9182 char *methods = NULL;
9186 * Wait for the result of the last authentication request.
9189 crWaitUntilV(pktin);
9191 * Now is a convenient point to spew any banner material
9192 * that we've accumulated. (This should ensure that when
9193 * we exit the auth loop, we haven't any left to deal
9197 int size = bufchain_size(&ssh->banner);
9199 * Don't show the banner if we're operating in
9200 * non-verbose non-interactive mode. (It's probably
9201 * a script, which means nobody will read the
9202 * banner _anyway_, and moreover the printing of
9203 * the banner will screw up processing on the
9204 * output of (say) plink.)
9206 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9207 char *banner = snewn(size, char);
9208 bufchain_fetch(&ssh->banner, banner, size);
9209 c_write_untrusted(ssh, banner, size);
9212 bufchain_clear(&ssh->banner);
9214 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9215 logevent("Access granted");
9216 s->we_are_in = s->userauth_success = TRUE;
9220 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9221 bombout(("Strange packet received during authentication: "
9222 "type %d", pktin->type));
9229 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9230 * we can look at the string in it and know what we can
9231 * helpfully try next.
9233 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9234 ssh_pkt_getstring(pktin, &methods, &methlen);
9235 if (!ssh2_pkt_getbool(pktin)) {
9237 * We have received an unequivocal Access
9238 * Denied. This can translate to a variety of
9239 * messages, or no message at all.
9241 * For forms of authentication which are attempted
9242 * implicitly, by which I mean without printing
9243 * anything in the window indicating that we're
9244 * trying them, we should never print 'Access
9247 * If we do print a message saying that we're
9248 * attempting some kind of authentication, it's OK
9249 * to print a followup message saying it failed -
9250 * but the message may sometimes be more specific
9251 * than simply 'Access denied'.
9253 * Additionally, if we'd just tried password
9254 * authentication, we should break out of this
9255 * whole loop so as to go back to the username
9256 * prompt (iff we're configured to allow
9257 * username change attempts).
9259 if (s->type == AUTH_TYPE_NONE) {
9261 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9262 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9263 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9264 c_write_str(ssh, "Server refused our key\r\n");
9265 logevent("Server refused our key");
9266 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9267 /* This _shouldn't_ happen except by a
9268 * protocol bug causing client and server to
9269 * disagree on what is a correct signature. */
9270 c_write_str(ssh, "Server refused public-key signature"
9271 " despite accepting key!\r\n");
9272 logevent("Server refused public-key signature"
9273 " despite accepting key!");
9274 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9275 /* quiet, so no c_write */
9276 logevent("Server refused keyboard-interactive authentication");
9277 } else if (s->type==AUTH_TYPE_GSSAPI) {
9278 /* always quiet, so no c_write */
9279 /* also, the code down in the GSSAPI block has
9280 * already logged this in the Event Log */
9281 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9282 logevent("Keyboard-interactive authentication failed");
9283 c_write_str(ssh, "Access denied\r\n");
9285 assert(s->type == AUTH_TYPE_PASSWORD);
9286 logevent("Password authentication failed");
9287 c_write_str(ssh, "Access denied\r\n");
9289 if (conf_get_int(ssh->conf, CONF_change_username)) {
9290 /* XXX perhaps we should allow
9291 * keyboard-interactive to do this too? */
9292 s->we_are_in = FALSE;
9297 c_write_str(ssh, "Further authentication required\r\n");
9298 logevent("Further authentication required");
9302 in_commasep_string("publickey", methods, methlen);
9304 in_commasep_string("password", methods, methlen);
9305 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9306 in_commasep_string("keyboard-interactive", methods, methlen);
9309 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9310 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9311 in_commasep_string("gssapi-with-mic", methods, methlen) &&
9312 ssh->gsslibs->nlibraries > 0;
9316 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9318 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9321 * Attempt public-key authentication using a key from Pageant.
9324 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9326 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9328 /* Unpack key from agent response */
9329 s->pklen = toint(GET_32BIT(s->agentp));
9331 s->pkblob = (char *)s->agentp;
9332 s->agentp += s->pklen;
9333 s->alglen = toint(GET_32BIT(s->pkblob));
9334 s->alg = s->pkblob + 4;
9335 s->commentlen = toint(GET_32BIT(s->agentp));
9337 s->commentp = (char *)s->agentp;
9338 s->agentp += s->commentlen;
9339 /* s->agentp now points at next key, if any */
9341 /* See if server will accept it */
9342 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9343 ssh2_pkt_addstring(s->pktout, ssh->username);
9344 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9345 /* service requested */
9346 ssh2_pkt_addstring(s->pktout, "publickey");
9348 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9349 ssh2_pkt_addstring_start(s->pktout);
9350 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9351 ssh2_pkt_addstring_start(s->pktout);
9352 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9353 ssh2_pkt_send(ssh, s->pktout);
9354 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9356 crWaitUntilV(pktin);
9357 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9359 /* Offer of key refused. */
9366 if (flags & FLAG_VERBOSE) {
9367 c_write_str(ssh, "Authenticating with "
9369 c_write(ssh, s->commentp, s->commentlen);
9370 c_write_str(ssh, "\" from agent\r\n");
9374 * Server is willing to accept the key.
9375 * Construct a SIGN_REQUEST.
9377 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9378 ssh2_pkt_addstring(s->pktout, ssh->username);
9379 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9380 /* service requested */
9381 ssh2_pkt_addstring(s->pktout, "publickey");
9383 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9384 ssh2_pkt_addstring_start(s->pktout);
9385 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9386 ssh2_pkt_addstring_start(s->pktout);
9387 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9389 /* Ask agent for signature. */
9390 s->siglen = s->pktout->length - 5 + 4 +
9391 ssh->v2_session_id_len;
9392 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9394 s->len = 1; /* message type */
9395 s->len += 4 + s->pklen; /* key blob */
9396 s->len += 4 + s->siglen; /* data to sign */
9397 s->len += 4; /* flags */
9398 s->agentreq = snewn(4 + s->len, char);
9399 PUT_32BIT(s->agentreq, s->len);
9400 s->q = s->agentreq + 4;
9401 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9402 PUT_32BIT(s->q, s->pklen);
9404 memcpy(s->q, s->pkblob, s->pklen);
9406 PUT_32BIT(s->q, s->siglen);
9408 /* Now the data to be signed... */
9409 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9410 PUT_32BIT(s->q, ssh->v2_session_id_len);
9413 memcpy(s->q, ssh->v2_session_id,
9414 ssh->v2_session_id_len);
9415 s->q += ssh->v2_session_id_len;
9416 memcpy(s->q, s->pktout->data + 5,
9417 s->pktout->length - 5);
9418 s->q += s->pktout->length - 5;
9419 /* And finally the (zero) flags word. */
9421 if (!agent_query(s->agentreq, s->len + 4,
9423 ssh_agent_callback, ssh)) {
9427 bombout(("Unexpected data from server"
9428 " while waiting for agent"
9432 } while (pktin || inlen > 0);
9433 vret = ssh->agent_response;
9434 s->retlen = ssh->agent_response_len;
9439 if (s->retlen >= 9 &&
9440 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9441 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9442 logevent("Sending Pageant's response");
9443 ssh2_add_sigblob(ssh, s->pktout,
9444 s->pkblob, s->pklen,
9446 GET_32BIT(s->ret + 5));
9447 ssh2_pkt_send(ssh, s->pktout);
9448 s->type = AUTH_TYPE_PUBLICKEY;
9450 /* FIXME: less drastic response */
9451 bombout(("Pageant failed to answer challenge"));
9457 /* Do we have any keys left to try? */
9458 if (s->pkblob_in_agent) {
9459 s->done_agent = TRUE;
9460 s->tried_pubkey_config = TRUE;
9463 if (s->keyi >= s->nkeys)
9464 s->done_agent = TRUE;
9467 } else if (s->can_pubkey && s->publickey_blob &&
9468 s->privatekey_available && !s->tried_pubkey_config) {
9470 struct ssh2_userkey *key; /* not live over crReturn */
9471 char *passphrase; /* not live over crReturn */
9473 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9475 s->tried_pubkey_config = TRUE;
9478 * Try the public key supplied in the configuration.
9480 * First, offer the public blob to see if the server is
9481 * willing to accept it.
9483 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9484 ssh2_pkt_addstring(s->pktout, ssh->username);
9485 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9486 /* service requested */
9487 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9488 ssh2_pkt_addbool(s->pktout, FALSE);
9489 /* no signature included */
9490 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9491 ssh2_pkt_addstring_start(s->pktout);
9492 ssh2_pkt_addstring_data(s->pktout,
9493 (char *)s->publickey_blob,
9494 s->publickey_bloblen);
9495 ssh2_pkt_send(ssh, s->pktout);
9496 logevent("Offered public key");
9498 crWaitUntilV(pktin);
9499 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9500 /* Key refused. Give up. */
9501 s->gotit = TRUE; /* reconsider message next loop */
9502 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9503 continue; /* process this new message */
9505 logevent("Offer of public key accepted");
9508 * Actually attempt a serious authentication using
9511 if (flags & FLAG_VERBOSE) {
9512 c_write_str(ssh, "Authenticating with public key \"");
9513 c_write_str(ssh, s->publickey_comment);
9514 c_write_str(ssh, "\"\r\n");
9518 const char *error; /* not live over crReturn */
9519 if (s->privatekey_encrypted) {
9521 * Get a passphrase from the user.
9523 int ret; /* need not be kept over crReturn */
9524 s->cur_prompt = new_prompts(ssh->frontend);
9525 s->cur_prompt->to_server = FALSE;
9526 s->cur_prompt->name = dupstr("SSH key passphrase");
9527 add_prompt(s->cur_prompt,
9528 dupprintf("Passphrase for key \"%.100s\": ",
9529 s->publickey_comment),
9531 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9534 crWaitUntilV(!pktin);
9535 ret = get_userpass_input(s->cur_prompt,
9540 /* Failed to get a passphrase. Terminate. */
9541 free_prompts(s->cur_prompt);
9542 ssh_disconnect(ssh, NULL,
9543 "Unable to authenticate",
9544 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9549 dupstr(s->cur_prompt->prompts[0]->result);
9550 free_prompts(s->cur_prompt);
9552 passphrase = NULL; /* no passphrase needed */
9556 * Try decrypting the key.
9558 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9559 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9561 /* burn the evidence */
9562 smemclr(passphrase, strlen(passphrase));
9565 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9567 (key == SSH2_WRONG_PASSPHRASE)) {
9568 c_write_str(ssh, "Wrong passphrase\r\n");
9570 /* and loop again */
9572 c_write_str(ssh, "Unable to load private key (");
9573 c_write_str(ssh, error);
9574 c_write_str(ssh, ")\r\n");
9576 break; /* try something else */
9582 unsigned char *pkblob, *sigblob, *sigdata;
9583 int pkblob_len, sigblob_len, sigdata_len;
9587 * We have loaded the private key and the server
9588 * has announced that it's willing to accept it.
9589 * Hallelujah. Generate a signature and send it.
9591 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9592 ssh2_pkt_addstring(s->pktout, ssh->username);
9593 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9594 /* service requested */
9595 ssh2_pkt_addstring(s->pktout, "publickey");
9597 ssh2_pkt_addbool(s->pktout, TRUE);
9598 /* signature follows */
9599 ssh2_pkt_addstring(s->pktout, key->alg->name);
9600 pkblob = key->alg->public_blob(key->data,
9602 ssh2_pkt_addstring_start(s->pktout);
9603 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9607 * The data to be signed is:
9611 * followed by everything so far placed in the
9614 sigdata_len = s->pktout->length - 5 + 4 +
9615 ssh->v2_session_id_len;
9616 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9618 sigdata = snewn(sigdata_len, unsigned char);
9620 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9621 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9624 memcpy(sigdata+p, ssh->v2_session_id,
9625 ssh->v2_session_id_len);
9626 p += ssh->v2_session_id_len;
9627 memcpy(sigdata+p, s->pktout->data + 5,
9628 s->pktout->length - 5);
9629 p += s->pktout->length - 5;
9630 assert(p == sigdata_len);
9631 sigblob = key->alg->sign(key->data, (char *)sigdata,
9632 sigdata_len, &sigblob_len);
9633 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9634 sigblob, sigblob_len);
9639 ssh2_pkt_send(ssh, s->pktout);
9640 logevent("Sent public key signature");
9641 s->type = AUTH_TYPE_PUBLICKEY;
9642 key->alg->freekey(key->data);
9643 sfree(key->comment);
9648 } else if (s->can_gssapi && !s->tried_gssapi) {
9650 /* GSSAPI Authentication */
9655 s->type = AUTH_TYPE_GSSAPI;
9656 s->tried_gssapi = TRUE;
9658 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9661 * Pick the highest GSS library on the preference
9667 for (i = 0; i < ngsslibs; i++) {
9668 int want_id = conf_get_int_int(ssh->conf,
9669 CONF_ssh_gsslist, i);
9670 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
9671 if (ssh->gsslibs->libraries[j].id == want_id) {
9672 s->gsslib = &ssh->gsslibs->libraries[j];
9673 goto got_gsslib; /* double break */
9678 * We always expect to have found something in
9679 * the above loop: we only came here if there
9680 * was at least one viable GSS library, and the
9681 * preference list should always mention
9682 * everything and only change the order.
9687 if (s->gsslib->gsslogmsg)
9688 logevent(s->gsslib->gsslogmsg);
9690 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
9691 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9692 ssh2_pkt_addstring(s->pktout, ssh->username);
9693 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9694 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
9695 logevent("Attempting GSSAPI authentication");
9697 /* add mechanism info */
9698 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
9700 /* number of GSSAPI mechanisms */
9701 ssh2_pkt_adduint32(s->pktout,1);
9703 /* length of OID + 2 */
9704 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
9705 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
9708 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
9710 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
9712 ssh2_pkt_send(ssh, s->pktout);
9713 crWaitUntilV(pktin);
9714 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
9715 logevent("GSSAPI authentication request refused");
9719 /* check returned packet ... */
9721 ssh_pkt_getstring(pktin, &data, &len);
9722 s->gss_rcvtok.value = data;
9723 s->gss_rcvtok.length = len;
9724 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
9725 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
9726 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
9727 memcmp((char *)s->gss_rcvtok.value + 2,
9728 s->gss_buf.value,s->gss_buf.length) ) {
9729 logevent("GSSAPI authentication - wrong response from server");
9733 /* now start running */
9734 s->gss_stat = s->gsslib->import_name(s->gsslib,
9737 if (s->gss_stat != SSH_GSS_OK) {
9738 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
9739 logevent("GSSAPI import name failed - Bad service name");
9741 logevent("GSSAPI import name failed");
9745 /* fetch TGT into GSS engine */
9746 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
9748 if (s->gss_stat != SSH_GSS_OK) {
9749 logevent("GSSAPI authentication failed to get credentials");
9750 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9754 /* initial tokens are empty */
9755 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
9756 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
9758 /* now enter the loop */
9760 s->gss_stat = s->gsslib->init_sec_context
9764 conf_get_int(ssh->conf, CONF_gssapifwd),
9768 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
9769 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
9770 logevent("GSSAPI authentication initialisation failed");
9772 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
9773 &s->gss_buf) == SSH_GSS_OK) {
9774 logevent(s->gss_buf.value);
9775 sfree(s->gss_buf.value);
9780 logevent("GSSAPI authentication initialised");
9782 /* Client and server now exchange tokens until GSSAPI
9783 * no longer says CONTINUE_NEEDED */
9785 if (s->gss_sndtok.length != 0) {
9786 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
9787 ssh_pkt_addstring_start(s->pktout);
9788 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
9789 ssh2_pkt_send(ssh, s->pktout);
9790 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
9793 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
9794 crWaitUntilV(pktin);
9795 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
9796 logevent("GSSAPI authentication - bad server response");
9797 s->gss_stat = SSH_GSS_FAILURE;
9800 ssh_pkt_getstring(pktin, &data, &len);
9801 s->gss_rcvtok.value = data;
9802 s->gss_rcvtok.length = len;
9804 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
9806 if (s->gss_stat != SSH_GSS_OK) {
9807 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9808 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9811 logevent("GSSAPI authentication loop finished OK");
9813 /* Now send the MIC */
9815 s->pktout = ssh2_pkt_init(0);
9816 micoffset = s->pktout->length;
9817 ssh_pkt_addstring_start(s->pktout);
9818 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
9819 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
9820 ssh_pkt_addstring(s->pktout, ssh->username);
9821 ssh_pkt_addstring(s->pktout, "ssh-connection");
9822 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
9824 s->gss_buf.value = (char *)s->pktout->data + micoffset;
9825 s->gss_buf.length = s->pktout->length - micoffset;
9827 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
9828 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
9829 ssh_pkt_addstring_start(s->pktout);
9830 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
9831 ssh2_pkt_send(ssh, s->pktout);
9832 s->gsslib->free_mic(s->gsslib, &mic);
9836 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9837 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9840 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
9843 * Keyboard-interactive authentication.
9846 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
9848 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
9850 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9851 ssh2_pkt_addstring(s->pktout, ssh->username);
9852 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9853 /* service requested */
9854 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
9856 ssh2_pkt_addstring(s->pktout, ""); /* lang */
9857 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
9858 ssh2_pkt_send(ssh, s->pktout);
9860 logevent("Attempting keyboard-interactive authentication");
9862 crWaitUntilV(pktin);
9863 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
9864 /* Server is not willing to do keyboard-interactive
9865 * at all (or, bizarrely but legally, accepts the
9866 * user without actually issuing any prompts).
9867 * Give up on it entirely. */
9869 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
9870 s->kbd_inter_refused = TRUE; /* don't try it again */
9875 * Loop while the server continues to send INFO_REQUESTs.
9877 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
9879 char *name, *inst, *lang;
9880 int name_len, inst_len, lang_len;
9884 * We've got a fresh USERAUTH_INFO_REQUEST.
9885 * Get the preamble and start building a prompt.
9887 ssh_pkt_getstring(pktin, &name, &name_len);
9888 ssh_pkt_getstring(pktin, &inst, &inst_len);
9889 ssh_pkt_getstring(pktin, &lang, &lang_len);
9890 s->cur_prompt = new_prompts(ssh->frontend);
9891 s->cur_prompt->to_server = TRUE;
9894 * Get any prompt(s) from the packet.
9896 s->num_prompts = ssh_pkt_getuint32(pktin);
9897 for (i = 0; i < s->num_prompts; i++) {
9901 static char noprompt[] =
9902 "<server failed to send prompt>: ";
9904 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9905 echo = ssh2_pkt_getbool(pktin);
9908 prompt_len = lenof(noprompt)-1;
9910 add_prompt(s->cur_prompt,
9911 dupprintf("%.*s", prompt_len, prompt),
9916 /* FIXME: better prefix to distinguish from
9918 s->cur_prompt->name =
9919 dupprintf("SSH server: %.*s", name_len, name);
9920 s->cur_prompt->name_reqd = TRUE;
9922 s->cur_prompt->name =
9923 dupstr("SSH server authentication");
9924 s->cur_prompt->name_reqd = FALSE;
9926 /* We add a prefix to try to make it clear that a prompt
9927 * has come from the server.
9928 * FIXME: ugly to print "Using..." in prompt _every_
9929 * time round. Can this be done more subtly? */
9930 /* Special case: for reasons best known to themselves,
9931 * some servers send k-i requests with no prompts and
9932 * nothing to display. Keep quiet in this case. */
9933 if (s->num_prompts || name_len || inst_len) {
9934 s->cur_prompt->instruction =
9935 dupprintf("Using keyboard-interactive authentication.%s%.*s",
9936 inst_len ? "\n" : "", inst_len, inst);
9937 s->cur_prompt->instr_reqd = TRUE;
9939 s->cur_prompt->instr_reqd = FALSE;
9943 * Display any instructions, and get the user's
9947 int ret; /* not live over crReturn */
9948 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9951 crWaitUntilV(!pktin);
9952 ret = get_userpass_input(s->cur_prompt, in, inlen);
9957 * Failed to get responses. Terminate.
9959 free_prompts(s->cur_prompt);
9960 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9961 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9968 * Send the response(s) to the server.
9970 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
9971 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
9972 for (i=0; i < s->num_prompts; i++) {
9973 ssh2_pkt_addstring(s->pktout,
9974 s->cur_prompt->prompts[i]->result);
9976 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9979 * Free the prompts structure from this iteration.
9980 * If there's another, a new one will be allocated
9981 * when we return to the top of this while loop.
9983 free_prompts(s->cur_prompt);
9986 * Get the next packet in case it's another
9989 crWaitUntilV(pktin);
9994 * We should have SUCCESS or FAILURE now.
9998 } else if (s->can_passwd) {
10001 * Plain old password authentication.
10003 int ret; /* not live over crReturn */
10004 int changereq_first_time; /* not live over crReturn */
10006 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10008 s->cur_prompt = new_prompts(ssh->frontend);
10009 s->cur_prompt->to_server = TRUE;
10010 s->cur_prompt->name = dupstr("SSH password");
10011 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10016 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10019 crWaitUntilV(!pktin);
10020 ret = get_userpass_input(s->cur_prompt, in, inlen);
10025 * Failed to get responses. Terminate.
10027 free_prompts(s->cur_prompt);
10028 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10029 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10034 * Squirrel away the password. (We may need it later if
10035 * asked to change it.)
10037 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10038 free_prompts(s->cur_prompt);
10041 * Send the password packet.
10043 * We pad out the password packet to 256 bytes to make
10044 * it harder for an attacker to find the length of the
10047 * Anyone using a password longer than 256 bytes
10048 * probably doesn't have much to worry about from
10049 * people who find out how long their password is!
10051 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10052 ssh2_pkt_addstring(s->pktout, ssh->username);
10053 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10054 /* service requested */
10055 ssh2_pkt_addstring(s->pktout, "password");
10056 ssh2_pkt_addbool(s->pktout, FALSE);
10057 ssh2_pkt_addstring(s->pktout, s->password);
10058 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10059 logevent("Sent password");
10060 s->type = AUTH_TYPE_PASSWORD;
10063 * Wait for next packet, in case it's a password change
10066 crWaitUntilV(pktin);
10067 changereq_first_time = TRUE;
10069 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10072 * We're being asked for a new password
10073 * (perhaps not for the first time).
10074 * Loop until the server accepts it.
10077 int got_new = FALSE; /* not live over crReturn */
10078 char *prompt; /* not live over crReturn */
10079 int prompt_len; /* not live over crReturn */
10083 if (changereq_first_time)
10084 msg = "Server requested password change";
10086 msg = "Server rejected new password";
10088 c_write_str(ssh, msg);
10089 c_write_str(ssh, "\r\n");
10092 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10094 s->cur_prompt = new_prompts(ssh->frontend);
10095 s->cur_prompt->to_server = TRUE;
10096 s->cur_prompt->name = dupstr("New SSH password");
10097 s->cur_prompt->instruction =
10098 dupprintf("%.*s", prompt_len, prompt);
10099 s->cur_prompt->instr_reqd = TRUE;
10101 * There's no explicit requirement in the protocol
10102 * for the "old" passwords in the original and
10103 * password-change messages to be the same, and
10104 * apparently some Cisco kit supports password change
10105 * by the user entering a blank password originally
10106 * and the real password subsequently, so,
10107 * reluctantly, we prompt for the old password again.
10109 * (On the other hand, some servers don't even bother
10110 * to check this field.)
10112 add_prompt(s->cur_prompt,
10113 dupstr("Current password (blank for previously entered password): "),
10115 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10117 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10121 * Loop until the user manages to enter the same
10126 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10129 crWaitUntilV(!pktin);
10130 ret = get_userpass_input(s->cur_prompt, in, inlen);
10135 * Failed to get responses. Terminate.
10137 /* burn the evidence */
10138 free_prompts(s->cur_prompt);
10139 smemclr(s->password, strlen(s->password));
10140 sfree(s->password);
10141 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10142 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10148 * If the user specified a new original password
10149 * (IYSWIM), overwrite any previously specified
10151 * (A side effect is that the user doesn't have to
10152 * re-enter it if they louse up the new password.)
10154 if (s->cur_prompt->prompts[0]->result[0]) {
10155 smemclr(s->password, strlen(s->password));
10156 /* burn the evidence */
10157 sfree(s->password);
10159 dupstr(s->cur_prompt->prompts[0]->result);
10163 * Check the two new passwords match.
10165 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10166 s->cur_prompt->prompts[2]->result)
10169 /* They don't. Silly user. */
10170 c_write_str(ssh, "Passwords do not match\r\n");
10175 * Send the new password (along with the old one).
10176 * (see above for padding rationale)
10178 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10179 ssh2_pkt_addstring(s->pktout, ssh->username);
10180 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10181 /* service requested */
10182 ssh2_pkt_addstring(s->pktout, "password");
10183 ssh2_pkt_addbool(s->pktout, TRUE);
10184 ssh2_pkt_addstring(s->pktout, s->password);
10185 ssh2_pkt_addstring(s->pktout,
10186 s->cur_prompt->prompts[1]->result);
10187 free_prompts(s->cur_prompt);
10188 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10189 logevent("Sent new password");
10192 * Now see what the server has to say about it.
10193 * (If it's CHANGEREQ again, it's not happy with the
10196 crWaitUntilV(pktin);
10197 changereq_first_time = FALSE;
10202 * We need to reexamine the current pktin at the top
10203 * of the loop. Either:
10204 * - we weren't asked to change password at all, in
10205 * which case it's a SUCCESS or FAILURE with the
10207 * - we sent a new password, and the server was
10208 * either OK with it (SUCCESS or FAILURE w/partial
10209 * success) or unhappy with the _old_ password
10210 * (FAILURE w/o partial success)
10211 * In any of these cases, we go back to the top of
10212 * the loop and start again.
10217 * We don't need the old password any more, in any
10218 * case. Burn the evidence.
10220 smemclr(s->password, strlen(s->password));
10221 sfree(s->password);
10224 char *str = dupprintf("No supported authentication methods available"
10225 " (server sent: %.*s)",
10228 ssh_disconnect(ssh, str,
10229 "No supported authentication methods available",
10230 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10240 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10242 /* Clear up various bits and pieces from authentication. */
10243 if (s->publickey_blob) {
10244 sfree(s->publickey_algorithm);
10245 sfree(s->publickey_blob);
10246 sfree(s->publickey_comment);
10248 if (s->agent_response)
10249 sfree(s->agent_response);
10251 if (s->userauth_success && !ssh->bare_connection) {
10253 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10254 * packets since. Signal the transport layer to consider enacting
10255 * delayed compression.
10257 * (Relying on we_are_in is not sufficient, as
10258 * draft-miller-secsh-compression-delayed is quite clear that it
10259 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10260 * become set for other reasons.)
10262 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10265 ssh->channels = newtree234(ssh_channelcmp);
10268 * Set up handlers for some connection protocol messages, so we
10269 * don't have to handle them repeatedly in this coroutine.
10271 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10272 ssh2_msg_channel_window_adjust;
10273 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10274 ssh2_msg_global_request;
10277 * Create the main session channel.
10279 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10280 ssh->mainchan = NULL;
10282 ssh->mainchan = snew(struct ssh_channel);
10283 ssh->mainchan->ssh = ssh;
10284 ssh2_channel_init(ssh->mainchan);
10286 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10288 * Just start a direct-tcpip channel and use it as the main
10291 ssh_send_port_open(ssh->mainchan,
10292 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10293 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10295 ssh->ncmode = TRUE;
10297 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10298 logevent("Opening session as main channel");
10299 ssh2_pkt_send(ssh, s->pktout);
10300 ssh->ncmode = FALSE;
10302 crWaitUntilV(pktin);
10303 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10304 bombout(("Server refused to open channel"));
10306 /* FIXME: error data comes back in FAILURE packet */
10308 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10309 bombout(("Server's channel confirmation cited wrong channel"));
10312 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10313 ssh->mainchan->halfopen = FALSE;
10314 ssh->mainchan->type = CHAN_MAINSESSION;
10315 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10316 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10317 add234(ssh->channels, ssh->mainchan);
10318 update_specials_menu(ssh->frontend);
10319 logevent("Opened main channel");
10323 * Now we have a channel, make dispatch table entries for
10324 * general channel-based messages.
10326 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10327 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10328 ssh2_msg_channel_data;
10329 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10330 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10331 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10332 ssh2_msg_channel_open_confirmation;
10333 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10334 ssh2_msg_channel_open_failure;
10335 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10336 ssh2_msg_channel_request;
10337 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10338 ssh2_msg_channel_open;
10339 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10340 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10343 * Now the connection protocol is properly up and running, with
10344 * all those dispatch table entries, so it's safe to let
10345 * downstreams start trying to open extra channels through us.
10347 if (ssh->connshare)
10348 share_activate(ssh->connshare, ssh->v_s);
10350 if (ssh->mainchan && ssh_is_simple(ssh)) {
10352 * This message indicates to the server that we promise
10353 * not to try to run any other channel in parallel with
10354 * this one, so it's safe for it to advertise a very large
10355 * window and leave the flow control to TCP.
10357 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10358 "simple@putty.projects.tartarus.org",
10360 ssh2_pkt_send(ssh, s->pktout);
10364 * Enable port forwardings.
10366 ssh_setup_portfwd(ssh, ssh->conf);
10368 if (ssh->mainchan && !ssh->ncmode) {
10370 * Send the CHANNEL_REQUESTS for the main session channel.
10371 * Each one is handled by its own little asynchronous
10375 /* Potentially enable X11 forwarding. */
10376 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10378 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10380 if (!ssh->x11disp) {
10381 /* FIXME: return an error message from x11_setup_display */
10382 logevent("X11 forwarding not enabled: unable to"
10383 " initialise X display");
10385 ssh->x11auth = x11_invent_fake_auth
10386 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10387 ssh->x11auth->disp = ssh->x11disp;
10389 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10393 /* Potentially enable agent forwarding. */
10394 if (ssh_agent_forwarding_permitted(ssh))
10395 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10397 /* Now allocate a pty for the session. */
10398 if (!conf_get_int(ssh->conf, CONF_nopty))
10399 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10401 /* Send environment variables. */
10402 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10405 * Start a shell or a remote command. We may have to attempt
10406 * this twice if the config data has provided a second choice
10413 if (ssh->fallback_cmd) {
10414 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10415 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10417 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10418 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10422 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10423 ssh2_response_authconn, NULL);
10424 ssh2_pkt_addstring(s->pktout, cmd);
10426 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10427 ssh2_response_authconn, NULL);
10428 ssh2_pkt_addstring(s->pktout, cmd);
10430 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10431 ssh2_response_authconn, NULL);
10433 ssh2_pkt_send(ssh, s->pktout);
10435 crWaitUntilV(pktin);
10437 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10438 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10439 bombout(("Unexpected response to shell/command request:"
10440 " packet type %d", pktin->type));
10444 * We failed to start the command. If this is the
10445 * fallback command, we really are finished; if it's
10446 * not, and if the fallback command exists, try falling
10447 * back to it before complaining.
10449 if (!ssh->fallback_cmd &&
10450 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10451 logevent("Primary command failed; attempting fallback");
10452 ssh->fallback_cmd = TRUE;
10455 bombout(("Server refused to start a shell/command"));
10458 logevent("Started a shell/command");
10463 ssh->editing = ssh->echoing = TRUE;
10466 ssh->state = SSH_STATE_SESSION;
10467 if (ssh->size_needed)
10468 ssh_size(ssh, ssh->term_width, ssh->term_height);
10469 if (ssh->eof_needed)
10470 ssh_special(ssh, TS_EOF);
10476 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10481 s->try_send = FALSE;
10485 * _All_ the connection-layer packets we expect to
10486 * receive are now handled by the dispatch table.
10487 * Anything that reaches here must be bogus.
10490 bombout(("Strange packet received: type %d", pktin->type));
10492 } else if (ssh->mainchan) {
10494 * We have spare data. Add it to the channel buffer.
10496 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
10497 s->try_send = TRUE;
10501 struct ssh_channel *c;
10503 * Try to send data on all channels if we can.
10505 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
10506 ssh2_try_send_and_unthrottle(ssh, c);
10514 * Handlers for SSH-2 messages that might arrive at any moment.
10516 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10518 /* log reason code in disconnect message */
10520 int reason, msglen;
10522 reason = ssh_pkt_getuint32(pktin);
10523 ssh_pkt_getstring(pktin, &msg, &msglen);
10525 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10526 buf = dupprintf("Received disconnect message (%s)",
10527 ssh2_disconnect_reasons[reason]);
10529 buf = dupprintf("Received disconnect message (unknown"
10530 " type %d)", reason);
10534 buf = dupprintf("Disconnection message text: %.*s",
10537 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10539 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10540 ssh2_disconnect_reasons[reason] : "unknown",
10545 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10547 /* log the debug message */
10551 /* XXX maybe we should actually take notice of the return value */
10552 ssh2_pkt_getbool(pktin);
10553 ssh_pkt_getstring(pktin, &msg, &msglen);
10555 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
10558 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10560 do_ssh2_transport(ssh, NULL, 0, pktin);
10564 * Called if we receive a packet that isn't allowed by the protocol.
10565 * This only applies to packets whose meaning PuTTY understands.
10566 * Entirely unknown packets are handled below.
10568 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10570 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10571 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10573 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10577 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10579 struct Packet *pktout;
10580 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10581 ssh2_pkt_adduint32(pktout, pktin->sequence);
10583 * UNIMPLEMENTED messages MUST appear in the same order as the
10584 * messages they respond to. Hence, never queue them.
10586 ssh2_pkt_send_noqueue(ssh, pktout);
10590 * Handle the top-level SSH-2 protocol.
10592 static void ssh2_protocol_setup(Ssh ssh)
10597 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10599 for (i = 0; i < 256; i++)
10600 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10603 * Initially, we only accept transport messages (and a few generic
10604 * ones). do_ssh2_authconn will add more when it starts.
10605 * Messages that are understood but not currently acceptable go to
10606 * ssh2_msg_unexpected.
10608 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10609 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10610 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10611 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10612 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10613 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10614 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10615 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10616 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10617 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10618 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10619 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10620 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10621 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10622 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10623 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10624 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10625 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10626 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10627 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10628 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10629 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10630 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10631 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10632 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10633 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10634 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10635 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10636 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10637 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10638 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10639 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10640 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10643 * These messages have a special handler from the start.
10645 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10646 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10647 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10650 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10655 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10657 for (i = 0; i < 256; i++)
10658 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10661 * Initially, we set all ssh-connection messages to 'unexpected';
10662 * do_ssh2_authconn will fill things in properly. We also handle a
10663 * couple of messages from the transport protocol which aren't
10664 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10667 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10668 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10669 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10670 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10671 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10672 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10673 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10674 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10675 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10676 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10677 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10678 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10679 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10680 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10682 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10685 * These messages have a special handler from the start.
10687 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10688 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
10689 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10692 static void ssh2_timer(void *ctx, unsigned long now)
10694 Ssh ssh = (Ssh)ctx;
10696 if (ssh->state == SSH_STATE_CLOSED)
10699 if (!ssh->kex_in_progress && !ssh->bare_connection &&
10700 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
10701 now == ssh->next_rekey) {
10702 do_ssh2_transport(ssh, "timeout", -1, NULL);
10706 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
10707 struct Packet *pktin)
10709 const unsigned char *in = (const unsigned char *)vin;
10710 if (ssh->state == SSH_STATE_CLOSED)
10714 ssh->incoming_data_size += pktin->encrypted_len;
10715 if (!ssh->kex_in_progress &&
10716 ssh->max_data_size != 0 &&
10717 ssh->incoming_data_size > ssh->max_data_size)
10718 do_ssh2_transport(ssh, "too much data received", -1, NULL);
10722 ssh->packet_dispatch[pktin->type](ssh, pktin);
10723 else if (!ssh->protocol_initial_phase_done)
10724 do_ssh2_transport(ssh, in, inlen, pktin);
10726 do_ssh2_authconn(ssh, in, inlen, pktin);
10729 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
10730 struct Packet *pktin)
10732 const unsigned char *in = (const unsigned char *)vin;
10733 if (ssh->state == SSH_STATE_CLOSED)
10737 ssh->packet_dispatch[pktin->type](ssh, pktin);
10739 do_ssh2_authconn(ssh, in, inlen, pktin);
10742 static void ssh_cache_conf_values(Ssh ssh)
10744 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
10748 * Called to set up the connection.
10750 * Returns an error message, or NULL on success.
10752 static const char *ssh_init(void *frontend_handle, void **backend_handle,
10754 const char *host, int port, char **realhost,
10755 int nodelay, int keepalive)
10760 ssh = snew(struct ssh_tag);
10761 ssh->conf = conf_copy(conf);
10762 ssh_cache_conf_values(ssh);
10763 ssh->version = 0; /* when not ready yet */
10765 ssh->cipher = NULL;
10766 ssh->v1_cipher_ctx = NULL;
10767 ssh->crcda_ctx = NULL;
10768 ssh->cscipher = NULL;
10769 ssh->cs_cipher_ctx = NULL;
10770 ssh->sccipher = NULL;
10771 ssh->sc_cipher_ctx = NULL;
10773 ssh->cs_mac_ctx = NULL;
10775 ssh->sc_mac_ctx = NULL;
10776 ssh->cscomp = NULL;
10777 ssh->cs_comp_ctx = NULL;
10778 ssh->sccomp = NULL;
10779 ssh->sc_comp_ctx = NULL;
10781 ssh->kex_ctx = NULL;
10782 ssh->hostkey = NULL;
10783 ssh->hostkey_str = NULL;
10784 ssh->exitcode = -1;
10785 ssh->close_expected = FALSE;
10786 ssh->clean_exit = FALSE;
10787 ssh->state = SSH_STATE_PREPACKET;
10788 ssh->size_needed = FALSE;
10789 ssh->eof_needed = FALSE;
10791 ssh->logctx = NULL;
10792 ssh->deferred_send_data = NULL;
10793 ssh->deferred_len = 0;
10794 ssh->deferred_size = 0;
10795 ssh->fallback_cmd = 0;
10796 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
10797 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
10798 ssh->x11disp = NULL;
10799 ssh->x11auth = NULL;
10800 ssh->x11authtree = newtree234(x11_authcmp);
10801 ssh->v1_compressing = FALSE;
10802 ssh->v2_outgoing_sequence = 0;
10803 ssh->ssh1_rdpkt_crstate = 0;
10804 ssh->ssh2_rdpkt_crstate = 0;
10805 ssh->ssh2_bare_rdpkt_crstate = 0;
10806 ssh->ssh_gotdata_crstate = 0;
10807 ssh->do_ssh1_connection_crstate = 0;
10808 ssh->do_ssh_init_state = NULL;
10809 ssh->do_ssh_connection_init_state = NULL;
10810 ssh->do_ssh1_login_state = NULL;
10811 ssh->do_ssh2_transport_state = NULL;
10812 ssh->do_ssh2_authconn_state = NULL;
10815 ssh->mainchan = NULL;
10816 ssh->throttled_all = 0;
10817 ssh->v1_stdout_throttling = 0;
10819 ssh->queuelen = ssh->queuesize = 0;
10820 ssh->queueing = FALSE;
10821 ssh->qhead = ssh->qtail = NULL;
10822 ssh->deferred_rekey_reason = NULL;
10823 bufchain_init(&ssh->queued_incoming_data);
10824 ssh->frozen = FALSE;
10825 ssh->username = NULL;
10826 ssh->sent_console_eof = FALSE;
10827 ssh->got_pty = FALSE;
10828 ssh->bare_connection = FALSE;
10829 ssh->X11_fwd_enabled = FALSE;
10830 ssh->connshare = NULL;
10831 ssh->attempting_connshare = FALSE;
10833 *backend_handle = ssh;
10836 if (crypto_startup() == 0)
10837 return "Microsoft high encryption pack not installed!";
10840 ssh->frontend = frontend_handle;
10841 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
10842 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
10844 ssh->channels = NULL;
10845 ssh->rportfwds = NULL;
10846 ssh->portfwds = NULL;
10851 ssh->conn_throttle_count = 0;
10852 ssh->overall_bufsize = 0;
10853 ssh->fallback_cmd = 0;
10855 ssh->protocol = NULL;
10857 ssh->protocol_initial_phase_done = FALSE;
10859 ssh->pinger = NULL;
10861 ssh->incoming_data_size = ssh->outgoing_data_size =
10862 ssh->deferred_data_size = 0L;
10863 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10864 CONF_ssh_rekey_data));
10865 ssh->kex_in_progress = FALSE;
10868 ssh->gsslibs = NULL;
10871 random_ref(); /* do this now - may be needed by sharing setup code */
10873 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
10882 static void ssh_free(void *handle)
10884 Ssh ssh = (Ssh) handle;
10885 struct ssh_channel *c;
10886 struct ssh_rportfwd *pf;
10887 struct X11FakeAuth *auth;
10889 if (ssh->v1_cipher_ctx)
10890 ssh->cipher->free_context(ssh->v1_cipher_ctx);
10891 if (ssh->cs_cipher_ctx)
10892 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
10893 if (ssh->sc_cipher_ctx)
10894 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
10895 if (ssh->cs_mac_ctx)
10896 ssh->csmac->free_context(ssh->cs_mac_ctx);
10897 if (ssh->sc_mac_ctx)
10898 ssh->scmac->free_context(ssh->sc_mac_ctx);
10899 if (ssh->cs_comp_ctx) {
10901 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
10903 zlib_compress_cleanup(ssh->cs_comp_ctx);
10905 if (ssh->sc_comp_ctx) {
10907 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
10909 zlib_decompress_cleanup(ssh->sc_comp_ctx);
10912 dh_cleanup(ssh->kex_ctx);
10913 sfree(ssh->savedhost);
10915 while (ssh->queuelen-- > 0)
10916 ssh_free_packet(ssh->queue[ssh->queuelen]);
10919 while (ssh->qhead) {
10920 struct queued_handler *qh = ssh->qhead;
10921 ssh->qhead = qh->next;
10924 ssh->qhead = ssh->qtail = NULL;
10926 if (ssh->channels) {
10927 while ((c = delpos234(ssh->channels, 0)) != NULL) {
10930 if (c->u.x11.xconn != NULL)
10931 x11_close(c->u.x11.xconn);
10933 case CHAN_SOCKDATA:
10934 case CHAN_SOCKDATA_DORMANT:
10935 if (c->u.pfd.pf != NULL)
10936 pfd_close(c->u.pfd.pf);
10939 if (ssh->version == 2) {
10940 struct outstanding_channel_request *ocr, *nocr;
10941 ocr = c->v.v2.chanreq_head;
10943 ocr->handler(c, NULL, ocr->ctx);
10948 bufchain_clear(&c->v.v2.outbuffer);
10952 freetree234(ssh->channels);
10953 ssh->channels = NULL;
10956 if (ssh->connshare)
10957 sharestate_free(ssh->connshare);
10959 if (ssh->rportfwds) {
10960 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
10962 freetree234(ssh->rportfwds);
10963 ssh->rportfwds = NULL;
10965 sfree(ssh->deferred_send_data);
10967 x11_free_display(ssh->x11disp);
10968 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
10969 x11_free_fake_auth(auth);
10970 freetree234(ssh->x11authtree);
10971 sfree(ssh->do_ssh_init_state);
10972 sfree(ssh->do_ssh1_login_state);
10973 sfree(ssh->do_ssh2_transport_state);
10974 sfree(ssh->do_ssh2_authconn_state);
10977 sfree(ssh->fullhostname);
10978 sfree(ssh->hostkey_str);
10979 if (ssh->crcda_ctx) {
10980 crcda_free_context(ssh->crcda_ctx);
10981 ssh->crcda_ctx = NULL;
10984 ssh_do_close(ssh, TRUE);
10985 expire_timer_context(ssh);
10987 pinger_free(ssh->pinger);
10988 bufchain_clear(&ssh->queued_incoming_data);
10989 sfree(ssh->username);
10990 conf_free(ssh->conf);
10993 ssh_gss_cleanup(ssh->gsslibs);
11001 * Reconfigure the SSH backend.
11003 static void ssh_reconfig(void *handle, Conf *conf)
11005 Ssh ssh = (Ssh) handle;
11006 const char *rekeying = NULL;
11007 int rekey_mandatory = FALSE;
11008 unsigned long old_max_data_size;
11011 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11013 ssh_setup_portfwd(ssh, conf);
11015 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11016 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11018 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11019 unsigned long now = GETTICKCOUNT();
11021 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11022 rekeying = "timeout shortened";
11024 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11028 old_max_data_size = ssh->max_data_size;
11029 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11030 CONF_ssh_rekey_data));
11031 if (old_max_data_size != ssh->max_data_size &&
11032 ssh->max_data_size != 0) {
11033 if (ssh->outgoing_data_size > ssh->max_data_size ||
11034 ssh->incoming_data_size > ssh->max_data_size)
11035 rekeying = "data limit lowered";
11038 if (conf_get_int(ssh->conf, CONF_compression) !=
11039 conf_get_int(conf, CONF_compression)) {
11040 rekeying = "compression setting changed";
11041 rekey_mandatory = TRUE;
11044 for (i = 0; i < CIPHER_MAX; i++)
11045 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11046 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11047 rekeying = "cipher settings changed";
11048 rekey_mandatory = TRUE;
11050 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11051 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11052 rekeying = "cipher settings changed";
11053 rekey_mandatory = TRUE;
11056 conf_free(ssh->conf);
11057 ssh->conf = conf_copy(conf);
11058 ssh_cache_conf_values(ssh);
11060 if (!ssh->bare_connection && rekeying) {
11061 if (!ssh->kex_in_progress) {
11062 do_ssh2_transport(ssh, rekeying, -1, NULL);
11063 } else if (rekey_mandatory) {
11064 ssh->deferred_rekey_reason = rekeying;
11070 * Called to send data down the SSH connection.
11072 static int ssh_send(void *handle, const char *buf, int len)
11074 Ssh ssh = (Ssh) handle;
11076 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11079 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11081 return ssh_sendbuffer(ssh);
11085 * Called to query the current amount of buffered stdin data.
11087 static int ssh_sendbuffer(void *handle)
11089 Ssh ssh = (Ssh) handle;
11090 int override_value;
11092 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11096 * If the SSH socket itself has backed up, add the total backup
11097 * size on that to any individual buffer on the stdin channel.
11099 override_value = 0;
11100 if (ssh->throttled_all)
11101 override_value = ssh->overall_bufsize;
11103 if (ssh->version == 1) {
11104 return override_value;
11105 } else if (ssh->version == 2) {
11106 if (!ssh->mainchan)
11107 return override_value;
11109 return (override_value +
11110 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11117 * Called to set the size of the window from SSH's POV.
11119 static void ssh_size(void *handle, int width, int height)
11121 Ssh ssh = (Ssh) handle;
11122 struct Packet *pktout;
11124 ssh->term_width = width;
11125 ssh->term_height = height;
11127 switch (ssh->state) {
11128 case SSH_STATE_BEFORE_SIZE:
11129 case SSH_STATE_PREPACKET:
11130 case SSH_STATE_CLOSED:
11131 break; /* do nothing */
11132 case SSH_STATE_INTERMED:
11133 ssh->size_needed = TRUE; /* buffer for later */
11135 case SSH_STATE_SESSION:
11136 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11137 if (ssh->version == 1) {
11138 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11139 PKT_INT, ssh->term_height,
11140 PKT_INT, ssh->term_width,
11141 PKT_INT, 0, PKT_INT, 0, PKT_END);
11142 } else if (ssh->mainchan) {
11143 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11145 ssh2_pkt_adduint32(pktout, ssh->term_width);
11146 ssh2_pkt_adduint32(pktout, ssh->term_height);
11147 ssh2_pkt_adduint32(pktout, 0);
11148 ssh2_pkt_adduint32(pktout, 0);
11149 ssh2_pkt_send(ssh, pktout);
11157 * Return a list of the special codes that make sense in this
11160 static const struct telnet_special *ssh_get_specials(void *handle)
11162 static const struct telnet_special ssh1_ignore_special[] = {
11163 {"IGNORE message", TS_NOP}
11165 static const struct telnet_special ssh2_ignore_special[] = {
11166 {"IGNORE message", TS_NOP},
11168 static const struct telnet_special ssh2_rekey_special[] = {
11169 {"Repeat key exchange", TS_REKEY},
11171 static const struct telnet_special ssh2_session_specials[] = {
11174 /* These are the signal names defined by RFC 4254.
11175 * They include all the ISO C signals, but are a subset of the POSIX
11176 * required signals. */
11177 {"SIGINT (Interrupt)", TS_SIGINT},
11178 {"SIGTERM (Terminate)", TS_SIGTERM},
11179 {"SIGKILL (Kill)", TS_SIGKILL},
11180 {"SIGQUIT (Quit)", TS_SIGQUIT},
11181 {"SIGHUP (Hangup)", TS_SIGHUP},
11182 {"More signals", TS_SUBMENU},
11183 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11184 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11185 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11186 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11187 {NULL, TS_EXITMENU}
11189 static const struct telnet_special specials_end[] = {
11190 {NULL, TS_EXITMENU}
11192 /* XXX review this length for any changes: */
11193 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
11194 lenof(ssh2_rekey_special) +
11195 lenof(ssh2_session_specials) +
11196 lenof(specials_end)];
11197 Ssh ssh = (Ssh) handle;
11199 #define ADD_SPECIALS(name) \
11201 assert((i + lenof(name)) <= lenof(ssh_specials)); \
11202 memcpy(&ssh_specials[i], name, sizeof name); \
11203 i += lenof(name); \
11206 if (ssh->version == 1) {
11207 /* Don't bother offering IGNORE if we've decided the remote
11208 * won't cope with it, since we wouldn't bother sending it if
11210 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11211 ADD_SPECIALS(ssh1_ignore_special);
11212 } else if (ssh->version == 2) {
11213 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11214 ADD_SPECIALS(ssh2_ignore_special);
11215 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11216 ADD_SPECIALS(ssh2_rekey_special);
11218 ADD_SPECIALS(ssh2_session_specials);
11219 } /* else we're not ready yet */
11222 ADD_SPECIALS(specials_end);
11223 return ssh_specials;
11227 #undef ADD_SPECIALS
11231 * Send special codes. TS_EOF is useful for `plink', so you
11232 * can send an EOF and collect resulting output (e.g. `plink
11235 static void ssh_special(void *handle, Telnet_Special code)
11237 Ssh ssh = (Ssh) handle;
11238 struct Packet *pktout;
11240 if (code == TS_EOF) {
11241 if (ssh->state != SSH_STATE_SESSION) {
11243 * Buffer the EOF in case we are pre-SESSION, so we can
11244 * send it as soon as we reach SESSION.
11246 if (code == TS_EOF)
11247 ssh->eof_needed = TRUE;
11250 if (ssh->version == 1) {
11251 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11252 } else if (ssh->mainchan) {
11253 sshfwd_write_eof(ssh->mainchan);
11254 ssh->send_ok = 0; /* now stop trying to read from stdin */
11256 logevent("Sent EOF message");
11257 } else if (code == TS_PING || code == TS_NOP) {
11258 if (ssh->state == SSH_STATE_CLOSED
11259 || ssh->state == SSH_STATE_PREPACKET) return;
11260 if (ssh->version == 1) {
11261 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11262 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11264 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11265 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11266 ssh2_pkt_addstring_start(pktout);
11267 ssh2_pkt_send_noqueue(ssh, pktout);
11270 } else if (code == TS_REKEY) {
11271 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11272 ssh->version == 2) {
11273 do_ssh2_transport(ssh, "at user request", -1, NULL);
11275 } else if (code == TS_BRK) {
11276 if (ssh->state == SSH_STATE_CLOSED
11277 || ssh->state == SSH_STATE_PREPACKET) return;
11278 if (ssh->version == 1) {
11279 logevent("Unable to send BREAK signal in SSH-1");
11280 } else if (ssh->mainchan) {
11281 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11282 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11283 ssh2_pkt_send(ssh, pktout);
11286 /* Is is a POSIX signal? */
11287 const char *signame = NULL;
11288 if (code == TS_SIGABRT) signame = "ABRT";
11289 if (code == TS_SIGALRM) signame = "ALRM";
11290 if (code == TS_SIGFPE) signame = "FPE";
11291 if (code == TS_SIGHUP) signame = "HUP";
11292 if (code == TS_SIGILL) signame = "ILL";
11293 if (code == TS_SIGINT) signame = "INT";
11294 if (code == TS_SIGKILL) signame = "KILL";
11295 if (code == TS_SIGPIPE) signame = "PIPE";
11296 if (code == TS_SIGQUIT) signame = "QUIT";
11297 if (code == TS_SIGSEGV) signame = "SEGV";
11298 if (code == TS_SIGTERM) signame = "TERM";
11299 if (code == TS_SIGUSR1) signame = "USR1";
11300 if (code == TS_SIGUSR2) signame = "USR2";
11301 /* The SSH-2 protocol does in principle support arbitrary named
11302 * signals, including signame@domain, but we don't support those. */
11304 /* It's a signal. */
11305 if (ssh->version == 2 && ssh->mainchan) {
11306 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11307 ssh2_pkt_addstring(pktout, signame);
11308 ssh2_pkt_send(ssh, pktout);
11309 logeventf(ssh, "Sent signal SIG%s", signame);
11312 /* Never heard of it. Do nothing */
11317 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11319 Ssh ssh = (Ssh) handle;
11320 struct ssh_channel *c;
11321 c = snew(struct ssh_channel);
11324 ssh2_channel_init(c);
11325 c->halfopen = TRUE;
11326 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11328 add234(ssh->channels, c);
11332 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11334 struct ssh_channel *c;
11335 c = snew(struct ssh_channel);
11338 ssh2_channel_init(c);
11339 c->type = CHAN_SHARING;
11340 c->u.sharing.ctx = sharing_ctx;
11341 add234(ssh->channels, c);
11345 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11347 struct ssh_channel *c;
11349 c = find234(ssh->channels, &localid, ssh_channelfind);
11351 ssh_channel_destroy(c);
11354 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11355 const void *data, int datalen,
11356 const char *additional_log_text)
11358 struct Packet *pkt;
11360 pkt = ssh2_pkt_init(type);
11361 pkt->downstream_id = id;
11362 pkt->additional_log_text = additional_log_text;
11363 ssh2_pkt_adddata(pkt, data, datalen);
11364 ssh2_pkt_send(ssh, pkt);
11368 * This is called when stdout/stderr (the entity to which
11369 * from_backend sends data) manages to clear some backlog.
11371 static void ssh_unthrottle(void *handle, int bufsize)
11373 Ssh ssh = (Ssh) handle;
11376 if (ssh->version == 1) {
11377 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11378 ssh->v1_stdout_throttling = 0;
11379 ssh_throttle_conn(ssh, -1);
11382 if (ssh->mainchan) {
11383 ssh2_set_window(ssh->mainchan,
11384 bufsize < ssh->mainchan->v.v2.locmaxwin ?
11385 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11386 if (ssh_is_simple(ssh))
11389 buflimit = ssh->mainchan->v.v2.locmaxwin;
11390 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11391 ssh->mainchan->throttling_conn = 0;
11392 ssh_throttle_conn(ssh, -1);
11398 * Now process any SSH connection data that was stashed in our
11399 * queue while we were frozen.
11401 ssh_process_queued_incoming_data(ssh);
11404 void ssh_send_port_open(void *channel, const char *hostname, int port,
11407 struct ssh_channel *c = (struct ssh_channel *)channel;
11409 struct Packet *pktout;
11411 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11413 if (ssh->version == 1) {
11414 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11415 PKT_INT, c->localid,
11418 /* PKT_STR, <org:orgport>, */
11421 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11423 char *trimmed_host = host_strduptrim(hostname);
11424 ssh2_pkt_addstring(pktout, trimmed_host);
11425 sfree(trimmed_host);
11427 ssh2_pkt_adduint32(pktout, port);
11429 * We make up values for the originator data; partly it's
11430 * too much hassle to keep track, and partly I'm not
11431 * convinced the server should be told details like that
11432 * about my local network configuration.
11433 * The "originator IP address" is syntactically a numeric
11434 * IP address, and some servers (e.g., Tectia) get upset
11435 * if it doesn't match this syntax.
11437 ssh2_pkt_addstring(pktout, "0.0.0.0");
11438 ssh2_pkt_adduint32(pktout, 0);
11439 ssh2_pkt_send(ssh, pktout);
11443 static int ssh_connected(void *handle)
11445 Ssh ssh = (Ssh) handle;
11446 return ssh->s != NULL;
11449 static int ssh_sendok(void *handle)
11451 Ssh ssh = (Ssh) handle;
11452 return ssh->send_ok;
11455 static int ssh_ldisc(void *handle, int option)
11457 Ssh ssh = (Ssh) handle;
11458 if (option == LD_ECHO)
11459 return ssh->echoing;
11460 if (option == LD_EDIT)
11461 return ssh->editing;
11465 static void ssh_provide_ldisc(void *handle, void *ldisc)
11467 Ssh ssh = (Ssh) handle;
11468 ssh->ldisc = ldisc;
11471 static void ssh_provide_logctx(void *handle, void *logctx)
11473 Ssh ssh = (Ssh) handle;
11474 ssh->logctx = logctx;
11477 static int ssh_return_exitcode(void *handle)
11479 Ssh ssh = (Ssh) handle;
11480 if (ssh->s != NULL)
11483 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11487 * cfg_info for SSH is the protocol running in this session.
11488 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11489 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11491 static int ssh_cfg_info(void *handle)
11493 Ssh ssh = (Ssh) handle;
11494 if (ssh->version == 0)
11495 return 0; /* don't know yet */
11496 else if (ssh->bare_connection)
11499 return ssh->version;
11503 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11504 * that fails. This variable is the means by which scp.c can reach
11505 * into the SSH code and find out which one it got.
11507 extern int ssh_fallback_cmd(void *handle)
11509 Ssh ssh = (Ssh) handle;
11510 return ssh->fallback_cmd;
11513 Backend ssh_backend = {
11523 ssh_return_exitcode,
11527 ssh_provide_logctx,