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
1652 * unencrypted, unless the cipher supports length encryption.
1654 for (st->i = st->len = 0; st->i < 4; st->i++) {
1655 while ((*datalen) == 0)
1657 st->pktin->data[st->i] = *(*data)++;
1660 /* Cipher supports length decryption, so do it */
1661 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
1662 /* Keep the packet the same though, so the MAC passes */
1663 unsigned char len[4];
1664 memcpy(len, st->pktin->data, 4);
1665 ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
1666 st->len = toint(GET_32BIT(len));
1668 st->len = toint(GET_32BIT(st->pktin->data));
1672 * _Completely_ silly lengths should be stomped on before they
1673 * do us any more damage.
1675 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1676 st->len % st->cipherblk != 0) {
1677 bombout(("Incoming packet length field was garbled"));
1678 ssh_free_packet(st->pktin);
1683 * So now we can work out the total packet length.
1685 st->packetlen = st->len + 4;
1688 * Allocate memory for the rest of the packet.
1690 st->pktin->maxlen = st->packetlen + st->maclen;
1691 st->pktin->data = sresize(st->pktin->data,
1692 st->pktin->maxlen + APIEXTRA,
1696 * Read the remainder of the packet.
1698 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1699 while ((*datalen) == 0)
1701 st->pktin->data[st->i] = *(*data)++;
1709 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1710 st->len + 4, st->incoming_sequence)) {
1711 bombout(("Incorrect MAC received on packet"));
1712 ssh_free_packet(st->pktin);
1716 /* Decrypt everything between the length field and the MAC. */
1718 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1719 st->pktin->data + 4,
1722 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1725 * Acquire and decrypt the first block of the packet. This will
1726 * contain the length and padding details.
1728 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1729 while ((*datalen) == 0)
1731 st->pktin->data[st->i] = *(*data)++;
1736 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1737 st->pktin->data, st->cipherblk);
1740 * Now get the length figure.
1742 st->len = toint(GET_32BIT(st->pktin->data));
1745 * _Completely_ silly lengths should be stomped on before they
1746 * do us any more damage.
1748 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1749 (st->len + 4) % st->cipherblk != 0) {
1750 bombout(("Incoming packet was garbled on decryption"));
1751 ssh_free_packet(st->pktin);
1756 * So now we can work out the total packet length.
1758 st->packetlen = st->len + 4;
1761 * Allocate memory for the rest of the packet.
1763 st->pktin->maxlen = st->packetlen + st->maclen;
1764 st->pktin->data = sresize(st->pktin->data,
1765 st->pktin->maxlen + APIEXTRA,
1769 * Read and decrypt the remainder of the packet.
1771 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1773 while ((*datalen) == 0)
1775 st->pktin->data[st->i] = *(*data)++;
1778 /* Decrypt everything _except_ the MAC. */
1780 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1781 st->pktin->data + st->cipherblk,
1782 st->packetlen - st->cipherblk);
1788 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1789 st->len + 4, st->incoming_sequence)) {
1790 bombout(("Incorrect MAC received on packet"));
1791 ssh_free_packet(st->pktin);
1795 /* Get and sanity-check the amount of random padding. */
1796 st->pad = st->pktin->data[4];
1797 if (st->pad < 4 || st->len - st->pad < 1) {
1798 bombout(("Invalid padding length on received packet"));
1799 ssh_free_packet(st->pktin);
1803 * This enables us to deduce the payload length.
1805 st->payload = st->len - st->pad - 1;
1807 st->pktin->length = st->payload + 5;
1808 st->pktin->encrypted_len = st->packetlen;
1810 st->pktin->sequence = st->incoming_sequence++;
1812 st->pktin->length = st->packetlen - st->pad;
1813 assert(st->pktin->length >= 0);
1816 * Decompress packet payload.
1819 unsigned char *newpayload;
1822 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1823 st->pktin->data + 5, st->pktin->length - 5,
1824 &newpayload, &newlen)) {
1825 if (st->pktin->maxlen < newlen + 5) {
1826 st->pktin->maxlen = newlen + 5;
1827 st->pktin->data = sresize(st->pktin->data,
1828 st->pktin->maxlen + APIEXTRA,
1831 st->pktin->length = 5 + newlen;
1832 memcpy(st->pktin->data + 5, newpayload, newlen);
1838 * pktin->body and pktin->length should identify the semantic
1839 * content of the packet, excluding the initial type byte.
1841 st->pktin->type = st->pktin->data[5];
1842 st->pktin->body = st->pktin->data + 6;
1843 st->pktin->length -= 6;
1844 assert(st->pktin->length >= 0); /* one last double-check */
1847 ssh2_log_incoming_packet(ssh, st->pktin);
1849 st->pktin->savedpos = 0;
1851 crFinish(st->pktin);
1854 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
1855 const unsigned char **data,
1858 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1860 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1863 * Read the packet length field.
1865 for (st->i = 0; st->i < 4; st->i++) {
1866 while ((*datalen) == 0)
1868 st->length[st->i] = *(*data)++;
1872 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1873 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1874 bombout(("Invalid packet length received"));
1878 st->pktin = ssh_new_packet();
1879 st->pktin->data = snewn(st->packetlen, unsigned char);
1881 st->pktin->encrypted_len = st->packetlen;
1883 st->pktin->sequence = st->incoming_sequence++;
1886 * Read the remainder of the packet.
1888 for (st->i = 0; st->i < st->packetlen; st->i++) {
1889 while ((*datalen) == 0)
1891 st->pktin->data[st->i] = *(*data)++;
1896 * pktin->body and pktin->length should identify the semantic
1897 * content of the packet, excluding the initial type byte.
1899 st->pktin->type = st->pktin->data[0];
1900 st->pktin->body = st->pktin->data + 1;
1901 st->pktin->length = st->packetlen - 1;
1904 * Log incoming packet, possibly omitting sensitive fields.
1907 ssh2_log_incoming_packet(ssh, st->pktin);
1909 st->pktin->savedpos = 0;
1911 crFinish(st->pktin);
1914 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1916 int pad, biglen, i, pktoffs;
1920 * XXX various versions of SC (including 8.8.4) screw up the
1921 * register allocation in this function and use the same register
1922 * (D6) for len and as a temporary, with predictable results. The
1923 * following sledgehammer prevents this.
1930 ssh1_log_outgoing_packet(ssh, pkt);
1932 if (ssh->v1_compressing) {
1933 unsigned char *compblk;
1935 zlib_compress_block(ssh->cs_comp_ctx,
1936 pkt->data + 12, pkt->length - 12,
1937 &compblk, &complen);
1938 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1939 memcpy(pkt->data + 12, compblk, complen);
1941 pkt->length = complen + 12;
1944 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1946 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1947 pad = 8 - (len % 8);
1949 biglen = len + pad; /* len(padding+type+data+CRC) */
1951 for (i = pktoffs; i < 4+8; i++)
1952 pkt->data[i] = random_byte();
1953 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1954 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1955 PUT_32BIT(pkt->data + pktoffs, len);
1958 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1959 pkt->data + pktoffs + 4, biglen);
1961 if (offset_p) *offset_p = pktoffs;
1962 return biglen + 4; /* len(length+padding+type+data+CRC) */
1965 static int s_write(Ssh ssh, void *data, int len)
1968 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1969 0, NULL, NULL, 0, NULL);
1972 return sk_write(ssh->s, (char *)data, len);
1975 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1977 int len, backlog, offset;
1978 len = s_wrpkt_prepare(ssh, pkt, &offset);
1979 backlog = s_write(ssh, pkt->data + offset, len);
1980 if (backlog > SSH_MAX_BACKLOG)
1981 ssh_throttle_all(ssh, 1, backlog);
1982 ssh_free_packet(pkt);
1985 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1988 len = s_wrpkt_prepare(ssh, pkt, &offset);
1989 if (ssh->deferred_len + len > ssh->deferred_size) {
1990 ssh->deferred_size = ssh->deferred_len + len + 128;
1991 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1995 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1996 pkt->data + offset, len);
1997 ssh->deferred_len += len;
1998 ssh_free_packet(pkt);
2002 * Construct a SSH-1 packet with the specified contents.
2003 * (This all-at-once interface used to be the only one, but now SSH-1
2004 * packets can also be constructed incrementally.)
2006 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
2012 pkt = ssh1_pkt_init(pkttype);
2014 while ((argtype = va_arg(ap, int)) != PKT_END) {
2015 unsigned char *argp, argchar;
2017 unsigned long argint;
2020 /* Actual fields in the packet */
2022 argint = va_arg(ap, int);
2023 ssh_pkt_adduint32(pkt, argint);
2026 argchar = (unsigned char) va_arg(ap, int);
2027 ssh_pkt_addbyte(pkt, argchar);
2030 argp = va_arg(ap, unsigned char *);
2031 arglen = va_arg(ap, int);
2032 ssh_pkt_adddata(pkt, argp, arglen);
2035 sargp = va_arg(ap, char *);
2036 ssh_pkt_addstring(pkt, sargp);
2039 bn = va_arg(ap, Bignum);
2040 ssh1_pkt_addmp(pkt, bn);
2048 static void send_packet(Ssh ssh, int pkttype, ...)
2052 va_start(ap, pkttype);
2053 pkt = construct_packet(ssh, pkttype, ap);
2058 static void defer_packet(Ssh ssh, int pkttype, ...)
2062 va_start(ap, pkttype);
2063 pkt = construct_packet(ssh, pkttype, ap);
2065 s_wrpkt_defer(ssh, pkt);
2068 static int ssh_versioncmp(const char *a, const char *b)
2071 unsigned long av, bv;
2073 av = strtoul(a, &ae, 10);
2074 bv = strtoul(b, &be, 10);
2076 return (av < bv ? -1 : +1);
2081 av = strtoul(ae, &ae, 10);
2082 bv = strtoul(be, &be, 10);
2084 return (av < bv ? -1 : +1);
2089 * Utility routines for putting an SSH-protocol `string' and
2090 * `uint32' into a hash state.
2092 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2094 unsigned char lenblk[4];
2095 PUT_32BIT(lenblk, len);
2096 h->bytes(s, lenblk, 4);
2097 h->bytes(s, str, len);
2100 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2102 unsigned char intblk[4];
2103 PUT_32BIT(intblk, i);
2104 h->bytes(s, intblk, 4);
2108 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2110 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2112 if (pkt->maxlen < length) {
2113 unsigned char *body = pkt->body;
2114 int offset = body ? body - pkt->data : 0;
2115 pkt->maxlen = length + 256;
2116 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2117 if (body) pkt->body = pkt->data + offset;
2120 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2123 ssh_pkt_ensure(pkt, pkt->length);
2124 memcpy(pkt->data + pkt->length - len, data, len);
2126 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2128 ssh_pkt_adddata(pkt, &byte, 1);
2130 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2132 ssh_pkt_adddata(pkt, &value, 1);
2134 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2137 PUT_32BIT(x, value);
2138 ssh_pkt_adddata(pkt, x, 4);
2140 static void ssh_pkt_addstring_start(struct Packet *pkt)
2142 ssh_pkt_adduint32(pkt, 0);
2143 pkt->savedpos = pkt->length;
2145 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2148 ssh_pkt_adddata(pkt, data, len);
2149 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2151 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2153 ssh_pkt_addstring_data(pkt, data, strlen(data));
2155 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2157 ssh_pkt_addstring_start(pkt);
2158 ssh_pkt_addstring_str(pkt, data);
2160 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2162 int len = ssh1_bignum_length(b);
2163 unsigned char *data = snewn(len, unsigned char);
2164 (void) ssh1_write_bignum(data, b);
2165 ssh_pkt_adddata(pkt, data, len);
2168 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2171 int i, n = (bignum_bitcount(b) + 7) / 8;
2172 p = snewn(n + 1, unsigned char);
2174 for (i = 1; i <= n; i++)
2175 p[i] = bignum_byte(b, n - i);
2177 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2179 memmove(p, p + i, n + 1 - i);
2183 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2187 p = ssh2_mpint_fmt(b, &len);
2188 ssh_pkt_addstring_start(pkt);
2189 ssh_pkt_addstring_data(pkt, (char *)p, len);
2193 static struct Packet *ssh1_pkt_init(int pkt_type)
2195 struct Packet *pkt = ssh_new_packet();
2196 pkt->length = 4 + 8; /* space for length + max padding */
2197 ssh_pkt_addbyte(pkt, pkt_type);
2198 pkt->body = pkt->data + pkt->length;
2199 pkt->type = pkt_type;
2200 pkt->downstream_id = 0;
2201 pkt->additional_log_text = NULL;
2205 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2206 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2207 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2208 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2209 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2210 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2211 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2212 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2213 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2215 static struct Packet *ssh2_pkt_init(int pkt_type)
2217 struct Packet *pkt = ssh_new_packet();
2218 pkt->length = 5; /* space for packet length + padding length */
2220 pkt->type = pkt_type;
2221 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2222 pkt->body = pkt->data + pkt->length; /* after packet type */
2223 pkt->downstream_id = 0;
2224 pkt->additional_log_text = NULL;
2229 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2230 * put the MAC on it. Final packet, ready to be sent, is stored in
2231 * pkt->data. Total length is returned.
2233 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2235 int cipherblk, maclen, padding, unencrypted_prefix, i;
2238 ssh2_log_outgoing_packet(ssh, pkt);
2240 if (ssh->bare_connection) {
2242 * Trivial packet construction for the bare connection
2245 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2246 pkt->body = pkt->data + 1;
2247 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2248 return pkt->length - 1;
2252 * Compress packet payload.
2255 unsigned char *newpayload;
2258 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2260 &newpayload, &newlen)) {
2262 ssh2_pkt_adddata(pkt, newpayload, newlen);
2268 * Add padding. At least four bytes, and must also bring total
2269 * length (minus MAC) up to a multiple of the block size.
2270 * If pkt->forcepad is set, make sure the packet is at least that size
2273 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2274 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2276 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2277 if (pkt->length + padding < pkt->forcepad)
2278 padding = pkt->forcepad - pkt->length;
2280 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2282 assert(padding <= 255);
2283 maclen = ssh->csmac ? ssh->csmac->len : 0;
2284 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2285 pkt->data[4] = padding;
2286 for (i = 0; i < padding; i++)
2287 pkt->data[pkt->length + i] = random_byte();
2288 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2290 /* Encrypt length if the scheme requires it */
2291 if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
2292 ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
2293 ssh->v2_outgoing_sequence);
2296 if (ssh->csmac && ssh->csmac_etm) {
2298 * OpenSSH-defined encrypt-then-MAC protocol.
2301 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2302 pkt->data + 4, pkt->length + padding - 4);
2303 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2304 pkt->length + padding,
2305 ssh->v2_outgoing_sequence);
2308 * SSH-2 standard protocol.
2311 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2312 pkt->length + padding,
2313 ssh->v2_outgoing_sequence);
2315 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2316 pkt->data, pkt->length + padding);
2319 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2320 pkt->encrypted_len = pkt->length + padding;
2322 /* Ready-to-send packet starts at pkt->data. We return length. */
2323 pkt->body = pkt->data;
2324 return pkt->length + padding + maclen;
2328 * Routines called from the main SSH code to send packets. There
2329 * are quite a few of these, because we have two separate
2330 * mechanisms for delaying the sending of packets:
2332 * - In order to send an IGNORE message and a password message in
2333 * a single fixed-length blob, we require the ability to
2334 * concatenate the encrypted forms of those two packets _into_ a
2335 * single blob and then pass it to our <network.h> transport
2336 * layer in one go. Hence, there's a deferment mechanism which
2337 * works after packet encryption.
2339 * - In order to avoid sending any connection-layer messages
2340 * during repeat key exchange, we have to queue up any such
2341 * outgoing messages _before_ they are encrypted (and in
2342 * particular before they're allocated sequence numbers), and
2343 * then send them once we've finished.
2345 * I call these mechanisms `defer' and `queue' respectively, so as
2346 * to distinguish them reasonably easily.
2348 * The functions send_noqueue() and defer_noqueue() free the packet
2349 * structure they are passed. Every outgoing packet goes through
2350 * precisely one of these functions in its life; packets passed to
2351 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2352 * these or get queued, and then when the queue is later emptied
2353 * the packets are all passed to defer_noqueue().
2355 * When using a CBC-mode cipher, it's necessary to ensure that an
2356 * attacker can't provide data to be encrypted using an IV that they
2357 * know. We ensure this by prefixing each packet that might contain
2358 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2359 * mechanism, so in this case send_noqueue() ends up redirecting to
2360 * defer_noqueue(). If you don't like this inefficiency, don't use
2364 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2365 static void ssh_pkt_defersend(Ssh);
2368 * Send an SSH-2 packet immediately, without queuing or deferring.
2370 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2374 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2375 /* We need to send two packets, so use the deferral mechanism. */
2376 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2377 ssh_pkt_defersend(ssh);
2380 len = ssh2_pkt_construct(ssh, pkt);
2381 backlog = s_write(ssh, pkt->body, len);
2382 if (backlog > SSH_MAX_BACKLOG)
2383 ssh_throttle_all(ssh, 1, backlog);
2385 ssh->outgoing_data_size += pkt->encrypted_len;
2386 if (!ssh->kex_in_progress &&
2387 !ssh->bare_connection &&
2388 ssh->max_data_size != 0 &&
2389 ssh->outgoing_data_size > ssh->max_data_size)
2390 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2392 ssh_free_packet(pkt);
2396 * Defer an SSH-2 packet.
2398 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2401 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2402 ssh->deferred_len == 0 && !noignore &&
2403 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2405 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2406 * get encrypted with a known IV.
2408 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2409 ssh2_pkt_addstring_start(ipkt);
2410 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2412 len = ssh2_pkt_construct(ssh, pkt);
2413 if (ssh->deferred_len + len > ssh->deferred_size) {
2414 ssh->deferred_size = ssh->deferred_len + len + 128;
2415 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2419 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2420 ssh->deferred_len += len;
2421 ssh->deferred_data_size += pkt->encrypted_len;
2422 ssh_free_packet(pkt);
2426 * Queue an SSH-2 packet.
2428 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2430 assert(ssh->queueing);
2432 if (ssh->queuelen >= ssh->queuesize) {
2433 ssh->queuesize = ssh->queuelen + 32;
2434 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2437 ssh->queue[ssh->queuelen++] = pkt;
2441 * Either queue or send a packet, depending on whether queueing is
2444 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2447 ssh2_pkt_queue(ssh, pkt);
2449 ssh2_pkt_send_noqueue(ssh, pkt);
2453 * Either queue or defer a packet, depending on whether queueing is
2456 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2459 ssh2_pkt_queue(ssh, pkt);
2461 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2465 * Send the whole deferred data block constructed by
2466 * ssh2_pkt_defer() or SSH-1's defer_packet().
2468 * The expected use of the defer mechanism is that you call
2469 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2470 * not currently queueing, this simply sets up deferred_send_data
2471 * and then sends it. If we _are_ currently queueing, the calls to
2472 * ssh2_pkt_defer() put the deferred packets on to the queue
2473 * instead, and therefore ssh_pkt_defersend() has no deferred data
2474 * to send. Hence, there's no need to make it conditional on
2477 static void ssh_pkt_defersend(Ssh ssh)
2480 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2481 ssh->deferred_len = ssh->deferred_size = 0;
2482 sfree(ssh->deferred_send_data);
2483 ssh->deferred_send_data = NULL;
2484 if (backlog > SSH_MAX_BACKLOG)
2485 ssh_throttle_all(ssh, 1, backlog);
2487 ssh->outgoing_data_size += ssh->deferred_data_size;
2488 if (!ssh->kex_in_progress &&
2489 !ssh->bare_connection &&
2490 ssh->max_data_size != 0 &&
2491 ssh->outgoing_data_size > ssh->max_data_size)
2492 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2493 ssh->deferred_data_size = 0;
2497 * Send a packet whose length needs to be disguised (typically
2498 * passwords or keyboard-interactive responses).
2500 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2506 * The simplest way to do this is to adjust the
2507 * variable-length padding field in the outgoing packet.
2509 * Currently compiled out, because some Cisco SSH servers
2510 * don't like excessively padded packets (bah, why's it
2513 pkt->forcepad = padsize;
2514 ssh2_pkt_send(ssh, pkt);
2519 * If we can't do that, however, an alternative approach is
2520 * to use the pkt_defer mechanism to bundle the packet
2521 * tightly together with an SSH_MSG_IGNORE such that their
2522 * combined length is a constant. So first we construct the
2523 * final form of this packet and defer its sending.
2525 ssh2_pkt_defer(ssh, pkt);
2528 * Now construct an SSH_MSG_IGNORE which includes a string
2529 * that's an exact multiple of the cipher block size. (If
2530 * the cipher is NULL so that the block size is
2531 * unavailable, we don't do this trick at all, because we
2532 * gain nothing by it.)
2534 if (ssh->cscipher &&
2535 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2538 stringlen = (256 - ssh->deferred_len);
2539 stringlen += ssh->cscipher->blksize - 1;
2540 stringlen -= (stringlen % ssh->cscipher->blksize);
2543 * Temporarily disable actual compression, so we
2544 * can guarantee to get this string exactly the
2545 * length we want it. The compression-disabling
2546 * routine should return an integer indicating how
2547 * many bytes we should adjust our string length
2551 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2553 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2554 ssh2_pkt_addstring_start(pkt);
2555 for (i = 0; i < stringlen; i++) {
2556 char c = (char) random_byte();
2557 ssh2_pkt_addstring_data(pkt, &c, 1);
2559 ssh2_pkt_defer(ssh, pkt);
2561 ssh_pkt_defersend(ssh);
2566 * Send all queued SSH-2 packets. We send them by means of
2567 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2568 * packets that needed to be lumped together.
2570 static void ssh2_pkt_queuesend(Ssh ssh)
2574 assert(!ssh->queueing);
2576 for (i = 0; i < ssh->queuelen; i++)
2577 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2580 ssh_pkt_defersend(ssh);
2584 void bndebug(char *string, Bignum b)
2588 p = ssh2_mpint_fmt(b, &len);
2589 debug(("%s", string));
2590 for (i = 0; i < len; i++)
2591 debug((" %02x", p[i]));
2597 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2601 p = ssh2_mpint_fmt(b, &len);
2602 hash_string(h, s, p, len);
2607 * Packet decode functions for both SSH-1 and SSH-2.
2609 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2611 unsigned long value;
2612 if (pkt->length - pkt->savedpos < 4)
2613 return 0; /* arrgh, no way to decline (FIXME?) */
2614 value = GET_32BIT(pkt->body + pkt->savedpos);
2618 static int ssh2_pkt_getbool(struct Packet *pkt)
2620 unsigned long value;
2621 if (pkt->length - pkt->savedpos < 1)
2622 return 0; /* arrgh, no way to decline (FIXME?) */
2623 value = pkt->body[pkt->savedpos] != 0;
2627 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2632 if (pkt->length - pkt->savedpos < 4)
2634 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2639 if (pkt->length - pkt->savedpos < *length)
2641 *p = (char *)(pkt->body + pkt->savedpos);
2642 pkt->savedpos += *length;
2644 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2646 if (pkt->length - pkt->savedpos < length)
2648 pkt->savedpos += length;
2649 return pkt->body + (pkt->savedpos - length);
2651 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2652 const unsigned char **keystr)
2656 j = makekey(pkt->body + pkt->savedpos,
2657 pkt->length - pkt->savedpos,
2664 assert(pkt->savedpos < pkt->length);
2668 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2673 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2674 pkt->length - pkt->savedpos, &b);
2682 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2688 ssh_pkt_getstring(pkt, &p, &length);
2693 b = bignum_from_bytes((unsigned char *)p, length);
2698 * Helper function to add an SSH-2 signature blob to a packet.
2699 * Expects to be shown the public key blob as well as the signature
2700 * blob. Normally works just like ssh2_pkt_addstring, but will
2701 * fiddle with the signature packet if necessary for
2702 * BUG_SSH2_RSA_PADDING.
2704 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2705 void *pkblob_v, int pkblob_len,
2706 void *sigblob_v, int sigblob_len)
2708 unsigned char *pkblob = (unsigned char *)pkblob_v;
2709 unsigned char *sigblob = (unsigned char *)sigblob_v;
2711 /* dmemdump(pkblob, pkblob_len); */
2712 /* dmemdump(sigblob, sigblob_len); */
2715 * See if this is in fact an ssh-rsa signature and a buggy
2716 * server; otherwise we can just do this the easy way.
2718 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2719 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2720 int pos, len, siglen;
2723 * Find the byte length of the modulus.
2726 pos = 4+7; /* skip over "ssh-rsa" */
2727 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2728 if (len < 0 || len > pkblob_len - pos - 4)
2730 pos += 4 + len; /* skip over exponent */
2731 if (pkblob_len - pos < 4)
2733 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2734 if (len < 0 || len > pkblob_len - pos - 4)
2736 pos += 4; /* find modulus itself */
2737 while (len > 0 && pkblob[pos] == 0)
2739 /* debug(("modulus length is %d\n", len)); */
2742 * Now find the signature integer.
2744 pos = 4+7; /* skip over "ssh-rsa" */
2745 if (sigblob_len < pos+4)
2747 siglen = toint(GET_32BIT(sigblob+pos));
2748 if (siglen != sigblob_len - pos - 4)
2750 /* debug(("signature length is %d\n", siglen)); */
2752 if (len != siglen) {
2753 unsigned char newlen[4];
2754 ssh2_pkt_addstring_start(pkt);
2755 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2756 /* dmemdump(sigblob, pos); */
2757 pos += 4; /* point to start of actual sig */
2758 PUT_32BIT(newlen, len);
2759 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2760 /* dmemdump(newlen, 4); */
2762 while (len-- > siglen) {
2763 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2764 /* dmemdump(newlen, 1); */
2766 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2767 /* dmemdump(sigblob+pos, siglen); */
2771 /* Otherwise fall through and do it the easy way. We also come
2772 * here as a fallback if we discover above that the key blob
2773 * is misformatted in some way. */
2777 ssh2_pkt_addstring_start(pkt);
2778 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2782 * Examine the remote side's version string and compare it against
2783 * a list of known buggy implementations.
2785 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2787 char *imp; /* pointer to implementation part */
2789 imp += strcspn(imp, "-");
2791 imp += strcspn(imp, "-");
2794 ssh->remote_bugs = 0;
2797 * General notes on server version strings:
2798 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2799 * here -- in particular, we've heard of one that's perfectly happy
2800 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2801 * so we can't distinguish them.
2803 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2804 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2805 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2806 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2807 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2808 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2810 * These versions don't support SSH1_MSG_IGNORE, so we have
2811 * to use a different defence against password length
2814 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2815 logevent("We believe remote version has SSH-1 ignore bug");
2818 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2819 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2820 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2822 * These versions need a plain password sent; they can't
2823 * handle having a null and a random length of data after
2826 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2827 logevent("We believe remote version needs a plain SSH-1 password");
2830 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2831 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2832 (!strcmp(imp, "Cisco-1.25")))) {
2834 * These versions apparently have no clue whatever about
2835 * RSA authentication and will panic and die if they see
2836 * an AUTH_RSA message.
2838 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2839 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2842 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2843 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2844 !wc_match("* VShell", imp) &&
2845 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2846 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2847 wc_match("2.1 *", imp)))) {
2849 * These versions have the HMAC bug.
2851 ssh->remote_bugs |= BUG_SSH2_HMAC;
2852 logevent("We believe remote version has SSH-2 HMAC bug");
2855 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2856 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2857 !wc_match("* VShell", imp) &&
2858 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2860 * These versions have the key-derivation bug (failing to
2861 * include the literal shared secret in the hashes that
2862 * generate the keys).
2864 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2865 logevent("We believe remote version has SSH-2 key-derivation bug");
2868 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2869 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2870 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2871 wc_match("OpenSSH_3.[0-2]*", imp) ||
2872 wc_match("mod_sftp/0.[0-8]*", imp) ||
2873 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2875 * These versions have the SSH-2 RSA padding bug.
2877 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2878 logevent("We believe remote version has SSH-2 RSA padding bug");
2881 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2882 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2883 wc_match("OpenSSH_2.[0-2]*", imp))) {
2885 * These versions have the SSH-2 session-ID bug in
2886 * public-key authentication.
2888 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2889 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2892 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2893 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2894 (wc_match("DigiSSH_2.0", imp) ||
2895 wc_match("OpenSSH_2.[0-4]*", imp) ||
2896 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2897 wc_match("Sun_SSH_1.0", imp) ||
2898 wc_match("Sun_SSH_1.0.1", imp) ||
2899 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2900 wc_match("WeOnlyDo-*", imp)))) {
2902 * These versions have the SSH-2 rekey bug.
2904 ssh->remote_bugs |= BUG_SSH2_REKEY;
2905 logevent("We believe remote version has SSH-2 rekey bug");
2908 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2909 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2910 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2911 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2913 * This version ignores our makpkt and needs to be throttled.
2915 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2916 logevent("We believe remote version ignores SSH-2 maximum packet size");
2919 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2921 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2922 * none detected automatically.
2924 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2925 logevent("We believe remote version has SSH-2 ignore bug");
2928 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2929 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2930 (wc_match("OpenSSH_2.[235]*", imp)))) {
2932 * These versions only support the original (pre-RFC4419)
2933 * SSH-2 GEX request, and disconnect with a protocol error if
2934 * we use the newer version.
2936 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2937 logevent("We believe remote version has outdated SSH-2 GEX");
2940 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2942 * Servers that don't support our winadj request for one
2943 * reason or another. Currently, none detected automatically.
2945 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2946 logevent("We believe remote version has winadj bug");
2949 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
2950 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
2951 (wc_match("OpenSSH_[2-5].*", imp) ||
2952 wc_match("OpenSSH_6.[0-6]*", imp) ||
2953 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
2954 wc_match("dropbear_0.5[01]*", imp)))) {
2956 * These versions have the SSH-2 channel request bug.
2957 * OpenSSH 6.7 and above do not:
2958 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
2959 * dropbear_0.52 and above do not:
2960 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
2962 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
2963 logevent("We believe remote version has SSH-2 channel request bug");
2968 * The `software version' part of an SSH version string is required
2969 * to contain no spaces or minus signs.
2971 static void ssh_fix_verstring(char *str)
2973 /* Eat "<protoversion>-". */
2974 while (*str && *str != '-') str++;
2975 assert(*str == '-'); str++;
2977 /* Convert minus signs and spaces in the remaining string into
2980 if (*str == '-' || *str == ' ')
2987 * Send an appropriate SSH version string.
2989 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
2993 if (ssh->version == 2) {
2995 * Construct a v2 version string.
2997 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
3000 * Construct a v1 version string.
3002 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
3003 verstring = dupprintf("SSH-%s-%s\012",
3004 (ssh_versioncmp(svers, "1.5") <= 0 ?
3009 ssh_fix_verstring(verstring + strlen(protoname));
3011 if (ssh->version == 2) {
3014 * Record our version string.
3016 len = strcspn(verstring, "\015\012");
3017 ssh->v_c = snewn(len + 1, char);
3018 memcpy(ssh->v_c, verstring, len);
3022 logeventf(ssh, "We claim version: %.*s",
3023 strcspn(verstring, "\015\012"), verstring);
3024 s_write(ssh, verstring, strlen(verstring));
3028 static int do_ssh_init(Ssh ssh, unsigned char c)
3030 static const char protoname[] = "SSH-";
3032 struct do_ssh_init_state {
3041 crState(do_ssh_init_state);
3045 /* Search for a line beginning with the protocol name prefix in
3048 for (s->i = 0; protoname[s->i]; s->i++) {
3049 if ((char)c != protoname[s->i]) goto no;
3059 s->vstrsize = sizeof(protoname) + 16;
3060 s->vstring = snewn(s->vstrsize, char);
3061 strcpy(s->vstring, protoname);
3062 s->vslen = strlen(protoname);
3065 if (s->vslen >= s->vstrsize - 1) {
3067 s->vstring = sresize(s->vstring, s->vstrsize, char);
3069 s->vstring[s->vslen++] = c;
3072 s->version[s->i] = '\0';
3074 } else if (s->i < sizeof(s->version) - 1)
3075 s->version[s->i++] = c;
3076 } else if (c == '\012')
3078 crReturn(1); /* get another char */
3081 ssh->agentfwd_enabled = FALSE;
3082 ssh->rdpkt2_state.incoming_sequence = 0;
3084 s->vstring[s->vslen] = 0;
3085 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3086 logeventf(ssh, "Server version: %s", s->vstring);
3087 ssh_detect_bugs(ssh, s->vstring);
3090 * Decide which SSH protocol version to support.
3093 /* Anything strictly below "2.0" means protocol 1 is supported. */
3094 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3095 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3096 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3098 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
3099 bombout(("SSH protocol version 1 required by configuration but "
3100 "not provided by server"));
3103 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
3104 bombout(("SSH protocol version 2 required by configuration but "
3105 "not provided by server"));
3109 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3114 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3116 /* Send the version string, if we haven't already */
3117 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3118 ssh_send_verstring(ssh, protoname, s->version);
3120 if (ssh->version == 2) {
3123 * Record their version string.
3125 len = strcspn(s->vstring, "\015\012");
3126 ssh->v_s = snewn(len + 1, char);
3127 memcpy(ssh->v_s, s->vstring, len);
3131 * Initialise SSH-2 protocol.
3133 ssh->protocol = ssh2_protocol;
3134 ssh2_protocol_setup(ssh);
3135 ssh->s_rdpkt = ssh2_rdpkt;
3138 * Initialise SSH-1 protocol.
3140 ssh->protocol = ssh1_protocol;
3141 ssh1_protocol_setup(ssh);
3142 ssh->s_rdpkt = ssh1_rdpkt;
3144 if (ssh->version == 2)
3145 do_ssh2_transport(ssh, NULL, -1, NULL);
3147 update_specials_menu(ssh->frontend);
3148 ssh->state = SSH_STATE_BEFORE_SIZE;
3149 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3156 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3159 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3160 * the ssh-connection part, extracted and given a trivial binary
3161 * packet protocol, so we replace 'SSH-' at the start with a new
3162 * name. In proper SSH style (though of course this part of the
3163 * proper SSH protocol _isn't_ subject to this kind of
3164 * DNS-domain-based extension), we define the new name in our
3167 static const char protoname[] =
3168 "SSHCONNECTION@putty.projects.tartarus.org-";
3170 struct do_ssh_connection_init_state {
3178 crState(do_ssh_connection_init_state);
3182 /* Search for a line beginning with the protocol name prefix in
3185 for (s->i = 0; protoname[s->i]; s->i++) {
3186 if ((char)c != protoname[s->i]) goto no;
3196 s->vstrsize = sizeof(protoname) + 16;
3197 s->vstring = snewn(s->vstrsize, char);
3198 strcpy(s->vstring, protoname);
3199 s->vslen = strlen(protoname);
3202 if (s->vslen >= s->vstrsize - 1) {
3204 s->vstring = sresize(s->vstring, s->vstrsize, char);
3206 s->vstring[s->vslen++] = c;
3209 s->version[s->i] = '\0';
3211 } else if (s->i < sizeof(s->version) - 1)
3212 s->version[s->i++] = c;
3213 } else if (c == '\012')
3215 crReturn(1); /* get another char */
3218 ssh->agentfwd_enabled = FALSE;
3219 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3221 s->vstring[s->vslen] = 0;
3222 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3223 logeventf(ssh, "Server version: %s", s->vstring);
3224 ssh_detect_bugs(ssh, s->vstring);
3227 * Decide which SSH protocol version to support. This is easy in
3228 * bare ssh-connection mode: only 2.0 is legal.
3230 if (ssh_versioncmp(s->version, "2.0") < 0) {
3231 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3234 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3235 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3241 logeventf(ssh, "Using bare ssh-connection protocol");
3243 /* Send the version string, if we haven't already */
3244 ssh_send_verstring(ssh, protoname, s->version);
3247 * Initialise bare connection protocol.
3249 ssh->protocol = ssh2_bare_connection_protocol;
3250 ssh2_bare_connection_protocol_setup(ssh);
3251 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3253 update_specials_menu(ssh->frontend);
3254 ssh->state = SSH_STATE_BEFORE_SIZE;
3255 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3258 * Get authconn (really just conn) under way.
3260 do_ssh2_authconn(ssh, NULL, 0, NULL);
3267 static void ssh_process_incoming_data(Ssh ssh,
3268 const unsigned char **data, int *datalen)
3270 struct Packet *pktin;
3272 pktin = ssh->s_rdpkt(ssh, data, datalen);
3274 ssh->protocol(ssh, NULL, 0, pktin);
3275 ssh_free_packet(pktin);
3279 static void ssh_queue_incoming_data(Ssh ssh,
3280 const unsigned char **data, int *datalen)
3282 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3287 static void ssh_process_queued_incoming_data(Ssh ssh)
3290 const unsigned char *data;
3293 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3294 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3298 while (!ssh->frozen && len > 0)
3299 ssh_process_incoming_data(ssh, &data, &len);
3302 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3306 static void ssh_set_frozen(Ssh ssh, int frozen)
3309 sk_set_frozen(ssh->s, frozen);
3310 ssh->frozen = frozen;
3313 static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
3315 /* Log raw data, if we're in that mode. */
3317 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3318 0, NULL, NULL, 0, NULL);
3320 crBegin(ssh->ssh_gotdata_crstate);
3323 * To begin with, feed the characters one by one to the
3324 * protocol initialisation / selection function do_ssh_init().
3325 * When that returns 0, we're done with the initial greeting
3326 * exchange and can move on to packet discipline.
3329 int ret; /* need not be kept across crReturn */
3331 crReturnV; /* more data please */
3332 ret = ssh->do_ssh_init(ssh, *data);
3340 * We emerge from that loop when the initial negotiation is
3341 * over and we have selected an s_rdpkt function. Now pass
3342 * everything to s_rdpkt, and then pass the resulting packets
3343 * to the proper protocol handler.
3347 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3349 ssh_queue_incoming_data(ssh, &data, &datalen);
3350 /* This uses up all data and cannot cause anything interesting
3351 * to happen; indeed, for anything to happen at all, we must
3352 * return, so break out. */
3354 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3355 /* This uses up some or all data, and may freeze the
3357 ssh_process_queued_incoming_data(ssh);
3359 /* This uses up some or all data, and may freeze the
3361 ssh_process_incoming_data(ssh, &data, &datalen);
3363 /* FIXME this is probably EBW. */
3364 if (ssh->state == SSH_STATE_CLOSED)
3367 /* We're out of data. Go and get some more. */
3373 static int ssh_do_close(Ssh ssh, int notify_exit)
3376 struct ssh_channel *c;
3378 ssh->state = SSH_STATE_CLOSED;
3379 expire_timer_context(ssh);
3384 notify_remote_exit(ssh->frontend);
3389 * Now we must shut down any port- and X-forwarded channels going
3390 * through this connection.
3392 if (ssh->channels) {
3393 while (NULL != (c = index234(ssh->channels, 0))) {
3396 x11_close(c->u.x11.xconn);
3399 case CHAN_SOCKDATA_DORMANT:
3400 pfd_close(c->u.pfd.pf);
3403 del234(ssh->channels, c); /* moving next one to index 0 */
3404 if (ssh->version == 2)
3405 bufchain_clear(&c->v.v2.outbuffer);
3410 * Go through port-forwardings, and close any associated
3411 * listening sockets.
3413 if (ssh->portfwds) {
3414 struct ssh_portfwd *pf;
3415 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3416 /* Dispose of any listening socket. */
3418 pfl_terminate(pf->local);
3419 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3422 freetree234(ssh->portfwds);
3423 ssh->portfwds = NULL;
3427 * Also stop attempting to connection-share.
3429 if (ssh->connshare) {
3430 sharestate_free(ssh->connshare);
3431 ssh->connshare = NULL;
3437 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3438 const char *error_msg, int error_code)
3440 Ssh ssh = (Ssh) plug;
3441 char addrbuf[256], *msg;
3443 if (ssh->attempting_connshare) {
3445 * While we're attempting connection sharing, don't loudly log
3446 * everything that happens. Real TCP connections need to be
3447 * logged when we _start_ trying to connect, because it might
3448 * be ages before they respond if something goes wrong; but
3449 * connection sharing is local and quick to respond, and it's
3450 * sufficient to simply wait and see whether it worked
3454 sk_getaddr(addr, addrbuf, lenof(addrbuf));
3457 if (sk_addr_needs_port(addr)) {
3458 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
3460 msg = dupprintf("Connecting to %s", addrbuf);
3463 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
3471 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3472 const char *ds_err, const char *us_err)
3474 if (event == SHARE_NONE) {
3475 /* In this case, 'logtext' is an error message indicating a
3476 * reason why connection sharing couldn't be set up _at all_.
3477 * Failing that, ds_err and us_err indicate why we couldn't be
3478 * a downstream and an upstream respectively. */
3480 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3483 logeventf(ssh, "Could not set up connection sharing"
3484 " as downstream: %s", ds_err);
3486 logeventf(ssh, "Could not set up connection sharing"
3487 " as upstream: %s", us_err);
3489 } else if (event == SHARE_DOWNSTREAM) {
3490 /* In this case, 'logtext' is a local endpoint address */
3491 logeventf(ssh, "Using existing shared connection at %s", logtext);
3492 /* Also we should mention this in the console window to avoid
3493 * confusing users as to why this window doesn't behave the
3495 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3496 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3498 } else if (event == SHARE_UPSTREAM) {
3499 /* In this case, 'logtext' is a local endpoint address too */
3500 logeventf(ssh, "Sharing this connection at %s", logtext);
3504 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3507 Ssh ssh = (Ssh) plug;
3508 int need_notify = ssh_do_close(ssh, FALSE);
3511 if (!ssh->close_expected)
3512 error_msg = "Server unexpectedly closed network connection";
3514 error_msg = "Server closed network connection";
3517 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3521 notify_remote_exit(ssh->frontend);
3524 logevent(error_msg);
3525 if (!ssh->close_expected || !ssh->clean_exit)
3526 connection_fatal(ssh->frontend, "%s", error_msg);
3530 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3532 Ssh ssh = (Ssh) plug;
3533 ssh_gotdata(ssh, (unsigned char *)data, len);
3534 if (ssh->state == SSH_STATE_CLOSED) {
3535 ssh_do_close(ssh, TRUE);
3541 static void ssh_sent(Plug plug, int bufsize)
3543 Ssh ssh = (Ssh) plug;
3545 * If the send backlog on the SSH socket itself clears, we
3546 * should unthrottle the whole world if it was throttled.
3548 if (bufsize < SSH_MAX_BACKLOG)
3549 ssh_throttle_all(ssh, 0, bufsize);
3553 * Connect to specified host and port.
3554 * Returns an error message, or NULL on success.
3555 * Also places the canonical host name into `realhost'. It must be
3556 * freed by the caller.
3558 static const char *connect_to_host(Ssh ssh, const char *host, int port,
3559 char **realhost, int nodelay, int keepalive)
3561 static const struct plug_function_table fn_table = {
3572 int addressfamily, sshprot;
3574 loghost = conf_get_str(ssh->conf, CONF_loghost);
3579 tmphost = dupstr(loghost);
3580 ssh->savedport = 22; /* default ssh port */
3583 * A colon suffix on the hostname string also lets us affect
3584 * savedport. (Unless there are multiple colons, in which case
3585 * we assume this is an unbracketed IPv6 literal.)
3587 colon = host_strrchr(tmphost, ':');
3588 if (colon && colon == host_strchr(tmphost, ':')) {
3591 ssh->savedport = atoi(colon);
3594 ssh->savedhost = host_strduptrim(tmphost);
3597 ssh->savedhost = host_strduptrim(host);
3599 port = 22; /* default ssh port */
3600 ssh->savedport = port;
3603 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3606 * Try connection-sharing, in case that means we don't open a
3607 * socket after all. ssh_connection_sharing_init will connect to a
3608 * previously established upstream if it can, and failing that,
3609 * establish a listening socket for _us_ to be the upstream. In
3610 * the latter case it will return NULL just as if it had done
3611 * nothing, because here we only need to care if we're a
3612 * downstream and need to do our connection setup differently.
3614 ssh->connshare = NULL;
3615 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3616 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3617 ssh->conf, ssh, &ssh->connshare);
3618 ssh->attempting_connshare = FALSE;
3619 if (ssh->s != NULL) {
3621 * We are a downstream.
3623 ssh->bare_connection = TRUE;
3624 ssh->do_ssh_init = do_ssh_connection_init;
3625 ssh->fullhostname = NULL;
3626 *realhost = dupstr(host); /* best we can do */
3629 * We're not a downstream, so open a normal socket.
3631 ssh->do_ssh_init = do_ssh_init;
3636 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3637 logeventf(ssh, "Looking up host \"%s\"%s", host,
3638 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3639 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3640 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3641 if ((err = sk_addr_error(addr)) != NULL) {
3645 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3647 ssh->s = new_connection(addr, *realhost, port,
3648 0, 1, nodelay, keepalive,
3649 (Plug) ssh, ssh->conf);
3650 if ((err = sk_socket_error(ssh->s)) != NULL) {
3652 notify_remote_exit(ssh->frontend);
3658 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3659 * send the version string too.
3661 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3664 if (sshprot == 3 && !ssh->bare_connection) {
3666 ssh_send_verstring(ssh, "SSH-", NULL);
3670 * loghost, if configured, overrides realhost.
3674 *realhost = dupstr(loghost);
3681 * Throttle or unthrottle the SSH connection.
3683 static void ssh_throttle_conn(Ssh ssh, int adjust)
3685 int old_count = ssh->conn_throttle_count;
3686 ssh->conn_throttle_count += adjust;
3687 assert(ssh->conn_throttle_count >= 0);
3688 if (ssh->conn_throttle_count && !old_count) {
3689 ssh_set_frozen(ssh, 1);
3690 } else if (!ssh->conn_throttle_count && old_count) {
3691 ssh_set_frozen(ssh, 0);
3696 * Throttle or unthrottle _all_ local data streams (for when sends
3697 * on the SSH connection itself back up).
3699 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3702 struct ssh_channel *c;
3704 if (enable == ssh->throttled_all)
3706 ssh->throttled_all = enable;
3707 ssh->overall_bufsize = bufsize;
3710 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3712 case CHAN_MAINSESSION:
3714 * This is treated separately, outside the switch.
3718 x11_override_throttle(c->u.x11.xconn, enable);
3721 /* Agent channels require no buffer management. */
3724 pfd_override_throttle(c->u.pfd.pf, enable);
3730 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3732 Ssh ssh = (Ssh) sshv;
3734 ssh->agent_response = reply;
3735 ssh->agent_response_len = replylen;
3737 if (ssh->version == 1)
3738 do_ssh1_login(ssh, NULL, -1, NULL);
3740 do_ssh2_authconn(ssh, NULL, -1, NULL);
3743 static void ssh_dialog_callback(void *sshv, int ret)
3745 Ssh ssh = (Ssh) sshv;
3747 ssh->user_response = ret;
3749 if (ssh->version == 1)
3750 do_ssh1_login(ssh, NULL, -1, NULL);
3752 do_ssh2_transport(ssh, NULL, -1, NULL);
3755 * This may have unfrozen the SSH connection, so do a
3758 ssh_process_queued_incoming_data(ssh);
3761 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3763 struct ssh_channel *c = (struct ssh_channel *)cv;
3765 const void *sentreply = reply;
3767 c->u.a.outstanding_requests--;
3769 /* Fake SSH_AGENT_FAILURE. */
3770 sentreply = "\0\0\0\1\5";
3773 if (ssh->version == 2) {
3774 ssh2_add_channel_data(c, sentreply, replylen);
3777 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3778 PKT_INT, c->remoteid,
3780 PKT_DATA, sentreply, replylen,
3786 * If we've already seen an incoming EOF but haven't sent an
3787 * outgoing one, this may be the moment to send it.
3789 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3790 sshfwd_write_eof(c);
3794 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3795 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3796 * => log `wire_reason'.
3798 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3799 const char *wire_reason,
3800 int code, int clean_exit)
3804 client_reason = wire_reason;
3806 error = dupprintf("Disconnected: %s", client_reason);
3808 error = dupstr("Disconnected");
3810 if (ssh->version == 1) {
3811 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3813 } else if (ssh->version == 2) {
3814 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3815 ssh2_pkt_adduint32(pktout, code);
3816 ssh2_pkt_addstring(pktout, wire_reason);
3817 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3818 ssh2_pkt_send_noqueue(ssh, pktout);
3821 ssh->close_expected = TRUE;
3822 ssh->clean_exit = clean_exit;
3823 ssh_closing((Plug)ssh, error, 0, 0);
3827 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3828 const struct ssh_signkey *ssh2keytype,
3831 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3832 return -1; /* no manual keys configured */
3837 * The fingerprint string we've been given will have things
3838 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3839 * narrow down to just the colon-separated hex block at the
3840 * end of the string.
3842 const char *p = strrchr(fingerprint, ' ');
3843 fingerprint = p ? p+1 : fingerprint;
3844 /* Quick sanity checks, including making sure it's in lowercase */
3845 assert(strlen(fingerprint) == 16*3 - 1);
3846 assert(fingerprint[2] == ':');
3847 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3849 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3851 return 1; /* success */
3856 * Construct the base64-encoded public key blob and see if
3859 unsigned char *binblob;
3861 int binlen, atoms, i;
3862 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3863 atoms = (binlen + 2) / 3;
3864 base64blob = snewn(atoms * 4 + 1, char);
3865 for (i = 0; i < atoms; i++)
3866 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3867 base64blob[atoms * 4] = '\0';
3869 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3872 return 1; /* success */
3881 * Handle the key exchange and user authentication phases.
3883 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
3884 struct Packet *pktin)
3887 unsigned char cookie[8], *ptr;
3888 struct MD5Context md5c;
3889 struct do_ssh1_login_state {
3892 unsigned char *rsabuf;
3893 const unsigned char *keystr1, *keystr2;
3894 unsigned long supported_ciphers_mask, supported_auths_mask;
3895 int tried_publickey, tried_agent;
3896 int tis_auth_refused, ccard_auth_refused;
3897 unsigned char session_id[16];
3899 void *publickey_blob;
3900 int publickey_bloblen;
3901 char *publickey_comment;
3902 int privatekey_available, privatekey_encrypted;
3903 prompts_t *cur_prompt;
3906 unsigned char request[5], *response, *p;
3916 struct RSAKey servkey, hostkey;
3918 crState(do_ssh1_login_state);
3925 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3926 bombout(("Public key packet not received"));
3930 logevent("Received public keys");
3932 ptr = ssh_pkt_getdata(pktin, 8);
3934 bombout(("SSH-1 public key packet stopped before random cookie"));
3937 memcpy(cookie, ptr, 8);
3939 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3940 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3941 bombout(("Failed to read SSH-1 public keys from public key packet"));
3946 * Log the host key fingerprint.
3950 logevent("Host key fingerprint is:");
3951 strcpy(logmsg, " ");
3952 s->hostkey.comment = NULL;
3953 rsa_fingerprint(logmsg + strlen(logmsg),
3954 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3958 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3959 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3960 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3961 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3962 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3964 ssh->v1_local_protoflags =
3965 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3966 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3969 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3970 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3971 MD5Update(&md5c, cookie, 8);
3972 MD5Final(s->session_id, &md5c);
3974 for (i = 0; i < 32; i++)
3975 ssh->session_key[i] = random_byte();
3978 * Verify that the `bits' and `bytes' parameters match.
3980 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3981 s->servkey.bits > s->servkey.bytes * 8) {
3982 bombout(("SSH-1 public keys were badly formatted"));
3986 s->len = (s->hostkey.bytes > s->servkey.bytes ?
3987 s->hostkey.bytes : s->servkey.bytes);
3989 s->rsabuf = snewn(s->len, unsigned char);
3992 * Verify the host key.
3996 * First format the key into a string.
3998 int len = rsastr_len(&s->hostkey);
3999 char fingerprint[100];
4000 char *keystr = snewn(len, char);
4001 rsastr_fmt(keystr, &s->hostkey);
4002 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4004 /* First check against manually configured host keys. */
4005 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4006 if (s->dlgret == 0) { /* did not match */
4007 bombout(("Host key did not appear in manually configured list"));
4010 } else if (s->dlgret < 0) { /* none configured; use standard handling */
4011 ssh_set_frozen(ssh, 1);
4012 s->dlgret = verify_ssh_host_key(ssh->frontend,
4013 ssh->savedhost, ssh->savedport,
4014 "rsa", keystr, fingerprint,
4015 ssh_dialog_callback, ssh);
4017 if (s->dlgret < 0) {
4021 bombout(("Unexpected data from server while waiting"
4022 " for user host key response"));
4025 } while (pktin || inlen > 0);
4026 s->dlgret = ssh->user_response;
4028 ssh_set_frozen(ssh, 0);
4030 if (s->dlgret == 0) {
4031 ssh_disconnect(ssh, "User aborted at host key verification",
4040 for (i = 0; i < 32; i++) {
4041 s->rsabuf[i] = ssh->session_key[i];
4043 s->rsabuf[i] ^= s->session_id[i];
4046 if (s->hostkey.bytes > s->servkey.bytes) {
4047 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4049 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4051 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4053 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4056 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4060 logevent("Encrypted session key");
4063 int cipher_chosen = 0, warn = 0;
4064 const char *cipher_string = NULL;
4066 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4067 int next_cipher = conf_get_int_int(ssh->conf,
4068 CONF_ssh_cipherlist, i);
4069 if (next_cipher == CIPHER_WARN) {
4070 /* If/when we choose a cipher, warn about it */
4072 } else if (next_cipher == CIPHER_AES) {
4073 /* XXX Probably don't need to mention this. */
4074 logevent("AES not supported in SSH-1, skipping");
4076 switch (next_cipher) {
4077 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4078 cipher_string = "3DES"; break;
4079 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4080 cipher_string = "Blowfish"; break;
4081 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4082 cipher_string = "single-DES"; break;
4084 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4088 if (!cipher_chosen) {
4089 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4090 bombout(("Server violates SSH-1 protocol by not "
4091 "supporting 3DES encryption"));
4093 /* shouldn't happen */
4094 bombout(("No supported ciphers found"));
4098 /* Warn about chosen cipher if necessary. */
4100 ssh_set_frozen(ssh, 1);
4101 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4102 ssh_dialog_callback, ssh);
4103 if (s->dlgret < 0) {
4107 bombout(("Unexpected data from server while waiting"
4108 " for user response"));
4111 } while (pktin || inlen > 0);
4112 s->dlgret = ssh->user_response;
4114 ssh_set_frozen(ssh, 0);
4115 if (s->dlgret == 0) {
4116 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4123 switch (s->cipher_type) {
4124 case SSH_CIPHER_3DES:
4125 logevent("Using 3DES encryption");
4127 case SSH_CIPHER_DES:
4128 logevent("Using single-DES encryption");
4130 case SSH_CIPHER_BLOWFISH:
4131 logevent("Using Blowfish encryption");
4135 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4136 PKT_CHAR, s->cipher_type,
4137 PKT_DATA, cookie, 8,
4138 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4139 PKT_DATA, s->rsabuf, s->len,
4140 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4142 logevent("Trying to enable encryption...");
4146 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4147 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4149 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4150 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4151 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4153 ssh->crcda_ctx = crcda_make_context();
4154 logevent("Installing CRC compensation attack detector");
4156 if (s->servkey.modulus) {
4157 sfree(s->servkey.modulus);
4158 s->servkey.modulus = NULL;
4160 if (s->servkey.exponent) {
4161 sfree(s->servkey.exponent);
4162 s->servkey.exponent = NULL;
4164 if (s->hostkey.modulus) {
4165 sfree(s->hostkey.modulus);
4166 s->hostkey.modulus = NULL;
4168 if (s->hostkey.exponent) {
4169 sfree(s->hostkey.exponent);
4170 s->hostkey.exponent = NULL;
4174 if (pktin->type != SSH1_SMSG_SUCCESS) {
4175 bombout(("Encryption not successfully enabled"));
4179 logevent("Successfully started encryption");
4181 fflush(stdout); /* FIXME eh? */
4183 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4184 int ret; /* need not be kept over crReturn */
4185 s->cur_prompt = new_prompts(ssh->frontend);
4186 s->cur_prompt->to_server = TRUE;
4187 s->cur_prompt->name = dupstr("SSH login name");
4188 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4189 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4192 crWaitUntil(!pktin);
4193 ret = get_userpass_input(s->cur_prompt, in, inlen);
4198 * Failed to get a username. Terminate.
4200 free_prompts(s->cur_prompt);
4201 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4204 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4205 free_prompts(s->cur_prompt);
4208 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4210 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4212 if (flags & FLAG_INTERACTIVE &&
4213 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4214 c_write_str(ssh, userlog);
4215 c_write_str(ssh, "\r\n");
4223 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4224 /* We must not attempt PK auth. Pretend we've already tried it. */
4225 s->tried_publickey = s->tried_agent = 1;
4227 s->tried_publickey = s->tried_agent = 0;
4229 s->tis_auth_refused = s->ccard_auth_refused = 0;
4231 * Load the public half of any configured keyfile for later use.
4233 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4234 if (!filename_is_null(s->keyfile)) {
4236 logeventf(ssh, "Reading key file \"%.150s\"",
4237 filename_to_str(s->keyfile));
4238 keytype = key_type(s->keyfile);
4239 if (keytype == SSH_KEYTYPE_SSH1 ||
4240 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4242 if (rsakey_pubblob(s->keyfile,
4243 &s->publickey_blob, &s->publickey_bloblen,
4244 &s->publickey_comment, &error)) {
4245 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4246 if (!s->privatekey_available)
4247 logeventf(ssh, "Key file contains public key only");
4248 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4252 logeventf(ssh, "Unable to load key (%s)", error);
4253 msgbuf = dupprintf("Unable to load key file "
4254 "\"%.150s\" (%s)\r\n",
4255 filename_to_str(s->keyfile),
4257 c_write_str(ssh, msgbuf);
4259 s->publickey_blob = NULL;
4263 logeventf(ssh, "Unable to use this key file (%s)",
4264 key_type_to_str(keytype));
4265 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4267 filename_to_str(s->keyfile),
4268 key_type_to_str(keytype));
4269 c_write_str(ssh, msgbuf);
4271 s->publickey_blob = NULL;
4274 s->publickey_blob = NULL;
4276 while (pktin->type == SSH1_SMSG_FAILURE) {
4277 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4279 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4281 * Attempt RSA authentication using Pageant.
4287 logevent("Pageant is running. Requesting keys.");
4289 /* Request the keys held by the agent. */
4290 PUT_32BIT(s->request, 1);
4291 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4292 if (!agent_query(s->request, 5, &r, &s->responselen,
4293 ssh_agent_callback, ssh)) {
4297 bombout(("Unexpected data from server while waiting"
4298 " for agent response"));
4301 } while (pktin || inlen > 0);
4302 r = ssh->agent_response;
4303 s->responselen = ssh->agent_response_len;
4305 s->response = (unsigned char *) r;
4306 if (s->response && s->responselen >= 5 &&
4307 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4308 s->p = s->response + 5;
4309 s->nkeys = toint(GET_32BIT(s->p));
4311 logeventf(ssh, "Pageant reported negative key count %d",
4316 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4317 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4318 unsigned char *pkblob = s->p;
4322 do { /* do while (0) to make breaking easy */
4323 n = ssh1_read_bignum
4324 (s->p, toint(s->responselen-(s->p-s->response)),
4329 n = ssh1_read_bignum
4330 (s->p, toint(s->responselen-(s->p-s->response)),
4335 if (s->responselen - (s->p-s->response) < 4)
4337 s->commentlen = toint(GET_32BIT(s->p));
4339 if (s->commentlen < 0 ||
4340 toint(s->responselen - (s->p-s->response)) <
4343 s->commentp = (char *)s->p;
4344 s->p += s->commentlen;
4348 logevent("Pageant key list packet was truncated");
4352 if (s->publickey_blob) {
4353 if (!memcmp(pkblob, s->publickey_blob,
4354 s->publickey_bloblen)) {
4355 logeventf(ssh, "Pageant key #%d matches "
4356 "configured key file", s->keyi);
4357 s->tried_publickey = 1;
4359 /* Skip non-configured key */
4362 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4363 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4364 PKT_BIGNUM, s->key.modulus, PKT_END);
4366 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4367 logevent("Key refused");
4370 logevent("Received RSA challenge");
4371 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4372 bombout(("Server's RSA challenge was badly formatted"));
4377 char *agentreq, *q, *ret;
4380 len = 1 + 4; /* message type, bit count */
4381 len += ssh1_bignum_length(s->key.exponent);
4382 len += ssh1_bignum_length(s->key.modulus);
4383 len += ssh1_bignum_length(s->challenge);
4384 len += 16; /* session id */
4385 len += 4; /* response format */
4386 agentreq = snewn(4 + len, char);
4387 PUT_32BIT(agentreq, len);
4389 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4390 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4392 q += ssh1_write_bignum(q, s->key.exponent);
4393 q += ssh1_write_bignum(q, s->key.modulus);
4394 q += ssh1_write_bignum(q, s->challenge);
4395 memcpy(q, s->session_id, 16);
4397 PUT_32BIT(q, 1); /* response format */
4398 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4399 ssh_agent_callback, ssh)) {
4404 bombout(("Unexpected data from server"
4405 " while waiting for agent"
4409 } while (pktin || inlen > 0);
4410 vret = ssh->agent_response;
4411 retlen = ssh->agent_response_len;
4416 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4417 logevent("Sending Pageant's response");
4418 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4419 PKT_DATA, ret + 5, 16,
4423 if (pktin->type == SSH1_SMSG_SUCCESS) {
4425 ("Pageant's response accepted");
4426 if (flags & FLAG_VERBOSE) {
4427 c_write_str(ssh, "Authenticated using"
4429 c_write(ssh, s->commentp,
4431 c_write_str(ssh, "\" from agent\r\n");
4436 ("Pageant's response not accepted");
4439 ("Pageant failed to answer challenge");
4443 logevent("No reply received from Pageant");
4446 freebn(s->key.exponent);
4447 freebn(s->key.modulus);
4448 freebn(s->challenge);
4453 if (s->publickey_blob && !s->tried_publickey)
4454 logevent("Configured key file not in Pageant");
4456 logevent("Failed to get reply from Pageant");
4461 if (s->publickey_blob && s->privatekey_available &&
4462 !s->tried_publickey) {
4464 * Try public key authentication with the specified
4467 int got_passphrase; /* need not be kept over crReturn */
4468 if (flags & FLAG_VERBOSE)
4469 c_write_str(ssh, "Trying public key authentication.\r\n");
4470 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4471 logeventf(ssh, "Trying public key \"%s\"",
4472 filename_to_str(s->keyfile));
4473 s->tried_publickey = 1;
4474 got_passphrase = FALSE;
4475 while (!got_passphrase) {
4477 * Get a passphrase, if necessary.
4479 char *passphrase = NULL; /* only written after crReturn */
4481 if (!s->privatekey_encrypted) {
4482 if (flags & FLAG_VERBOSE)
4483 c_write_str(ssh, "No passphrase required.\r\n");
4486 int ret; /* need not be kept over crReturn */
4487 s->cur_prompt = new_prompts(ssh->frontend);
4488 s->cur_prompt->to_server = FALSE;
4489 s->cur_prompt->name = dupstr("SSH key passphrase");
4490 add_prompt(s->cur_prompt,
4491 dupprintf("Passphrase for key \"%.100s\": ",
4492 s->publickey_comment), FALSE);
4493 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4496 crWaitUntil(!pktin);
4497 ret = get_userpass_input(s->cur_prompt, in, inlen);
4501 /* Failed to get a passphrase. Terminate. */
4502 free_prompts(s->cur_prompt);
4503 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4507 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4508 free_prompts(s->cur_prompt);
4511 * Try decrypting key with passphrase.
4513 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4514 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4517 smemclr(passphrase, strlen(passphrase));
4521 /* Correct passphrase. */
4522 got_passphrase = TRUE;
4523 } else if (ret == 0) {
4524 c_write_str(ssh, "Couldn't load private key from ");
4525 c_write_str(ssh, filename_to_str(s->keyfile));
4526 c_write_str(ssh, " (");
4527 c_write_str(ssh, error);
4528 c_write_str(ssh, ").\r\n");
4529 got_passphrase = FALSE;
4530 break; /* go and try something else */
4531 } else if (ret == -1) {
4532 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4533 got_passphrase = FALSE;
4536 assert(0 && "unexpected return from loadrsakey()");
4537 got_passphrase = FALSE; /* placate optimisers */
4541 if (got_passphrase) {
4544 * Send a public key attempt.
4546 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4547 PKT_BIGNUM, s->key.modulus, PKT_END);
4550 if (pktin->type == SSH1_SMSG_FAILURE) {
4551 c_write_str(ssh, "Server refused our public key.\r\n");
4552 continue; /* go and try something else */
4554 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4555 bombout(("Bizarre response to offer of public key"));
4561 unsigned char buffer[32];
4562 Bignum challenge, response;
4564 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4565 bombout(("Server's RSA challenge was badly formatted"));
4568 response = rsadecrypt(challenge, &s->key);
4569 freebn(s->key.private_exponent);/* burn the evidence */
4571 for (i = 0; i < 32; i++) {
4572 buffer[i] = bignum_byte(response, 31 - i);
4576 MD5Update(&md5c, buffer, 32);
4577 MD5Update(&md5c, s->session_id, 16);
4578 MD5Final(buffer, &md5c);
4580 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4581 PKT_DATA, buffer, 16, PKT_END);
4588 if (pktin->type == SSH1_SMSG_FAILURE) {
4589 if (flags & FLAG_VERBOSE)
4590 c_write_str(ssh, "Failed to authenticate with"
4591 " our public key.\r\n");
4592 continue; /* go and try something else */
4593 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4594 bombout(("Bizarre response to RSA authentication response"));
4598 break; /* we're through! */
4604 * Otherwise, try various forms of password-like authentication.
4606 s->cur_prompt = new_prompts(ssh->frontend);
4608 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4609 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4610 !s->tis_auth_refused) {
4611 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4612 logevent("Requested TIS authentication");
4613 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4615 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4616 logevent("TIS authentication declined");
4617 if (flags & FLAG_INTERACTIVE)
4618 c_write_str(ssh, "TIS authentication refused.\r\n");
4619 s->tis_auth_refused = 1;
4624 char *instr_suf, *prompt;
4626 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4628 bombout(("TIS challenge packet was badly formed"));
4631 logevent("Received TIS challenge");
4632 s->cur_prompt->to_server = TRUE;
4633 s->cur_prompt->name = dupstr("SSH TIS authentication");
4634 /* Prompt heuristic comes from OpenSSH */
4635 if (memchr(challenge, '\n', challengelen)) {
4636 instr_suf = dupstr("");
4637 prompt = dupprintf("%.*s", challengelen, challenge);
4639 instr_suf = dupprintf("%.*s", challengelen, challenge);
4640 prompt = dupstr("Response: ");
4642 s->cur_prompt->instruction =
4643 dupprintf("Using TIS authentication.%s%s",
4644 (*instr_suf) ? "\n" : "",
4646 s->cur_prompt->instr_reqd = TRUE;
4647 add_prompt(s->cur_prompt, prompt, FALSE);
4651 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4652 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4653 !s->ccard_auth_refused) {
4654 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4655 logevent("Requested CryptoCard authentication");
4656 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4658 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4659 logevent("CryptoCard authentication declined");
4660 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4661 s->ccard_auth_refused = 1;
4666 char *instr_suf, *prompt;
4668 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4670 bombout(("CryptoCard challenge packet was badly formed"));
4673 logevent("Received CryptoCard challenge");
4674 s->cur_prompt->to_server = TRUE;
4675 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4676 s->cur_prompt->name_reqd = FALSE;
4677 /* Prompt heuristic comes from OpenSSH */
4678 if (memchr(challenge, '\n', challengelen)) {
4679 instr_suf = dupstr("");
4680 prompt = dupprintf("%.*s", challengelen, challenge);
4682 instr_suf = dupprintf("%.*s", challengelen, challenge);
4683 prompt = dupstr("Response: ");
4685 s->cur_prompt->instruction =
4686 dupprintf("Using CryptoCard authentication.%s%s",
4687 (*instr_suf) ? "\n" : "",
4689 s->cur_prompt->instr_reqd = TRUE;
4690 add_prompt(s->cur_prompt, prompt, FALSE);
4694 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4695 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4696 bombout(("No supported authentication methods available"));
4699 s->cur_prompt->to_server = TRUE;
4700 s->cur_prompt->name = dupstr("SSH password");
4701 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4702 ssh->username, ssh->savedhost),
4707 * Show password prompt, having first obtained it via a TIS
4708 * or CryptoCard exchange if we're doing TIS or CryptoCard
4712 int ret; /* need not be kept over crReturn */
4713 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4716 crWaitUntil(!pktin);
4717 ret = get_userpass_input(s->cur_prompt, in, inlen);
4722 * Failed to get a password (for example
4723 * because one was supplied on the command line
4724 * which has already failed to work). Terminate.
4726 free_prompts(s->cur_prompt);
4727 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4732 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4734 * Defence against traffic analysis: we send a
4735 * whole bunch of packets containing strings of
4736 * different lengths. One of these strings is the
4737 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4738 * The others are all random data in
4739 * SSH1_MSG_IGNORE packets. This way a passive
4740 * listener can't tell which is the password, and
4741 * hence can't deduce the password length.
4743 * Anybody with a password length greater than 16
4744 * bytes is going to have enough entropy in their
4745 * password that a listener won't find it _that_
4746 * much help to know how long it is. So what we'll
4749 * - if password length < 16, we send 15 packets
4750 * containing string lengths 1 through 15
4752 * - otherwise, we let N be the nearest multiple
4753 * of 8 below the password length, and send 8
4754 * packets containing string lengths N through
4755 * N+7. This won't obscure the order of
4756 * magnitude of the password length, but it will
4757 * introduce a bit of extra uncertainty.
4759 * A few servers can't deal with SSH1_MSG_IGNORE, at
4760 * least in this context. For these servers, we need
4761 * an alternative defence. We make use of the fact
4762 * that the password is interpreted as a C string:
4763 * so we can append a NUL, then some random data.
4765 * A few servers can deal with neither SSH1_MSG_IGNORE
4766 * here _nor_ a padded password string.
4767 * For these servers we are left with no defences
4768 * against password length sniffing.
4770 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4771 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4773 * The server can deal with SSH1_MSG_IGNORE, so
4774 * we can use the primary defence.
4776 int bottom, top, pwlen, i;
4779 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4781 bottom = 0; /* zero length passwords are OK! :-) */
4784 bottom = pwlen & ~7;
4788 assert(pwlen >= bottom && pwlen <= top);
4790 randomstr = snewn(top + 1, char);
4792 for (i = bottom; i <= top; i++) {
4794 defer_packet(ssh, s->pwpkt_type,
4795 PKT_STR,s->cur_prompt->prompts[0]->result,
4798 for (j = 0; j < i; j++) {
4800 randomstr[j] = random_byte();
4801 } while (randomstr[j] == '\0');
4803 randomstr[i] = '\0';
4804 defer_packet(ssh, SSH1_MSG_IGNORE,
4805 PKT_STR, randomstr, PKT_END);
4808 logevent("Sending password with camouflage packets");
4809 ssh_pkt_defersend(ssh);
4812 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4814 * The server can't deal with SSH1_MSG_IGNORE
4815 * but can deal with padded passwords, so we
4816 * can use the secondary defence.
4822 len = strlen(s->cur_prompt->prompts[0]->result);
4823 if (len < sizeof(string)) {
4825 strcpy(string, s->cur_prompt->prompts[0]->result);
4826 len++; /* cover the zero byte */
4827 while (len < sizeof(string)) {
4828 string[len++] = (char) random_byte();
4831 ss = s->cur_prompt->prompts[0]->result;
4833 logevent("Sending length-padded password");
4834 send_packet(ssh, s->pwpkt_type,
4835 PKT_INT, len, PKT_DATA, ss, len,
4839 * The server is believed unable to cope with
4840 * any of our password camouflage methods.
4843 len = strlen(s->cur_prompt->prompts[0]->result);
4844 logevent("Sending unpadded password");
4845 send_packet(ssh, s->pwpkt_type,
4847 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4851 send_packet(ssh, s->pwpkt_type,
4852 PKT_STR, s->cur_prompt->prompts[0]->result,
4855 logevent("Sent password");
4856 free_prompts(s->cur_prompt);
4858 if (pktin->type == SSH1_SMSG_FAILURE) {
4859 if (flags & FLAG_VERBOSE)
4860 c_write_str(ssh, "Access denied\r\n");
4861 logevent("Authentication refused");
4862 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4863 bombout(("Strange packet received, type %d", pktin->type));
4869 if (s->publickey_blob) {
4870 sfree(s->publickey_blob);
4871 sfree(s->publickey_comment);
4874 logevent("Authentication successful");
4879 static void ssh_channel_try_eof(struct ssh_channel *c)
4882 assert(c->pending_eof); /* precondition for calling us */
4884 return; /* can't close: not even opened yet */
4885 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4886 return; /* can't send EOF: pending outgoing data */
4888 c->pending_eof = FALSE; /* we're about to send it */
4889 if (ssh->version == 1) {
4890 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4892 c->closes |= CLOSES_SENT_EOF;
4894 struct Packet *pktout;
4895 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4896 ssh2_pkt_adduint32(pktout, c->remoteid);
4897 ssh2_pkt_send(ssh, pktout);
4898 c->closes |= CLOSES_SENT_EOF;
4899 ssh2_channel_check_close(c);
4903 Conf *sshfwd_get_conf(struct ssh_channel *c)
4909 void sshfwd_write_eof(struct ssh_channel *c)
4913 if (ssh->state == SSH_STATE_CLOSED)
4916 if (c->closes & CLOSES_SENT_EOF)
4919 c->pending_eof = TRUE;
4920 ssh_channel_try_eof(c);
4923 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4927 if (ssh->state == SSH_STATE_CLOSED)
4932 x11_close(c->u.x11.xconn);
4933 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4937 case CHAN_SOCKDATA_DORMANT:
4938 pfd_close(c->u.pfd.pf);
4939 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4942 c->type = CHAN_ZOMBIE;
4943 c->pending_eof = FALSE; /* this will confuse a zombie channel */
4945 ssh2_channel_check_close(c);
4948 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4952 if (ssh->state == SSH_STATE_CLOSED)
4955 if (ssh->version == 1) {
4956 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4957 PKT_INT, c->remoteid,
4958 PKT_INT, len, PKT_DATA, buf, len,
4961 * In SSH-1 we can return 0 here - implying that forwarded
4962 * connections are never individually throttled - because
4963 * the only circumstance that can cause throttling will be
4964 * the whole SSH connection backing up, in which case
4965 * _everything_ will be throttled as a whole.
4969 ssh2_add_channel_data(c, buf, len);
4970 return ssh2_try_send(c);
4974 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4979 if (ssh->state == SSH_STATE_CLOSED)
4982 if (ssh->version == 1) {
4983 buflimit = SSH1_BUFFER_LIMIT;
4985 buflimit = c->v.v2.locmaxwin;
4986 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4988 if (c->throttling_conn && bufsize <= buflimit) {
4989 c->throttling_conn = 0;
4990 ssh_throttle_conn(ssh, -1);
4994 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4996 struct queued_handler *qh = ssh->qhead;
5000 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5003 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5004 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5007 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5008 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5012 ssh->qhead = qh->next;
5014 if (ssh->qhead->msg1 > 0) {
5015 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5016 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5018 if (ssh->qhead->msg2 > 0) {
5019 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5020 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5023 ssh->qhead = ssh->qtail = NULL;
5026 qh->handler(ssh, pktin, qh->ctx);
5031 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5032 chandler_fn_t handler, void *ctx)
5034 struct queued_handler *qh;
5036 qh = snew(struct queued_handler);
5039 qh->handler = handler;
5043 if (ssh->qtail == NULL) {
5047 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5048 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5051 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5052 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5055 ssh->qtail->next = qh;
5060 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5062 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5064 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5065 SSH2_MSG_REQUEST_SUCCESS)) {
5066 logeventf(ssh, "Remote port forwarding from %s enabled",
5069 logeventf(ssh, "Remote port forwarding from %s refused",
5072 rpf = del234(ssh->rportfwds, pf);
5074 pf->pfrec->remote = NULL;
5079 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5082 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5085 pf->share_ctx = share_ctx;
5086 pf->shost = dupstr(shost);
5088 pf->sportdesc = NULL;
5089 if (!ssh->rportfwds) {
5090 assert(ssh->version == 2);
5091 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5093 if (add234(ssh->rportfwds, pf) != pf) {
5101 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5104 share_got_pkt_from_server(ctx, pktin->type,
5105 pktin->body, pktin->length);
5108 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5110 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5111 ssh_sharing_global_request_response, share_ctx);
5114 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5116 struct ssh_portfwd *epf;
5120 if (!ssh->portfwds) {
5121 ssh->portfwds = newtree234(ssh_portcmp);
5124 * Go through the existing port forwardings and tag them
5125 * with status==DESTROY. Any that we want to keep will be
5126 * re-enabled (status==KEEP) as we go through the
5127 * configuration and find out which bits are the same as
5130 struct ssh_portfwd *epf;
5132 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5133 epf->status = DESTROY;
5136 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5138 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5139 char *kp, *kp2, *vp, *vp2;
5140 char address_family, type;
5141 int sport,dport,sserv,dserv;
5142 char *sports, *dports, *saddr, *host;
5146 address_family = 'A';
5148 if (*kp == 'A' || *kp == '4' || *kp == '6')
5149 address_family = *kp++;
5150 if (*kp == 'L' || *kp == 'R')
5153 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5155 * There's a colon in the middle of the source port
5156 * string, which means that the part before it is
5157 * actually a source address.
5159 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5160 saddr = host_strduptrim(saddr_tmp);
5167 sport = atoi(sports);
5171 sport = net_service_lookup(sports);
5173 logeventf(ssh, "Service lookup failed for source"
5174 " port \"%s\"", sports);
5178 if (type == 'L' && !strcmp(val, "D")) {
5179 /* dynamic forwarding */
5186 /* ordinary forwarding */
5188 vp2 = vp + host_strcspn(vp, ":");
5189 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5193 dport = atoi(dports);
5197 dport = net_service_lookup(dports);
5199 logeventf(ssh, "Service lookup failed for destination"
5200 " port \"%s\"", dports);
5205 if (sport && dport) {
5206 /* Set up a description of the source port. */
5207 struct ssh_portfwd *pfrec, *epfrec;
5209 pfrec = snew(struct ssh_portfwd);
5211 pfrec->saddr = saddr;
5212 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5213 pfrec->sport = sport;
5214 pfrec->daddr = host;
5215 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5216 pfrec->dport = dport;
5217 pfrec->local = NULL;
5218 pfrec->remote = NULL;
5219 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5220 address_family == '6' ? ADDRTYPE_IPV6 :
5223 epfrec = add234(ssh->portfwds, pfrec);
5224 if (epfrec != pfrec) {
5225 if (epfrec->status == DESTROY) {
5227 * We already have a port forwarding up and running
5228 * with precisely these parameters. Hence, no need
5229 * to do anything; simply re-tag the existing one
5232 epfrec->status = KEEP;
5235 * Anything else indicates that there was a duplicate
5236 * in our input, which we'll silently ignore.
5238 free_portfwd(pfrec);
5240 pfrec->status = CREATE;
5249 * Now go through and destroy any port forwardings which were
5252 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5253 if (epf->status == DESTROY) {
5256 message = dupprintf("%s port forwarding from %s%s%d",
5257 epf->type == 'L' ? "local" :
5258 epf->type == 'R' ? "remote" : "dynamic",
5259 epf->saddr ? epf->saddr : "",
5260 epf->saddr ? ":" : "",
5263 if (epf->type != 'D') {
5264 char *msg2 = dupprintf("%s to %s:%d", message,
5265 epf->daddr, epf->dport);
5270 logeventf(ssh, "Cancelling %s", message);
5273 /* epf->remote or epf->local may be NULL if setting up a
5274 * forwarding failed. */
5276 struct ssh_rportfwd *rpf = epf->remote;
5277 struct Packet *pktout;
5280 * Cancel the port forwarding at the server
5283 if (ssh->version == 1) {
5285 * We cannot cancel listening ports on the
5286 * server side in SSH-1! There's no message
5287 * to support it. Instead, we simply remove
5288 * the rportfwd record from the local end
5289 * so that any connections the server tries
5290 * to make on it are rejected.
5293 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5294 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5295 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5297 ssh2_pkt_addstring(pktout, epf->saddr);
5298 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5299 /* XXX: rport_acceptall may not represent
5300 * what was used to open the original connection,
5301 * since it's reconfigurable. */
5302 ssh2_pkt_addstring(pktout, "");
5304 ssh2_pkt_addstring(pktout, "localhost");
5306 ssh2_pkt_adduint32(pktout, epf->sport);
5307 ssh2_pkt_send(ssh, pktout);
5310 del234(ssh->rportfwds, rpf);
5312 } else if (epf->local) {
5313 pfl_terminate(epf->local);
5316 delpos234(ssh->portfwds, i);
5318 i--; /* so we don't skip one in the list */
5322 * And finally, set up any new port forwardings (status==CREATE).
5324 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5325 if (epf->status == CREATE) {
5326 char *sportdesc, *dportdesc;
5327 sportdesc = dupprintf("%s%s%s%s%d%s",
5328 epf->saddr ? epf->saddr : "",
5329 epf->saddr ? ":" : "",
5330 epf->sserv ? epf->sserv : "",
5331 epf->sserv ? "(" : "",
5333 epf->sserv ? ")" : "");
5334 if (epf->type == 'D') {
5337 dportdesc = dupprintf("%s:%s%s%d%s",
5339 epf->dserv ? epf->dserv : "",
5340 epf->dserv ? "(" : "",
5342 epf->dserv ? ")" : "");
5345 if (epf->type == 'L') {
5346 char *err = pfl_listen(epf->daddr, epf->dport,
5347 epf->saddr, epf->sport,
5348 ssh, conf, &epf->local,
5349 epf->addressfamily);
5351 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5352 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5353 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5354 sportdesc, dportdesc,
5355 err ? " failed: " : "", err ? err : "");
5358 } else if (epf->type == 'D') {
5359 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5360 ssh, conf, &epf->local,
5361 epf->addressfamily);
5363 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5364 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5365 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5367 err ? " failed: " : "", err ? err : "");
5372 struct ssh_rportfwd *pf;
5375 * Ensure the remote port forwardings tree exists.
5377 if (!ssh->rportfwds) {
5378 if (ssh->version == 1)
5379 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5381 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5384 pf = snew(struct ssh_rportfwd);
5385 pf->share_ctx = NULL;
5386 pf->dhost = dupstr(epf->daddr);
5387 pf->dport = epf->dport;
5389 pf->shost = dupstr(epf->saddr);
5390 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5391 pf->shost = dupstr("");
5393 pf->shost = dupstr("localhost");
5395 pf->sport = epf->sport;
5396 if (add234(ssh->rportfwds, pf) != pf) {
5397 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5398 epf->daddr, epf->dport);
5401 logeventf(ssh, "Requesting remote port %s"
5402 " forward to %s", sportdesc, dportdesc);
5404 pf->sportdesc = sportdesc;
5409 if (ssh->version == 1) {
5410 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5411 PKT_INT, epf->sport,
5412 PKT_STR, epf->daddr,
5413 PKT_INT, epf->dport,
5415 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5417 ssh_rportfwd_succfail, pf);
5419 struct Packet *pktout;
5420 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5421 ssh2_pkt_addstring(pktout, "tcpip-forward");
5422 ssh2_pkt_addbool(pktout, 1);/* want reply */
5423 ssh2_pkt_addstring(pktout, pf->shost);
5424 ssh2_pkt_adduint32(pktout, pf->sport);
5425 ssh2_pkt_send(ssh, pktout);
5427 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5428 SSH2_MSG_REQUEST_FAILURE,
5429 ssh_rportfwd_succfail, pf);
5438 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5441 int stringlen, bufsize;
5443 ssh_pkt_getstring(pktin, &string, &stringlen);
5444 if (string == NULL) {
5445 bombout(("Incoming terminal data packet was badly formed"));
5449 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5451 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5452 ssh->v1_stdout_throttling = 1;
5453 ssh_throttle_conn(ssh, +1);
5457 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5459 /* Remote side is trying to open a channel to talk to our
5460 * X-Server. Give them back a local channel number. */
5461 struct ssh_channel *c;
5462 int remoteid = ssh_pkt_getuint32(pktin);
5464 logevent("Received X11 connect request");
5465 /* Refuse if X11 forwarding is disabled. */
5466 if (!ssh->X11_fwd_enabled) {
5467 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5468 PKT_INT, remoteid, PKT_END);
5469 logevent("Rejected X11 connect request");
5471 c = snew(struct ssh_channel);
5474 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5475 c->remoteid = remoteid;
5476 c->halfopen = FALSE;
5477 c->localid = alloc_channel_id(ssh);
5479 c->pending_eof = FALSE;
5480 c->throttling_conn = 0;
5481 c->type = CHAN_X11; /* identify channel type */
5482 add234(ssh->channels, c);
5483 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5484 PKT_INT, c->remoteid, PKT_INT,
5485 c->localid, PKT_END);
5486 logevent("Opened X11 forward channel");
5490 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5492 /* Remote side is trying to open a channel to talk to our
5493 * agent. Give them back a local channel number. */
5494 struct ssh_channel *c;
5495 int remoteid = ssh_pkt_getuint32(pktin);
5497 /* Refuse if agent forwarding is disabled. */
5498 if (!ssh->agentfwd_enabled) {
5499 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5500 PKT_INT, remoteid, PKT_END);
5502 c = snew(struct ssh_channel);
5504 c->remoteid = remoteid;
5505 c->halfopen = FALSE;
5506 c->localid = alloc_channel_id(ssh);
5508 c->pending_eof = FALSE;
5509 c->throttling_conn = 0;
5510 c->type = CHAN_AGENT; /* identify channel type */
5511 c->u.a.lensofar = 0;
5512 c->u.a.message = NULL;
5513 c->u.a.outstanding_requests = 0;
5514 add234(ssh->channels, c);
5515 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5516 PKT_INT, c->remoteid, PKT_INT, c->localid,
5521 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5523 /* Remote side is trying to open a channel to talk to a
5524 * forwarded port. Give them back a local channel number. */
5525 struct ssh_rportfwd pf, *pfp;
5531 remoteid = ssh_pkt_getuint32(pktin);
5532 ssh_pkt_getstring(pktin, &host, &hostsize);
5533 port = ssh_pkt_getuint32(pktin);
5535 pf.dhost = dupprintf("%.*s", hostsize, host);
5537 pfp = find234(ssh->rportfwds, &pf, NULL);
5540 logeventf(ssh, "Rejected remote port open request for %s:%d",
5542 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5543 PKT_INT, remoteid, PKT_END);
5545 struct ssh_channel *c = snew(struct ssh_channel);
5548 logeventf(ssh, "Received remote port open request for %s:%d",
5550 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5551 c, ssh->conf, pfp->pfrec->addressfamily);
5553 logeventf(ssh, "Port open failed: %s", err);
5556 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5557 PKT_INT, remoteid, PKT_END);
5559 c->remoteid = remoteid;
5560 c->halfopen = FALSE;
5561 c->localid = alloc_channel_id(ssh);
5563 c->pending_eof = FALSE;
5564 c->throttling_conn = 0;
5565 c->type = CHAN_SOCKDATA; /* identify channel type */
5566 add234(ssh->channels, c);
5567 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5568 PKT_INT, c->remoteid, PKT_INT,
5569 c->localid, PKT_END);
5570 logevent("Forwarded port opened successfully");
5577 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5579 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5580 unsigned int localid = ssh_pkt_getuint32(pktin);
5581 struct ssh_channel *c;
5583 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5584 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5585 c->remoteid = localid;
5586 c->halfopen = FALSE;
5587 c->type = CHAN_SOCKDATA;
5588 c->throttling_conn = 0;
5589 pfd_confirm(c->u.pfd.pf);
5592 if (c && c->pending_eof) {
5594 * We have a pending close on this channel,
5595 * which we decided on before the server acked
5596 * the channel open. So now we know the
5597 * remoteid, we can close it again.
5599 ssh_channel_try_eof(c);
5603 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5605 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5606 struct ssh_channel *c;
5608 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5609 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5610 logevent("Forwarded connection refused by server");
5611 pfd_close(c->u.pfd.pf);
5612 del234(ssh->channels, c);
5617 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5619 /* Remote side closes a channel. */
5620 unsigned i = ssh_pkt_getuint32(pktin);
5621 struct ssh_channel *c;
5622 c = find234(ssh->channels, &i, ssh_channelfind);
5623 if (c && !c->halfopen) {
5625 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5626 !(c->closes & CLOSES_RCVD_EOF)) {
5628 * Received CHANNEL_CLOSE, which we translate into
5631 int send_close = FALSE;
5633 c->closes |= CLOSES_RCVD_EOF;
5638 x11_send_eof(c->u.x11.xconn);
5644 pfd_send_eof(c->u.pfd.pf);
5653 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5654 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5656 c->closes |= CLOSES_SENT_EOF;
5660 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5661 !(c->closes & CLOSES_RCVD_CLOSE)) {
5663 if (!(c->closes & CLOSES_SENT_EOF)) {
5664 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5665 " for which we never sent CHANNEL_CLOSE\n", i));
5668 c->closes |= CLOSES_RCVD_CLOSE;
5671 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5672 !(c->closes & CLOSES_SENT_CLOSE)) {
5673 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5674 PKT_INT, c->remoteid, PKT_END);
5675 c->closes |= CLOSES_SENT_CLOSE;
5678 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5679 ssh_channel_destroy(c);
5681 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5682 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5683 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5688 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5690 /* Data sent down one of our channels. */
5691 int i = ssh_pkt_getuint32(pktin);
5694 struct ssh_channel *c;
5696 ssh_pkt_getstring(pktin, &p, &len);
5698 c = find234(ssh->channels, &i, ssh_channelfind);
5703 bufsize = x11_send(c->u.x11.xconn, p, len);
5706 bufsize = pfd_send(c->u.pfd.pf, p, len);
5709 /* Data for an agent message. Buffer it. */
5711 if (c->u.a.lensofar < 4) {
5712 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5713 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5717 c->u.a.lensofar += l;
5719 if (c->u.a.lensofar == 4) {
5721 4 + GET_32BIT(c->u.a.msglen);
5722 c->u.a.message = snewn(c->u.a.totallen,
5724 memcpy(c->u.a.message, c->u.a.msglen, 4);
5726 if (c->u.a.lensofar >= 4 && len > 0) {
5728 min(c->u.a.totallen - c->u.a.lensofar,
5730 memcpy(c->u.a.message + c->u.a.lensofar, p,
5734 c->u.a.lensofar += l;
5736 if (c->u.a.lensofar == c->u.a.totallen) {
5739 c->u.a.outstanding_requests++;
5740 if (agent_query(c->u.a.message,
5743 ssh_agentf_callback, c))
5744 ssh_agentf_callback(c, reply, replylen);
5745 sfree(c->u.a.message);
5746 c->u.a.lensofar = 0;
5749 bufsize = 0; /* agent channels never back up */
5752 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5753 c->throttling_conn = 1;
5754 ssh_throttle_conn(ssh, +1);
5759 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5761 ssh->exitcode = ssh_pkt_getuint32(pktin);
5762 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5763 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5765 * In case `helpful' firewalls or proxies tack
5766 * extra human-readable text on the end of the
5767 * session which we might mistake for another
5768 * encrypted packet, we close the session once
5769 * we've sent EXIT_CONFIRMATION.
5771 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5774 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5775 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5777 struct Packet *pktout = (struct Packet *)data;
5779 unsigned int arg = 0;
5780 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5781 if (i == lenof(ssh_ttymodes)) return;
5782 switch (ssh_ttymodes[i].type) {
5784 arg = ssh_tty_parse_specchar(val);
5787 arg = ssh_tty_parse_boolean(val);
5790 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5791 ssh2_pkt_addbyte(pktout, arg);
5794 int ssh_agent_forwarding_permitted(Ssh ssh)
5796 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5799 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5800 struct Packet *pktin)
5802 crBegin(ssh->do_ssh1_connection_crstate);
5804 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5805 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5806 ssh1_smsg_stdout_stderr_data;
5808 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5809 ssh1_msg_channel_open_confirmation;
5810 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5811 ssh1_msg_channel_open_failure;
5812 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5813 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5814 ssh1_msg_channel_close;
5815 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5816 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5818 if (ssh_agent_forwarding_permitted(ssh)) {
5819 logevent("Requesting agent forwarding");
5820 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5824 if (pktin->type != SSH1_SMSG_SUCCESS
5825 && pktin->type != SSH1_SMSG_FAILURE) {
5826 bombout(("Protocol confusion"));
5828 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5829 logevent("Agent forwarding refused");
5831 logevent("Agent forwarding enabled");
5832 ssh->agentfwd_enabled = TRUE;
5833 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5837 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5839 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5841 if (!ssh->x11disp) {
5842 /* FIXME: return an error message from x11_setup_display */
5843 logevent("X11 forwarding not enabled: unable to"
5844 " initialise X display");
5846 ssh->x11auth = x11_invent_fake_auth
5847 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5848 ssh->x11auth->disp = ssh->x11disp;
5850 logevent("Requesting X11 forwarding");
5851 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5852 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5853 PKT_STR, ssh->x11auth->protoname,
5854 PKT_STR, ssh->x11auth->datastring,
5855 PKT_INT, ssh->x11disp->screennum,
5858 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5859 PKT_STR, ssh->x11auth->protoname,
5860 PKT_STR, ssh->x11auth->datastring,
5866 if (pktin->type != SSH1_SMSG_SUCCESS
5867 && pktin->type != SSH1_SMSG_FAILURE) {
5868 bombout(("Protocol confusion"));
5870 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5871 logevent("X11 forwarding refused");
5873 logevent("X11 forwarding enabled");
5874 ssh->X11_fwd_enabled = TRUE;
5875 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5880 ssh_setup_portfwd(ssh, ssh->conf);
5881 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5883 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5885 /* Unpick the terminal-speed string. */
5886 /* XXX perhaps we should allow no speeds to be sent. */
5887 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5888 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5889 /* Send the pty request. */
5890 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5891 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5892 ssh_pkt_adduint32(pkt, ssh->term_height);
5893 ssh_pkt_adduint32(pkt, ssh->term_width);
5894 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5895 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5896 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5897 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5898 ssh_pkt_adduint32(pkt, ssh->ispeed);
5899 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5900 ssh_pkt_adduint32(pkt, ssh->ospeed);
5901 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5903 ssh->state = SSH_STATE_INTERMED;
5907 if (pktin->type != SSH1_SMSG_SUCCESS
5908 && pktin->type != SSH1_SMSG_FAILURE) {
5909 bombout(("Protocol confusion"));
5911 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5912 c_write_str(ssh, "Server refused to allocate pty\r\n");
5913 ssh->editing = ssh->echoing = 1;
5915 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5916 ssh->ospeed, ssh->ispeed);
5917 ssh->got_pty = TRUE;
5920 ssh->editing = ssh->echoing = 1;
5923 if (conf_get_int(ssh->conf, CONF_compression)) {
5924 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5928 if (pktin->type != SSH1_SMSG_SUCCESS
5929 && pktin->type != SSH1_SMSG_FAILURE) {
5930 bombout(("Protocol confusion"));
5932 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5933 c_write_str(ssh, "Server refused to compress\r\n");
5935 logevent("Started compression");
5936 ssh->v1_compressing = TRUE;
5937 ssh->cs_comp_ctx = zlib_compress_init();
5938 logevent("Initialised zlib (RFC1950) compression");
5939 ssh->sc_comp_ctx = zlib_decompress_init();
5940 logevent("Initialised zlib (RFC1950) decompression");
5944 * Start the shell or command.
5946 * Special case: if the first-choice command is an SSH-2
5947 * subsystem (hence not usable here) and the second choice
5948 * exists, we fall straight back to that.
5951 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5953 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5954 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5955 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5956 ssh->fallback_cmd = TRUE;
5959 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5961 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5962 logevent("Started session");
5965 ssh->state = SSH_STATE_SESSION;
5966 if (ssh->size_needed)
5967 ssh_size(ssh, ssh->term_width, ssh->term_height);
5968 if (ssh->eof_needed)
5969 ssh_special(ssh, TS_EOF);
5972 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
5974 ssh->channels = newtree234(ssh_channelcmp);
5978 * By this point, most incoming packets are already being
5979 * handled by the dispatch table, and we need only pay
5980 * attention to the unusual ones.
5985 if (pktin->type == SSH1_SMSG_SUCCESS) {
5986 /* may be from EXEC_SHELL on some servers */
5987 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5988 /* may be from EXEC_SHELL on some servers
5989 * if no pty is available or in other odd cases. Ignore */
5991 bombout(("Strange packet received: type %d", pktin->type));
5996 int len = min(inlen, 512);
5997 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5998 PKT_INT, len, PKT_DATA, in, len,
6010 * Handle the top-level SSH-2 protocol.
6012 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6017 ssh_pkt_getstring(pktin, &msg, &msglen);
6018 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
6021 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6023 /* log reason code in disconnect message */
6027 ssh_pkt_getstring(pktin, &msg, &msglen);
6028 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
6031 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6033 /* Do nothing, because we're ignoring it! Duhh. */
6036 static void ssh1_protocol_setup(Ssh ssh)
6041 * Most messages are handled by the coroutines.
6043 for (i = 0; i < 256; i++)
6044 ssh->packet_dispatch[i] = NULL;
6047 * These special message types we install handlers for.
6049 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6050 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6051 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6054 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6055 struct Packet *pktin)
6057 const unsigned char *in = (const unsigned char *)vin;
6058 if (ssh->state == SSH_STATE_CLOSED)
6061 if (pktin && ssh->packet_dispatch[pktin->type]) {
6062 ssh->packet_dispatch[pktin->type](ssh, pktin);
6066 if (!ssh->protocol_initial_phase_done) {
6067 if (do_ssh1_login(ssh, in, inlen, pktin))
6068 ssh->protocol_initial_phase_done = TRUE;
6073 do_ssh1_connection(ssh, in, inlen, pktin);
6077 * Utility routines for decoding comma-separated strings in KEXINIT.
6079 static int first_in_commasep_string(char const *needle, char const *haystack,
6083 if (!needle || !haystack) /* protect against null pointers */
6085 needlen = strlen(needle);
6087 if (haylen >= needlen && /* haystack is long enough */
6088 !memcmp(needle, haystack, needlen) && /* initial match */
6089 (haylen == needlen || haystack[needlen] == ',')
6090 /* either , or EOS follows */
6096 static int in_commasep_string(char const *needle, char const *haystack,
6101 if (!needle || !haystack) /* protect against null pointers */
6104 * Is it at the start of the string?
6106 if (first_in_commasep_string(needle, haystack, haylen))
6109 * If not, search for the next comma and resume after that.
6110 * If no comma found, terminate.
6112 p = memchr(haystack, ',', haylen);
6114 /* + 1 to skip over comma */
6115 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6119 * Add a value to the comma-separated string at the end of the packet.
6121 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6123 if (pkt->length - pkt->savedpos > 0)
6124 ssh_pkt_addstring_str(pkt, ",");
6125 ssh_pkt_addstring_str(pkt, data);
6130 * SSH-2 key derivation (RFC 4253 section 7.2).
6132 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6133 char chr, int keylen)
6135 const struct ssh_hash *h = ssh->kex->hash;
6143 /* Round up to the next multiple of hash length. */
6144 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6146 key = snewn(keylen_padded, unsigned char);
6148 /* First hlen bytes. */
6150 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6151 hash_mpint(h, s, K);
6152 h->bytes(s, H, h->hlen);
6153 h->bytes(s, &chr, 1);
6154 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6157 /* Subsequent blocks of hlen bytes. */
6158 if (keylen_padded > h->hlen) {
6162 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6163 hash_mpint(h, s, K);
6164 h->bytes(s, H, h->hlen);
6166 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6167 h->bytes(s, key + offset - h->hlen, h->hlen);
6169 h->final(s2, key + offset);
6175 /* Now clear any extra bytes of key material beyond the length
6176 * we're officially returning, because the caller won't know to
6178 if (keylen_padded > keylen)
6179 smemclr(key + keylen, keylen_padded - keylen);
6185 * Structure for constructing KEXINIT algorithm lists.
6187 #define MAXKEXLIST 16
6188 struct kexinit_algorithm {
6192 const struct ssh_kex *kex;
6195 const struct ssh_signkey *hostkey;
6197 const struct ssh2_cipher *cipher;
6201 const struct ssh_mac *mac;
6204 const struct ssh_compress *comp;
6209 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6210 * If the algorithm is already in the list, return a pointer to its
6211 * entry, otherwise return an entry from the end of the list.
6212 * This assumes that every time a particular name is passed in, it
6213 * comes from the same string constant. If this isn't true, this
6214 * function may need to be rewritten to use strcmp() instead.
6216 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6217 *list, const char *name)
6221 for (i = 0; i < MAXKEXLIST; i++)
6222 if (list[i].name == NULL || list[i].name == name) {
6223 list[i].name = name;
6226 assert(!"No space in KEXINIT list");
6231 * Handle the SSH-2 transport layer.
6233 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6234 struct Packet *pktin)
6236 const unsigned char *in = (const unsigned char *)vin;
6238 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6239 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6242 const char * kexlist_descr[NKEXLIST] = {
6243 "key exchange algorithm", "host key algorithm",
6244 "client-to-server cipher", "server-to-client cipher",
6245 "client-to-server MAC", "server-to-client MAC",
6246 "client-to-server compression method",
6247 "server-to-client compression method" };
6248 struct do_ssh2_transport_state {
6250 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
6251 Bignum p, g, e, f, K;
6254 int kex_init_value, kex_reply_value;
6255 const struct ssh_mac **maclist;
6257 const struct ssh2_cipher *cscipher_tobe;
6258 const struct ssh2_cipher *sccipher_tobe;
6259 const struct ssh_mac *csmac_tobe;
6260 const struct ssh_mac *scmac_tobe;
6261 int csmac_etm_tobe, scmac_etm_tobe;
6262 const struct ssh_compress *cscomp_tobe;
6263 const struct ssh_compress *sccomp_tobe;
6264 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6265 int hostkeylen, siglen, rsakeylen;
6266 void *hkey; /* actual host key */
6267 void *rsakey; /* for RSA kex */
6268 void *eckey; /* for ECDH kex */
6269 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6270 int n_preferred_kex;
6271 const struct ssh_kexes *preferred_kex[KEX_MAX];
6272 int n_preferred_ciphers;
6273 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6274 const struct ssh_compress *preferred_comp;
6275 int userauth_succeeded; /* for delayed compression */
6276 int pending_compression;
6277 int got_session_id, activated_authconn;
6278 struct Packet *pktout;
6282 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6284 crState(do_ssh2_transport_state);
6286 assert(!ssh->bare_connection);
6290 s->cscipher_tobe = s->sccipher_tobe = NULL;
6291 s->csmac_tobe = s->scmac_tobe = NULL;
6292 s->cscomp_tobe = s->sccomp_tobe = NULL;
6294 s->got_session_id = s->activated_authconn = FALSE;
6295 s->userauth_succeeded = FALSE;
6296 s->pending_compression = FALSE;
6299 * Be prepared to work around the buggy MAC problem.
6301 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6302 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6304 s->maclist = macs, s->nmacs = lenof(macs);
6307 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6310 struct kexinit_algorithm *alg;
6313 * Set up the preferred key exchange. (NULL => warn below here)
6315 s->n_preferred_kex = 0;
6316 for (i = 0; i < KEX_MAX; i++) {
6317 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6319 s->preferred_kex[s->n_preferred_kex++] =
6320 &ssh_diffiehellman_gex;
6323 s->preferred_kex[s->n_preferred_kex++] =
6324 &ssh_diffiehellman_group14;
6327 s->preferred_kex[s->n_preferred_kex++] =
6328 &ssh_diffiehellman_group1;
6331 s->preferred_kex[s->n_preferred_kex++] =
6335 s->preferred_kex[s->n_preferred_kex++] =
6339 /* Flag for later. Don't bother if it's the last in
6341 if (i < KEX_MAX - 1) {
6342 s->preferred_kex[s->n_preferred_kex++] = NULL;
6349 * Set up the preferred ciphers. (NULL => warn below here)
6351 s->n_preferred_ciphers = 0;
6352 for (i = 0; i < CIPHER_MAX; i++) {
6353 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6354 case CIPHER_BLOWFISH:
6355 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6358 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6359 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6363 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6366 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6368 case CIPHER_ARCFOUR:
6369 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6371 case CIPHER_CHACHA20:
6372 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6375 /* Flag for later. Don't bother if it's the last in
6377 if (i < CIPHER_MAX - 1) {
6378 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6385 * Set up preferred compression.
6387 if (conf_get_int(ssh->conf, CONF_compression))
6388 s->preferred_comp = &ssh_zlib;
6390 s->preferred_comp = &ssh_comp_none;
6393 * Enable queueing of outgoing auth- or connection-layer
6394 * packets while we are in the middle of a key exchange.
6396 ssh->queueing = TRUE;
6399 * Flag that KEX is in progress.
6401 ssh->kex_in_progress = TRUE;
6403 for (i = 0; i < NKEXLIST; i++)
6404 for (j = 0; j < MAXKEXLIST; j++)
6405 s->kexlists[i][j].name = NULL;
6406 /* List key exchange algorithms. */
6408 for (i = 0; i < s->n_preferred_kex; i++) {
6409 const struct ssh_kexes *k = s->preferred_kex[i];
6410 if (!k) warn = TRUE;
6411 else for (j = 0; j < k->nkexes; j++) {
6412 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6414 alg->u.kex.kex = k->list[j];
6415 alg->u.kex.warn = warn;
6418 /* List server host key algorithms. */
6419 if (!s->got_session_id) {
6421 * In the first key exchange, we list all the algorithms
6422 * we're prepared to cope with, but prefer those algorithms
6423 * for which we have a host key for this host.
6425 for (i = 0; i < lenof(hostkey_algs); i++) {
6426 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6427 hostkey_algs[i]->keytype)) {
6428 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6429 hostkey_algs[i]->name);
6430 alg->u.hostkey = hostkey_algs[i];
6433 for (i = 0; i < lenof(hostkey_algs); i++) {
6434 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6435 hostkey_algs[i]->name);
6436 alg->u.hostkey = hostkey_algs[i];
6440 * In subsequent key exchanges, we list only the kex
6441 * algorithm that was selected in the first key exchange,
6442 * so that we keep getting the same host key and hence
6443 * don't have to interrupt the user's session to ask for
6447 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6448 ssh->hostkey->name);
6449 alg->u.hostkey = ssh->hostkey;
6451 /* List encryption algorithms (client->server then server->client). */
6452 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6454 for (i = 0; i < s->n_preferred_ciphers; i++) {
6455 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6456 if (!c) warn = TRUE;
6457 else for (j = 0; j < c->nciphers; j++) {
6458 alg = ssh2_kexinit_addalg(s->kexlists[k],
6460 alg->u.cipher.cipher = c->list[j];
6461 alg->u.cipher.warn = warn;
6465 /* List MAC algorithms (client->server then server->client). */
6466 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6467 for (i = 0; i < s->nmacs; i++) {
6468 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6469 alg->u.mac.mac = s->maclist[i];
6470 alg->u.mac.etm = FALSE;
6472 for (i = 0; i < s->nmacs; i++)
6473 /* For each MAC, there may also be an ETM version,
6474 * which we list second. */
6475 if (s->maclist[i]->etm_name) {
6476 alg = ssh2_kexinit_addalg(s->kexlists[j],
6477 s->maclist[i]->etm_name);
6478 alg->u.mac.mac = s->maclist[i];
6479 alg->u.mac.etm = TRUE;
6482 /* List client->server compression algorithms,
6483 * then server->client compression algorithms. (We use the
6484 * same set twice.) */
6485 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6486 assert(lenof(compressions) > 1);
6487 /* Prefer non-delayed versions */
6488 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6489 alg->u.comp = s->preferred_comp;
6490 /* We don't even list delayed versions of algorithms until
6491 * they're allowed to be used, to avoid a race. See the end of
6493 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6494 alg = ssh2_kexinit_addalg(s->kexlists[j],
6495 s->preferred_comp->delayed_name);
6496 alg->u.comp = s->preferred_comp;
6498 for (i = 0; i < lenof(compressions); i++) {
6499 const struct ssh_compress *c = compressions[i];
6500 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6502 if (s->userauth_succeeded && c->delayed_name) {
6503 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6509 * Construct and send our key exchange packet.
6511 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6512 for (i = 0; i < 16; i++)
6513 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6514 for (i = 0; i < NKEXLIST; i++) {
6515 ssh2_pkt_addstring_start(s->pktout);
6516 for (j = 0; j < MAXKEXLIST; j++) {
6517 if (s->kexlists[i][j].name == NULL) break;
6518 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6521 /* List client->server languages. Empty list. */
6522 ssh2_pkt_addstring_start(s->pktout);
6523 /* List server->client languages. Empty list. */
6524 ssh2_pkt_addstring_start(s->pktout);
6525 /* First KEX packet does _not_ follow, because we're not that brave. */
6526 ssh2_pkt_addbool(s->pktout, FALSE);
6528 ssh2_pkt_adduint32(s->pktout, 0);
6531 s->our_kexinitlen = s->pktout->length - 5;
6532 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6533 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6535 ssh2_pkt_send_noqueue(ssh, s->pktout);
6538 crWaitUntilV(pktin);
6541 * Now examine the other side's KEXINIT to see what we're up
6548 if (pktin->type != SSH2_MSG_KEXINIT) {
6549 bombout(("expected key exchange packet from server"));
6553 ssh->hostkey = NULL;
6554 s->cscipher_tobe = NULL;
6555 s->sccipher_tobe = NULL;
6556 s->csmac_tobe = NULL;
6557 s->scmac_tobe = NULL;
6558 s->cscomp_tobe = NULL;
6559 s->sccomp_tobe = NULL;
6560 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
6562 pktin->savedpos += 16; /* skip garbage cookie */
6565 for (i = 0; i < NKEXLIST; i++) {
6566 ssh_pkt_getstring(pktin, &str, &len);
6568 bombout(("KEXINIT packet was incomplete"));
6572 /* If we've already selected a cipher which requires a
6573 * particular MAC, then just select that, and don't even
6574 * bother looking through the server's KEXINIT string for
6576 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6577 s->cscipher_tobe->required_mac) {
6578 s->csmac_tobe = s->cscipher_tobe->required_mac;
6579 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6582 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6583 s->sccipher_tobe->required_mac) {
6584 s->scmac_tobe = s->sccipher_tobe->required_mac;
6585 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6589 for (j = 0; j < MAXKEXLIST; j++) {
6590 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6591 if (alg->name == NULL) break;
6592 if (in_commasep_string(alg->name, str, len)) {
6593 /* We've found a matching algorithm. */
6594 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6595 /* Check if we might need to ignore first kex pkt */
6597 !first_in_commasep_string(alg->name, str, len))
6600 if (i == KEXLIST_KEX) {
6601 ssh->kex = alg->u.kex.kex;
6602 s->warn_kex = alg->u.kex.warn;
6603 } else if (i == KEXLIST_HOSTKEY) {
6604 ssh->hostkey = alg->u.hostkey;
6605 } else if (i == KEXLIST_CSCIPHER) {
6606 s->cscipher_tobe = alg->u.cipher.cipher;
6607 s->warn_cscipher = alg->u.cipher.warn;
6608 } else if (i == KEXLIST_SCCIPHER) {
6609 s->sccipher_tobe = alg->u.cipher.cipher;
6610 s->warn_sccipher = alg->u.cipher.warn;
6611 } else if (i == KEXLIST_CSMAC) {
6612 s->csmac_tobe = alg->u.mac.mac;
6613 s->csmac_etm_tobe = alg->u.mac.etm;
6614 } else if (i == KEXLIST_SCMAC) {
6615 s->scmac_tobe = alg->u.mac.mac;
6616 s->scmac_etm_tobe = alg->u.mac.etm;
6617 } else if (i == KEXLIST_CSCOMP) {
6618 s->cscomp_tobe = alg->u.comp;
6619 } else if (i == KEXLIST_SCCOMP) {
6620 s->sccomp_tobe = alg->u.comp;
6624 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6625 in_commasep_string(alg->u.comp->delayed_name, str, len))
6626 s->pending_compression = TRUE; /* try this later */
6628 bombout(("Couldn't agree a %s ((available: %.*s)",
6629 kexlist_descr[i], len, str));
6634 if (s->pending_compression) {
6635 logevent("Server supports delayed compression; "
6636 "will try this later");
6638 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6639 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6640 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6642 ssh->exhash = ssh->kex->hash->init();
6643 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6644 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6645 hash_string(ssh->kex->hash, ssh->exhash,
6646 s->our_kexinit, s->our_kexinitlen);
6647 sfree(s->our_kexinit);
6648 /* Include the type byte in the hash of server's KEXINIT */
6649 hash_string(ssh->kex->hash, ssh->exhash,
6650 pktin->body - 1, pktin->length + 1);
6653 ssh_set_frozen(ssh, 1);
6654 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6656 ssh_dialog_callback, ssh);
6657 if (s->dlgret < 0) {
6661 bombout(("Unexpected data from server while"
6662 " waiting for user response"));
6665 } while (pktin || inlen > 0);
6666 s->dlgret = ssh->user_response;
6668 ssh_set_frozen(ssh, 0);
6669 if (s->dlgret == 0) {
6670 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6676 if (s->warn_cscipher) {
6677 ssh_set_frozen(ssh, 1);
6678 s->dlgret = askalg(ssh->frontend,
6679 "client-to-server cipher",
6680 s->cscipher_tobe->name,
6681 ssh_dialog_callback, ssh);
6682 if (s->dlgret < 0) {
6686 bombout(("Unexpected data from server while"
6687 " waiting for user response"));
6690 } while (pktin || inlen > 0);
6691 s->dlgret = ssh->user_response;
6693 ssh_set_frozen(ssh, 0);
6694 if (s->dlgret == 0) {
6695 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6701 if (s->warn_sccipher) {
6702 ssh_set_frozen(ssh, 1);
6703 s->dlgret = askalg(ssh->frontend,
6704 "server-to-client cipher",
6705 s->sccipher_tobe->name,
6706 ssh_dialog_callback, ssh);
6707 if (s->dlgret < 0) {
6711 bombout(("Unexpected data from server while"
6712 " waiting for user response"));
6715 } while (pktin || inlen > 0);
6716 s->dlgret = ssh->user_response;
6718 ssh_set_frozen(ssh, 0);
6719 if (s->dlgret == 0) {
6720 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6726 if (s->ignorepkt) /* first_kex_packet_follows */
6727 crWaitUntilV(pktin); /* Ignore packet */
6730 if (ssh->kex->main_type == KEXTYPE_DH) {
6732 * Work out the number of bits of key we will need from the
6733 * key exchange. We start with the maximum key length of
6739 csbits = s->cscipher_tobe->real_keybits;
6740 scbits = s->sccipher_tobe->real_keybits;
6741 s->nbits = (csbits > scbits ? csbits : scbits);
6743 /* The keys only have hlen-bit entropy, since they're based on
6744 * a hash. So cap the key size at hlen bits. */
6745 if (s->nbits > ssh->kex->hash->hlen * 8)
6746 s->nbits = ssh->kex->hash->hlen * 8;
6749 * If we're doing Diffie-Hellman group exchange, start by
6750 * requesting a group.
6752 if (dh_is_gex(ssh->kex)) {
6753 logevent("Doing Diffie-Hellman group exchange");
6754 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6756 * Work out how big a DH group we will need to allow that
6759 s->pbits = 512 << ((s->nbits - 1) / 64);
6760 if (s->pbits < DH_MIN_SIZE)
6761 s->pbits = DH_MIN_SIZE;
6762 if (s->pbits > DH_MAX_SIZE)
6763 s->pbits = DH_MAX_SIZE;
6764 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6765 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6766 ssh2_pkt_adduint32(s->pktout, s->pbits);
6768 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6769 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6770 ssh2_pkt_adduint32(s->pktout, s->pbits);
6771 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6773 ssh2_pkt_send_noqueue(ssh, s->pktout);
6775 crWaitUntilV(pktin);
6776 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6777 bombout(("expected key exchange group packet from server"));
6780 s->p = ssh2_pkt_getmp(pktin);
6781 s->g = ssh2_pkt_getmp(pktin);
6782 if (!s->p || !s->g) {
6783 bombout(("unable to read mp-ints from incoming group packet"));
6786 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6787 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6788 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6790 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6791 ssh->kex_ctx = dh_setup_group(ssh->kex);
6792 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6793 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6794 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6795 ssh->kex->groupname);
6798 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6799 ssh->kex->hash->text_name);
6801 * Now generate and send e for Diffie-Hellman.
6803 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6804 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6805 s->pktout = ssh2_pkt_init(s->kex_init_value);
6806 ssh2_pkt_addmp(s->pktout, s->e);
6807 ssh2_pkt_send_noqueue(ssh, s->pktout);
6809 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6810 crWaitUntilV(pktin);
6811 if (pktin->type != s->kex_reply_value) {
6812 bombout(("expected key exchange reply packet from server"));
6815 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6816 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6817 if (!s->hostkeydata) {
6818 bombout(("unable to parse key exchange reply packet"));
6821 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6822 s->hostkeydata, s->hostkeylen);
6823 s->f = ssh2_pkt_getmp(pktin);
6825 bombout(("unable to parse key exchange reply packet"));
6828 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6830 bombout(("unable to parse key exchange reply packet"));
6835 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
6837 bombout(("key exchange reply failed validation: %s", err));
6841 s->K = dh_find_K(ssh->kex_ctx, s->f);
6843 /* We assume everything from now on will be quick, and it might
6844 * involve user interaction. */
6845 set_busy_status(ssh->frontend, BUSY_NOT);
6847 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6848 if (dh_is_gex(ssh->kex)) {
6849 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6850 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
6851 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6852 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6853 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
6854 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6855 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6857 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6858 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6860 dh_cleanup(ssh->kex_ctx);
6862 if (dh_is_gex(ssh->kex)) {
6866 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
6868 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
6869 ssh_ecdhkex_curve_textname(ssh->kex),
6870 ssh->kex->hash->text_name);
6871 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
6873 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
6875 bombout(("Unable to generate key for ECDH"));
6881 int publicPointLength;
6882 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6884 ssh_ecdhkex_freekey(s->eckey);
6885 bombout(("Unable to encode public key for ECDH"));
6888 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
6889 ssh2_pkt_addstring_start(s->pktout);
6890 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
6894 ssh2_pkt_send_noqueue(ssh, s->pktout);
6896 crWaitUntilV(pktin);
6897 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
6898 ssh_ecdhkex_freekey(s->eckey);
6899 bombout(("expected ECDH reply packet from server"));
6903 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6904 if (!s->hostkeydata) {
6905 bombout(("unable to parse ECDH reply packet"));
6908 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6909 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6910 s->hostkeydata, s->hostkeylen);
6914 int publicPointLength;
6915 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6917 ssh_ecdhkex_freekey(s->eckey);
6918 bombout(("Unable to encode public key for ECDH hash"));
6921 hash_string(ssh->kex->hash, ssh->exhash,
6922 publicPoint, publicPointLength);
6929 ssh_pkt_getstring(pktin, &keydata, &keylen);
6931 bombout(("unable to parse ECDH reply packet"));
6934 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
6935 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
6937 ssh_ecdhkex_freekey(s->eckey);
6938 bombout(("point received in ECDH was not valid"));
6943 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6945 bombout(("unable to parse key exchange reply packet"));
6949 ssh_ecdhkex_freekey(s->eckey);
6951 logeventf(ssh, "Doing RSA key exchange with hash %s",
6952 ssh->kex->hash->text_name);
6953 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6955 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6958 crWaitUntilV(pktin);
6959 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6960 bombout(("expected RSA public key packet from server"));
6964 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6965 if (!s->hostkeydata) {
6966 bombout(("unable to parse RSA public key packet"));
6969 hash_string(ssh->kex->hash, ssh->exhash,
6970 s->hostkeydata, s->hostkeylen);
6971 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6972 s->hostkeydata, s->hostkeylen);
6976 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6978 bombout(("unable to parse RSA public key packet"));
6981 s->rsakeydata = snewn(s->rsakeylen, char);
6982 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6985 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6987 sfree(s->rsakeydata);
6988 bombout(("unable to parse RSA public key from server"));
6992 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6995 * Next, set up a shared secret K, of precisely KLEN -
6996 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6997 * RSA key modulus and HLEN is the bit length of the hash
7001 int klen = ssh_rsakex_klen(s->rsakey);
7002 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7004 unsigned char *kstr1, *kstr2, *outstr;
7005 int kstr1len, kstr2len, outstrlen;
7007 s->K = bn_power_2(nbits - 1);
7009 for (i = 0; i < nbits; i++) {
7011 byte = random_byte();
7013 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7017 * Encode this as an mpint.
7019 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7020 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7021 PUT_32BIT(kstr2, kstr1len);
7022 memcpy(kstr2 + 4, kstr1, kstr1len);
7025 * Encrypt it with the given RSA key.
7027 outstrlen = (klen + 7) / 8;
7028 outstr = snewn(outstrlen, unsigned char);
7029 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7030 outstr, outstrlen, s->rsakey);
7033 * And send it off in a return packet.
7035 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7036 ssh2_pkt_addstring_start(s->pktout);
7037 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7038 ssh2_pkt_send_noqueue(ssh, s->pktout);
7040 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7047 ssh_rsakex_freekey(s->rsakey);
7049 crWaitUntilV(pktin);
7050 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7051 sfree(s->rsakeydata);
7052 bombout(("expected signature packet from server"));
7056 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7058 bombout(("unable to parse signature packet"));
7062 sfree(s->rsakeydata);
7065 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7066 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7067 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7069 ssh->kex_ctx = NULL;
7072 debug(("Exchange hash is:\n"));
7073 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7077 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7078 (char *)s->exchange_hash,
7079 ssh->kex->hash->hlen)) {
7080 bombout(("Server's host key did not match the signature supplied"));
7084 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7085 if (!s->got_session_id) {
7087 * Authenticate remote host: verify host key. (We've already
7088 * checked the signature of the exchange hash.)
7090 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7091 logevent("Host key fingerprint is:");
7092 logevent(s->fingerprint);
7093 /* First check against manually configured host keys. */
7094 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7095 ssh->hostkey, s->hkey);
7096 if (s->dlgret == 0) { /* did not match */
7097 bombout(("Host key did not appear in manually configured list"));
7099 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7100 ssh_set_frozen(ssh, 1);
7101 s->dlgret = verify_ssh_host_key(ssh->frontend,
7102 ssh->savedhost, ssh->savedport,
7103 ssh->hostkey->keytype, s->keystr,
7105 ssh_dialog_callback, ssh);
7106 if (s->dlgret < 0) {
7110 bombout(("Unexpected data from server while waiting"
7111 " for user host key response"));
7114 } while (pktin || inlen > 0);
7115 s->dlgret = ssh->user_response;
7117 ssh_set_frozen(ssh, 0);
7118 if (s->dlgret == 0) {
7119 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7124 sfree(s->fingerprint);
7126 * Save this host key, to check against the one presented in
7127 * subsequent rekeys.
7129 ssh->hostkey_str = s->keystr;
7132 * In a rekey, we never present an interactive host key
7133 * verification request to the user. Instead, we simply
7134 * enforce that the key we're seeing this time is identical to
7135 * the one we saw before.
7137 if (strcmp(ssh->hostkey_str, s->keystr)) {
7138 bombout(("Host key was different in repeat key exchange"));
7143 ssh->hostkey->freekey(s->hkey);
7146 * The exchange hash from the very first key exchange is also
7147 * the session id, used in session key construction and
7150 if (!s->got_session_id) {
7151 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7152 memcpy(ssh->v2_session_id, s->exchange_hash,
7153 sizeof(s->exchange_hash));
7154 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7155 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7156 s->got_session_id = TRUE;
7160 * Send SSH2_MSG_NEWKEYS.
7162 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7163 ssh2_pkt_send_noqueue(ssh, s->pktout);
7164 ssh->outgoing_data_size = 0; /* start counting from here */
7167 * We've sent client NEWKEYS, so create and initialise
7168 * client-to-server session keys.
7170 if (ssh->cs_cipher_ctx)
7171 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7172 ssh->cscipher = s->cscipher_tobe;
7173 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7175 if (ssh->cs_mac_ctx)
7176 ssh->csmac->free_context(ssh->cs_mac_ctx);
7177 ssh->csmac = s->csmac_tobe;
7178 ssh->csmac_etm = s->csmac_etm_tobe;
7179 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7181 if (ssh->cs_comp_ctx)
7182 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7183 ssh->cscomp = s->cscomp_tobe;
7184 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7187 * Set IVs on client-to-server keys. Here we use the exchange
7188 * hash from the _first_ key exchange.
7193 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7194 ssh->cscipher->padded_keybytes);
7195 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7196 smemclr(key, ssh->cscipher->padded_keybytes);
7199 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7200 ssh->cscipher->blksize);
7201 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7202 smemclr(key, ssh->cscipher->blksize);
7205 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7206 ssh->csmac->keylen);
7207 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7208 smemclr(key, ssh->csmac->keylen);
7212 logeventf(ssh, "Initialised %.200s client->server encryption",
7213 ssh->cscipher->text_name);
7214 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7215 ssh->csmac->text_name,
7216 ssh->csmac_etm ? " (in ETM mode)" : "",
7217 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7218 if (ssh->cscomp->text_name)
7219 logeventf(ssh, "Initialised %s compression",
7220 ssh->cscomp->text_name);
7223 * Now our end of the key exchange is complete, we can send all
7224 * our queued higher-layer packets.
7226 ssh->queueing = FALSE;
7227 ssh2_pkt_queuesend(ssh);
7230 * Expect SSH2_MSG_NEWKEYS from server.
7232 crWaitUntilV(pktin);
7233 if (pktin->type != SSH2_MSG_NEWKEYS) {
7234 bombout(("expected new-keys packet from server"));
7237 ssh->incoming_data_size = 0; /* start counting from here */
7240 * We've seen server NEWKEYS, so create and initialise
7241 * server-to-client session keys.
7243 if (ssh->sc_cipher_ctx)
7244 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7245 ssh->sccipher = s->sccipher_tobe;
7246 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7248 if (ssh->sc_mac_ctx)
7249 ssh->scmac->free_context(ssh->sc_mac_ctx);
7250 ssh->scmac = s->scmac_tobe;
7251 ssh->scmac_etm = s->scmac_etm_tobe;
7252 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7254 if (ssh->sc_comp_ctx)
7255 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7256 ssh->sccomp = s->sccomp_tobe;
7257 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7260 * Set IVs on server-to-client keys. Here we use the exchange
7261 * hash from the _first_ key exchange.
7266 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7267 ssh->sccipher->padded_keybytes);
7268 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7269 smemclr(key, ssh->sccipher->padded_keybytes);
7272 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7273 ssh->sccipher->blksize);
7274 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7275 smemclr(key, ssh->sccipher->blksize);
7278 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7279 ssh->scmac->keylen);
7280 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7281 smemclr(key, ssh->scmac->keylen);
7284 logeventf(ssh, "Initialised %.200s server->client encryption",
7285 ssh->sccipher->text_name);
7286 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7287 ssh->scmac->text_name,
7288 ssh->scmac_etm ? " (in ETM mode)" : "",
7289 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7290 if (ssh->sccomp->text_name)
7291 logeventf(ssh, "Initialised %s decompression",
7292 ssh->sccomp->text_name);
7295 * Free shared secret.
7300 * Key exchange is over. Loop straight back round if we have a
7301 * deferred rekey reason.
7303 if (ssh->deferred_rekey_reason) {
7304 logevent(ssh->deferred_rekey_reason);
7306 ssh->deferred_rekey_reason = NULL;
7307 goto begin_key_exchange;
7311 * Otherwise, schedule a timer for our next rekey.
7313 ssh->kex_in_progress = FALSE;
7314 ssh->last_rekey = GETTICKCOUNT();
7315 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7316 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7320 * Now we're encrypting. Begin returning 1 to the protocol main
7321 * function so that other things can run on top of the
7322 * transport. If we ever see a KEXINIT, we must go back to the
7325 * We _also_ go back to the start if we see pktin==NULL and
7326 * inlen negative, because this is a special signal meaning
7327 * `initiate client-driven rekey', and `in' contains a message
7328 * giving the reason for the rekey.
7330 * inlen==-1 means always initiate a rekey;
7331 * inlen==-2 means that userauth has completed successfully and
7332 * we should consider rekeying (for delayed compression).
7334 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7335 (!pktin && inlen < 0))) {
7337 if (!ssh->protocol_initial_phase_done) {
7338 ssh->protocol_initial_phase_done = TRUE;
7340 * Allow authconn to initialise itself.
7342 do_ssh2_authconn(ssh, NULL, 0, NULL);
7347 logevent("Server initiated key re-exchange");
7351 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7352 * delayed compression, if it's available.
7354 * draft-miller-secsh-compression-delayed-00 says that you
7355 * negotiate delayed compression in the first key exchange, and
7356 * both sides start compressing when the server has sent
7357 * USERAUTH_SUCCESS. This has a race condition -- the server
7358 * can't know when the client has seen it, and thus which incoming
7359 * packets it should treat as compressed.
7361 * Instead, we do the initial key exchange without offering the
7362 * delayed methods, but note if the server offers them; when we
7363 * get here, if a delayed method was available that was higher
7364 * on our list than what we got, we initiate a rekey in which we
7365 * _do_ list the delayed methods (and hopefully get it as a
7366 * result). Subsequent rekeys will do the same.
7368 assert(!s->userauth_succeeded); /* should only happen once */
7369 s->userauth_succeeded = TRUE;
7370 if (!s->pending_compression)
7371 /* Can't see any point rekeying. */
7372 goto wait_for_rekey; /* this is utterly horrid */
7373 /* else fall through to rekey... */
7374 s->pending_compression = FALSE;
7377 * Now we've decided to rekey.
7379 * Special case: if the server bug is set that doesn't
7380 * allow rekeying, we give a different log message and
7381 * continue waiting. (If such a server _initiates_ a rekey,
7382 * we process it anyway!)
7384 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7385 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7387 /* Reset the counters, so that at least this message doesn't
7388 * hit the event log _too_ often. */
7389 ssh->outgoing_data_size = 0;
7390 ssh->incoming_data_size = 0;
7391 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7393 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7396 goto wait_for_rekey; /* this is still utterly horrid */
7398 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7401 goto begin_key_exchange;
7407 * Add data to an SSH-2 channel output buffer.
7409 static void ssh2_add_channel_data(struct ssh_channel *c, const char *buf,
7412 bufchain_add(&c->v.v2.outbuffer, buf, len);
7416 * Attempt to send data on an SSH-2 channel.
7418 static int ssh2_try_send(struct ssh_channel *c)
7421 struct Packet *pktout;
7424 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7427 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7428 if ((unsigned)len > c->v.v2.remwindow)
7429 len = c->v.v2.remwindow;
7430 if ((unsigned)len > c->v.v2.remmaxpkt)
7431 len = c->v.v2.remmaxpkt;
7432 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7433 ssh2_pkt_adduint32(pktout, c->remoteid);
7434 ssh2_pkt_addstring_start(pktout);
7435 ssh2_pkt_addstring_data(pktout, data, len);
7436 ssh2_pkt_send(ssh, pktout);
7437 bufchain_consume(&c->v.v2.outbuffer, len);
7438 c->v.v2.remwindow -= len;
7442 * After having sent as much data as we can, return the amount
7445 ret = bufchain_size(&c->v.v2.outbuffer);
7448 * And if there's no data pending but we need to send an EOF, send
7451 if (!ret && c->pending_eof)
7452 ssh_channel_try_eof(c);
7457 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7460 if (c->closes & CLOSES_SENT_EOF)
7461 return; /* don't send on channels we've EOFed */
7462 bufsize = ssh2_try_send(c);
7465 case CHAN_MAINSESSION:
7466 /* stdin need not receive an unthrottle
7467 * notification since it will be polled */
7470 x11_unthrottle(c->u.x11.xconn);
7473 /* agent sockets are request/response and need no
7474 * buffer management */
7477 pfd_unthrottle(c->u.pfd.pf);
7483 static int ssh_is_simple(Ssh ssh)
7486 * We use the 'simple' variant of the SSH protocol if we're asked
7487 * to, except not if we're also doing connection-sharing (either
7488 * tunnelling our packets over an upstream or expecting to be
7489 * tunnelled over ourselves), since then the assumption that we
7490 * have only one channel to worry about is not true after all.
7492 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7493 !ssh->bare_connection && !ssh->connshare);
7497 * Set up most of a new ssh_channel for SSH-2.
7499 static void ssh2_channel_init(struct ssh_channel *c)
7502 c->localid = alloc_channel_id(ssh);
7504 c->pending_eof = FALSE;
7505 c->throttling_conn = FALSE;
7506 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7507 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7508 c->v.v2.chanreq_head = NULL;
7509 c->v.v2.throttle_state = UNTHROTTLED;
7510 bufchain_init(&c->v.v2.outbuffer);
7514 * Construct the common parts of a CHANNEL_OPEN.
7516 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7519 struct Packet *pktout;
7521 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7522 ssh2_pkt_addstring(pktout, type);
7523 ssh2_pkt_adduint32(pktout, c->localid);
7524 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7525 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7530 * CHANNEL_FAILURE doesn't come with any indication of what message
7531 * caused it, so we have to keep track of the outstanding
7532 * CHANNEL_REQUESTs ourselves.
7534 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7535 cchandler_fn_t handler, void *ctx)
7537 struct outstanding_channel_request *ocr =
7538 snew(struct outstanding_channel_request);
7540 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7541 ocr->handler = handler;
7544 if (!c->v.v2.chanreq_head)
7545 c->v.v2.chanreq_head = ocr;
7547 c->v.v2.chanreq_tail->next = ocr;
7548 c->v.v2.chanreq_tail = ocr;
7552 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7553 * NULL then a reply will be requested and the handler will be called
7554 * when it arrives. The returned packet is ready to have any
7555 * request-specific data added and be sent. Note that if a handler is
7556 * provided, it's essential that the request actually be sent.
7558 * The handler will usually be passed the response packet in pktin. If
7559 * pktin is NULL, this means that no reply will ever be forthcoming
7560 * (e.g. because the entire connection is being destroyed, or because
7561 * the server initiated channel closure before we saw the response)
7562 * and the handler should free any storage it's holding.
7564 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7566 cchandler_fn_t handler, void *ctx)
7568 struct Packet *pktout;
7570 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7571 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7572 ssh2_pkt_adduint32(pktout, c->remoteid);
7573 ssh2_pkt_addstring(pktout, type);
7574 ssh2_pkt_addbool(pktout, handler != NULL);
7575 if (handler != NULL)
7576 ssh2_queue_chanreq_handler(c, handler, ctx);
7581 * Potentially enlarge the window on an SSH-2 channel.
7583 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7585 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7590 * Never send WINDOW_ADJUST for a channel that the remote side has
7591 * already sent EOF on; there's no point, since it won't be
7592 * sending any more data anyway. Ditto if _we've_ already sent
7595 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7599 * Also, never widen the window for an X11 channel when we're
7600 * still waiting to see its initial auth and may yet hand it off
7603 if (c->type == CHAN_X11 && c->u.x11.initial)
7607 * If the remote end has a habit of ignoring maxpkt, limit the
7608 * window so that it has no choice (assuming it doesn't ignore the
7611 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7612 newwin = OUR_V2_MAXPKT;
7615 * Only send a WINDOW_ADJUST if there's significantly more window
7616 * available than the other end thinks there is. This saves us
7617 * sending a WINDOW_ADJUST for every character in a shell session.
7619 * "Significant" is arbitrarily defined as half the window size.
7621 if (newwin / 2 >= c->v.v2.locwindow) {
7622 struct Packet *pktout;
7626 * In order to keep track of how much window the client
7627 * actually has available, we'd like it to acknowledge each
7628 * WINDOW_ADJUST. We can't do that directly, so we accompany
7629 * it with a CHANNEL_REQUEST that has to be acknowledged.
7631 * This is only necessary if we're opening the window wide.
7632 * If we're not, then throughput is being constrained by
7633 * something other than the maximum window size anyway.
7635 if (newwin == c->v.v2.locmaxwin &&
7636 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7637 up = snew(unsigned);
7638 *up = newwin - c->v.v2.locwindow;
7639 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7640 ssh2_handle_winadj_response, up);
7641 ssh2_pkt_send(ssh, pktout);
7643 if (c->v.v2.throttle_state != UNTHROTTLED)
7644 c->v.v2.throttle_state = UNTHROTTLING;
7646 /* Pretend the WINDOW_ADJUST was acked immediately. */
7647 c->v.v2.remlocwin = newwin;
7648 c->v.v2.throttle_state = THROTTLED;
7650 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7651 ssh2_pkt_adduint32(pktout, c->remoteid);
7652 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7653 ssh2_pkt_send(ssh, pktout);
7654 c->v.v2.locwindow = newwin;
7659 * Find the channel associated with a message. If there's no channel,
7660 * or it's not properly open, make a noise about it and return NULL.
7662 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7664 unsigned localid = ssh_pkt_getuint32(pktin);
7665 struct ssh_channel *c;
7667 c = find234(ssh->channels, &localid, ssh_channelfind);
7669 (c->type != CHAN_SHARING && c->halfopen &&
7670 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7671 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7672 char *buf = dupprintf("Received %s for %s channel %u",
7673 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7675 c ? "half-open" : "nonexistent", localid);
7676 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7683 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7684 struct Packet *pktin, void *ctx)
7686 unsigned *sizep = ctx;
7689 * Winadj responses should always be failures. However, at least
7690 * one server ("boks_sshd") is known to return SUCCESS for channel
7691 * requests it's never heard of, such as "winadj@putty". Raised
7692 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7693 * life, we don't worry about what kind of response we got.
7696 c->v.v2.remlocwin += *sizep;
7699 * winadj messages are only sent when the window is fully open, so
7700 * if we get an ack of one, we know any pending unthrottle is
7703 if (c->v.v2.throttle_state == UNTHROTTLING)
7704 c->v.v2.throttle_state = UNTHROTTLED;
7707 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
7709 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
7710 struct outstanding_channel_request *ocr;
7713 if (c->type == CHAN_SHARING) {
7714 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7715 pktin->body, pktin->length);
7718 ocr = c->v.v2.chanreq_head;
7720 ssh2_msg_unexpected(ssh, pktin);
7723 ocr->handler(c, pktin, ocr->ctx);
7724 c->v.v2.chanreq_head = ocr->next;
7727 * We may now initiate channel-closing procedures, if that
7728 * CHANNEL_REQUEST was the last thing outstanding before we send
7731 ssh2_channel_check_close(c);
7734 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
7736 struct ssh_channel *c;
7737 c = ssh2_channel_msg(ssh, pktin);
7740 if (c->type == CHAN_SHARING) {
7741 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7742 pktin->body, pktin->length);
7745 if (!(c->closes & CLOSES_SENT_EOF)) {
7746 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
7747 ssh2_try_send_and_unthrottle(ssh, c);
7751 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
7755 struct ssh_channel *c;
7756 c = ssh2_channel_msg(ssh, pktin);
7759 if (c->type == CHAN_SHARING) {
7760 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7761 pktin->body, pktin->length);
7764 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
7765 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
7766 return; /* extended but not stderr */
7767 ssh_pkt_getstring(pktin, &data, &length);
7770 c->v.v2.locwindow -= length;
7771 c->v.v2.remlocwin -= length;
7773 case CHAN_MAINSESSION:
7775 from_backend(ssh->frontend, pktin->type ==
7776 SSH2_MSG_CHANNEL_EXTENDED_DATA,
7780 bufsize = x11_send(c->u.x11.xconn, data, length);
7783 bufsize = pfd_send(c->u.pfd.pf, data, length);
7786 while (length > 0) {
7787 if (c->u.a.lensofar < 4) {
7788 unsigned int l = min(4 - c->u.a.lensofar,
7790 memcpy(c->u.a.msglen + c->u.a.lensofar,
7794 c->u.a.lensofar += l;
7796 if (c->u.a.lensofar == 4) {
7798 4 + GET_32BIT(c->u.a.msglen);
7799 c->u.a.message = snewn(c->u.a.totallen,
7801 memcpy(c->u.a.message, c->u.a.msglen, 4);
7803 if (c->u.a.lensofar >= 4 && length > 0) {
7805 min(c->u.a.totallen - c->u.a.lensofar,
7807 memcpy(c->u.a.message + c->u.a.lensofar,
7811 c->u.a.lensofar += l;
7813 if (c->u.a.lensofar == c->u.a.totallen) {
7816 c->u.a.outstanding_requests++;
7817 if (agent_query(c->u.a.message,
7820 ssh_agentf_callback, c))
7821 ssh_agentf_callback(c, reply, replylen);
7822 sfree(c->u.a.message);
7823 c->u.a.message = NULL;
7824 c->u.a.lensofar = 0;
7831 * If it looks like the remote end hit the end of its window,
7832 * and we didn't want it to do that, think about using a
7835 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
7836 c->v.v2.locmaxwin < 0x40000000)
7837 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
7839 * If we are not buffering too much data,
7840 * enlarge the window again at the remote side.
7841 * If we are buffering too much, we may still
7842 * need to adjust the window if the server's
7845 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7846 c->v.v2.locmaxwin - bufsize : 0);
7848 * If we're either buffering way too much data, or if we're
7849 * buffering anything at all and we're in "simple" mode,
7850 * throttle the whole channel.
7852 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
7853 && !c->throttling_conn) {
7854 c->throttling_conn = 1;
7855 ssh_throttle_conn(ssh, +1);
7860 static void ssh_check_termination(Ssh ssh)
7862 if (ssh->version == 2 &&
7863 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7864 (ssh->channels && count234(ssh->channels) == 0) &&
7865 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
7867 * We used to send SSH_MSG_DISCONNECT here, because I'd
7868 * believed that _every_ conforming SSH-2 connection had to
7869 * end with a disconnect being sent by at least one side;
7870 * apparently I was wrong and it's perfectly OK to
7871 * unceremoniously slam the connection shut when you're done,
7872 * and indeed OpenSSH feels this is more polite than sending a
7873 * DISCONNECT. So now we don't.
7875 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7879 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
7880 const char *peerinfo)
7883 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
7886 logeventf(ssh, "Connection sharing downstream #%u connected", id);
7889 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
7891 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
7892 ssh_check_termination(ssh);
7895 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
7900 va_start(ap, logfmt);
7901 buf = dupvprintf(logfmt, ap);
7904 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
7906 logeventf(ssh, "Connection sharing: %s", buf);
7910 static void ssh_channel_destroy(struct ssh_channel *c)
7915 case CHAN_MAINSESSION:
7916 ssh->mainchan = NULL;
7917 update_specials_menu(ssh->frontend);
7920 if (c->u.x11.xconn != NULL)
7921 x11_close(c->u.x11.xconn);
7922 logevent("Forwarded X11 connection terminated");
7925 sfree(c->u.a.message);
7928 if (c->u.pfd.pf != NULL)
7929 pfd_close(c->u.pfd.pf);
7930 logevent("Forwarded port closed");
7934 del234(ssh->channels, c);
7935 if (ssh->version == 2) {
7936 bufchain_clear(&c->v.v2.outbuffer);
7937 assert(c->v.v2.chanreq_head == NULL);
7942 * If that was the last channel left open, we might need to
7945 ssh_check_termination(ssh);
7948 static void ssh2_channel_check_close(struct ssh_channel *c)
7951 struct Packet *pktout;
7955 * If we've sent out our own CHANNEL_OPEN but not yet seen
7956 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
7957 * it's too early to be sending close messages of any kind.
7962 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
7963 c->type == CHAN_ZOMBIE) &&
7964 !c->v.v2.chanreq_head &&
7965 !(c->closes & CLOSES_SENT_CLOSE)) {
7967 * We have both sent and received EOF (or the channel is a
7968 * zombie), and we have no outstanding channel requests, which
7969 * means the channel is in final wind-up. But we haven't sent
7970 * CLOSE, so let's do so now.
7972 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
7973 ssh2_pkt_adduint32(pktout, c->remoteid);
7974 ssh2_pkt_send(ssh, pktout);
7975 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
7978 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
7979 assert(c->v.v2.chanreq_head == NULL);
7981 * We have both sent and received CLOSE, which means we're
7982 * completely done with the channel.
7984 ssh_channel_destroy(c);
7988 static void ssh2_channel_got_eof(struct ssh_channel *c)
7990 if (c->closes & CLOSES_RCVD_EOF)
7991 return; /* already seen EOF */
7992 c->closes |= CLOSES_RCVD_EOF;
7994 if (c->type == CHAN_X11) {
7995 x11_send_eof(c->u.x11.xconn);
7996 } else if (c->type == CHAN_AGENT) {
7997 if (c->u.a.outstanding_requests == 0) {
7998 /* Manufacture an outgoing EOF in response to the incoming one. */
7999 sshfwd_write_eof(c);
8001 } else if (c->type == CHAN_SOCKDATA) {
8002 pfd_send_eof(c->u.pfd.pf);
8003 } else if (c->type == CHAN_MAINSESSION) {
8006 if (!ssh->sent_console_eof &&
8007 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8009 * Either from_backend_eof told us that the front end
8010 * wants us to close the outgoing side of the connection
8011 * as soon as we see EOF from the far end, or else we've
8012 * unilaterally decided to do that because we've allocated
8013 * a remote pty and hence EOF isn't a particularly
8014 * meaningful concept.
8016 sshfwd_write_eof(c);
8018 ssh->sent_console_eof = TRUE;
8021 ssh2_channel_check_close(c);
8024 static void ssh2_msg_channel_eof(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 ssh2_channel_got_eof(c);
8039 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8041 struct ssh_channel *c;
8043 c = ssh2_channel_msg(ssh, pktin);
8046 if (c->type == CHAN_SHARING) {
8047 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8048 pktin->body, pktin->length);
8053 * When we receive CLOSE on a channel, we assume it comes with an
8054 * implied EOF if we haven't seen EOF yet.
8056 ssh2_channel_got_eof(c);
8058 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8060 * It also means we stop expecting to see replies to any
8061 * outstanding channel requests, so clean those up too.
8062 * (ssh_chanreq_init will enforce by assertion that we don't
8063 * subsequently put anything back on this list.)
8065 while (c->v.v2.chanreq_head) {
8066 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8067 ocr->handler(c, NULL, ocr->ctx);
8068 c->v.v2.chanreq_head = ocr->next;
8074 * And we also send an outgoing EOF, if we haven't already, on the
8075 * assumption that CLOSE is a pretty forceful announcement that
8076 * the remote side is doing away with the entire channel. (If it
8077 * had wanted to send us EOF and continue receiving data from us,
8078 * it would have just sent CHANNEL_EOF.)
8080 if (!(c->closes & CLOSES_SENT_EOF)) {
8082 * Make sure we don't read any more from whatever our local
8083 * data source is for this channel.
8086 case CHAN_MAINSESSION:
8087 ssh->send_ok = 0; /* stop trying to read from stdin */
8090 x11_override_throttle(c->u.x11.xconn, 1);
8093 pfd_override_throttle(c->u.pfd.pf, 1);
8098 * Abandon any buffered data we still wanted to send to this
8099 * channel. Receiving a CHANNEL_CLOSE is an indication that
8100 * the server really wants to get on and _destroy_ this
8101 * channel, and it isn't going to send us any further
8102 * WINDOW_ADJUSTs to permit us to send pending stuff.
8104 bufchain_clear(&c->v.v2.outbuffer);
8107 * Send outgoing EOF.
8109 sshfwd_write_eof(c);
8113 * Now process the actual close.
8115 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8116 c->closes |= CLOSES_RCVD_CLOSE;
8117 ssh2_channel_check_close(c);
8121 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8123 struct ssh_channel *c;
8125 c = ssh2_channel_msg(ssh, pktin);
8128 if (c->type == CHAN_SHARING) {
8129 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8130 pktin->body, pktin->length);
8133 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8134 c->remoteid = ssh_pkt_getuint32(pktin);
8135 c->halfopen = FALSE;
8136 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8137 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8139 if (c->type == CHAN_SOCKDATA_DORMANT) {
8140 c->type = CHAN_SOCKDATA;
8142 pfd_confirm(c->u.pfd.pf);
8143 } else if (c->type == CHAN_ZOMBIE) {
8145 * This case can occur if a local socket error occurred
8146 * between us sending out CHANNEL_OPEN and receiving
8147 * OPEN_CONFIRMATION. In this case, all we can do is
8148 * immediately initiate close proceedings now that we know the
8149 * server's id to put in the close message.
8151 ssh2_channel_check_close(c);
8154 * We never expect to receive OPEN_CONFIRMATION for any
8155 * *other* channel type (since only local-to-remote port
8156 * forwardings cause us to send CHANNEL_OPEN after the main
8157 * channel is live - all other auxiliary channel types are
8158 * initiated from the server end). It's safe to enforce this
8159 * by assertion rather than by ssh_disconnect, because the
8160 * real point is that we never constructed a half-open channel
8161 * structure in the first place with any type other than the
8164 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8168 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8171 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8173 static const char *const reasons[] = {
8174 "<unknown reason code>",
8175 "Administratively prohibited",
8177 "Unknown channel type",
8178 "Resource shortage",
8180 unsigned reason_code;
8181 char *reason_string;
8183 struct ssh_channel *c;
8185 c = ssh2_channel_msg(ssh, pktin);
8188 if (c->type == CHAN_SHARING) {
8189 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8190 pktin->body, pktin->length);
8193 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8195 if (c->type == CHAN_SOCKDATA_DORMANT) {
8196 reason_code = ssh_pkt_getuint32(pktin);
8197 if (reason_code >= lenof(reasons))
8198 reason_code = 0; /* ensure reasons[reason_code] in range */
8199 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8200 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8201 reasons[reason_code], reason_length, reason_string);
8203 pfd_close(c->u.pfd.pf);
8204 } else if (c->type == CHAN_ZOMBIE) {
8206 * This case can occur if a local socket error occurred
8207 * between us sending out CHANNEL_OPEN and receiving
8208 * OPEN_FAILURE. In this case, we need do nothing except allow
8209 * the code below to throw the half-open channel away.
8213 * We never expect to receive OPEN_FAILURE for any *other*
8214 * channel type (since only local-to-remote port forwardings
8215 * cause us to send CHANNEL_OPEN after the main channel is
8216 * live - all other auxiliary channel types are initiated from
8217 * the server end). It's safe to enforce this by assertion
8218 * rather than by ssh_disconnect, because the real point is
8219 * that we never constructed a half-open channel structure in
8220 * the first place with any type other than the above.
8222 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8225 del234(ssh->channels, c);
8229 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8232 int typelen, want_reply;
8233 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8234 struct ssh_channel *c;
8235 struct Packet *pktout;
8237 c = ssh2_channel_msg(ssh, pktin);
8240 if (c->type == CHAN_SHARING) {
8241 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8242 pktin->body, pktin->length);
8245 ssh_pkt_getstring(pktin, &type, &typelen);
8246 want_reply = ssh2_pkt_getbool(pktin);
8248 if (c->closes & CLOSES_SENT_CLOSE) {
8250 * We don't reply to channel requests after we've sent
8251 * CHANNEL_CLOSE for the channel, because our reply might
8252 * cross in the network with the other side's CHANNEL_CLOSE
8253 * and arrive after they have wound the channel up completely.
8259 * Having got the channel number, we now look at
8260 * the request type string to see if it's something
8263 if (c == ssh->mainchan) {
8265 * We recognise "exit-status" and "exit-signal" on
8266 * the primary channel.
8268 if (typelen == 11 &&
8269 !memcmp(type, "exit-status", 11)) {
8271 ssh->exitcode = ssh_pkt_getuint32(pktin);
8272 logeventf(ssh, "Server sent command exit status %d",
8274 reply = SSH2_MSG_CHANNEL_SUCCESS;
8276 } else if (typelen == 11 &&
8277 !memcmp(type, "exit-signal", 11)) {
8279 int is_plausible = TRUE, is_int = FALSE;
8280 char *fmt_sig = NULL, *fmt_msg = NULL;
8282 int msglen = 0, core = FALSE;
8283 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8284 * provide an `int' for the signal, despite its
8285 * having been a `string' in the drafts of RFC 4254 since at
8286 * least 2001. (Fixed in session.c 1.147.) Try to
8287 * infer which we can safely parse it as. */
8289 unsigned char *p = pktin->body +
8291 long len = pktin->length - pktin->savedpos;
8292 unsigned long num = GET_32BIT(p); /* what is it? */
8293 /* If it's 0, it hardly matters; assume string */
8297 int maybe_int = FALSE, maybe_str = FALSE;
8298 #define CHECK_HYPOTHESIS(offset, result) \
8301 int q = toint(offset); \
8302 if (q >= 0 && q+4 <= len) { \
8303 q = toint(q + 4 + GET_32BIT(p+q)); \
8304 if (q >= 0 && q+4 <= len && \
8305 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8310 CHECK_HYPOTHESIS(4+1, maybe_int);
8311 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8312 #undef CHECK_HYPOTHESIS
8313 if (maybe_int && !maybe_str)
8315 else if (!maybe_int && maybe_str)
8318 /* Crikey. Either or neither. Panic. */
8319 is_plausible = FALSE;
8322 ssh->exitcode = 128; /* means `unknown signal' */
8325 /* Old non-standard OpenSSH. */
8326 int signum = ssh_pkt_getuint32(pktin);
8327 fmt_sig = dupprintf(" %d", signum);
8328 ssh->exitcode = 128 + signum;
8330 /* As per RFC 4254. */
8333 ssh_pkt_getstring(pktin, &sig, &siglen);
8334 /* Signal name isn't supposed to be blank, but
8335 * let's cope gracefully if it is. */
8337 fmt_sig = dupprintf(" \"%.*s\"",
8342 * Really hideous method of translating the
8343 * signal description back into a locally
8344 * meaningful number.
8349 #define TRANSLATE_SIGNAL(s) \
8350 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8351 ssh->exitcode = 128 + SIG ## s
8353 TRANSLATE_SIGNAL(ABRT);
8356 TRANSLATE_SIGNAL(ALRM);
8359 TRANSLATE_SIGNAL(FPE);
8362 TRANSLATE_SIGNAL(HUP);
8365 TRANSLATE_SIGNAL(ILL);
8368 TRANSLATE_SIGNAL(INT);
8371 TRANSLATE_SIGNAL(KILL);
8374 TRANSLATE_SIGNAL(PIPE);
8377 TRANSLATE_SIGNAL(QUIT);
8380 TRANSLATE_SIGNAL(SEGV);
8383 TRANSLATE_SIGNAL(TERM);
8386 TRANSLATE_SIGNAL(USR1);
8389 TRANSLATE_SIGNAL(USR2);
8391 #undef TRANSLATE_SIGNAL
8393 ssh->exitcode = 128;
8395 core = ssh2_pkt_getbool(pktin);
8396 ssh_pkt_getstring(pktin, &msg, &msglen);
8398 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8400 /* ignore lang tag */
8401 } /* else don't attempt to parse */
8402 logeventf(ssh, "Server exited on signal%s%s%s",
8403 fmt_sig ? fmt_sig : "",
8404 core ? " (core dumped)" : "",
8405 fmt_msg ? fmt_msg : "");
8408 reply = SSH2_MSG_CHANNEL_SUCCESS;
8413 * This is a channel request we don't know
8414 * about, so we now either ignore the request
8415 * or respond with CHANNEL_FAILURE, depending
8418 reply = SSH2_MSG_CHANNEL_FAILURE;
8421 pktout = ssh2_pkt_init(reply);
8422 ssh2_pkt_adduint32(pktout, c->remoteid);
8423 ssh2_pkt_send(ssh, pktout);
8427 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8430 int typelen, want_reply;
8431 struct Packet *pktout;
8433 ssh_pkt_getstring(pktin, &type, &typelen);
8434 want_reply = ssh2_pkt_getbool(pktin);
8437 * We currently don't support any global requests
8438 * at all, so we either ignore the request or
8439 * respond with REQUEST_FAILURE, depending on
8443 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8444 ssh2_pkt_send(ssh, pktout);
8448 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8452 struct X11FakeAuth *auth;
8455 * Make up a new set of fake X11 auth data, and add it to the tree
8456 * of currently valid ones with an indication of the sharing
8457 * context that it's relevant to.
8459 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8460 auth->share_cs = share_cs;
8461 auth->share_chan = share_chan;
8466 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8468 del234(ssh->x11authtree, auth);
8469 x11_free_fake_auth(auth);
8472 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8479 const char *error = NULL;
8480 struct ssh_channel *c;
8481 unsigned remid, winsize, pktsize;
8482 unsigned our_winsize_override = 0;
8483 struct Packet *pktout;
8485 ssh_pkt_getstring(pktin, &type, &typelen);
8486 c = snew(struct ssh_channel);
8489 remid = ssh_pkt_getuint32(pktin);
8490 winsize = ssh_pkt_getuint32(pktin);
8491 pktsize = ssh_pkt_getuint32(pktin);
8493 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8496 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8497 addrstr = snewn(peeraddrlen+1, char);
8498 memcpy(addrstr, peeraddr, peeraddrlen);
8499 addrstr[peeraddrlen] = '\0';
8500 peerport = ssh_pkt_getuint32(pktin);
8502 logeventf(ssh, "Received X11 connect request from %s:%d",
8505 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8506 error = "X11 forwarding is not enabled";
8508 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8511 c->u.x11.initial = TRUE;
8514 * If we are a connection-sharing upstream, then we should
8515 * initially present a very small window, adequate to take
8516 * the X11 initial authorisation packet but not much more.
8517 * Downstream will then present us a larger window (by
8518 * fiat of the connection-sharing protocol) and we can
8519 * guarantee to send a positive-valued WINDOW_ADJUST.
8522 our_winsize_override = 128;
8524 logevent("Opened X11 forward channel");
8528 } else if (typelen == 15 &&
8529 !memcmp(type, "forwarded-tcpip", 15)) {
8530 struct ssh_rportfwd pf, *realpf;
8533 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8534 pf.shost = dupprintf("%.*s", shostlen, shost);
8535 pf.sport = ssh_pkt_getuint32(pktin);
8536 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8537 peerport = ssh_pkt_getuint32(pktin);
8538 realpf = find234(ssh->rportfwds, &pf, NULL);
8539 logeventf(ssh, "Received remote port %s:%d open request "
8540 "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
8543 if (realpf == NULL) {
8544 error = "Remote port is not recognised";
8548 if (realpf->share_ctx) {
8550 * This port forwarding is on behalf of a
8551 * connection-sharing downstream, so abandon our own
8552 * channel-open procedure and just pass the message on
8555 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8556 pktin->body, pktin->length);
8561 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8562 c, ssh->conf, realpf->pfrec->addressfamily);
8563 logeventf(ssh, "Attempting to forward remote port to "
8564 "%s:%d", realpf->dhost, realpf->dport);
8566 logeventf(ssh, "Port open failed: %s", err);
8568 error = "Port open failed";
8570 logevent("Forwarded port opened successfully");
8571 c->type = CHAN_SOCKDATA;
8574 } else if (typelen == 22 &&
8575 !memcmp(type, "auth-agent@openssh.com", 22)) {
8576 if (!ssh->agentfwd_enabled)
8577 error = "Agent forwarding is not enabled";
8579 c->type = CHAN_AGENT; /* identify channel type */
8580 c->u.a.lensofar = 0;
8581 c->u.a.message = NULL;
8582 c->u.a.outstanding_requests = 0;
8585 error = "Unsupported channel type requested";
8588 c->remoteid = remid;
8589 c->halfopen = FALSE;
8591 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8592 ssh2_pkt_adduint32(pktout, c->remoteid);
8593 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8594 ssh2_pkt_addstring(pktout, error);
8595 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8596 ssh2_pkt_send(ssh, pktout);
8597 logeventf(ssh, "Rejected channel open: %s", error);
8600 ssh2_channel_init(c);
8601 c->v.v2.remwindow = winsize;
8602 c->v.v2.remmaxpkt = pktsize;
8603 if (our_winsize_override) {
8604 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8605 our_winsize_override;
8607 add234(ssh->channels, c);
8608 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8609 ssh2_pkt_adduint32(pktout, c->remoteid);
8610 ssh2_pkt_adduint32(pktout, c->localid);
8611 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8612 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8613 ssh2_pkt_send(ssh, pktout);
8617 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8618 void *share_cs, void *share_chan,
8619 const char *peer_addr, int peer_port,
8620 int endian, int protomajor, int protominor,
8621 const void *initial_data, int initial_len)
8624 * This function is called when we've just discovered that an X
8625 * forwarding channel on which we'd been handling the initial auth
8626 * ourselves turns out to be destined for a connection-sharing
8627 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8628 * that we completely stop tracking windows and buffering data and
8629 * just pass more or less unmodified SSH messages back and forth.
8631 c->type = CHAN_SHARING;
8632 c->u.sharing.ctx = share_cs;
8633 share_setup_x11_channel(share_cs, share_chan,
8634 c->localid, c->remoteid, c->v.v2.remwindow,
8635 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8636 peer_addr, peer_port, endian,
8637 protomajor, protominor,
8638 initial_data, initial_len);
8641 void sshfwd_x11_is_local(struct ssh_channel *c)
8644 * This function is called when we've just discovered that an X
8645 * forwarding channel is _not_ destined for a connection-sharing
8646 * downstream but we're going to handle it ourselves. We stop
8647 * presenting a cautiously small window and go into ordinary data
8650 c->u.x11.initial = FALSE;
8651 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8655 * Buffer banner messages for later display at some convenient point,
8656 * if we're going to display them.
8658 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8660 /* Arbitrary limit to prevent unbounded inflation of buffer */
8661 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8662 bufchain_size(&ssh->banner) <= 131072) {
8663 char *banner = NULL;
8665 ssh_pkt_getstring(pktin, &banner, &size);
8667 bufchain_add(&ssh->banner, banner, size);
8671 /* Helper function to deal with sending tty modes for "pty-req" */
8672 static void ssh2_send_ttymode(void *data, char *mode, char *val)
8674 struct Packet *pktout = (struct Packet *)data;
8676 unsigned int arg = 0;
8677 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
8678 if (i == lenof(ssh_ttymodes)) return;
8679 switch (ssh_ttymodes[i].type) {
8681 arg = ssh_tty_parse_specchar(val);
8684 arg = ssh_tty_parse_boolean(val);
8687 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
8688 ssh2_pkt_adduint32(pktout, arg);
8691 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8694 struct ssh2_setup_x11_state {
8698 struct Packet *pktout;
8699 crStateP(ssh2_setup_x11_state, ctx);
8703 logevent("Requesting X11 forwarding");
8704 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8706 ssh2_pkt_addbool(pktout, 0); /* many connections */
8707 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8708 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8709 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8710 ssh2_pkt_send(ssh, pktout);
8712 /* Wait to be called back with either a response packet, or NULL
8713 * meaning clean up and free our data */
8717 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8718 logevent("X11 forwarding enabled");
8719 ssh->X11_fwd_enabled = TRUE;
8721 logevent("X11 forwarding refused");
8727 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8730 struct ssh2_setup_agent_state {
8734 struct Packet *pktout;
8735 crStateP(ssh2_setup_agent_state, ctx);
8739 logevent("Requesting OpenSSH-style agent forwarding");
8740 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8741 ssh2_setup_agent, s);
8742 ssh2_pkt_send(ssh, pktout);
8744 /* Wait to be called back with either a response packet, or NULL
8745 * meaning clean up and free our data */
8749 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8750 logevent("Agent forwarding enabled");
8751 ssh->agentfwd_enabled = TRUE;
8753 logevent("Agent forwarding refused");
8759 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8762 struct ssh2_setup_pty_state {
8766 struct Packet *pktout;
8767 crStateP(ssh2_setup_pty_state, ctx);
8771 /* Unpick the terminal-speed string. */
8772 /* XXX perhaps we should allow no speeds to be sent. */
8773 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8774 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8775 /* Build the pty request. */
8776 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
8778 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
8779 ssh2_pkt_adduint32(pktout, ssh->term_width);
8780 ssh2_pkt_adduint32(pktout, ssh->term_height);
8781 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
8782 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
8783 ssh2_pkt_addstring_start(pktout);
8784 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
8785 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
8786 ssh2_pkt_adduint32(pktout, ssh->ispeed);
8787 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
8788 ssh2_pkt_adduint32(pktout, ssh->ospeed);
8789 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
8790 ssh2_pkt_send(ssh, pktout);
8791 ssh->state = SSH_STATE_INTERMED;
8793 /* Wait to be called back with either a response packet, or NULL
8794 * meaning clean up and free our data */
8798 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8799 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8800 ssh->ospeed, ssh->ispeed);
8801 ssh->got_pty = TRUE;
8803 c_write_str(ssh, "Server refused to allocate pty\r\n");
8804 ssh->editing = ssh->echoing = 1;
8811 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
8814 struct ssh2_setup_env_state {
8816 int num_env, env_left, env_ok;
8819 struct Packet *pktout;
8820 crStateP(ssh2_setup_env_state, ctx);
8825 * Send environment variables.
8827 * Simplest thing here is to send all the requests at once, and
8828 * then wait for a whole bunch of successes or failures.
8834 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
8836 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
8837 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
8838 ssh2_pkt_addstring(pktout, key);
8839 ssh2_pkt_addstring(pktout, val);
8840 ssh2_pkt_send(ssh, pktout);
8845 logeventf(ssh, "Sent %d environment variables", s->num_env);
8850 s->env_left = s->num_env;
8852 while (s->env_left > 0) {
8853 /* Wait to be called back with either a response packet,
8854 * or NULL meaning clean up and free our data */
8856 if (!pktin) goto out;
8857 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
8862 if (s->env_ok == s->num_env) {
8863 logevent("All environment variables successfully set");
8864 } else if (s->env_ok == 0) {
8865 logevent("All environment variables refused");
8866 c_write_str(ssh, "Server refused to set environment variables\r\n");
8868 logeventf(ssh, "%d environment variables refused",
8869 s->num_env - s->env_ok);
8870 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8878 * Handle the SSH-2 userauth and connection layers.
8880 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
8882 do_ssh2_authconn(ssh, NULL, 0, pktin);
8885 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
8889 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
8892 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
8893 struct Packet *pktin)
8895 struct do_ssh2_authconn_state {
8899 AUTH_TYPE_PUBLICKEY,
8900 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
8901 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
8903 AUTH_TYPE_GSSAPI, /* always QUIET */
8904 AUTH_TYPE_KEYBOARD_INTERACTIVE,
8905 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
8907 int done_service_req;
8908 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
8909 int tried_pubkey_config, done_agent;
8914 int kbd_inter_refused;
8915 int we_are_in, userauth_success;
8916 prompts_t *cur_prompt;
8921 void *publickey_blob;
8922 int publickey_bloblen;
8923 int privatekey_available, privatekey_encrypted;
8924 char *publickey_algorithm;
8925 char *publickey_comment;
8926 unsigned char agent_request[5], *agent_response, *agentp;
8927 int agent_responselen;
8928 unsigned char *pkblob_in_agent;
8930 char *pkblob, *alg, *commentp;
8931 int pklen, alglen, commentlen;
8932 int siglen, retlen, len;
8933 char *q, *agentreq, *ret;
8935 struct Packet *pktout;
8938 struct ssh_gss_library *gsslib;
8939 Ssh_gss_ctx gss_ctx;
8940 Ssh_gss_buf gss_buf;
8941 Ssh_gss_buf gss_rcvtok, gss_sndtok;
8942 Ssh_gss_name gss_srv_name;
8943 Ssh_gss_stat gss_stat;
8946 crState(do_ssh2_authconn_state);
8950 /* Register as a handler for all the messages this coroutine handles. */
8951 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
8952 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
8953 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
8954 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
8955 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
8956 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
8957 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
8958 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
8959 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
8960 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
8961 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
8962 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
8963 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
8964 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
8965 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
8966 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
8967 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
8968 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
8969 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
8970 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
8972 s->done_service_req = FALSE;
8973 s->we_are_in = s->userauth_success = FALSE;
8974 s->agent_response = NULL;
8976 s->tried_gssapi = FALSE;
8979 if (!ssh->bare_connection) {
8980 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
8982 * Request userauth protocol, and await a response to it.
8984 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8985 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
8986 ssh2_pkt_send(ssh, s->pktout);
8987 crWaitUntilV(pktin);
8988 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
8989 s->done_service_req = TRUE;
8991 if (!s->done_service_req) {
8993 * Request connection protocol directly, without authentication.
8995 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8996 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8997 ssh2_pkt_send(ssh, s->pktout);
8998 crWaitUntilV(pktin);
8999 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9000 s->we_are_in = TRUE; /* no auth required */
9002 bombout(("Server refused service request"));
9007 s->we_are_in = TRUE;
9010 /* Arrange to be able to deal with any BANNERs that come in.
9011 * (We do this now as packets may come in during the next bit.) */
9012 bufchain_init(&ssh->banner);
9013 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9014 ssh2_msg_userauth_banner;
9017 * Misc one-time setup for authentication.
9019 s->publickey_blob = NULL;
9020 if (!s->we_are_in) {
9023 * Load the public half of any configured public key file
9026 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9027 if (!filename_is_null(s->keyfile)) {
9029 logeventf(ssh, "Reading key file \"%.150s\"",
9030 filename_to_str(s->keyfile));
9031 keytype = key_type(s->keyfile);
9032 if (keytype == SSH_KEYTYPE_SSH2 ||
9033 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9034 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9037 ssh2_userkey_loadpub(s->keyfile,
9038 &s->publickey_algorithm,
9039 &s->publickey_bloblen,
9040 &s->publickey_comment, &error);
9041 if (s->publickey_blob) {
9042 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9043 if (!s->privatekey_available)
9044 logeventf(ssh, "Key file contains public key only");
9045 s->privatekey_encrypted =
9046 ssh2_userkey_encrypted(s->keyfile, NULL);
9049 logeventf(ssh, "Unable to load key (%s)",
9051 msgbuf = dupprintf("Unable to load key file "
9052 "\"%.150s\" (%s)\r\n",
9053 filename_to_str(s->keyfile),
9055 c_write_str(ssh, msgbuf);
9060 logeventf(ssh, "Unable to use this key file (%s)",
9061 key_type_to_str(keytype));
9062 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9064 filename_to_str(s->keyfile),
9065 key_type_to_str(keytype));
9066 c_write_str(ssh, msgbuf);
9068 s->publickey_blob = NULL;
9073 * Find out about any keys Pageant has (but if there's a
9074 * public key configured, filter out all others).
9077 s->agent_response = NULL;
9078 s->pkblob_in_agent = NULL;
9079 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9083 logevent("Pageant is running. Requesting keys.");
9085 /* Request the keys held by the agent. */
9086 PUT_32BIT(s->agent_request, 1);
9087 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9088 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9089 ssh_agent_callback, ssh)) {
9093 bombout(("Unexpected data from server while"
9094 " waiting for agent response"));
9097 } while (pktin || inlen > 0);
9098 r = ssh->agent_response;
9099 s->agent_responselen = ssh->agent_response_len;
9101 s->agent_response = (unsigned char *) r;
9102 if (s->agent_response && s->agent_responselen >= 5 &&
9103 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9106 p = s->agent_response + 5;
9107 s->nkeys = toint(GET_32BIT(p));
9110 * Vet the Pageant response to ensure that the key
9111 * count and blob lengths make sense.
9114 logeventf(ssh, "Pageant response contained a negative"
9115 " key count %d", s->nkeys);
9117 goto done_agent_query;
9119 unsigned char *q = p + 4;
9120 int lenleft = s->agent_responselen - 5 - 4;
9122 for (keyi = 0; keyi < s->nkeys; keyi++) {
9123 int bloblen, commentlen;
9125 logeventf(ssh, "Pageant response was truncated");
9127 goto done_agent_query;
9129 bloblen = toint(GET_32BIT(q));
9130 if (bloblen < 0 || bloblen > lenleft) {
9131 logeventf(ssh, "Pageant response was truncated");
9133 goto done_agent_query;
9135 lenleft -= 4 + bloblen;
9137 commentlen = toint(GET_32BIT(q));
9138 if (commentlen < 0 || commentlen > lenleft) {
9139 logeventf(ssh, "Pageant response was truncated");
9141 goto done_agent_query;
9143 lenleft -= 4 + commentlen;
9144 q += 4 + commentlen;
9149 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9150 if (s->publickey_blob) {
9151 /* See if configured key is in agent. */
9152 for (keyi = 0; keyi < s->nkeys; keyi++) {
9153 s->pklen = toint(GET_32BIT(p));
9154 if (s->pklen == s->publickey_bloblen &&
9155 !memcmp(p+4, s->publickey_blob,
9156 s->publickey_bloblen)) {
9157 logeventf(ssh, "Pageant key #%d matches "
9158 "configured key file", keyi);
9160 s->pkblob_in_agent = p;
9164 p += toint(GET_32BIT(p)) + 4; /* comment */
9166 if (!s->pkblob_in_agent) {
9167 logevent("Configured key file not in Pageant");
9172 logevent("Failed to get reply from Pageant");
9180 * We repeat this whole loop, including the username prompt,
9181 * until we manage a successful authentication. If the user
9182 * types the wrong _password_, they can be sent back to the
9183 * beginning to try another username, if this is configured on.
9184 * (If they specify a username in the config, they are never
9185 * asked, even if they do give a wrong password.)
9187 * I think this best serves the needs of
9189 * - the people who have no configuration, no keys, and just
9190 * want to try repeated (username,password) pairs until they
9191 * type both correctly
9193 * - people who have keys and configuration but occasionally
9194 * need to fall back to passwords
9196 * - people with a key held in Pageant, who might not have
9197 * logged in to a particular machine before; so they want to
9198 * type a username, and then _either_ their key will be
9199 * accepted, _or_ they will type a password. If they mistype
9200 * the username they will want to be able to get back and
9203 s->got_username = FALSE;
9204 while (!s->we_are_in) {
9208 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9210 * We got a username last time round this loop, and
9211 * with change_username turned off we don't try to get
9214 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9215 int ret; /* need not be kept over crReturn */
9216 s->cur_prompt = new_prompts(ssh->frontend);
9217 s->cur_prompt->to_server = TRUE;
9218 s->cur_prompt->name = dupstr("SSH login name");
9219 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9220 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9223 crWaitUntilV(!pktin);
9224 ret = get_userpass_input(s->cur_prompt, in, inlen);
9229 * get_userpass_input() failed to get a username.
9232 free_prompts(s->cur_prompt);
9233 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9236 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9237 free_prompts(s->cur_prompt);
9240 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9241 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9242 c_write_str(ssh, stuff);
9246 s->got_username = TRUE;
9249 * Send an authentication request using method "none": (a)
9250 * just in case it succeeds, and (b) so that we know what
9251 * authentication methods we can usefully try next.
9253 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9255 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9256 ssh2_pkt_addstring(s->pktout, ssh->username);
9257 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9258 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9259 ssh2_pkt_send(ssh, s->pktout);
9260 s->type = AUTH_TYPE_NONE;
9262 s->we_are_in = FALSE;
9264 s->tried_pubkey_config = FALSE;
9265 s->kbd_inter_refused = FALSE;
9267 /* Reset agent request state. */
9268 s->done_agent = FALSE;
9269 if (s->agent_response) {
9270 if (s->pkblob_in_agent) {
9271 s->agentp = s->pkblob_in_agent;
9273 s->agentp = s->agent_response + 5 + 4;
9279 char *methods = NULL;
9283 * Wait for the result of the last authentication request.
9286 crWaitUntilV(pktin);
9288 * Now is a convenient point to spew any banner material
9289 * that we've accumulated. (This should ensure that when
9290 * we exit the auth loop, we haven't any left to deal
9294 int size = bufchain_size(&ssh->banner);
9296 * Don't show the banner if we're operating in
9297 * non-verbose non-interactive mode. (It's probably
9298 * a script, which means nobody will read the
9299 * banner _anyway_, and moreover the printing of
9300 * the banner will screw up processing on the
9301 * output of (say) plink.)
9303 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9304 char *banner = snewn(size, char);
9305 bufchain_fetch(&ssh->banner, banner, size);
9306 c_write_untrusted(ssh, banner, size);
9309 bufchain_clear(&ssh->banner);
9311 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9312 logevent("Access granted");
9313 s->we_are_in = s->userauth_success = TRUE;
9317 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9318 bombout(("Strange packet received during authentication: "
9319 "type %d", pktin->type));
9326 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9327 * we can look at the string in it and know what we can
9328 * helpfully try next.
9330 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9331 ssh_pkt_getstring(pktin, &methods, &methlen);
9332 if (!ssh2_pkt_getbool(pktin)) {
9334 * We have received an unequivocal Access
9335 * Denied. This can translate to a variety of
9336 * messages, or no message at all.
9338 * For forms of authentication which are attempted
9339 * implicitly, by which I mean without printing
9340 * anything in the window indicating that we're
9341 * trying them, we should never print 'Access
9344 * If we do print a message saying that we're
9345 * attempting some kind of authentication, it's OK
9346 * to print a followup message saying it failed -
9347 * but the message may sometimes be more specific
9348 * than simply 'Access denied'.
9350 * Additionally, if we'd just tried password
9351 * authentication, we should break out of this
9352 * whole loop so as to go back to the username
9353 * prompt (iff we're configured to allow
9354 * username change attempts).
9356 if (s->type == AUTH_TYPE_NONE) {
9358 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9359 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9360 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9361 c_write_str(ssh, "Server refused our key\r\n");
9362 logevent("Server refused our key");
9363 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9364 /* This _shouldn't_ happen except by a
9365 * protocol bug causing client and server to
9366 * disagree on what is a correct signature. */
9367 c_write_str(ssh, "Server refused public-key signature"
9368 " despite accepting key!\r\n");
9369 logevent("Server refused public-key signature"
9370 " despite accepting key!");
9371 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9372 /* quiet, so no c_write */
9373 logevent("Server refused keyboard-interactive authentication");
9374 } else if (s->type==AUTH_TYPE_GSSAPI) {
9375 /* always quiet, so no c_write */
9376 /* also, the code down in the GSSAPI block has
9377 * already logged this in the Event Log */
9378 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9379 logevent("Keyboard-interactive authentication failed");
9380 c_write_str(ssh, "Access denied\r\n");
9382 assert(s->type == AUTH_TYPE_PASSWORD);
9383 logevent("Password authentication failed");
9384 c_write_str(ssh, "Access denied\r\n");
9386 if (conf_get_int(ssh->conf, CONF_change_username)) {
9387 /* XXX perhaps we should allow
9388 * keyboard-interactive to do this too? */
9389 s->we_are_in = FALSE;
9394 c_write_str(ssh, "Further authentication required\r\n");
9395 logevent("Further authentication required");
9399 in_commasep_string("publickey", methods, methlen);
9401 in_commasep_string("password", methods, methlen);
9402 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9403 in_commasep_string("keyboard-interactive", methods, methlen);
9405 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9406 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9407 /* Try loading the GSS libraries and see if we
9410 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9411 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9413 /* No point in even bothering to try to load the
9414 * GSS libraries, if the user configuration and
9415 * server aren't both prepared to attempt GSSAPI
9416 * auth in the first place. */
9417 s->can_gssapi = FALSE;
9422 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9424 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9427 * Attempt public-key authentication using a key from Pageant.
9430 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9432 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9434 /* Unpack key from agent response */
9435 s->pklen = toint(GET_32BIT(s->agentp));
9437 s->pkblob = (char *)s->agentp;
9438 s->agentp += s->pklen;
9439 s->alglen = toint(GET_32BIT(s->pkblob));
9440 s->alg = s->pkblob + 4;
9441 s->commentlen = toint(GET_32BIT(s->agentp));
9443 s->commentp = (char *)s->agentp;
9444 s->agentp += s->commentlen;
9445 /* s->agentp now points at next key, if any */
9447 /* See if server will accept it */
9448 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9449 ssh2_pkt_addstring(s->pktout, ssh->username);
9450 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9451 /* service requested */
9452 ssh2_pkt_addstring(s->pktout, "publickey");
9454 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9455 ssh2_pkt_addstring_start(s->pktout);
9456 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9457 ssh2_pkt_addstring_start(s->pktout);
9458 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9459 ssh2_pkt_send(ssh, s->pktout);
9460 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9462 crWaitUntilV(pktin);
9463 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9465 /* Offer of key refused. */
9472 if (flags & FLAG_VERBOSE) {
9473 c_write_str(ssh, "Authenticating with "
9475 c_write(ssh, s->commentp, s->commentlen);
9476 c_write_str(ssh, "\" from agent\r\n");
9480 * Server is willing to accept the key.
9481 * Construct a SIGN_REQUEST.
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");
9489 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9490 ssh2_pkt_addstring_start(s->pktout);
9491 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9492 ssh2_pkt_addstring_start(s->pktout);
9493 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9495 /* Ask agent for signature. */
9496 s->siglen = s->pktout->length - 5 + 4 +
9497 ssh->v2_session_id_len;
9498 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9500 s->len = 1; /* message type */
9501 s->len += 4 + s->pklen; /* key blob */
9502 s->len += 4 + s->siglen; /* data to sign */
9503 s->len += 4; /* flags */
9504 s->agentreq = snewn(4 + s->len, char);
9505 PUT_32BIT(s->agentreq, s->len);
9506 s->q = s->agentreq + 4;
9507 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9508 PUT_32BIT(s->q, s->pklen);
9510 memcpy(s->q, s->pkblob, s->pklen);
9512 PUT_32BIT(s->q, s->siglen);
9514 /* Now the data to be signed... */
9515 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9516 PUT_32BIT(s->q, ssh->v2_session_id_len);
9519 memcpy(s->q, ssh->v2_session_id,
9520 ssh->v2_session_id_len);
9521 s->q += ssh->v2_session_id_len;
9522 memcpy(s->q, s->pktout->data + 5,
9523 s->pktout->length - 5);
9524 s->q += s->pktout->length - 5;
9525 /* And finally the (zero) flags word. */
9527 if (!agent_query(s->agentreq, s->len + 4,
9529 ssh_agent_callback, ssh)) {
9533 bombout(("Unexpected data from server"
9534 " while waiting for agent"
9538 } while (pktin || inlen > 0);
9539 vret = ssh->agent_response;
9540 s->retlen = ssh->agent_response_len;
9545 if (s->retlen >= 9 &&
9546 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9547 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9548 logevent("Sending Pageant's response");
9549 ssh2_add_sigblob(ssh, s->pktout,
9550 s->pkblob, s->pklen,
9552 GET_32BIT(s->ret + 5));
9553 ssh2_pkt_send(ssh, s->pktout);
9554 s->type = AUTH_TYPE_PUBLICKEY;
9556 /* FIXME: less drastic response */
9557 bombout(("Pageant failed to answer challenge"));
9563 /* Do we have any keys left to try? */
9564 if (s->pkblob_in_agent) {
9565 s->done_agent = TRUE;
9566 s->tried_pubkey_config = TRUE;
9569 if (s->keyi >= s->nkeys)
9570 s->done_agent = TRUE;
9573 } else if (s->can_pubkey && s->publickey_blob &&
9574 s->privatekey_available && !s->tried_pubkey_config) {
9576 struct ssh2_userkey *key; /* not live over crReturn */
9577 char *passphrase; /* not live over crReturn */
9579 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9581 s->tried_pubkey_config = TRUE;
9584 * Try the public key supplied in the configuration.
9586 * First, offer the public blob to see if the server is
9587 * willing to accept it.
9589 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9590 ssh2_pkt_addstring(s->pktout, ssh->username);
9591 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9592 /* service requested */
9593 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9594 ssh2_pkt_addbool(s->pktout, FALSE);
9595 /* no signature included */
9596 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9597 ssh2_pkt_addstring_start(s->pktout);
9598 ssh2_pkt_addstring_data(s->pktout,
9599 (char *)s->publickey_blob,
9600 s->publickey_bloblen);
9601 ssh2_pkt_send(ssh, s->pktout);
9602 logevent("Offered public key");
9604 crWaitUntilV(pktin);
9605 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9606 /* Key refused. Give up. */
9607 s->gotit = TRUE; /* reconsider message next loop */
9608 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9609 continue; /* process this new message */
9611 logevent("Offer of public key accepted");
9614 * Actually attempt a serious authentication using
9617 if (flags & FLAG_VERBOSE) {
9618 c_write_str(ssh, "Authenticating with public key \"");
9619 c_write_str(ssh, s->publickey_comment);
9620 c_write_str(ssh, "\"\r\n");
9624 const char *error; /* not live over crReturn */
9625 if (s->privatekey_encrypted) {
9627 * Get a passphrase from the user.
9629 int ret; /* need not be kept over crReturn */
9630 s->cur_prompt = new_prompts(ssh->frontend);
9631 s->cur_prompt->to_server = FALSE;
9632 s->cur_prompt->name = dupstr("SSH key passphrase");
9633 add_prompt(s->cur_prompt,
9634 dupprintf("Passphrase for key \"%.100s\": ",
9635 s->publickey_comment),
9637 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9640 crWaitUntilV(!pktin);
9641 ret = get_userpass_input(s->cur_prompt,
9646 /* Failed to get a passphrase. Terminate. */
9647 free_prompts(s->cur_prompt);
9648 ssh_disconnect(ssh, NULL,
9649 "Unable to authenticate",
9650 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9655 dupstr(s->cur_prompt->prompts[0]->result);
9656 free_prompts(s->cur_prompt);
9658 passphrase = NULL; /* no passphrase needed */
9662 * Try decrypting the key.
9664 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9665 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9667 /* burn the evidence */
9668 smemclr(passphrase, strlen(passphrase));
9671 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9673 (key == SSH2_WRONG_PASSPHRASE)) {
9674 c_write_str(ssh, "Wrong passphrase\r\n");
9676 /* and loop again */
9678 c_write_str(ssh, "Unable to load private key (");
9679 c_write_str(ssh, error);
9680 c_write_str(ssh, ")\r\n");
9682 break; /* try something else */
9688 unsigned char *pkblob, *sigblob, *sigdata;
9689 int pkblob_len, sigblob_len, sigdata_len;
9693 * We have loaded the private key and the server
9694 * has announced that it's willing to accept it.
9695 * Hallelujah. Generate a signature and send it.
9697 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9698 ssh2_pkt_addstring(s->pktout, ssh->username);
9699 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9700 /* service requested */
9701 ssh2_pkt_addstring(s->pktout, "publickey");
9703 ssh2_pkt_addbool(s->pktout, TRUE);
9704 /* signature follows */
9705 ssh2_pkt_addstring(s->pktout, key->alg->name);
9706 pkblob = key->alg->public_blob(key->data,
9708 ssh2_pkt_addstring_start(s->pktout);
9709 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9713 * The data to be signed is:
9717 * followed by everything so far placed in the
9720 sigdata_len = s->pktout->length - 5 + 4 +
9721 ssh->v2_session_id_len;
9722 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9724 sigdata = snewn(sigdata_len, unsigned char);
9726 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9727 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9730 memcpy(sigdata+p, ssh->v2_session_id,
9731 ssh->v2_session_id_len);
9732 p += ssh->v2_session_id_len;
9733 memcpy(sigdata+p, s->pktout->data + 5,
9734 s->pktout->length - 5);
9735 p += s->pktout->length - 5;
9736 assert(p == sigdata_len);
9737 sigblob = key->alg->sign(key->data, (char *)sigdata,
9738 sigdata_len, &sigblob_len);
9739 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9740 sigblob, sigblob_len);
9745 ssh2_pkt_send(ssh, s->pktout);
9746 logevent("Sent public key signature");
9747 s->type = AUTH_TYPE_PUBLICKEY;
9748 key->alg->freekey(key->data);
9749 sfree(key->comment);
9754 } else if (s->can_gssapi && !s->tried_gssapi) {
9756 /* GSSAPI Authentication */
9761 s->type = AUTH_TYPE_GSSAPI;
9762 s->tried_gssapi = TRUE;
9764 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9767 * Pick the highest GSS library on the preference
9773 for (i = 0; i < ngsslibs; i++) {
9774 int want_id = conf_get_int_int(ssh->conf,
9775 CONF_ssh_gsslist, i);
9776 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
9777 if (ssh->gsslibs->libraries[j].id == want_id) {
9778 s->gsslib = &ssh->gsslibs->libraries[j];
9779 goto got_gsslib; /* double break */
9784 * We always expect to have found something in
9785 * the above loop: we only came here if there
9786 * was at least one viable GSS library, and the
9787 * preference list should always mention
9788 * everything and only change the order.
9793 if (s->gsslib->gsslogmsg)
9794 logevent(s->gsslib->gsslogmsg);
9796 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
9797 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9798 ssh2_pkt_addstring(s->pktout, ssh->username);
9799 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9800 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
9801 logevent("Attempting GSSAPI authentication");
9803 /* add mechanism info */
9804 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
9806 /* number of GSSAPI mechanisms */
9807 ssh2_pkt_adduint32(s->pktout,1);
9809 /* length of OID + 2 */
9810 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
9811 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
9814 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
9816 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
9818 ssh2_pkt_send(ssh, s->pktout);
9819 crWaitUntilV(pktin);
9820 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
9821 logevent("GSSAPI authentication request refused");
9825 /* check returned packet ... */
9827 ssh_pkt_getstring(pktin, &data, &len);
9828 s->gss_rcvtok.value = data;
9829 s->gss_rcvtok.length = len;
9830 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
9831 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
9832 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
9833 memcmp((char *)s->gss_rcvtok.value + 2,
9834 s->gss_buf.value,s->gss_buf.length) ) {
9835 logevent("GSSAPI authentication - wrong response from server");
9839 /* now start running */
9840 s->gss_stat = s->gsslib->import_name(s->gsslib,
9843 if (s->gss_stat != SSH_GSS_OK) {
9844 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
9845 logevent("GSSAPI import name failed - Bad service name");
9847 logevent("GSSAPI import name failed");
9851 /* fetch TGT into GSS engine */
9852 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
9854 if (s->gss_stat != SSH_GSS_OK) {
9855 logevent("GSSAPI authentication failed to get credentials");
9856 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9860 /* initial tokens are empty */
9861 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
9862 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
9864 /* now enter the loop */
9866 s->gss_stat = s->gsslib->init_sec_context
9870 conf_get_int(ssh->conf, CONF_gssapifwd),
9874 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
9875 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
9876 logevent("GSSAPI authentication initialisation failed");
9878 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
9879 &s->gss_buf) == SSH_GSS_OK) {
9880 logevent(s->gss_buf.value);
9881 sfree(s->gss_buf.value);
9886 logevent("GSSAPI authentication initialised");
9888 /* Client and server now exchange tokens until GSSAPI
9889 * no longer says CONTINUE_NEEDED */
9891 if (s->gss_sndtok.length != 0) {
9892 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
9893 ssh_pkt_addstring_start(s->pktout);
9894 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
9895 ssh2_pkt_send(ssh, s->pktout);
9896 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
9899 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
9900 crWaitUntilV(pktin);
9901 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
9902 logevent("GSSAPI authentication - bad server response");
9903 s->gss_stat = SSH_GSS_FAILURE;
9906 ssh_pkt_getstring(pktin, &data, &len);
9907 s->gss_rcvtok.value = data;
9908 s->gss_rcvtok.length = len;
9910 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
9912 if (s->gss_stat != SSH_GSS_OK) {
9913 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9914 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9917 logevent("GSSAPI authentication loop finished OK");
9919 /* Now send the MIC */
9921 s->pktout = ssh2_pkt_init(0);
9922 micoffset = s->pktout->length;
9923 ssh_pkt_addstring_start(s->pktout);
9924 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
9925 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
9926 ssh_pkt_addstring(s->pktout, ssh->username);
9927 ssh_pkt_addstring(s->pktout, "ssh-connection");
9928 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
9930 s->gss_buf.value = (char *)s->pktout->data + micoffset;
9931 s->gss_buf.length = s->pktout->length - micoffset;
9933 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
9934 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
9935 ssh_pkt_addstring_start(s->pktout);
9936 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
9937 ssh2_pkt_send(ssh, s->pktout);
9938 s->gsslib->free_mic(s->gsslib, &mic);
9942 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9943 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9946 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
9949 * Keyboard-interactive authentication.
9952 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
9954 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
9956 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9957 ssh2_pkt_addstring(s->pktout, ssh->username);
9958 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9959 /* service requested */
9960 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
9962 ssh2_pkt_addstring(s->pktout, ""); /* lang */
9963 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
9964 ssh2_pkt_send(ssh, s->pktout);
9966 logevent("Attempting keyboard-interactive authentication");
9968 crWaitUntilV(pktin);
9969 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
9970 /* Server is not willing to do keyboard-interactive
9971 * at all (or, bizarrely but legally, accepts the
9972 * user without actually issuing any prompts).
9973 * Give up on it entirely. */
9975 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
9976 s->kbd_inter_refused = TRUE; /* don't try it again */
9981 * Loop while the server continues to send INFO_REQUESTs.
9983 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
9985 char *name, *inst, *lang;
9986 int name_len, inst_len, lang_len;
9990 * We've got a fresh USERAUTH_INFO_REQUEST.
9991 * Get the preamble and start building a prompt.
9993 ssh_pkt_getstring(pktin, &name, &name_len);
9994 ssh_pkt_getstring(pktin, &inst, &inst_len);
9995 ssh_pkt_getstring(pktin, &lang, &lang_len);
9996 s->cur_prompt = new_prompts(ssh->frontend);
9997 s->cur_prompt->to_server = TRUE;
10000 * Get any prompt(s) from the packet.
10002 s->num_prompts = ssh_pkt_getuint32(pktin);
10003 for (i = 0; i < s->num_prompts; i++) {
10007 static char noprompt[] =
10008 "<server failed to send prompt>: ";
10010 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10011 echo = ssh2_pkt_getbool(pktin);
10014 prompt_len = lenof(noprompt)-1;
10016 add_prompt(s->cur_prompt,
10017 dupprintf("%.*s", prompt_len, prompt),
10022 /* FIXME: better prefix to distinguish from
10023 * local prompts? */
10024 s->cur_prompt->name =
10025 dupprintf("SSH server: %.*s", name_len, name);
10026 s->cur_prompt->name_reqd = TRUE;
10028 s->cur_prompt->name =
10029 dupstr("SSH server authentication");
10030 s->cur_prompt->name_reqd = FALSE;
10032 /* We add a prefix to try to make it clear that a prompt
10033 * has come from the server.
10034 * FIXME: ugly to print "Using..." in prompt _every_
10035 * time round. Can this be done more subtly? */
10036 /* Special case: for reasons best known to themselves,
10037 * some servers send k-i requests with no prompts and
10038 * nothing to display. Keep quiet in this case. */
10039 if (s->num_prompts || name_len || inst_len) {
10040 s->cur_prompt->instruction =
10041 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10042 inst_len ? "\n" : "", inst_len, inst);
10043 s->cur_prompt->instr_reqd = TRUE;
10045 s->cur_prompt->instr_reqd = FALSE;
10049 * Display any instructions, and get the user's
10053 int ret; /* not live over crReturn */
10054 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10057 crWaitUntilV(!pktin);
10058 ret = get_userpass_input(s->cur_prompt, in, inlen);
10063 * Failed to get responses. Terminate.
10065 free_prompts(s->cur_prompt);
10066 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10067 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10074 * Send the response(s) to the server.
10076 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10077 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10078 for (i=0; i < s->num_prompts; i++) {
10079 ssh2_pkt_addstring(s->pktout,
10080 s->cur_prompt->prompts[i]->result);
10082 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10085 * Free the prompts structure from this iteration.
10086 * If there's another, a new one will be allocated
10087 * when we return to the top of this while loop.
10089 free_prompts(s->cur_prompt);
10092 * Get the next packet in case it's another
10095 crWaitUntilV(pktin);
10100 * We should have SUCCESS or FAILURE now.
10104 } else if (s->can_passwd) {
10107 * Plain old password authentication.
10109 int ret; /* not live over crReturn */
10110 int changereq_first_time; /* not live over crReturn */
10112 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10114 s->cur_prompt = new_prompts(ssh->frontend);
10115 s->cur_prompt->to_server = TRUE;
10116 s->cur_prompt->name = dupstr("SSH password");
10117 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10122 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10125 crWaitUntilV(!pktin);
10126 ret = get_userpass_input(s->cur_prompt, in, inlen);
10131 * Failed to get responses. Terminate.
10133 free_prompts(s->cur_prompt);
10134 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10135 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10140 * Squirrel away the password. (We may need it later if
10141 * asked to change it.)
10143 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10144 free_prompts(s->cur_prompt);
10147 * Send the password packet.
10149 * We pad out the password packet to 256 bytes to make
10150 * it harder for an attacker to find the length of the
10153 * Anyone using a password longer than 256 bytes
10154 * probably doesn't have much to worry about from
10155 * people who find out how long their password is!
10157 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10158 ssh2_pkt_addstring(s->pktout, ssh->username);
10159 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10160 /* service requested */
10161 ssh2_pkt_addstring(s->pktout, "password");
10162 ssh2_pkt_addbool(s->pktout, FALSE);
10163 ssh2_pkt_addstring(s->pktout, s->password);
10164 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10165 logevent("Sent password");
10166 s->type = AUTH_TYPE_PASSWORD;
10169 * Wait for next packet, in case it's a password change
10172 crWaitUntilV(pktin);
10173 changereq_first_time = TRUE;
10175 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10178 * We're being asked for a new password
10179 * (perhaps not for the first time).
10180 * Loop until the server accepts it.
10183 int got_new = FALSE; /* not live over crReturn */
10184 char *prompt; /* not live over crReturn */
10185 int prompt_len; /* not live over crReturn */
10189 if (changereq_first_time)
10190 msg = "Server requested password change";
10192 msg = "Server rejected new password";
10194 c_write_str(ssh, msg);
10195 c_write_str(ssh, "\r\n");
10198 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10200 s->cur_prompt = new_prompts(ssh->frontend);
10201 s->cur_prompt->to_server = TRUE;
10202 s->cur_prompt->name = dupstr("New SSH password");
10203 s->cur_prompt->instruction =
10204 dupprintf("%.*s", prompt_len, prompt);
10205 s->cur_prompt->instr_reqd = TRUE;
10207 * There's no explicit requirement in the protocol
10208 * for the "old" passwords in the original and
10209 * password-change messages to be the same, and
10210 * apparently some Cisco kit supports password change
10211 * by the user entering a blank password originally
10212 * and the real password subsequently, so,
10213 * reluctantly, we prompt for the old password again.
10215 * (On the other hand, some servers don't even bother
10216 * to check this field.)
10218 add_prompt(s->cur_prompt,
10219 dupstr("Current password (blank for previously entered password): "),
10221 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10223 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10227 * Loop until the user manages to enter the same
10232 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10235 crWaitUntilV(!pktin);
10236 ret = get_userpass_input(s->cur_prompt, in, inlen);
10241 * Failed to get responses. Terminate.
10243 /* burn the evidence */
10244 free_prompts(s->cur_prompt);
10245 smemclr(s->password, strlen(s->password));
10246 sfree(s->password);
10247 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10248 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10254 * If the user specified a new original password
10255 * (IYSWIM), overwrite any previously specified
10257 * (A side effect is that the user doesn't have to
10258 * re-enter it if they louse up the new password.)
10260 if (s->cur_prompt->prompts[0]->result[0]) {
10261 smemclr(s->password, strlen(s->password));
10262 /* burn the evidence */
10263 sfree(s->password);
10265 dupstr(s->cur_prompt->prompts[0]->result);
10269 * Check the two new passwords match.
10271 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10272 s->cur_prompt->prompts[2]->result)
10275 /* They don't. Silly user. */
10276 c_write_str(ssh, "Passwords do not match\r\n");
10281 * Send the new password (along with the old one).
10282 * (see above for padding rationale)
10284 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10285 ssh2_pkt_addstring(s->pktout, ssh->username);
10286 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10287 /* service requested */
10288 ssh2_pkt_addstring(s->pktout, "password");
10289 ssh2_pkt_addbool(s->pktout, TRUE);
10290 ssh2_pkt_addstring(s->pktout, s->password);
10291 ssh2_pkt_addstring(s->pktout,
10292 s->cur_prompt->prompts[1]->result);
10293 free_prompts(s->cur_prompt);
10294 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10295 logevent("Sent new password");
10298 * Now see what the server has to say about it.
10299 * (If it's CHANGEREQ again, it's not happy with the
10302 crWaitUntilV(pktin);
10303 changereq_first_time = FALSE;
10308 * We need to reexamine the current pktin at the top
10309 * of the loop. Either:
10310 * - we weren't asked to change password at all, in
10311 * which case it's a SUCCESS or FAILURE with the
10313 * - we sent a new password, and the server was
10314 * either OK with it (SUCCESS or FAILURE w/partial
10315 * success) or unhappy with the _old_ password
10316 * (FAILURE w/o partial success)
10317 * In any of these cases, we go back to the top of
10318 * the loop and start again.
10323 * We don't need the old password any more, in any
10324 * case. Burn the evidence.
10326 smemclr(s->password, strlen(s->password));
10327 sfree(s->password);
10330 char *str = dupprintf("No supported authentication methods available"
10331 " (server sent: %.*s)",
10334 ssh_disconnect(ssh, str,
10335 "No supported authentication methods available",
10336 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10346 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10348 /* Clear up various bits and pieces from authentication. */
10349 if (s->publickey_blob) {
10350 sfree(s->publickey_algorithm);
10351 sfree(s->publickey_blob);
10352 sfree(s->publickey_comment);
10354 if (s->agent_response)
10355 sfree(s->agent_response);
10357 if (s->userauth_success && !ssh->bare_connection) {
10359 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10360 * packets since. Signal the transport layer to consider enacting
10361 * delayed compression.
10363 * (Relying on we_are_in is not sufficient, as
10364 * draft-miller-secsh-compression-delayed is quite clear that it
10365 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10366 * become set for other reasons.)
10368 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10371 ssh->channels = newtree234(ssh_channelcmp);
10374 * Set up handlers for some connection protocol messages, so we
10375 * don't have to handle them repeatedly in this coroutine.
10377 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10378 ssh2_msg_channel_window_adjust;
10379 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10380 ssh2_msg_global_request;
10383 * Create the main session channel.
10385 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10386 ssh->mainchan = NULL;
10388 ssh->mainchan = snew(struct ssh_channel);
10389 ssh->mainchan->ssh = ssh;
10390 ssh2_channel_init(ssh->mainchan);
10392 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10394 * Just start a direct-tcpip channel and use it as the main
10397 ssh_send_port_open(ssh->mainchan,
10398 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10399 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10401 ssh->ncmode = TRUE;
10403 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10404 logevent("Opening session as main channel");
10405 ssh2_pkt_send(ssh, s->pktout);
10406 ssh->ncmode = FALSE;
10408 crWaitUntilV(pktin);
10409 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10410 bombout(("Server refused to open channel"));
10412 /* FIXME: error data comes back in FAILURE packet */
10414 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10415 bombout(("Server's channel confirmation cited wrong channel"));
10418 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10419 ssh->mainchan->halfopen = FALSE;
10420 ssh->mainchan->type = CHAN_MAINSESSION;
10421 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10422 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10423 add234(ssh->channels, ssh->mainchan);
10424 update_specials_menu(ssh->frontend);
10425 logevent("Opened main channel");
10429 * Now we have a channel, make dispatch table entries for
10430 * general channel-based messages.
10432 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10433 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10434 ssh2_msg_channel_data;
10435 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10436 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10437 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10438 ssh2_msg_channel_open_confirmation;
10439 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10440 ssh2_msg_channel_open_failure;
10441 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10442 ssh2_msg_channel_request;
10443 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10444 ssh2_msg_channel_open;
10445 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10446 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10449 * Now the connection protocol is properly up and running, with
10450 * all those dispatch table entries, so it's safe to let
10451 * downstreams start trying to open extra channels through us.
10453 if (ssh->connshare)
10454 share_activate(ssh->connshare, ssh->v_s);
10456 if (ssh->mainchan && ssh_is_simple(ssh)) {
10458 * This message indicates to the server that we promise
10459 * not to try to run any other channel in parallel with
10460 * this one, so it's safe for it to advertise a very large
10461 * window and leave the flow control to TCP.
10463 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10464 "simple@putty.projects.tartarus.org",
10466 ssh2_pkt_send(ssh, s->pktout);
10470 * Enable port forwardings.
10472 ssh_setup_portfwd(ssh, ssh->conf);
10474 if (ssh->mainchan && !ssh->ncmode) {
10476 * Send the CHANNEL_REQUESTS for the main session channel.
10477 * Each one is handled by its own little asynchronous
10481 /* Potentially enable X11 forwarding. */
10482 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10484 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10486 if (!ssh->x11disp) {
10487 /* FIXME: return an error message from x11_setup_display */
10488 logevent("X11 forwarding not enabled: unable to"
10489 " initialise X display");
10491 ssh->x11auth = x11_invent_fake_auth
10492 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10493 ssh->x11auth->disp = ssh->x11disp;
10495 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10499 /* Potentially enable agent forwarding. */
10500 if (ssh_agent_forwarding_permitted(ssh))
10501 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10503 /* Now allocate a pty for the session. */
10504 if (!conf_get_int(ssh->conf, CONF_nopty))
10505 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10507 /* Send environment variables. */
10508 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10511 * Start a shell or a remote command. We may have to attempt
10512 * this twice if the config data has provided a second choice
10519 if (ssh->fallback_cmd) {
10520 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10521 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10523 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10524 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10528 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10529 ssh2_response_authconn, NULL);
10530 ssh2_pkt_addstring(s->pktout, cmd);
10532 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10533 ssh2_response_authconn, NULL);
10534 ssh2_pkt_addstring(s->pktout, cmd);
10536 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10537 ssh2_response_authconn, NULL);
10539 ssh2_pkt_send(ssh, s->pktout);
10541 crWaitUntilV(pktin);
10543 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10544 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10545 bombout(("Unexpected response to shell/command request:"
10546 " packet type %d", pktin->type));
10550 * We failed to start the command. If this is the
10551 * fallback command, we really are finished; if it's
10552 * not, and if the fallback command exists, try falling
10553 * back to it before complaining.
10555 if (!ssh->fallback_cmd &&
10556 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10557 logevent("Primary command failed; attempting fallback");
10558 ssh->fallback_cmd = TRUE;
10561 bombout(("Server refused to start a shell/command"));
10564 logevent("Started a shell/command");
10569 ssh->editing = ssh->echoing = TRUE;
10572 ssh->state = SSH_STATE_SESSION;
10573 if (ssh->size_needed)
10574 ssh_size(ssh, ssh->term_width, ssh->term_height);
10575 if (ssh->eof_needed)
10576 ssh_special(ssh, TS_EOF);
10582 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10587 s->try_send = FALSE;
10591 * _All_ the connection-layer packets we expect to
10592 * receive are now handled by the dispatch table.
10593 * Anything that reaches here must be bogus.
10596 bombout(("Strange packet received: type %d", pktin->type));
10598 } else if (ssh->mainchan) {
10600 * We have spare data. Add it to the channel buffer.
10602 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
10603 s->try_send = TRUE;
10607 struct ssh_channel *c;
10609 * Try to send data on all channels if we can.
10611 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
10612 if (c->type != CHAN_SHARING)
10613 ssh2_try_send_and_unthrottle(ssh, c);
10621 * Handlers for SSH-2 messages that might arrive at any moment.
10623 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10625 /* log reason code in disconnect message */
10627 int reason, msglen;
10629 reason = ssh_pkt_getuint32(pktin);
10630 ssh_pkt_getstring(pktin, &msg, &msglen);
10632 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10633 buf = dupprintf("Received disconnect message (%s)",
10634 ssh2_disconnect_reasons[reason]);
10636 buf = dupprintf("Received disconnect message (unknown"
10637 " type %d)", reason);
10641 buf = dupprintf("Disconnection message text: %.*s",
10644 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10646 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10647 ssh2_disconnect_reasons[reason] : "unknown",
10652 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10654 /* log the debug message */
10658 /* XXX maybe we should actually take notice of the return value */
10659 ssh2_pkt_getbool(pktin);
10660 ssh_pkt_getstring(pktin, &msg, &msglen);
10662 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
10665 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10667 do_ssh2_transport(ssh, NULL, 0, pktin);
10671 * Called if we receive a packet that isn't allowed by the protocol.
10672 * This only applies to packets whose meaning PuTTY understands.
10673 * Entirely unknown packets are handled below.
10675 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10677 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10678 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10680 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10684 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10686 struct Packet *pktout;
10687 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10688 ssh2_pkt_adduint32(pktout, pktin->sequence);
10690 * UNIMPLEMENTED messages MUST appear in the same order as the
10691 * messages they respond to. Hence, never queue them.
10693 ssh2_pkt_send_noqueue(ssh, pktout);
10697 * Handle the top-level SSH-2 protocol.
10699 static void ssh2_protocol_setup(Ssh ssh)
10704 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10706 for (i = 0; i < 256; i++)
10707 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10710 * Initially, we only accept transport messages (and a few generic
10711 * ones). do_ssh2_authconn will add more when it starts.
10712 * Messages that are understood but not currently acceptable go to
10713 * ssh2_msg_unexpected.
10715 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10716 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10717 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10718 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10719 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10720 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10721 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10722 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10723 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10724 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10725 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10726 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10727 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10728 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10729 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10730 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10731 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10732 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10733 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10734 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10735 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10736 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10737 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10738 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10739 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10740 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10741 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10742 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10743 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10744 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10745 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10746 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10747 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10750 * These messages have a special handler from the start.
10752 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10753 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10754 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10757 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10762 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10764 for (i = 0; i < 256; i++)
10765 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10768 * Initially, we set all ssh-connection messages to 'unexpected';
10769 * do_ssh2_authconn will fill things in properly. We also handle a
10770 * couple of messages from the transport protocol which aren't
10771 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10774 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10775 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10776 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10777 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10778 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10779 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10780 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10781 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10782 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10783 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10784 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10785 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10786 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10787 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10789 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10792 * These messages have a special handler from the start.
10794 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10795 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
10796 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10799 static void ssh2_timer(void *ctx, unsigned long now)
10801 Ssh ssh = (Ssh)ctx;
10803 if (ssh->state == SSH_STATE_CLOSED)
10806 if (!ssh->kex_in_progress && !ssh->bare_connection &&
10807 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
10808 now == ssh->next_rekey) {
10809 do_ssh2_transport(ssh, "timeout", -1, NULL);
10813 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
10814 struct Packet *pktin)
10816 const unsigned char *in = (const unsigned char *)vin;
10817 if (ssh->state == SSH_STATE_CLOSED)
10821 ssh->incoming_data_size += pktin->encrypted_len;
10822 if (!ssh->kex_in_progress &&
10823 ssh->max_data_size != 0 &&
10824 ssh->incoming_data_size > ssh->max_data_size)
10825 do_ssh2_transport(ssh, "too much data received", -1, NULL);
10829 ssh->packet_dispatch[pktin->type](ssh, pktin);
10830 else if (!ssh->protocol_initial_phase_done)
10831 do_ssh2_transport(ssh, in, inlen, pktin);
10833 do_ssh2_authconn(ssh, in, inlen, pktin);
10836 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
10837 struct Packet *pktin)
10839 const unsigned char *in = (const unsigned char *)vin;
10840 if (ssh->state == SSH_STATE_CLOSED)
10844 ssh->packet_dispatch[pktin->type](ssh, pktin);
10846 do_ssh2_authconn(ssh, in, inlen, pktin);
10849 static void ssh_cache_conf_values(Ssh ssh)
10851 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
10855 * Called to set up the connection.
10857 * Returns an error message, or NULL on success.
10859 static const char *ssh_init(void *frontend_handle, void **backend_handle,
10861 const char *host, int port, char **realhost,
10862 int nodelay, int keepalive)
10867 ssh = snew(struct ssh_tag);
10868 ssh->conf = conf_copy(conf);
10869 ssh_cache_conf_values(ssh);
10870 ssh->version = 0; /* when not ready yet */
10872 ssh->cipher = NULL;
10873 ssh->v1_cipher_ctx = NULL;
10874 ssh->crcda_ctx = NULL;
10875 ssh->cscipher = NULL;
10876 ssh->cs_cipher_ctx = NULL;
10877 ssh->sccipher = NULL;
10878 ssh->sc_cipher_ctx = NULL;
10880 ssh->cs_mac_ctx = NULL;
10882 ssh->sc_mac_ctx = NULL;
10883 ssh->cscomp = NULL;
10884 ssh->cs_comp_ctx = NULL;
10885 ssh->sccomp = NULL;
10886 ssh->sc_comp_ctx = NULL;
10888 ssh->kex_ctx = NULL;
10889 ssh->hostkey = NULL;
10890 ssh->hostkey_str = NULL;
10891 ssh->exitcode = -1;
10892 ssh->close_expected = FALSE;
10893 ssh->clean_exit = FALSE;
10894 ssh->state = SSH_STATE_PREPACKET;
10895 ssh->size_needed = FALSE;
10896 ssh->eof_needed = FALSE;
10898 ssh->logctx = NULL;
10899 ssh->deferred_send_data = NULL;
10900 ssh->deferred_len = 0;
10901 ssh->deferred_size = 0;
10902 ssh->fallback_cmd = 0;
10903 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
10904 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
10905 ssh->x11disp = NULL;
10906 ssh->x11auth = NULL;
10907 ssh->x11authtree = newtree234(x11_authcmp);
10908 ssh->v1_compressing = FALSE;
10909 ssh->v2_outgoing_sequence = 0;
10910 ssh->ssh1_rdpkt_crstate = 0;
10911 ssh->ssh2_rdpkt_crstate = 0;
10912 ssh->ssh2_bare_rdpkt_crstate = 0;
10913 ssh->ssh_gotdata_crstate = 0;
10914 ssh->do_ssh1_connection_crstate = 0;
10915 ssh->do_ssh_init_state = NULL;
10916 ssh->do_ssh_connection_init_state = NULL;
10917 ssh->do_ssh1_login_state = NULL;
10918 ssh->do_ssh2_transport_state = NULL;
10919 ssh->do_ssh2_authconn_state = NULL;
10922 ssh->mainchan = NULL;
10923 ssh->throttled_all = 0;
10924 ssh->v1_stdout_throttling = 0;
10926 ssh->queuelen = ssh->queuesize = 0;
10927 ssh->queueing = FALSE;
10928 ssh->qhead = ssh->qtail = NULL;
10929 ssh->deferred_rekey_reason = NULL;
10930 bufchain_init(&ssh->queued_incoming_data);
10931 ssh->frozen = FALSE;
10932 ssh->username = NULL;
10933 ssh->sent_console_eof = FALSE;
10934 ssh->got_pty = FALSE;
10935 ssh->bare_connection = FALSE;
10936 ssh->X11_fwd_enabled = FALSE;
10937 ssh->connshare = NULL;
10938 ssh->attempting_connshare = FALSE;
10940 *backend_handle = ssh;
10943 if (crypto_startup() == 0)
10944 return "Microsoft high encryption pack not installed!";
10947 ssh->frontend = frontend_handle;
10948 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
10949 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
10951 ssh->channels = NULL;
10952 ssh->rportfwds = NULL;
10953 ssh->portfwds = NULL;
10958 ssh->conn_throttle_count = 0;
10959 ssh->overall_bufsize = 0;
10960 ssh->fallback_cmd = 0;
10962 ssh->protocol = NULL;
10964 ssh->protocol_initial_phase_done = FALSE;
10966 ssh->pinger = NULL;
10968 ssh->incoming_data_size = ssh->outgoing_data_size =
10969 ssh->deferred_data_size = 0L;
10970 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10971 CONF_ssh_rekey_data));
10972 ssh->kex_in_progress = FALSE;
10975 ssh->gsslibs = NULL;
10978 random_ref(); /* do this now - may be needed by sharing setup code */
10980 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
10989 static void ssh_free(void *handle)
10991 Ssh ssh = (Ssh) handle;
10992 struct ssh_channel *c;
10993 struct ssh_rportfwd *pf;
10994 struct X11FakeAuth *auth;
10996 if (ssh->v1_cipher_ctx)
10997 ssh->cipher->free_context(ssh->v1_cipher_ctx);
10998 if (ssh->cs_cipher_ctx)
10999 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11000 if (ssh->sc_cipher_ctx)
11001 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11002 if (ssh->cs_mac_ctx)
11003 ssh->csmac->free_context(ssh->cs_mac_ctx);
11004 if (ssh->sc_mac_ctx)
11005 ssh->scmac->free_context(ssh->sc_mac_ctx);
11006 if (ssh->cs_comp_ctx) {
11008 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11010 zlib_compress_cleanup(ssh->cs_comp_ctx);
11012 if (ssh->sc_comp_ctx) {
11014 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11016 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11019 dh_cleanup(ssh->kex_ctx);
11020 sfree(ssh->savedhost);
11022 while (ssh->queuelen-- > 0)
11023 ssh_free_packet(ssh->queue[ssh->queuelen]);
11026 while (ssh->qhead) {
11027 struct queued_handler *qh = ssh->qhead;
11028 ssh->qhead = qh->next;
11031 ssh->qhead = ssh->qtail = NULL;
11033 if (ssh->channels) {
11034 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11037 if (c->u.x11.xconn != NULL)
11038 x11_close(c->u.x11.xconn);
11040 case CHAN_SOCKDATA:
11041 case CHAN_SOCKDATA_DORMANT:
11042 if (c->u.pfd.pf != NULL)
11043 pfd_close(c->u.pfd.pf);
11046 if (ssh->version == 2) {
11047 struct outstanding_channel_request *ocr, *nocr;
11048 ocr = c->v.v2.chanreq_head;
11050 ocr->handler(c, NULL, ocr->ctx);
11055 bufchain_clear(&c->v.v2.outbuffer);
11059 freetree234(ssh->channels);
11060 ssh->channels = NULL;
11063 if (ssh->connshare)
11064 sharestate_free(ssh->connshare);
11066 if (ssh->rportfwds) {
11067 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11069 freetree234(ssh->rportfwds);
11070 ssh->rportfwds = NULL;
11072 sfree(ssh->deferred_send_data);
11074 x11_free_display(ssh->x11disp);
11075 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11076 x11_free_fake_auth(auth);
11077 freetree234(ssh->x11authtree);
11078 sfree(ssh->do_ssh_init_state);
11079 sfree(ssh->do_ssh1_login_state);
11080 sfree(ssh->do_ssh2_transport_state);
11081 sfree(ssh->do_ssh2_authconn_state);
11084 sfree(ssh->fullhostname);
11085 sfree(ssh->hostkey_str);
11086 if (ssh->crcda_ctx) {
11087 crcda_free_context(ssh->crcda_ctx);
11088 ssh->crcda_ctx = NULL;
11091 ssh_do_close(ssh, TRUE);
11092 expire_timer_context(ssh);
11094 pinger_free(ssh->pinger);
11095 bufchain_clear(&ssh->queued_incoming_data);
11096 sfree(ssh->username);
11097 conf_free(ssh->conf);
11100 ssh_gss_cleanup(ssh->gsslibs);
11108 * Reconfigure the SSH backend.
11110 static void ssh_reconfig(void *handle, Conf *conf)
11112 Ssh ssh = (Ssh) handle;
11113 const char *rekeying = NULL;
11114 int rekey_mandatory = FALSE;
11115 unsigned long old_max_data_size;
11118 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11120 ssh_setup_portfwd(ssh, conf);
11122 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11123 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11125 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11126 unsigned long now = GETTICKCOUNT();
11128 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11129 rekeying = "timeout shortened";
11131 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11135 old_max_data_size = ssh->max_data_size;
11136 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11137 CONF_ssh_rekey_data));
11138 if (old_max_data_size != ssh->max_data_size &&
11139 ssh->max_data_size != 0) {
11140 if (ssh->outgoing_data_size > ssh->max_data_size ||
11141 ssh->incoming_data_size > ssh->max_data_size)
11142 rekeying = "data limit lowered";
11145 if (conf_get_int(ssh->conf, CONF_compression) !=
11146 conf_get_int(conf, CONF_compression)) {
11147 rekeying = "compression setting changed";
11148 rekey_mandatory = TRUE;
11151 for (i = 0; i < CIPHER_MAX; i++)
11152 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11153 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11154 rekeying = "cipher settings changed";
11155 rekey_mandatory = TRUE;
11157 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11158 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11159 rekeying = "cipher settings changed";
11160 rekey_mandatory = TRUE;
11163 conf_free(ssh->conf);
11164 ssh->conf = conf_copy(conf);
11165 ssh_cache_conf_values(ssh);
11167 if (!ssh->bare_connection && rekeying) {
11168 if (!ssh->kex_in_progress) {
11169 do_ssh2_transport(ssh, rekeying, -1, NULL);
11170 } else if (rekey_mandatory) {
11171 ssh->deferred_rekey_reason = rekeying;
11177 * Called to send data down the SSH connection.
11179 static int ssh_send(void *handle, const char *buf, int len)
11181 Ssh ssh = (Ssh) handle;
11183 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11186 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11188 return ssh_sendbuffer(ssh);
11192 * Called to query the current amount of buffered stdin data.
11194 static int ssh_sendbuffer(void *handle)
11196 Ssh ssh = (Ssh) handle;
11197 int override_value;
11199 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11203 * If the SSH socket itself has backed up, add the total backup
11204 * size on that to any individual buffer on the stdin channel.
11206 override_value = 0;
11207 if (ssh->throttled_all)
11208 override_value = ssh->overall_bufsize;
11210 if (ssh->version == 1) {
11211 return override_value;
11212 } else if (ssh->version == 2) {
11213 if (!ssh->mainchan)
11214 return override_value;
11216 return (override_value +
11217 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11224 * Called to set the size of the window from SSH's POV.
11226 static void ssh_size(void *handle, int width, int height)
11228 Ssh ssh = (Ssh) handle;
11229 struct Packet *pktout;
11231 ssh->term_width = width;
11232 ssh->term_height = height;
11234 switch (ssh->state) {
11235 case SSH_STATE_BEFORE_SIZE:
11236 case SSH_STATE_PREPACKET:
11237 case SSH_STATE_CLOSED:
11238 break; /* do nothing */
11239 case SSH_STATE_INTERMED:
11240 ssh->size_needed = TRUE; /* buffer for later */
11242 case SSH_STATE_SESSION:
11243 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11244 if (ssh->version == 1) {
11245 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11246 PKT_INT, ssh->term_height,
11247 PKT_INT, ssh->term_width,
11248 PKT_INT, 0, PKT_INT, 0, PKT_END);
11249 } else if (ssh->mainchan) {
11250 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11252 ssh2_pkt_adduint32(pktout, ssh->term_width);
11253 ssh2_pkt_adduint32(pktout, ssh->term_height);
11254 ssh2_pkt_adduint32(pktout, 0);
11255 ssh2_pkt_adduint32(pktout, 0);
11256 ssh2_pkt_send(ssh, pktout);
11264 * Return a list of the special codes that make sense in this
11267 static const struct telnet_special *ssh_get_specials(void *handle)
11269 static const struct telnet_special ssh1_ignore_special[] = {
11270 {"IGNORE message", TS_NOP}
11272 static const struct telnet_special ssh2_ignore_special[] = {
11273 {"IGNORE message", TS_NOP},
11275 static const struct telnet_special ssh2_rekey_special[] = {
11276 {"Repeat key exchange", TS_REKEY},
11278 static const struct telnet_special ssh2_session_specials[] = {
11281 /* These are the signal names defined by RFC 4254.
11282 * They include all the ISO C signals, but are a subset of the POSIX
11283 * required signals. */
11284 {"SIGINT (Interrupt)", TS_SIGINT},
11285 {"SIGTERM (Terminate)", TS_SIGTERM},
11286 {"SIGKILL (Kill)", TS_SIGKILL},
11287 {"SIGQUIT (Quit)", TS_SIGQUIT},
11288 {"SIGHUP (Hangup)", TS_SIGHUP},
11289 {"More signals", TS_SUBMENU},
11290 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11291 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11292 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11293 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11294 {NULL, TS_EXITMENU}
11296 static const struct telnet_special specials_end[] = {
11297 {NULL, TS_EXITMENU}
11299 /* XXX review this length for any changes: */
11300 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
11301 lenof(ssh2_rekey_special) +
11302 lenof(ssh2_session_specials) +
11303 lenof(specials_end)];
11304 Ssh ssh = (Ssh) handle;
11306 #define ADD_SPECIALS(name) \
11308 assert((i + lenof(name)) <= lenof(ssh_specials)); \
11309 memcpy(&ssh_specials[i], name, sizeof name); \
11310 i += lenof(name); \
11313 if (ssh->version == 1) {
11314 /* Don't bother offering IGNORE if we've decided the remote
11315 * won't cope with it, since we wouldn't bother sending it if
11317 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11318 ADD_SPECIALS(ssh1_ignore_special);
11319 } else if (ssh->version == 2) {
11320 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11321 ADD_SPECIALS(ssh2_ignore_special);
11322 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11323 ADD_SPECIALS(ssh2_rekey_special);
11325 ADD_SPECIALS(ssh2_session_specials);
11326 } /* else we're not ready yet */
11329 ADD_SPECIALS(specials_end);
11330 return ssh_specials;
11334 #undef ADD_SPECIALS
11338 * Send special codes. TS_EOF is useful for `plink', so you
11339 * can send an EOF and collect resulting output (e.g. `plink
11342 static void ssh_special(void *handle, Telnet_Special code)
11344 Ssh ssh = (Ssh) handle;
11345 struct Packet *pktout;
11347 if (code == TS_EOF) {
11348 if (ssh->state != SSH_STATE_SESSION) {
11350 * Buffer the EOF in case we are pre-SESSION, so we can
11351 * send it as soon as we reach SESSION.
11353 if (code == TS_EOF)
11354 ssh->eof_needed = TRUE;
11357 if (ssh->version == 1) {
11358 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11359 } else if (ssh->mainchan) {
11360 sshfwd_write_eof(ssh->mainchan);
11361 ssh->send_ok = 0; /* now stop trying to read from stdin */
11363 logevent("Sent EOF message");
11364 } else if (code == TS_PING || code == TS_NOP) {
11365 if (ssh->state == SSH_STATE_CLOSED
11366 || ssh->state == SSH_STATE_PREPACKET) return;
11367 if (ssh->version == 1) {
11368 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11369 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11371 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11372 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11373 ssh2_pkt_addstring_start(pktout);
11374 ssh2_pkt_send_noqueue(ssh, pktout);
11377 } else if (code == TS_REKEY) {
11378 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11379 ssh->version == 2) {
11380 do_ssh2_transport(ssh, "at user request", -1, NULL);
11382 } else if (code == TS_BRK) {
11383 if (ssh->state == SSH_STATE_CLOSED
11384 || ssh->state == SSH_STATE_PREPACKET) return;
11385 if (ssh->version == 1) {
11386 logevent("Unable to send BREAK signal in SSH-1");
11387 } else if (ssh->mainchan) {
11388 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11389 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11390 ssh2_pkt_send(ssh, pktout);
11393 /* Is is a POSIX signal? */
11394 const char *signame = NULL;
11395 if (code == TS_SIGABRT) signame = "ABRT";
11396 if (code == TS_SIGALRM) signame = "ALRM";
11397 if (code == TS_SIGFPE) signame = "FPE";
11398 if (code == TS_SIGHUP) signame = "HUP";
11399 if (code == TS_SIGILL) signame = "ILL";
11400 if (code == TS_SIGINT) signame = "INT";
11401 if (code == TS_SIGKILL) signame = "KILL";
11402 if (code == TS_SIGPIPE) signame = "PIPE";
11403 if (code == TS_SIGQUIT) signame = "QUIT";
11404 if (code == TS_SIGSEGV) signame = "SEGV";
11405 if (code == TS_SIGTERM) signame = "TERM";
11406 if (code == TS_SIGUSR1) signame = "USR1";
11407 if (code == TS_SIGUSR2) signame = "USR2";
11408 /* The SSH-2 protocol does in principle support arbitrary named
11409 * signals, including signame@domain, but we don't support those. */
11411 /* It's a signal. */
11412 if (ssh->version == 2 && ssh->mainchan) {
11413 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11414 ssh2_pkt_addstring(pktout, signame);
11415 ssh2_pkt_send(ssh, pktout);
11416 logeventf(ssh, "Sent signal SIG%s", signame);
11419 /* Never heard of it. Do nothing */
11424 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11426 Ssh ssh = (Ssh) handle;
11427 struct ssh_channel *c;
11428 c = snew(struct ssh_channel);
11431 ssh2_channel_init(c);
11432 c->halfopen = TRUE;
11433 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11435 add234(ssh->channels, c);
11439 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11441 struct ssh_channel *c;
11442 c = snew(struct ssh_channel);
11445 ssh2_channel_init(c);
11446 c->type = CHAN_SHARING;
11447 c->u.sharing.ctx = sharing_ctx;
11448 add234(ssh->channels, c);
11452 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11454 struct ssh_channel *c;
11456 c = find234(ssh->channels, &localid, ssh_channelfind);
11458 ssh_channel_destroy(c);
11461 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11462 const void *data, int datalen,
11463 const char *additional_log_text)
11465 struct Packet *pkt;
11467 pkt = ssh2_pkt_init(type);
11468 pkt->downstream_id = id;
11469 pkt->additional_log_text = additional_log_text;
11470 ssh2_pkt_adddata(pkt, data, datalen);
11471 ssh2_pkt_send(ssh, pkt);
11475 * This is called when stdout/stderr (the entity to which
11476 * from_backend sends data) manages to clear some backlog.
11478 static void ssh_unthrottle(void *handle, int bufsize)
11480 Ssh ssh = (Ssh) handle;
11483 if (ssh->version == 1) {
11484 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11485 ssh->v1_stdout_throttling = 0;
11486 ssh_throttle_conn(ssh, -1);
11489 if (ssh->mainchan) {
11490 ssh2_set_window(ssh->mainchan,
11491 bufsize < ssh->mainchan->v.v2.locmaxwin ?
11492 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11493 if (ssh_is_simple(ssh))
11496 buflimit = ssh->mainchan->v.v2.locmaxwin;
11497 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11498 ssh->mainchan->throttling_conn = 0;
11499 ssh_throttle_conn(ssh, -1);
11505 * Now process any SSH connection data that was stashed in our
11506 * queue while we were frozen.
11508 ssh_process_queued_incoming_data(ssh);
11511 void ssh_send_port_open(void *channel, const char *hostname, int port,
11514 struct ssh_channel *c = (struct ssh_channel *)channel;
11516 struct Packet *pktout;
11518 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11520 if (ssh->version == 1) {
11521 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11522 PKT_INT, c->localid,
11525 /* PKT_STR, <org:orgport>, */
11528 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11530 char *trimmed_host = host_strduptrim(hostname);
11531 ssh2_pkt_addstring(pktout, trimmed_host);
11532 sfree(trimmed_host);
11534 ssh2_pkt_adduint32(pktout, port);
11536 * We make up values for the originator data; partly it's
11537 * too much hassle to keep track, and partly I'm not
11538 * convinced the server should be told details like that
11539 * about my local network configuration.
11540 * The "originator IP address" is syntactically a numeric
11541 * IP address, and some servers (e.g., Tectia) get upset
11542 * if it doesn't match this syntax.
11544 ssh2_pkt_addstring(pktout, "0.0.0.0");
11545 ssh2_pkt_adduint32(pktout, 0);
11546 ssh2_pkt_send(ssh, pktout);
11550 static int ssh_connected(void *handle)
11552 Ssh ssh = (Ssh) handle;
11553 return ssh->s != NULL;
11556 static int ssh_sendok(void *handle)
11558 Ssh ssh = (Ssh) handle;
11559 return ssh->send_ok;
11562 static int ssh_ldisc(void *handle, int option)
11564 Ssh ssh = (Ssh) handle;
11565 if (option == LD_ECHO)
11566 return ssh->echoing;
11567 if (option == LD_EDIT)
11568 return ssh->editing;
11572 static void ssh_provide_ldisc(void *handle, void *ldisc)
11574 Ssh ssh = (Ssh) handle;
11575 ssh->ldisc = ldisc;
11578 static void ssh_provide_logctx(void *handle, void *logctx)
11580 Ssh ssh = (Ssh) handle;
11581 ssh->logctx = logctx;
11584 static int ssh_return_exitcode(void *handle)
11586 Ssh ssh = (Ssh) handle;
11587 if (ssh->s != NULL)
11590 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11594 * cfg_info for SSH is the protocol running in this session.
11595 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11596 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11598 static int ssh_cfg_info(void *handle)
11600 Ssh ssh = (Ssh) handle;
11601 if (ssh->version == 0)
11602 return 0; /* don't know yet */
11603 else if (ssh->bare_connection)
11606 return ssh->version;
11610 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11611 * that fails. This variable is the means by which scp.c can reach
11612 * into the SSH code and find out which one it got.
11614 extern int ssh_fallback_cmd(void *handle)
11616 Ssh ssh = (Ssh) handle;
11617 return ssh->fallback_cmd;
11620 Backend ssh_backend = {
11630 ssh_return_exitcode,
11634 ssh_provide_logctx,