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);
367 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin);
370 * Buffer management constants. There are several of these for
371 * various different purposes:
373 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
374 * on a local data stream before we throttle the whole SSH
375 * connection (in SSH-1 only). Throttling the whole connection is
376 * pretty drastic so we set this high in the hope it won't
379 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
380 * on the SSH connection itself before we defensively throttle
381 * _all_ local data streams. This is pretty drastic too (though
382 * thankfully unlikely in SSH-2 since the window mechanism should
383 * ensure that the server never has any need to throttle its end
384 * of the connection), so we set this high as well.
386 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
389 * - OUR_V2_BIGWIN is the window size we advertise for the only
390 * channel in a simple connection. It must be <= INT_MAX.
392 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
393 * to the remote side. This actually has nothing to do with the
394 * size of the _packet_, but is instead a limit on the amount
395 * of data we're willing to receive in a single SSH2 channel
398 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
399 * _packet_ we're prepared to cope with. It must be a multiple
400 * of the cipher block size, and must be at least 35000.
403 #define SSH1_BUFFER_LIMIT 32768
404 #define SSH_MAX_BACKLOG 32768
405 #define OUR_V2_WINSIZE 16384
406 #define OUR_V2_BIGWIN 0x7fffffff
407 #define OUR_V2_MAXPKT 0x4000UL
408 #define OUR_V2_PACKETLIMIT 0x9000UL
410 const static struct ssh_signkey *hostkey_algs[] = {
412 &ssh_ecdsa_nistp256, &ssh_ecdsa_nistp384, &ssh_ecdsa_nistp521,
416 const static struct ssh_mac *macs[] = {
417 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
419 const static struct ssh_mac *buggymacs[] = {
420 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
423 static void *ssh_comp_none_init(void)
427 static void ssh_comp_none_cleanup(void *handle)
430 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
431 unsigned char **outblock, int *outlen)
435 static int ssh_comp_none_disable(void *handle)
439 const static struct ssh_compress ssh_comp_none = {
441 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
442 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
443 ssh_comp_none_disable, NULL
445 extern const struct ssh_compress ssh_zlib;
446 const static struct ssh_compress *compressions[] = {
447 &ssh_zlib, &ssh_comp_none
450 enum { /* channel types */
455 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
457 * CHAN_SHARING indicates a channel which is tracked here on
458 * behalf of a connection-sharing downstream. We do almost nothing
459 * with these channels ourselves: all messages relating to them
460 * get thrown straight to sshshare.c and passed on almost
461 * unmodified to downstream.
465 * CHAN_ZOMBIE is used to indicate a channel for which we've
466 * already destroyed the local data source: for instance, if a
467 * forwarded port experiences a socket error on the local side, we
468 * immediately destroy its local socket and turn the SSH channel
474 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
475 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
476 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
479 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
482 struct outstanding_channel_request {
483 cchandler_fn_t handler;
485 struct outstanding_channel_request *next;
489 * 2-3-4 tree storing channels.
492 Ssh ssh; /* pointer back to main context */
493 unsigned remoteid, localid;
495 /* True if we opened this channel but server hasn't confirmed. */
498 * In SSH-1, this value contains four bits:
500 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
501 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
502 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
503 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
505 * A channel is completely finished with when all four bits are set.
507 * In SSH-2, the four bits mean:
509 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
510 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
511 * 4 We have received SSH2_MSG_CHANNEL_EOF.
512 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
514 * A channel is completely finished with when we have both sent
515 * and received CLOSE.
517 * The symbolic constants below use the SSH-2 terminology, which
518 * is a bit confusing in SSH-1, but we have to use _something_.
520 #define CLOSES_SENT_EOF 1
521 #define CLOSES_SENT_CLOSE 2
522 #define CLOSES_RCVD_EOF 4
523 #define CLOSES_RCVD_CLOSE 8
527 * This flag indicates that an EOF is pending on the outgoing side
528 * of the channel: that is, wherever we're getting the data for
529 * this channel has sent us some data followed by EOF. We can't
530 * actually send the EOF until we've finished sending the data, so
531 * we set this flag instead to remind us to do so once our buffer
537 * True if this channel is causing the underlying connection to be
542 struct ssh2_data_channel {
544 unsigned remwindow, remmaxpkt;
545 /* locwindow is signed so we can cope with excess data. */
546 int locwindow, locmaxwin;
548 * remlocwin is the amount of local window that we think
549 * the remote end had available to it after it sent the
550 * last data packet or window adjust ack.
554 * These store the list of channel requests that haven't
557 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
558 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
562 struct ssh_agent_channel {
563 unsigned char *message;
564 unsigned char msglen[4];
565 unsigned lensofar, totallen;
566 int outstanding_requests;
568 struct ssh_x11_channel {
569 struct X11Connection *xconn;
572 struct ssh_pfd_channel {
573 struct PortForwarding *pf;
575 struct ssh_sharing_channel {
582 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
583 * use this structure in different ways, reflecting SSH-2's
584 * altogether saner approach to port forwarding.
586 * In SSH-1, you arrange a remote forwarding by sending the server
587 * the remote port number, and the local destination host:port.
588 * When a connection comes in, the server sends you back that
589 * host:port pair, and you connect to it. This is a ready-made
590 * security hole if you're not on the ball: a malicious server
591 * could send you back _any_ host:port pair, so if you trustingly
592 * connect to the address it gives you then you've just opened the
593 * entire inside of your corporate network just by connecting
594 * through it to a dodgy SSH server. Hence, we must store a list of
595 * host:port pairs we _are_ trying to forward to, and reject a
596 * connection request from the server if it's not in the list.
598 * In SSH-2, each side of the connection minds its own business and
599 * doesn't send unnecessary information to the other. You arrange a
600 * remote forwarding by sending the server just the remote port
601 * number. When a connection comes in, the server tells you which
602 * of its ports was connected to; and _you_ have to remember what
603 * local host:port pair went with that port number.
605 * Hence, in SSH-1 this structure is indexed by destination
606 * host:port pair, whereas in SSH-2 it is indexed by source port.
608 struct ssh_portfwd; /* forward declaration */
610 struct ssh_rportfwd {
611 unsigned sport, dport;
615 struct ssh_portfwd *pfrec;
618 static void free_rportfwd(struct ssh_rportfwd *pf)
621 sfree(pf->sportdesc);
629 * Separately to the rportfwd tree (which is for looking up port
630 * open requests from the server), a tree of _these_ structures is
631 * used to keep track of all the currently open port forwardings,
632 * so that we can reconfigure in mid-session if the user requests
636 enum { DESTROY, KEEP, CREATE } status;
638 unsigned sport, dport;
641 struct ssh_rportfwd *remote;
643 struct PortListener *local;
645 #define free_portfwd(pf) ( \
646 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
647 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
650 long length; /* length of packet: see below */
651 long forcepad; /* SSH-2: force padding to at least this length */
652 int type; /* only used for incoming packets */
653 unsigned long sequence; /* SSH-2 incoming sequence number */
654 unsigned char *data; /* allocated storage */
655 unsigned char *body; /* offset of payload within `data' */
656 long savedpos; /* dual-purpose saved packet position: see below */
657 long maxlen; /* amount of storage allocated for `data' */
658 long encrypted_len; /* for SSH-2 total-size counting */
661 * A note on the 'length' and 'savedpos' fields above.
663 * Incoming packets are set up so that pkt->length is measured
664 * relative to pkt->body, which itself points to a few bytes after
665 * pkt->data (skipping some uninteresting header fields including
666 * the packet type code). The ssh_pkt_get* functions all expect
667 * this setup, and they also use pkt->savedpos to indicate how far
668 * through the packet being decoded they've got - and that, too,
669 * is an offset from pkt->body rather than pkt->data.
671 * During construction of an outgoing packet, however, pkt->length
672 * is measured relative to the base pointer pkt->data, and
673 * pkt->body is not really used for anything until the packet is
674 * ready for sending. In this mode, pkt->savedpos is reused as a
675 * temporary variable by the addstring functions, which write out
676 * a string length field and then keep going back and updating it
677 * as more data is appended to the subsequent string data field;
678 * pkt->savedpos stores the offset (again relative to pkt->data)
679 * of the start of the string data field.
682 /* Extra metadata used in SSH packet logging mode, allowing us to
683 * log in the packet header line that the packet came from a
684 * connection-sharing downstream and what if anything unusual was
685 * done to it. The additional_log_text field is expected to be a
686 * static string - it will not be freed. */
687 unsigned downstream_id;
688 const char *additional_log_text;
691 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
692 struct Packet *pktin);
693 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
694 struct Packet *pktin);
695 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
696 struct Packet *pktin);
697 static void ssh1_protocol_setup(Ssh ssh);
698 static void ssh2_protocol_setup(Ssh ssh);
699 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
700 static void ssh_size(void *handle, int width, int height);
701 static void ssh_special(void *handle, Telnet_Special);
702 static int ssh2_try_send(struct ssh_channel *c);
703 static void ssh2_add_channel_data(struct ssh_channel *c,
704 const char *buf, int len);
705 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
706 static void ssh2_set_window(struct ssh_channel *c, int newwin);
707 static int ssh_sendbuffer(void *handle);
708 static int ssh_do_close(Ssh ssh, int notify_exit);
709 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
710 static int ssh2_pkt_getbool(struct Packet *pkt);
711 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
712 static void ssh2_timer(void *ctx, unsigned long now);
713 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
714 struct Packet *pktin);
715 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
717 struct rdpkt1_state_tag {
718 long len, pad, biglen, to_read;
719 unsigned long realcrc, gotcrc;
723 struct Packet *pktin;
726 struct rdpkt2_state_tag {
727 long len, pad, payload, packetlen, maclen;
730 unsigned long incoming_sequence;
731 struct Packet *pktin;
734 struct rdpkt2_bare_state_tag {
738 unsigned long incoming_sequence;
739 struct Packet *pktin;
742 struct queued_handler;
743 struct queued_handler {
745 chandler_fn_t handler;
747 struct queued_handler *next;
751 const struct plug_function_table *fn;
752 /* the above field _must_ be first in the structure */
762 unsigned char session_key[32];
764 int v1_remote_protoflags;
765 int v1_local_protoflags;
766 int agentfwd_enabled;
769 const struct ssh_cipher *cipher;
772 const struct ssh2_cipher *cscipher, *sccipher;
773 void *cs_cipher_ctx, *sc_cipher_ctx;
774 const struct ssh_mac *csmac, *scmac;
775 int csmac_etm, scmac_etm;
776 void *cs_mac_ctx, *sc_mac_ctx;
777 const struct ssh_compress *cscomp, *sccomp;
778 void *cs_comp_ctx, *sc_comp_ctx;
779 const struct ssh_kex *kex;
780 const struct ssh_signkey *hostkey;
781 char *hostkey_str; /* string representation, for easy checking in rekeys */
782 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
783 int v2_session_id_len;
787 int attempting_connshare;
793 int echoing, editing;
797 int ospeed, ispeed; /* temporaries */
798 int term_width, term_height;
800 tree234 *channels; /* indexed by local id */
801 struct ssh_channel *mainchan; /* primary session channel */
802 int ncmode; /* is primary channel direct-tcpip? */
807 tree234 *rportfwds, *portfwds;
811 SSH_STATE_BEFORE_SIZE,
817 int size_needed, eof_needed;
818 int sent_console_eof;
819 int got_pty; /* affects EOF behaviour on main channel */
821 struct Packet **queue;
822 int queuelen, queuesize;
824 unsigned char *deferred_send_data;
825 int deferred_len, deferred_size;
828 * Gross hack: pscp will try to start SFTP but fall back to
829 * scp1 if that fails. This variable is the means by which
830 * scp.c can reach into the SSH code and find out which one it
835 bufchain banner; /* accumulates banners during do_ssh2_authconn */
840 struct X11Display *x11disp;
841 struct X11FakeAuth *x11auth;
842 tree234 *x11authtree;
845 int conn_throttle_count;
848 int v1_stdout_throttling;
849 unsigned long v2_outgoing_sequence;
851 int ssh1_rdpkt_crstate;
852 int ssh2_rdpkt_crstate;
853 int ssh2_bare_rdpkt_crstate;
854 int ssh_gotdata_crstate;
855 int do_ssh1_connection_crstate;
857 void *do_ssh_init_state;
858 void *do_ssh1_login_state;
859 void *do_ssh2_transport_state;
860 void *do_ssh2_authconn_state;
861 void *do_ssh_connection_init_state;
863 struct rdpkt1_state_tag rdpkt1_state;
864 struct rdpkt2_state_tag rdpkt2_state;
865 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
867 /* SSH-1 and SSH-2 use this for different things, but both use it */
868 int protocol_initial_phase_done;
870 void (*protocol) (Ssh ssh, const void *vin, int inlen,
872 struct Packet *(*s_rdpkt) (Ssh ssh, const unsigned char **data,
874 int (*do_ssh_init)(Ssh ssh, unsigned char c);
877 * We maintain our own copy of a Conf structure here. That way,
878 * when we're passed a new one for reconfiguration, we can check
879 * the differences and potentially reconfigure port forwardings
880 * etc in mid-session.
885 * Values cached out of conf so as to avoid the tree234 lookup
886 * cost every time they're used.
891 * Dynamically allocated username string created during SSH
892 * login. Stored in here rather than in the coroutine state so
893 * that it'll be reliably freed if we shut down the SSH session
894 * at some unexpected moment.
899 * Used to transfer data back from async callbacks.
901 void *agent_response;
902 int agent_response_len;
906 * The SSH connection can be set as `frozen', meaning we are
907 * not currently accepting incoming data from the network. This
908 * is slightly more serious than setting the _socket_ as
909 * frozen, because we may already have had data passed to us
910 * from the network which we need to delay processing until
911 * after the freeze is lifted, so we also need a bufchain to
915 bufchain queued_incoming_data;
918 * Dispatch table for packet types that we may have to deal
921 handler_fn_t packet_dispatch[256];
924 * Queues of one-off handler functions for success/failure
925 * indications from a request.
927 struct queued_handler *qhead, *qtail;
928 handler_fn_t q_saved_handler1, q_saved_handler2;
931 * This module deals with sending keepalives.
936 * Track incoming and outgoing data sizes and time, for
939 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
940 unsigned long max_data_size;
942 unsigned long next_rekey, last_rekey;
943 const char *deferred_rekey_reason;
946 * Fully qualified host name, which we need if doing GSSAPI.
952 * GSSAPI libraries for this session.
954 struct ssh_gss_liblist *gsslibs;
958 #define logevent(s) logevent(ssh->frontend, s)
960 /* logevent, only printf-formatted. */
961 static void logeventf(Ssh ssh, const char *fmt, ...)
967 buf = dupvprintf(fmt, ap);
973 static void bomb_out(Ssh ssh, char *text)
975 ssh_do_close(ssh, FALSE);
977 connection_fatal(ssh->frontend, "%s", text);
981 #define bombout(msg) bomb_out(ssh, dupprintf msg)
983 /* Helper function for common bits of parsing ttymodes. */
984 static void parse_ttymodes(Ssh ssh,
985 void (*do_mode)(void *data, char *mode, char *val),
990 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
992 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
994 * val[0] is either 'V', indicating that an explicit value
995 * follows it, or 'A' indicating that we should pass the
996 * value through from the local environment via get_ttymode.
999 val = get_ttymode(ssh->frontend, key);
1001 do_mode(data, key, val);
1005 do_mode(data, key, val + 1); /* skip the 'V' */
1009 static int ssh_channelcmp(void *av, void *bv)
1011 struct ssh_channel *a = (struct ssh_channel *) av;
1012 struct ssh_channel *b = (struct ssh_channel *) bv;
1013 if (a->localid < b->localid)
1015 if (a->localid > b->localid)
1019 static int ssh_channelfind(void *av, void *bv)
1021 unsigned *a = (unsigned *) av;
1022 struct ssh_channel *b = (struct ssh_channel *) bv;
1023 if (*a < b->localid)
1025 if (*a > b->localid)
1030 static int ssh_rportcmp_ssh1(void *av, void *bv)
1032 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1033 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1035 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1036 return i < 0 ? -1 : +1;
1037 if (a->dport > b->dport)
1039 if (a->dport < b->dport)
1044 static int ssh_rportcmp_ssh2(void *av, void *bv)
1046 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1047 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1049 if ( (i = strcmp(a->shost, b->shost)) != 0)
1050 return i < 0 ? -1 : +1;
1051 if (a->sport > b->sport)
1053 if (a->sport < b->sport)
1059 * Special form of strcmp which can cope with NULL inputs. NULL is
1060 * defined to sort before even the empty string.
1062 static int nullstrcmp(const char *a, const char *b)
1064 if (a == NULL && b == NULL)
1070 return strcmp(a, b);
1073 static int ssh_portcmp(void *av, void *bv)
1075 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1076 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1078 if (a->type > b->type)
1080 if (a->type < b->type)
1082 if (a->addressfamily > b->addressfamily)
1084 if (a->addressfamily < b->addressfamily)
1086 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1087 return i < 0 ? -1 : +1;
1088 if (a->sport > b->sport)
1090 if (a->sport < b->sport)
1092 if (a->type != 'D') {
1093 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1094 return i < 0 ? -1 : +1;
1095 if (a->dport > b->dport)
1097 if (a->dport < b->dport)
1103 static int alloc_channel_id(Ssh ssh)
1105 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1106 unsigned low, high, mid;
1108 struct ssh_channel *c;
1111 * First-fit allocation of channel numbers: always pick the
1112 * lowest unused one. To do this, binary-search using the
1113 * counted B-tree to find the largest channel ID which is in a
1114 * contiguous sequence from the beginning. (Precisely
1115 * everything in that sequence must have ID equal to its tree
1116 * index plus CHANNEL_NUMBER_OFFSET.)
1118 tsize = count234(ssh->channels);
1122 while (high - low > 1) {
1123 mid = (high + low) / 2;
1124 c = index234(ssh->channels, mid);
1125 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1126 low = mid; /* this one is fine */
1128 high = mid; /* this one is past it */
1131 * Now low points to either -1, or the tree index of the
1132 * largest ID in the initial sequence.
1135 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1136 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1138 return low + 1 + CHANNEL_NUMBER_OFFSET;
1141 static void c_write_stderr(int trusted, const char *buf, int len)
1144 for (i = 0; i < len; i++)
1145 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1146 fputc(buf[i], stderr);
1149 static void c_write(Ssh ssh, const char *buf, int len)
1151 if (flags & FLAG_STDERR)
1152 c_write_stderr(1, buf, len);
1154 from_backend(ssh->frontend, 1, buf, len);
1157 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1159 if (flags & FLAG_STDERR)
1160 c_write_stderr(0, buf, len);
1162 from_backend_untrusted(ssh->frontend, buf, len);
1165 static void c_write_str(Ssh ssh, const char *buf)
1167 c_write(ssh, buf, strlen(buf));
1170 static void ssh_free_packet(struct Packet *pkt)
1175 static struct Packet *ssh_new_packet(void)
1177 struct Packet *pkt = snew(struct Packet);
1179 pkt->body = pkt->data = NULL;
1185 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1188 struct logblank_t blanks[4];
1194 if (ssh->logomitdata &&
1195 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1196 pkt->type == SSH1_SMSG_STDERR_DATA ||
1197 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1198 /* "Session data" packets - omit the data string. */
1199 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1200 ssh_pkt_getuint32(pkt); /* skip channel id */
1201 blanks[nblanks].offset = pkt->savedpos + 4;
1202 blanks[nblanks].type = PKTLOG_OMIT;
1203 ssh_pkt_getstring(pkt, &str, &slen);
1205 blanks[nblanks].len = slen;
1209 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1210 ssh1_pkt_type(pkt->type),
1211 pkt->body, pkt->length, nblanks, blanks, NULL,
1215 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1218 struct logblank_t blanks[4];
1223 * For outgoing packets, pkt->length represents the length of the
1224 * whole packet starting at pkt->data (including some header), and
1225 * pkt->body refers to the point within that where the log-worthy
1226 * payload begins. However, incoming packets expect pkt->length to
1227 * represent only the payload length (that is, it's measured from
1228 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1229 * packet to conform to the incoming-packet semantics, so that we
1230 * can analyse it with the ssh_pkt_get functions.
1232 pkt->length -= (pkt->body - pkt->data);
1235 if (ssh->logomitdata &&
1236 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1237 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1238 /* "Session data" packets - omit the data string. */
1239 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1240 ssh_pkt_getuint32(pkt); /* skip channel id */
1241 blanks[nblanks].offset = pkt->savedpos + 4;
1242 blanks[nblanks].type = PKTLOG_OMIT;
1243 ssh_pkt_getstring(pkt, &str, &slen);
1245 blanks[nblanks].len = slen;
1250 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1251 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1252 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1253 conf_get_int(ssh->conf, CONF_logomitpass)) {
1254 /* If this is a password or similar packet, blank the password(s). */
1255 blanks[nblanks].offset = 0;
1256 blanks[nblanks].len = pkt->length;
1257 blanks[nblanks].type = PKTLOG_BLANK;
1259 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1260 conf_get_int(ssh->conf, CONF_logomitpass)) {
1262 * If this is an X forwarding request packet, blank the fake
1265 * Note that while we blank the X authentication data here, we
1266 * don't take any special action to blank the start of an X11
1267 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1268 * an X connection without having session blanking enabled is
1269 * likely to leak your cookie into the log.
1272 ssh_pkt_getstring(pkt, &str, &slen);
1273 blanks[nblanks].offset = pkt->savedpos;
1274 blanks[nblanks].type = PKTLOG_BLANK;
1275 ssh_pkt_getstring(pkt, &str, &slen);
1277 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1282 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1283 ssh1_pkt_type(pkt->data[12]),
1284 pkt->body, pkt->length,
1285 nblanks, blanks, NULL, 0, NULL);
1288 * Undo the above adjustment of pkt->length, to put the packet
1289 * back in the state we found it.
1291 pkt->length += (pkt->body - pkt->data);
1295 * Collect incoming data in the incoming packet buffer.
1296 * Decipher and verify the packet when it is completely read.
1297 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1298 * Update the *data and *datalen variables.
1299 * Return a Packet structure when a packet is completed.
1301 static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
1304 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1306 crBegin(ssh->ssh1_rdpkt_crstate);
1308 st->pktin = ssh_new_packet();
1310 st->pktin->type = 0;
1311 st->pktin->length = 0;
1313 for (st->i = st->len = 0; st->i < 4; st->i++) {
1314 while ((*datalen) == 0)
1316 st->len = (st->len << 8) + **data;
1317 (*data)++, (*datalen)--;
1320 st->pad = 8 - (st->len % 8);
1321 st->biglen = st->len + st->pad;
1322 st->pktin->length = st->len - 5;
1324 if (st->biglen < 0) {
1325 bombout(("Extremely large packet length from server suggests"
1326 " data stream corruption"));
1327 ssh_free_packet(st->pktin);
1331 st->pktin->maxlen = st->biglen;
1332 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1334 st->to_read = st->biglen;
1335 st->p = st->pktin->data;
1336 while (st->to_read > 0) {
1337 st->chunk = st->to_read;
1338 while ((*datalen) == 0)
1340 if (st->chunk > (*datalen))
1341 st->chunk = (*datalen);
1342 memcpy(st->p, *data, st->chunk);
1344 *datalen -= st->chunk;
1346 st->to_read -= st->chunk;
1349 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1350 st->biglen, NULL)) {
1351 bombout(("Network attack (CRC compensation) detected!"));
1352 ssh_free_packet(st->pktin);
1357 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1359 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1360 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1361 if (st->gotcrc != st->realcrc) {
1362 bombout(("Incorrect CRC received on packet"));
1363 ssh_free_packet(st->pktin);
1367 st->pktin->body = st->pktin->data + st->pad + 1;
1369 if (ssh->v1_compressing) {
1370 unsigned char *decompblk;
1372 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1373 st->pktin->body - 1, st->pktin->length + 1,
1374 &decompblk, &decomplen)) {
1375 bombout(("Zlib decompression encountered invalid data"));
1376 ssh_free_packet(st->pktin);
1380 if (st->pktin->maxlen < st->pad + decomplen) {
1381 st->pktin->maxlen = st->pad + decomplen;
1382 st->pktin->data = sresize(st->pktin->data,
1383 st->pktin->maxlen + APIEXTRA,
1385 st->pktin->body = st->pktin->data + st->pad + 1;
1388 memcpy(st->pktin->body - 1, decompblk, decomplen);
1390 st->pktin->length = decomplen - 1;
1393 st->pktin->type = st->pktin->body[-1];
1396 * Now pktin->body and pktin->length identify the semantic content
1397 * of the packet, excluding the initial type byte.
1401 ssh1_log_incoming_packet(ssh, st->pktin);
1403 st->pktin->savedpos = 0;
1405 crFinish(st->pktin);
1408 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1411 struct logblank_t blanks[4];
1417 if (ssh->logomitdata &&
1418 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1419 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1420 /* "Session data" packets - omit the data string. */
1421 ssh_pkt_getuint32(pkt); /* skip channel id */
1422 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1423 ssh_pkt_getuint32(pkt); /* skip extended data type */
1424 blanks[nblanks].offset = pkt->savedpos + 4;
1425 blanks[nblanks].type = PKTLOG_OMIT;
1426 ssh_pkt_getstring(pkt, &str, &slen);
1428 blanks[nblanks].len = slen;
1433 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1434 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1435 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1439 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1442 struct logblank_t blanks[4];
1447 * For outgoing packets, pkt->length represents the length of the
1448 * whole packet starting at pkt->data (including some header), and
1449 * pkt->body refers to the point within that where the log-worthy
1450 * payload begins. However, incoming packets expect pkt->length to
1451 * represent only the payload length (that is, it's measured from
1452 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1453 * packet to conform to the incoming-packet semantics, so that we
1454 * can analyse it with the ssh_pkt_get functions.
1456 pkt->length -= (pkt->body - pkt->data);
1459 if (ssh->logomitdata &&
1460 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1461 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1462 /* "Session data" packets - omit the data string. */
1463 ssh_pkt_getuint32(pkt); /* skip channel id */
1464 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1465 ssh_pkt_getuint32(pkt); /* skip extended data type */
1466 blanks[nblanks].offset = pkt->savedpos + 4;
1467 blanks[nblanks].type = PKTLOG_OMIT;
1468 ssh_pkt_getstring(pkt, &str, &slen);
1470 blanks[nblanks].len = slen;
1475 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1476 conf_get_int(ssh->conf, CONF_logomitpass)) {
1477 /* If this is a password packet, blank the password(s). */
1479 ssh_pkt_getstring(pkt, &str, &slen);
1480 ssh_pkt_getstring(pkt, &str, &slen);
1481 ssh_pkt_getstring(pkt, &str, &slen);
1482 if (slen == 8 && !memcmp(str, "password", 8)) {
1483 ssh2_pkt_getbool(pkt);
1484 /* Blank the password field. */
1485 blanks[nblanks].offset = pkt->savedpos;
1486 blanks[nblanks].type = PKTLOG_BLANK;
1487 ssh_pkt_getstring(pkt, &str, &slen);
1489 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1491 /* If there's another password field beyond it (change of
1492 * password), blank that too. */
1493 ssh_pkt_getstring(pkt, &str, &slen);
1495 blanks[nblanks-1].len =
1496 pkt->savedpos - blanks[nblanks].offset;
1499 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1500 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1501 conf_get_int(ssh->conf, CONF_logomitpass)) {
1502 /* If this is a keyboard-interactive response packet, blank
1505 ssh_pkt_getuint32(pkt);
1506 blanks[nblanks].offset = pkt->savedpos;
1507 blanks[nblanks].type = PKTLOG_BLANK;
1509 ssh_pkt_getstring(pkt, &str, &slen);
1513 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1515 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1516 conf_get_int(ssh->conf, CONF_logomitpass)) {
1518 * If this is an X forwarding request packet, blank the fake
1521 * Note that while we blank the X authentication data here, we
1522 * don't take any special action to blank the start of an X11
1523 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1524 * an X connection without having session blanking enabled is
1525 * likely to leak your cookie into the log.
1528 ssh_pkt_getuint32(pkt);
1529 ssh_pkt_getstring(pkt, &str, &slen);
1530 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1531 ssh2_pkt_getbool(pkt);
1532 ssh2_pkt_getbool(pkt);
1533 ssh_pkt_getstring(pkt, &str, &slen);
1534 blanks[nblanks].offset = pkt->savedpos;
1535 blanks[nblanks].type = PKTLOG_BLANK;
1536 ssh_pkt_getstring(pkt, &str, &slen);
1538 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1544 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1545 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1546 pkt->body, pkt->length, nblanks, blanks,
1547 &ssh->v2_outgoing_sequence,
1548 pkt->downstream_id, pkt->additional_log_text);
1551 * Undo the above adjustment of pkt->length, to put the packet
1552 * back in the state we found it.
1554 pkt->length += (pkt->body - pkt->data);
1557 static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
1560 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1562 crBegin(ssh->ssh2_rdpkt_crstate);
1564 st->pktin = ssh_new_packet();
1566 st->pktin->type = 0;
1567 st->pktin->length = 0;
1569 st->cipherblk = ssh->sccipher->blksize;
1572 if (st->cipherblk < 8)
1574 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1576 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1577 ssh->scmac && !ssh->scmac_etm) {
1579 * When dealing with a CBC-mode cipher, we want to avoid the
1580 * possibility of an attacker's tweaking the ciphertext stream
1581 * so as to cause us to feed the same block to the block
1582 * cipher more than once and thus leak information
1583 * (VU#958563). The way we do this is not to take any
1584 * decisions on the basis of anything we've decrypted until
1585 * we've verified it with a MAC. That includes the packet
1586 * length, so we just read data and check the MAC repeatedly,
1587 * and when the MAC passes, see if the length we've got is
1590 * This defence is unnecessary in OpenSSH ETM mode, because
1591 * the whole point of ETM mode is that the attacker can't
1592 * tweak the ciphertext stream at all without the MAC
1593 * detecting it before we decrypt anything.
1596 /* May as well allocate the whole lot now. */
1597 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1600 /* Read an amount corresponding to the MAC. */
1601 for (st->i = 0; st->i < st->maclen; st->i++) {
1602 while ((*datalen) == 0)
1604 st->pktin->data[st->i] = *(*data)++;
1610 unsigned char seq[4];
1611 ssh->scmac->start(ssh->sc_mac_ctx);
1612 PUT_32BIT(seq, st->incoming_sequence);
1613 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1616 for (;;) { /* Once around this loop per cipher block. */
1617 /* Read another cipher-block's worth, and tack it onto the end. */
1618 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1619 while ((*datalen) == 0)
1621 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1624 /* Decrypt one more block (a little further back in the stream). */
1625 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1626 st->pktin->data + st->packetlen,
1628 /* Feed that block to the MAC. */
1629 ssh->scmac->bytes(ssh->sc_mac_ctx,
1630 st->pktin->data + st->packetlen, st->cipherblk);
1631 st->packetlen += st->cipherblk;
1632 /* See if that gives us a valid packet. */
1633 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1634 st->pktin->data + st->packetlen) &&
1635 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1638 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1639 bombout(("No valid incoming packet found"));
1640 ssh_free_packet(st->pktin);
1644 st->pktin->maxlen = st->packetlen + st->maclen;
1645 st->pktin->data = sresize(st->pktin->data,
1646 st->pktin->maxlen + APIEXTRA,
1648 } else if (ssh->scmac && ssh->scmac_etm) {
1649 st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1652 * OpenSSH encrypt-then-MAC mode: the packet length is
1653 * unencrypted, unless the cipher supports length encryption.
1655 for (st->i = st->len = 0; st->i < 4; st->i++) {
1656 while ((*datalen) == 0)
1658 st->pktin->data[st->i] = *(*data)++;
1661 /* Cipher supports length decryption, so do it */
1662 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
1663 /* Keep the packet the same though, so the MAC passes */
1664 unsigned char len[4];
1665 memcpy(len, st->pktin->data, 4);
1666 ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
1667 st->len = toint(GET_32BIT(len));
1669 st->len = toint(GET_32BIT(st->pktin->data));
1673 * _Completely_ silly lengths should be stomped on before they
1674 * do us any more damage.
1676 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1677 st->len % st->cipherblk != 0) {
1678 bombout(("Incoming packet length field was garbled"));
1679 ssh_free_packet(st->pktin);
1684 * So now we can work out the total packet length.
1686 st->packetlen = st->len + 4;
1689 * Allocate memory for the rest of the packet.
1691 st->pktin->maxlen = st->packetlen + st->maclen;
1692 st->pktin->data = sresize(st->pktin->data,
1693 st->pktin->maxlen + APIEXTRA,
1697 * Read the remainder of the packet.
1699 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1700 while ((*datalen) == 0)
1702 st->pktin->data[st->i] = *(*data)++;
1710 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1711 st->len + 4, st->incoming_sequence)) {
1712 bombout(("Incorrect MAC received on packet"));
1713 ssh_free_packet(st->pktin);
1717 /* Decrypt everything between the length field and the MAC. */
1719 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1720 st->pktin->data + 4,
1723 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1726 * Acquire and decrypt the first block of the packet. This will
1727 * contain the length and padding details.
1729 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1730 while ((*datalen) == 0)
1732 st->pktin->data[st->i] = *(*data)++;
1737 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1738 st->pktin->data, st->cipherblk);
1741 * Now get the length figure.
1743 st->len = toint(GET_32BIT(st->pktin->data));
1746 * _Completely_ silly lengths should be stomped on before they
1747 * do us any more damage.
1749 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1750 (st->len + 4) % st->cipherblk != 0) {
1751 bombout(("Incoming packet was garbled on decryption"));
1752 ssh_free_packet(st->pktin);
1757 * So now we can work out the total packet length.
1759 st->packetlen = st->len + 4;
1762 * Allocate memory for the rest of the packet.
1764 st->pktin->maxlen = st->packetlen + st->maclen;
1765 st->pktin->data = sresize(st->pktin->data,
1766 st->pktin->maxlen + APIEXTRA,
1770 * Read and decrypt the remainder of the packet.
1772 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1774 while ((*datalen) == 0)
1776 st->pktin->data[st->i] = *(*data)++;
1779 /* Decrypt everything _except_ the MAC. */
1781 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1782 st->pktin->data + st->cipherblk,
1783 st->packetlen - st->cipherblk);
1789 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1790 st->len + 4, st->incoming_sequence)) {
1791 bombout(("Incorrect MAC received on packet"));
1792 ssh_free_packet(st->pktin);
1796 /* Get and sanity-check the amount of random padding. */
1797 st->pad = st->pktin->data[4];
1798 if (st->pad < 4 || st->len - st->pad < 1) {
1799 bombout(("Invalid padding length on received packet"));
1800 ssh_free_packet(st->pktin);
1804 * This enables us to deduce the payload length.
1806 st->payload = st->len - st->pad - 1;
1808 st->pktin->length = st->payload + 5;
1809 st->pktin->encrypted_len = st->packetlen;
1811 st->pktin->sequence = st->incoming_sequence++;
1813 st->pktin->length = st->packetlen - st->pad;
1814 assert(st->pktin->length >= 0);
1817 * Decompress packet payload.
1820 unsigned char *newpayload;
1823 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1824 st->pktin->data + 5, st->pktin->length - 5,
1825 &newpayload, &newlen)) {
1826 if (st->pktin->maxlen < newlen + 5) {
1827 st->pktin->maxlen = newlen + 5;
1828 st->pktin->data = sresize(st->pktin->data,
1829 st->pktin->maxlen + APIEXTRA,
1832 st->pktin->length = 5 + newlen;
1833 memcpy(st->pktin->data + 5, newpayload, newlen);
1839 * RFC 4253 doesn't explicitly say that completely empty packets
1840 * with no type byte are forbidden, so treat them as deserving
1841 * an SSH_MSG_UNIMPLEMENTED.
1843 if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */
1844 ssh2_msg_something_unimplemented(ssh, st->pktin);
1848 * pktin->body and pktin->length should identify the semantic
1849 * content of the packet, excluding the initial type byte.
1851 st->pktin->type = st->pktin->data[5];
1852 st->pktin->body = st->pktin->data + 6;
1853 st->pktin->length -= 6;
1854 assert(st->pktin->length >= 0); /* one last double-check */
1857 ssh2_log_incoming_packet(ssh, st->pktin);
1859 st->pktin->savedpos = 0;
1861 crFinish(st->pktin);
1864 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
1865 const unsigned char **data,
1868 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1870 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1873 * Read the packet length field.
1875 for (st->i = 0; st->i < 4; st->i++) {
1876 while ((*datalen) == 0)
1878 st->length[st->i] = *(*data)++;
1882 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1883 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1884 bombout(("Invalid packet length received"));
1888 st->pktin = ssh_new_packet();
1889 st->pktin->data = snewn(st->packetlen, unsigned char);
1891 st->pktin->encrypted_len = st->packetlen;
1893 st->pktin->sequence = st->incoming_sequence++;
1896 * Read the remainder of the packet.
1898 for (st->i = 0; st->i < st->packetlen; st->i++) {
1899 while ((*datalen) == 0)
1901 st->pktin->data[st->i] = *(*data)++;
1906 * pktin->body and pktin->length should identify the semantic
1907 * content of the packet, excluding the initial type byte.
1909 st->pktin->type = st->pktin->data[0];
1910 st->pktin->body = st->pktin->data + 1;
1911 st->pktin->length = st->packetlen - 1;
1914 * Log incoming packet, possibly omitting sensitive fields.
1917 ssh2_log_incoming_packet(ssh, st->pktin);
1919 st->pktin->savedpos = 0;
1921 crFinish(st->pktin);
1924 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1926 int pad, biglen, i, pktoffs;
1930 * XXX various versions of SC (including 8.8.4) screw up the
1931 * register allocation in this function and use the same register
1932 * (D6) for len and as a temporary, with predictable results. The
1933 * following sledgehammer prevents this.
1940 ssh1_log_outgoing_packet(ssh, pkt);
1942 if (ssh->v1_compressing) {
1943 unsigned char *compblk;
1945 zlib_compress_block(ssh->cs_comp_ctx,
1946 pkt->data + 12, pkt->length - 12,
1947 &compblk, &complen);
1948 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1949 memcpy(pkt->data + 12, compblk, complen);
1951 pkt->length = complen + 12;
1954 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1956 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1957 pad = 8 - (len % 8);
1959 biglen = len + pad; /* len(padding+type+data+CRC) */
1961 for (i = pktoffs; i < 4+8; i++)
1962 pkt->data[i] = random_byte();
1963 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1964 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1965 PUT_32BIT(pkt->data + pktoffs, len);
1968 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1969 pkt->data + pktoffs + 4, biglen);
1971 if (offset_p) *offset_p = pktoffs;
1972 return biglen + 4; /* len(length+padding+type+data+CRC) */
1975 static int s_write(Ssh ssh, void *data, int len)
1978 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1979 0, NULL, NULL, 0, NULL);
1982 return sk_write(ssh->s, (char *)data, len);
1985 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1987 int len, backlog, offset;
1988 len = s_wrpkt_prepare(ssh, pkt, &offset);
1989 backlog = s_write(ssh, pkt->data + offset, len);
1990 if (backlog > SSH_MAX_BACKLOG)
1991 ssh_throttle_all(ssh, 1, backlog);
1992 ssh_free_packet(pkt);
1995 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1998 len = s_wrpkt_prepare(ssh, pkt, &offset);
1999 if (ssh->deferred_len + len > ssh->deferred_size) {
2000 ssh->deferred_size = ssh->deferred_len + len + 128;
2001 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2005 memcpy(ssh->deferred_send_data + ssh->deferred_len,
2006 pkt->data + offset, len);
2007 ssh->deferred_len += len;
2008 ssh_free_packet(pkt);
2012 * Construct a SSH-1 packet with the specified contents.
2013 * (This all-at-once interface used to be the only one, but now SSH-1
2014 * packets can also be constructed incrementally.)
2016 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
2022 pkt = ssh1_pkt_init(pkttype);
2024 while ((argtype = va_arg(ap, int)) != PKT_END) {
2025 unsigned char *argp, argchar;
2027 unsigned long argint;
2030 /* Actual fields in the packet */
2032 argint = va_arg(ap, int);
2033 ssh_pkt_adduint32(pkt, argint);
2036 argchar = (unsigned char) va_arg(ap, int);
2037 ssh_pkt_addbyte(pkt, argchar);
2040 argp = va_arg(ap, unsigned char *);
2041 arglen = va_arg(ap, int);
2042 ssh_pkt_adddata(pkt, argp, arglen);
2045 sargp = va_arg(ap, char *);
2046 ssh_pkt_addstring(pkt, sargp);
2049 bn = va_arg(ap, Bignum);
2050 ssh1_pkt_addmp(pkt, bn);
2058 static void send_packet(Ssh ssh, int pkttype, ...)
2062 va_start(ap, pkttype);
2063 pkt = construct_packet(ssh, pkttype, ap);
2068 static void defer_packet(Ssh ssh, int pkttype, ...)
2072 va_start(ap, pkttype);
2073 pkt = construct_packet(ssh, pkttype, ap);
2075 s_wrpkt_defer(ssh, pkt);
2078 static int ssh_versioncmp(const char *a, const char *b)
2081 unsigned long av, bv;
2083 av = strtoul(a, &ae, 10);
2084 bv = strtoul(b, &be, 10);
2086 return (av < bv ? -1 : +1);
2091 av = strtoul(ae, &ae, 10);
2092 bv = strtoul(be, &be, 10);
2094 return (av < bv ? -1 : +1);
2099 * Utility routines for putting an SSH-protocol `string' and
2100 * `uint32' into a hash state.
2102 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2104 unsigned char lenblk[4];
2105 PUT_32BIT(lenblk, len);
2106 h->bytes(s, lenblk, 4);
2107 h->bytes(s, str, len);
2110 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2112 unsigned char intblk[4];
2113 PUT_32BIT(intblk, i);
2114 h->bytes(s, intblk, 4);
2118 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2120 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2122 if (pkt->maxlen < length) {
2123 unsigned char *body = pkt->body;
2124 int offset = body ? body - pkt->data : 0;
2125 pkt->maxlen = length + 256;
2126 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2127 if (body) pkt->body = pkt->data + offset;
2130 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2133 ssh_pkt_ensure(pkt, pkt->length);
2134 memcpy(pkt->data + pkt->length - len, data, len);
2136 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2138 ssh_pkt_adddata(pkt, &byte, 1);
2140 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2142 ssh_pkt_adddata(pkt, &value, 1);
2144 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2147 PUT_32BIT(x, value);
2148 ssh_pkt_adddata(pkt, x, 4);
2150 static void ssh_pkt_addstring_start(struct Packet *pkt)
2152 ssh_pkt_adduint32(pkt, 0);
2153 pkt->savedpos = pkt->length;
2155 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2158 ssh_pkt_adddata(pkt, data, len);
2159 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2161 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2163 ssh_pkt_addstring_data(pkt, data, strlen(data));
2165 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2167 ssh_pkt_addstring_start(pkt);
2168 ssh_pkt_addstring_str(pkt, data);
2170 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2172 int len = ssh1_bignum_length(b);
2173 unsigned char *data = snewn(len, unsigned char);
2174 (void) ssh1_write_bignum(data, b);
2175 ssh_pkt_adddata(pkt, data, len);
2178 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2181 int i, n = (bignum_bitcount(b) + 7) / 8;
2182 p = snewn(n + 1, unsigned char);
2184 for (i = 1; i <= n; i++)
2185 p[i] = bignum_byte(b, n - i);
2187 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2189 memmove(p, p + i, n + 1 - i);
2193 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2197 p = ssh2_mpint_fmt(b, &len);
2198 ssh_pkt_addstring_start(pkt);
2199 ssh_pkt_addstring_data(pkt, (char *)p, len);
2203 static struct Packet *ssh1_pkt_init(int pkt_type)
2205 struct Packet *pkt = ssh_new_packet();
2206 pkt->length = 4 + 8; /* space for length + max padding */
2207 ssh_pkt_addbyte(pkt, pkt_type);
2208 pkt->body = pkt->data + pkt->length;
2209 pkt->type = pkt_type;
2210 pkt->downstream_id = 0;
2211 pkt->additional_log_text = NULL;
2215 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2216 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2217 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2218 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2219 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2220 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2221 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2222 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2223 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2225 static struct Packet *ssh2_pkt_init(int pkt_type)
2227 struct Packet *pkt = ssh_new_packet();
2228 pkt->length = 5; /* space for packet length + padding length */
2230 pkt->type = pkt_type;
2231 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2232 pkt->body = pkt->data + pkt->length; /* after packet type */
2233 pkt->downstream_id = 0;
2234 pkt->additional_log_text = NULL;
2239 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2240 * put the MAC on it. Final packet, ready to be sent, is stored in
2241 * pkt->data. Total length is returned.
2243 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2245 int cipherblk, maclen, padding, unencrypted_prefix, i;
2248 ssh2_log_outgoing_packet(ssh, pkt);
2250 if (ssh->bare_connection) {
2252 * Trivial packet construction for the bare connection
2255 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2256 pkt->body = pkt->data + 1;
2257 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2258 return pkt->length - 1;
2262 * Compress packet payload.
2265 unsigned char *newpayload;
2268 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2270 &newpayload, &newlen)) {
2272 ssh2_pkt_adddata(pkt, newpayload, newlen);
2278 * Add padding. At least four bytes, and must also bring total
2279 * length (minus MAC) up to a multiple of the block size.
2280 * If pkt->forcepad is set, make sure the packet is at least that size
2283 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2284 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2286 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2287 if (pkt->length + padding < pkt->forcepad)
2288 padding = pkt->forcepad - pkt->length;
2290 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2292 assert(padding <= 255);
2293 maclen = ssh->csmac ? ssh->csmac->len : 0;
2294 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2295 pkt->data[4] = padding;
2296 for (i = 0; i < padding; i++)
2297 pkt->data[pkt->length + i] = random_byte();
2298 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2300 /* Encrypt length if the scheme requires it */
2301 if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
2302 ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
2303 ssh->v2_outgoing_sequence);
2306 if (ssh->csmac && ssh->csmac_etm) {
2308 * OpenSSH-defined encrypt-then-MAC protocol.
2311 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2312 pkt->data + 4, pkt->length + padding - 4);
2313 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2314 pkt->length + padding,
2315 ssh->v2_outgoing_sequence);
2318 * SSH-2 standard protocol.
2321 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2322 pkt->length + padding,
2323 ssh->v2_outgoing_sequence);
2325 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2326 pkt->data, pkt->length + padding);
2329 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2330 pkt->encrypted_len = pkt->length + padding;
2332 /* Ready-to-send packet starts at pkt->data. We return length. */
2333 pkt->body = pkt->data;
2334 return pkt->length + padding + maclen;
2338 * Routines called from the main SSH code to send packets. There
2339 * are quite a few of these, because we have two separate
2340 * mechanisms for delaying the sending of packets:
2342 * - In order to send an IGNORE message and a password message in
2343 * a single fixed-length blob, we require the ability to
2344 * concatenate the encrypted forms of those two packets _into_ a
2345 * single blob and then pass it to our <network.h> transport
2346 * layer in one go. Hence, there's a deferment mechanism which
2347 * works after packet encryption.
2349 * - In order to avoid sending any connection-layer messages
2350 * during repeat key exchange, we have to queue up any such
2351 * outgoing messages _before_ they are encrypted (and in
2352 * particular before they're allocated sequence numbers), and
2353 * then send them once we've finished.
2355 * I call these mechanisms `defer' and `queue' respectively, so as
2356 * to distinguish them reasonably easily.
2358 * The functions send_noqueue() and defer_noqueue() free the packet
2359 * structure they are passed. Every outgoing packet goes through
2360 * precisely one of these functions in its life; packets passed to
2361 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2362 * these or get queued, and then when the queue is later emptied
2363 * the packets are all passed to defer_noqueue().
2365 * When using a CBC-mode cipher, it's necessary to ensure that an
2366 * attacker can't provide data to be encrypted using an IV that they
2367 * know. We ensure this by prefixing each packet that might contain
2368 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2369 * mechanism, so in this case send_noqueue() ends up redirecting to
2370 * defer_noqueue(). If you don't like this inefficiency, don't use
2374 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2375 static void ssh_pkt_defersend(Ssh);
2378 * Send an SSH-2 packet immediately, without queuing or deferring.
2380 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2384 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2385 /* We need to send two packets, so use the deferral mechanism. */
2386 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2387 ssh_pkt_defersend(ssh);
2390 len = ssh2_pkt_construct(ssh, pkt);
2391 backlog = s_write(ssh, pkt->body, len);
2392 if (backlog > SSH_MAX_BACKLOG)
2393 ssh_throttle_all(ssh, 1, backlog);
2395 ssh->outgoing_data_size += pkt->encrypted_len;
2396 if (!ssh->kex_in_progress &&
2397 !ssh->bare_connection &&
2398 ssh->max_data_size != 0 &&
2399 ssh->outgoing_data_size > ssh->max_data_size)
2400 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2402 ssh_free_packet(pkt);
2406 * Defer an SSH-2 packet.
2408 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2411 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2412 ssh->deferred_len == 0 && !noignore &&
2413 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2415 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2416 * get encrypted with a known IV.
2418 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2419 ssh2_pkt_addstring_start(ipkt);
2420 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2422 len = ssh2_pkt_construct(ssh, pkt);
2423 if (ssh->deferred_len + len > ssh->deferred_size) {
2424 ssh->deferred_size = ssh->deferred_len + len + 128;
2425 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2429 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2430 ssh->deferred_len += len;
2431 ssh->deferred_data_size += pkt->encrypted_len;
2432 ssh_free_packet(pkt);
2436 * Queue an SSH-2 packet.
2438 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2440 assert(ssh->queueing);
2442 if (ssh->queuelen >= ssh->queuesize) {
2443 ssh->queuesize = ssh->queuelen + 32;
2444 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2447 ssh->queue[ssh->queuelen++] = pkt;
2451 * Either queue or send a packet, depending on whether queueing is
2454 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2457 ssh2_pkt_queue(ssh, pkt);
2459 ssh2_pkt_send_noqueue(ssh, pkt);
2463 * Either queue or defer a packet, depending on whether queueing is
2466 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2469 ssh2_pkt_queue(ssh, pkt);
2471 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2475 * Send the whole deferred data block constructed by
2476 * ssh2_pkt_defer() or SSH-1's defer_packet().
2478 * The expected use of the defer mechanism is that you call
2479 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2480 * not currently queueing, this simply sets up deferred_send_data
2481 * and then sends it. If we _are_ currently queueing, the calls to
2482 * ssh2_pkt_defer() put the deferred packets on to the queue
2483 * instead, and therefore ssh_pkt_defersend() has no deferred data
2484 * to send. Hence, there's no need to make it conditional on
2487 static void ssh_pkt_defersend(Ssh ssh)
2490 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2491 ssh->deferred_len = ssh->deferred_size = 0;
2492 sfree(ssh->deferred_send_data);
2493 ssh->deferred_send_data = NULL;
2494 if (backlog > SSH_MAX_BACKLOG)
2495 ssh_throttle_all(ssh, 1, backlog);
2497 ssh->outgoing_data_size += ssh->deferred_data_size;
2498 if (!ssh->kex_in_progress &&
2499 !ssh->bare_connection &&
2500 ssh->max_data_size != 0 &&
2501 ssh->outgoing_data_size > ssh->max_data_size)
2502 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2503 ssh->deferred_data_size = 0;
2507 * Send a packet whose length needs to be disguised (typically
2508 * passwords or keyboard-interactive responses).
2510 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2516 * The simplest way to do this is to adjust the
2517 * variable-length padding field in the outgoing packet.
2519 * Currently compiled out, because some Cisco SSH servers
2520 * don't like excessively padded packets (bah, why's it
2523 pkt->forcepad = padsize;
2524 ssh2_pkt_send(ssh, pkt);
2529 * If we can't do that, however, an alternative approach is
2530 * to use the pkt_defer mechanism to bundle the packet
2531 * tightly together with an SSH_MSG_IGNORE such that their
2532 * combined length is a constant. So first we construct the
2533 * final form of this packet and defer its sending.
2535 ssh2_pkt_defer(ssh, pkt);
2538 * Now construct an SSH_MSG_IGNORE which includes a string
2539 * that's an exact multiple of the cipher block size. (If
2540 * the cipher is NULL so that the block size is
2541 * unavailable, we don't do this trick at all, because we
2542 * gain nothing by it.)
2544 if (ssh->cscipher &&
2545 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2548 stringlen = (256 - ssh->deferred_len);
2549 stringlen += ssh->cscipher->blksize - 1;
2550 stringlen -= (stringlen % ssh->cscipher->blksize);
2553 * Temporarily disable actual compression, so we
2554 * can guarantee to get this string exactly the
2555 * length we want it. The compression-disabling
2556 * routine should return an integer indicating how
2557 * many bytes we should adjust our string length
2561 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2563 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2564 ssh2_pkt_addstring_start(pkt);
2565 for (i = 0; i < stringlen; i++) {
2566 char c = (char) random_byte();
2567 ssh2_pkt_addstring_data(pkt, &c, 1);
2569 ssh2_pkt_defer(ssh, pkt);
2571 ssh_pkt_defersend(ssh);
2576 * Send all queued SSH-2 packets. We send them by means of
2577 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2578 * packets that needed to be lumped together.
2580 static void ssh2_pkt_queuesend(Ssh ssh)
2584 assert(!ssh->queueing);
2586 for (i = 0; i < ssh->queuelen; i++)
2587 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2590 ssh_pkt_defersend(ssh);
2594 void bndebug(char *string, Bignum b)
2598 p = ssh2_mpint_fmt(b, &len);
2599 debug(("%s", string));
2600 for (i = 0; i < len; i++)
2601 debug((" %02x", p[i]));
2607 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2611 p = ssh2_mpint_fmt(b, &len);
2612 hash_string(h, s, p, len);
2617 * Packet decode functions for both SSH-1 and SSH-2.
2619 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2621 unsigned long value;
2622 if (pkt->length - pkt->savedpos < 4)
2623 return 0; /* arrgh, no way to decline (FIXME?) */
2624 value = GET_32BIT(pkt->body + pkt->savedpos);
2628 static int ssh2_pkt_getbool(struct Packet *pkt)
2630 unsigned long value;
2631 if (pkt->length - pkt->savedpos < 1)
2632 return 0; /* arrgh, no way to decline (FIXME?) */
2633 value = pkt->body[pkt->savedpos] != 0;
2637 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2642 if (pkt->length - pkt->savedpos < 4)
2644 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2649 if (pkt->length - pkt->savedpos < *length)
2651 *p = (char *)(pkt->body + pkt->savedpos);
2652 pkt->savedpos += *length;
2654 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2656 if (pkt->length - pkt->savedpos < length)
2658 pkt->savedpos += length;
2659 return pkt->body + (pkt->savedpos - length);
2661 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2662 const unsigned char **keystr)
2666 j = makekey(pkt->body + pkt->savedpos,
2667 pkt->length - pkt->savedpos,
2674 assert(pkt->savedpos < pkt->length);
2678 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2683 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2684 pkt->length - pkt->savedpos, &b);
2692 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2698 ssh_pkt_getstring(pkt, &p, &length);
2703 b = bignum_from_bytes((unsigned char *)p, length);
2708 * Helper function to add an SSH-2 signature blob to a packet.
2709 * Expects to be shown the public key blob as well as the signature
2710 * blob. Normally works just like ssh2_pkt_addstring, but will
2711 * fiddle with the signature packet if necessary for
2712 * BUG_SSH2_RSA_PADDING.
2714 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2715 void *pkblob_v, int pkblob_len,
2716 void *sigblob_v, int sigblob_len)
2718 unsigned char *pkblob = (unsigned char *)pkblob_v;
2719 unsigned char *sigblob = (unsigned char *)sigblob_v;
2721 /* dmemdump(pkblob, pkblob_len); */
2722 /* dmemdump(sigblob, sigblob_len); */
2725 * See if this is in fact an ssh-rsa signature and a buggy
2726 * server; otherwise we can just do this the easy way.
2728 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2729 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2730 int pos, len, siglen;
2733 * Find the byte length of the modulus.
2736 pos = 4+7; /* skip over "ssh-rsa" */
2737 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2738 if (len < 0 || len > pkblob_len - pos - 4)
2740 pos += 4 + len; /* skip over exponent */
2741 if (pkblob_len - pos < 4)
2743 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2744 if (len < 0 || len > pkblob_len - pos - 4)
2746 pos += 4; /* find modulus itself */
2747 while (len > 0 && pkblob[pos] == 0)
2749 /* debug(("modulus length is %d\n", len)); */
2752 * Now find the signature integer.
2754 pos = 4+7; /* skip over "ssh-rsa" */
2755 if (sigblob_len < pos+4)
2757 siglen = toint(GET_32BIT(sigblob+pos));
2758 if (siglen != sigblob_len - pos - 4)
2760 /* debug(("signature length is %d\n", siglen)); */
2762 if (len != siglen) {
2763 unsigned char newlen[4];
2764 ssh2_pkt_addstring_start(pkt);
2765 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2766 /* dmemdump(sigblob, pos); */
2767 pos += 4; /* point to start of actual sig */
2768 PUT_32BIT(newlen, len);
2769 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2770 /* dmemdump(newlen, 4); */
2772 while (len-- > siglen) {
2773 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2774 /* dmemdump(newlen, 1); */
2776 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2777 /* dmemdump(sigblob+pos, siglen); */
2781 /* Otherwise fall through and do it the easy way. We also come
2782 * here as a fallback if we discover above that the key blob
2783 * is misformatted in some way. */
2787 ssh2_pkt_addstring_start(pkt);
2788 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2792 * Examine the remote side's version string and compare it against
2793 * a list of known buggy implementations.
2795 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2797 char *imp; /* pointer to implementation part */
2799 imp += strcspn(imp, "-");
2801 imp += strcspn(imp, "-");
2804 ssh->remote_bugs = 0;
2807 * General notes on server version strings:
2808 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2809 * here -- in particular, we've heard of one that's perfectly happy
2810 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2811 * so we can't distinguish them.
2813 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2814 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2815 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2816 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2817 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2818 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2820 * These versions don't support SSH1_MSG_IGNORE, so we have
2821 * to use a different defence against password length
2824 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2825 logevent("We believe remote version has SSH-1 ignore bug");
2828 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2829 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2830 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2832 * These versions need a plain password sent; they can't
2833 * handle having a null and a random length of data after
2836 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2837 logevent("We believe remote version needs a plain SSH-1 password");
2840 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2841 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2842 (!strcmp(imp, "Cisco-1.25")))) {
2844 * These versions apparently have no clue whatever about
2845 * RSA authentication and will panic and die if they see
2846 * an AUTH_RSA message.
2848 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2849 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2852 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2853 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2854 !wc_match("* VShell", imp) &&
2855 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2856 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2857 wc_match("2.1 *", imp)))) {
2859 * These versions have the HMAC bug.
2861 ssh->remote_bugs |= BUG_SSH2_HMAC;
2862 logevent("We believe remote version has SSH-2 HMAC bug");
2865 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2866 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2867 !wc_match("* VShell", imp) &&
2868 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2870 * These versions have the key-derivation bug (failing to
2871 * include the literal shared secret in the hashes that
2872 * generate the keys).
2874 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2875 logevent("We believe remote version has SSH-2 key-derivation bug");
2878 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2879 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2880 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2881 wc_match("OpenSSH_3.[0-2]*", imp) ||
2882 wc_match("mod_sftp/0.[0-8]*", imp) ||
2883 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2885 * These versions have the SSH-2 RSA padding bug.
2887 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2888 logevent("We believe remote version has SSH-2 RSA padding bug");
2891 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2892 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2893 wc_match("OpenSSH_2.[0-2]*", imp))) {
2895 * These versions have the SSH-2 session-ID bug in
2896 * public-key authentication.
2898 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2899 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2902 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2903 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2904 (wc_match("DigiSSH_2.0", imp) ||
2905 wc_match("OpenSSH_2.[0-4]*", imp) ||
2906 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2907 wc_match("Sun_SSH_1.0", imp) ||
2908 wc_match("Sun_SSH_1.0.1", imp) ||
2909 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2910 wc_match("WeOnlyDo-*", imp)))) {
2912 * These versions have the SSH-2 rekey bug.
2914 ssh->remote_bugs |= BUG_SSH2_REKEY;
2915 logevent("We believe remote version has SSH-2 rekey bug");
2918 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2919 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2920 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2921 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2923 * This version ignores our makpkt and needs to be throttled.
2925 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2926 logevent("We believe remote version ignores SSH-2 maximum packet size");
2929 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2931 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2932 * none detected automatically.
2934 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2935 logevent("We believe remote version has SSH-2 ignore bug");
2938 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2939 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2940 (wc_match("OpenSSH_2.[235]*", imp)))) {
2942 * These versions only support the original (pre-RFC4419)
2943 * SSH-2 GEX request, and disconnect with a protocol error if
2944 * we use the newer version.
2946 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2947 logevent("We believe remote version has outdated SSH-2 GEX");
2950 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2952 * Servers that don't support our winadj request for one
2953 * reason or another. Currently, none detected automatically.
2955 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2956 logevent("We believe remote version has winadj bug");
2959 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
2960 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
2961 (wc_match("OpenSSH_[2-5].*", imp) ||
2962 wc_match("OpenSSH_6.[0-6]*", imp) ||
2963 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
2964 wc_match("dropbear_0.5[01]*", imp)))) {
2966 * These versions have the SSH-2 channel request bug.
2967 * OpenSSH 6.7 and above do not:
2968 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
2969 * dropbear_0.52 and above do not:
2970 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
2972 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
2973 logevent("We believe remote version has SSH-2 channel request bug");
2978 * The `software version' part of an SSH version string is required
2979 * to contain no spaces or minus signs.
2981 static void ssh_fix_verstring(char *str)
2983 /* Eat "<protoversion>-". */
2984 while (*str && *str != '-') str++;
2985 assert(*str == '-'); str++;
2987 /* Convert minus signs and spaces in the remaining string into
2990 if (*str == '-' || *str == ' ')
2997 * Send an appropriate SSH version string.
2999 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
3003 if (ssh->version == 2) {
3005 * Construct a v2 version string.
3007 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
3010 * Construct a v1 version string.
3012 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
3013 verstring = dupprintf("SSH-%s-%s\012",
3014 (ssh_versioncmp(svers, "1.5") <= 0 ?
3019 ssh_fix_verstring(verstring + strlen(protoname));
3021 /* FUZZING make PuTTY insecure, so make live use difficult. */
3025 if (ssh->version == 2) {
3028 * Record our version string.
3030 len = strcspn(verstring, "\015\012");
3031 ssh->v_c = snewn(len + 1, char);
3032 memcpy(ssh->v_c, verstring, len);
3036 logeventf(ssh, "We claim version: %.*s",
3037 strcspn(verstring, "\015\012"), verstring);
3038 s_write(ssh, verstring, strlen(verstring));
3042 static int do_ssh_init(Ssh ssh, unsigned char c)
3044 static const char protoname[] = "SSH-";
3046 struct do_ssh_init_state {
3055 crState(do_ssh_init_state);
3059 /* Search for a line beginning with the protocol name prefix in
3062 for (s->i = 0; protoname[s->i]; s->i++) {
3063 if ((char)c != protoname[s->i]) goto no;
3073 s->vstrsize = sizeof(protoname) + 16;
3074 s->vstring = snewn(s->vstrsize, char);
3075 strcpy(s->vstring, protoname);
3076 s->vslen = strlen(protoname);
3079 if (s->vslen >= s->vstrsize - 1) {
3081 s->vstring = sresize(s->vstring, s->vstrsize, char);
3083 s->vstring[s->vslen++] = c;
3086 s->version[s->i] = '\0';
3088 } else if (s->i < sizeof(s->version) - 1)
3089 s->version[s->i++] = c;
3090 } else if (c == '\012')
3092 crReturn(1); /* get another char */
3095 ssh->agentfwd_enabled = FALSE;
3096 ssh->rdpkt2_state.incoming_sequence = 0;
3098 s->vstring[s->vslen] = 0;
3099 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3100 logeventf(ssh, "Server version: %s", s->vstring);
3101 ssh_detect_bugs(ssh, s->vstring);
3104 * Decide which SSH protocol version to support.
3107 /* Anything strictly below "2.0" means protocol 1 is supported. */
3108 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3109 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3110 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3112 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
3113 bombout(("SSH protocol version 1 required by configuration but "
3114 "not provided by server"));
3117 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
3118 bombout(("SSH protocol version 2 required by configuration but "
3119 "not provided by server"));
3123 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3128 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3130 /* Send the version string, if we haven't already */
3131 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3132 ssh_send_verstring(ssh, protoname, s->version);
3134 if (ssh->version == 2) {
3137 * Record their version string.
3139 len = strcspn(s->vstring, "\015\012");
3140 ssh->v_s = snewn(len + 1, char);
3141 memcpy(ssh->v_s, s->vstring, len);
3145 * Initialise SSH-2 protocol.
3147 ssh->protocol = ssh2_protocol;
3148 ssh2_protocol_setup(ssh);
3149 ssh->s_rdpkt = ssh2_rdpkt;
3152 * Initialise SSH-1 protocol.
3154 ssh->protocol = ssh1_protocol;
3155 ssh1_protocol_setup(ssh);
3156 ssh->s_rdpkt = ssh1_rdpkt;
3158 if (ssh->version == 2)
3159 do_ssh2_transport(ssh, NULL, -1, NULL);
3161 update_specials_menu(ssh->frontend);
3162 ssh->state = SSH_STATE_BEFORE_SIZE;
3163 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3170 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3173 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3174 * the ssh-connection part, extracted and given a trivial binary
3175 * packet protocol, so we replace 'SSH-' at the start with a new
3176 * name. In proper SSH style (though of course this part of the
3177 * proper SSH protocol _isn't_ subject to this kind of
3178 * DNS-domain-based extension), we define the new name in our
3181 static const char protoname[] =
3182 "SSHCONNECTION@putty.projects.tartarus.org-";
3184 struct do_ssh_connection_init_state {
3192 crState(do_ssh_connection_init_state);
3196 /* Search for a line beginning with the protocol name prefix in
3199 for (s->i = 0; protoname[s->i]; s->i++) {
3200 if ((char)c != protoname[s->i]) goto no;
3210 s->vstrsize = sizeof(protoname) + 16;
3211 s->vstring = snewn(s->vstrsize, char);
3212 strcpy(s->vstring, protoname);
3213 s->vslen = strlen(protoname);
3216 if (s->vslen >= s->vstrsize - 1) {
3218 s->vstring = sresize(s->vstring, s->vstrsize, char);
3220 s->vstring[s->vslen++] = c;
3223 s->version[s->i] = '\0';
3225 } else if (s->i < sizeof(s->version) - 1)
3226 s->version[s->i++] = c;
3227 } else if (c == '\012')
3229 crReturn(1); /* get another char */
3232 ssh->agentfwd_enabled = FALSE;
3233 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3235 s->vstring[s->vslen] = 0;
3236 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3237 logeventf(ssh, "Server version: %s", s->vstring);
3238 ssh_detect_bugs(ssh, s->vstring);
3241 * Decide which SSH protocol version to support. This is easy in
3242 * bare ssh-connection mode: only 2.0 is legal.
3244 if (ssh_versioncmp(s->version, "2.0") < 0) {
3245 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3248 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3249 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3255 logeventf(ssh, "Using bare ssh-connection protocol");
3257 /* Send the version string, if we haven't already */
3258 ssh_send_verstring(ssh, protoname, s->version);
3261 * Initialise bare connection protocol.
3263 ssh->protocol = ssh2_bare_connection_protocol;
3264 ssh2_bare_connection_protocol_setup(ssh);
3265 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3267 update_specials_menu(ssh->frontend);
3268 ssh->state = SSH_STATE_BEFORE_SIZE;
3269 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3272 * Get authconn (really just conn) under way.
3274 do_ssh2_authconn(ssh, NULL, 0, NULL);
3281 static void ssh_process_incoming_data(Ssh ssh,
3282 const unsigned char **data, int *datalen)
3284 struct Packet *pktin;
3286 pktin = ssh->s_rdpkt(ssh, data, datalen);
3288 ssh->protocol(ssh, NULL, 0, pktin);
3289 ssh_free_packet(pktin);
3293 static void ssh_queue_incoming_data(Ssh ssh,
3294 const unsigned char **data, int *datalen)
3296 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3301 static void ssh_process_queued_incoming_data(Ssh ssh)
3304 const unsigned char *data;
3307 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3308 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3312 while (!ssh->frozen && len > 0)
3313 ssh_process_incoming_data(ssh, &data, &len);
3316 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3320 static void ssh_set_frozen(Ssh ssh, int frozen)
3323 sk_set_frozen(ssh->s, frozen);
3324 ssh->frozen = frozen;
3327 static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
3329 /* Log raw data, if we're in that mode. */
3331 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3332 0, NULL, NULL, 0, NULL);
3334 crBegin(ssh->ssh_gotdata_crstate);
3337 * To begin with, feed the characters one by one to the
3338 * protocol initialisation / selection function do_ssh_init().
3339 * When that returns 0, we're done with the initial greeting
3340 * exchange and can move on to packet discipline.
3343 int ret; /* need not be kept across crReturn */
3345 crReturnV; /* more data please */
3346 ret = ssh->do_ssh_init(ssh, *data);
3354 * We emerge from that loop when the initial negotiation is
3355 * over and we have selected an s_rdpkt function. Now pass
3356 * everything to s_rdpkt, and then pass the resulting packets
3357 * to the proper protocol handler.
3361 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3363 ssh_queue_incoming_data(ssh, &data, &datalen);
3364 /* This uses up all data and cannot cause anything interesting
3365 * to happen; indeed, for anything to happen at all, we must
3366 * return, so break out. */
3368 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3369 /* This uses up some or all data, and may freeze the
3371 ssh_process_queued_incoming_data(ssh);
3373 /* This uses up some or all data, and may freeze the
3375 ssh_process_incoming_data(ssh, &data, &datalen);
3377 /* FIXME this is probably EBW. */
3378 if (ssh->state == SSH_STATE_CLOSED)
3381 /* We're out of data. Go and get some more. */
3387 static int ssh_do_close(Ssh ssh, int notify_exit)
3390 struct ssh_channel *c;
3392 ssh->state = SSH_STATE_CLOSED;
3393 expire_timer_context(ssh);
3398 notify_remote_exit(ssh->frontend);
3403 * Now we must shut down any port- and X-forwarded channels going
3404 * through this connection.
3406 if (ssh->channels) {
3407 while (NULL != (c = index234(ssh->channels, 0))) {
3410 x11_close(c->u.x11.xconn);
3413 case CHAN_SOCKDATA_DORMANT:
3414 pfd_close(c->u.pfd.pf);
3417 del234(ssh->channels, c); /* moving next one to index 0 */
3418 if (ssh->version == 2)
3419 bufchain_clear(&c->v.v2.outbuffer);
3424 * Go through port-forwardings, and close any associated
3425 * listening sockets.
3427 if (ssh->portfwds) {
3428 struct ssh_portfwd *pf;
3429 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3430 /* Dispose of any listening socket. */
3432 pfl_terminate(pf->local);
3433 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3436 freetree234(ssh->portfwds);
3437 ssh->portfwds = NULL;
3441 * Also stop attempting to connection-share.
3443 if (ssh->connshare) {
3444 sharestate_free(ssh->connshare);
3445 ssh->connshare = NULL;
3451 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3452 const char *error_msg, int error_code)
3454 Ssh ssh = (Ssh) plug;
3455 char addrbuf[256], *msg;
3457 if (ssh->attempting_connshare) {
3459 * While we're attempting connection sharing, don't loudly log
3460 * everything that happens. Real TCP connections need to be
3461 * logged when we _start_ trying to connect, because it might
3462 * be ages before they respond if something goes wrong; but
3463 * connection sharing is local and quick to respond, and it's
3464 * sufficient to simply wait and see whether it worked
3468 sk_getaddr(addr, addrbuf, lenof(addrbuf));
3471 if (sk_addr_needs_port(addr)) {
3472 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
3474 msg = dupprintf("Connecting to %s", addrbuf);
3477 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
3485 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3486 const char *ds_err, const char *us_err)
3488 if (event == SHARE_NONE) {
3489 /* In this case, 'logtext' is an error message indicating a
3490 * reason why connection sharing couldn't be set up _at all_.
3491 * Failing that, ds_err and us_err indicate why we couldn't be
3492 * a downstream and an upstream respectively. */
3494 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3497 logeventf(ssh, "Could not set up connection sharing"
3498 " as downstream: %s", ds_err);
3500 logeventf(ssh, "Could not set up connection sharing"
3501 " as upstream: %s", us_err);
3503 } else if (event == SHARE_DOWNSTREAM) {
3504 /* In this case, 'logtext' is a local endpoint address */
3505 logeventf(ssh, "Using existing shared connection at %s", logtext);
3506 /* Also we should mention this in the console window to avoid
3507 * confusing users as to why this window doesn't behave the
3509 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3510 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3512 } else if (event == SHARE_UPSTREAM) {
3513 /* In this case, 'logtext' is a local endpoint address too */
3514 logeventf(ssh, "Sharing this connection at %s", logtext);
3518 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3521 Ssh ssh = (Ssh) plug;
3522 int need_notify = ssh_do_close(ssh, FALSE);
3525 if (!ssh->close_expected)
3526 error_msg = "Server unexpectedly closed network connection";
3528 error_msg = "Server closed network connection";
3531 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3535 notify_remote_exit(ssh->frontend);
3538 logevent(error_msg);
3539 if (!ssh->close_expected || !ssh->clean_exit)
3540 connection_fatal(ssh->frontend, "%s", error_msg);
3544 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3546 Ssh ssh = (Ssh) plug;
3547 ssh_gotdata(ssh, (unsigned char *)data, len);
3548 if (ssh->state == SSH_STATE_CLOSED) {
3549 ssh_do_close(ssh, TRUE);
3555 static void ssh_sent(Plug plug, int bufsize)
3557 Ssh ssh = (Ssh) plug;
3559 * If the send backlog on the SSH socket itself clears, we
3560 * should unthrottle the whole world if it was throttled.
3562 if (bufsize < SSH_MAX_BACKLOG)
3563 ssh_throttle_all(ssh, 0, bufsize);
3566 static void ssh_hostport_setup(const char *host, int port, Conf *conf,
3567 char **savedhost, int *savedport,
3570 char *loghost = conf_get_str(conf, CONF_loghost);
3572 *loghost_ret = loghost;
3578 tmphost = dupstr(loghost);
3579 *savedport = 22; /* default ssh port */
3582 * A colon suffix on the hostname string also lets us affect
3583 * savedport. (Unless there are multiple colons, in which case
3584 * we assume this is an unbracketed IPv6 literal.)
3586 colon = host_strrchr(tmphost, ':');
3587 if (colon && colon == host_strchr(tmphost, ':')) {
3590 *savedport = atoi(colon);
3593 *savedhost = host_strduptrim(tmphost);
3596 *savedhost = host_strduptrim(host);
3598 port = 22; /* default ssh port */
3603 static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
3609 random_ref(); /* platform may need this to determine share socket name */
3610 ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
3611 ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
3619 * Connect to specified host and port.
3620 * Returns an error message, or NULL on success.
3621 * Also places the canonical host name into `realhost'. It must be
3622 * freed by the caller.
3624 static const char *connect_to_host(Ssh ssh, const char *host, int port,
3625 char **realhost, int nodelay, int keepalive)
3627 static const struct plug_function_table fn_table = {
3638 int addressfamily, sshprot;
3640 ssh_hostport_setup(host, port, ssh->conf,
3641 &ssh->savedhost, &ssh->savedport, &loghost);
3643 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3646 * Try connection-sharing, in case that means we don't open a
3647 * socket after all. ssh_connection_sharing_init will connect to a
3648 * previously established upstream if it can, and failing that,
3649 * establish a listening socket for _us_ to be the upstream. In
3650 * the latter case it will return NULL just as if it had done
3651 * nothing, because here we only need to care if we're a
3652 * downstream and need to do our connection setup differently.
3654 ssh->connshare = NULL;
3655 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3656 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3657 ssh->conf, ssh, &ssh->connshare);
3658 ssh->attempting_connshare = FALSE;
3659 if (ssh->s != NULL) {
3661 * We are a downstream.
3663 ssh->bare_connection = TRUE;
3664 ssh->do_ssh_init = do_ssh_connection_init;
3665 ssh->fullhostname = NULL;
3666 *realhost = dupstr(host); /* best we can do */
3669 * We're not a downstream, so open a normal socket.
3671 ssh->do_ssh_init = do_ssh_init;
3676 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3677 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
3678 ssh->frontend, "SSH connection");
3679 if ((err = sk_addr_error(addr)) != NULL) {
3683 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3685 ssh->s = new_connection(addr, *realhost, port,
3686 0, 1, nodelay, keepalive,
3687 (Plug) ssh, ssh->conf);
3688 if ((err = sk_socket_error(ssh->s)) != NULL) {
3690 notify_remote_exit(ssh->frontend);
3696 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3697 * send the version string too.
3699 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3702 if (sshprot == 3 && !ssh->bare_connection) {
3704 ssh_send_verstring(ssh, "SSH-", NULL);
3708 * loghost, if configured, overrides realhost.
3712 *realhost = dupstr(loghost);
3719 * Throttle or unthrottle the SSH connection.
3721 static void ssh_throttle_conn(Ssh ssh, int adjust)
3723 int old_count = ssh->conn_throttle_count;
3724 ssh->conn_throttle_count += adjust;
3725 assert(ssh->conn_throttle_count >= 0);
3726 if (ssh->conn_throttle_count && !old_count) {
3727 ssh_set_frozen(ssh, 1);
3728 } else if (!ssh->conn_throttle_count && old_count) {
3729 ssh_set_frozen(ssh, 0);
3734 * Throttle or unthrottle _all_ local data streams (for when sends
3735 * on the SSH connection itself back up).
3737 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3740 struct ssh_channel *c;
3742 if (enable == ssh->throttled_all)
3744 ssh->throttled_all = enable;
3745 ssh->overall_bufsize = bufsize;
3748 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3750 case CHAN_MAINSESSION:
3752 * This is treated separately, outside the switch.
3756 x11_override_throttle(c->u.x11.xconn, enable);
3759 /* Agent channels require no buffer management. */
3762 pfd_override_throttle(c->u.pfd.pf, enable);
3768 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3770 Ssh ssh = (Ssh) sshv;
3772 ssh->agent_response = reply;
3773 ssh->agent_response_len = replylen;
3775 if (ssh->version == 1)
3776 do_ssh1_login(ssh, NULL, -1, NULL);
3778 do_ssh2_authconn(ssh, NULL, -1, NULL);
3781 static void ssh_dialog_callback(void *sshv, int ret)
3783 Ssh ssh = (Ssh) sshv;
3785 ssh->user_response = ret;
3787 if (ssh->version == 1)
3788 do_ssh1_login(ssh, NULL, -1, NULL);
3790 do_ssh2_transport(ssh, NULL, -1, NULL);
3793 * This may have unfrozen the SSH connection, so do a
3796 ssh_process_queued_incoming_data(ssh);
3799 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3801 struct ssh_channel *c = (struct ssh_channel *)cv;
3803 const void *sentreply = reply;
3805 c->u.a.outstanding_requests--;
3807 /* Fake SSH_AGENT_FAILURE. */
3808 sentreply = "\0\0\0\1\5";
3811 if (ssh->version == 2) {
3812 ssh2_add_channel_data(c, sentreply, replylen);
3815 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3816 PKT_INT, c->remoteid,
3818 PKT_DATA, sentreply, replylen,
3824 * If we've already seen an incoming EOF but haven't sent an
3825 * outgoing one, this may be the moment to send it.
3827 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3828 sshfwd_write_eof(c);
3832 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3833 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3834 * => log `wire_reason'.
3836 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3837 const char *wire_reason,
3838 int code, int clean_exit)
3842 client_reason = wire_reason;
3844 error = dupprintf("Disconnected: %s", client_reason);
3846 error = dupstr("Disconnected");
3848 if (ssh->version == 1) {
3849 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3851 } else if (ssh->version == 2) {
3852 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3853 ssh2_pkt_adduint32(pktout, code);
3854 ssh2_pkt_addstring(pktout, wire_reason);
3855 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3856 ssh2_pkt_send_noqueue(ssh, pktout);
3859 ssh->close_expected = TRUE;
3860 ssh->clean_exit = clean_exit;
3861 ssh_closing((Plug)ssh, error, 0, 0);
3865 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3866 const struct ssh_signkey *ssh2keytype,
3869 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3870 return -1; /* no manual keys configured */
3875 * The fingerprint string we've been given will have things
3876 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3877 * narrow down to just the colon-separated hex block at the
3878 * end of the string.
3880 const char *p = strrchr(fingerprint, ' ');
3881 fingerprint = p ? p+1 : fingerprint;
3882 /* Quick sanity checks, including making sure it's in lowercase */
3883 assert(strlen(fingerprint) == 16*3 - 1);
3884 assert(fingerprint[2] == ':');
3885 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3887 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3889 return 1; /* success */
3894 * Construct the base64-encoded public key blob and see if
3897 unsigned char *binblob;
3899 int binlen, atoms, i;
3900 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3901 atoms = (binlen + 2) / 3;
3902 base64blob = snewn(atoms * 4 + 1, char);
3903 for (i = 0; i < atoms; i++)
3904 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3905 base64blob[atoms * 4] = '\0';
3907 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3910 return 1; /* success */
3919 * Handle the key exchange and user authentication phases.
3921 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
3922 struct Packet *pktin)
3925 unsigned char cookie[8], *ptr;
3926 struct MD5Context md5c;
3927 struct do_ssh1_login_state {
3930 unsigned char *rsabuf;
3931 const unsigned char *keystr1, *keystr2;
3932 unsigned long supported_ciphers_mask, supported_auths_mask;
3933 int tried_publickey, tried_agent;
3934 int tis_auth_refused, ccard_auth_refused;
3935 unsigned char session_id[16];
3937 void *publickey_blob;
3938 int publickey_bloblen;
3939 char *publickey_comment;
3940 int privatekey_available, privatekey_encrypted;
3941 prompts_t *cur_prompt;
3944 unsigned char request[5], *response, *p;
3954 struct RSAKey servkey, hostkey;
3956 crState(do_ssh1_login_state);
3963 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3964 bombout(("Public key packet not received"));
3968 logevent("Received public keys");
3970 ptr = ssh_pkt_getdata(pktin, 8);
3972 bombout(("SSH-1 public key packet stopped before random cookie"));
3975 memcpy(cookie, ptr, 8);
3977 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3978 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3979 bombout(("Failed to read SSH-1 public keys from public key packet"));
3984 * Log the host key fingerprint.
3988 logevent("Host key fingerprint is:");
3989 strcpy(logmsg, " ");
3990 s->hostkey.comment = NULL;
3991 rsa_fingerprint(logmsg + strlen(logmsg),
3992 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3996 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3997 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3998 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3999 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
4000 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
4002 ssh->v1_local_protoflags =
4003 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
4004 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
4007 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
4008 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
4009 MD5Update(&md5c, cookie, 8);
4010 MD5Final(s->session_id, &md5c);
4012 for (i = 0; i < 32; i++)
4013 ssh->session_key[i] = random_byte();
4016 * Verify that the `bits' and `bytes' parameters match.
4018 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
4019 s->servkey.bits > s->servkey.bytes * 8) {
4020 bombout(("SSH-1 public keys were badly formatted"));
4024 s->len = (s->hostkey.bytes > s->servkey.bytes ?
4025 s->hostkey.bytes : s->servkey.bytes);
4027 s->rsabuf = snewn(s->len, unsigned char);
4030 * Verify the host key.
4034 * First format the key into a string.
4036 int len = rsastr_len(&s->hostkey);
4037 char fingerprint[100];
4038 char *keystr = snewn(len, char);
4039 rsastr_fmt(keystr, &s->hostkey);
4040 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4042 /* First check against manually configured host keys. */
4043 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4044 if (s->dlgret == 0) { /* did not match */
4045 bombout(("Host key did not appear in manually configured list"));
4048 } else if (s->dlgret < 0) { /* none configured; use standard handling */
4049 ssh_set_frozen(ssh, 1);
4050 s->dlgret = verify_ssh_host_key(ssh->frontend,
4051 ssh->savedhost, ssh->savedport,
4052 "rsa", keystr, fingerprint,
4053 ssh_dialog_callback, ssh);
4058 if (s->dlgret < 0) {
4062 bombout(("Unexpected data from server while waiting"
4063 " for user host key response"));
4066 } while (pktin || inlen > 0);
4067 s->dlgret = ssh->user_response;
4069 ssh_set_frozen(ssh, 0);
4071 if (s->dlgret == 0) {
4072 ssh_disconnect(ssh, "User aborted at host key verification",
4081 for (i = 0; i < 32; i++) {
4082 s->rsabuf[i] = ssh->session_key[i];
4084 s->rsabuf[i] ^= s->session_id[i];
4087 if (s->hostkey.bytes > s->servkey.bytes) {
4088 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4090 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4092 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4094 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4097 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4101 logevent("Encrypted session key");
4104 int cipher_chosen = 0, warn = 0;
4105 const char *cipher_string = NULL;
4107 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4108 int next_cipher = conf_get_int_int(ssh->conf,
4109 CONF_ssh_cipherlist, i);
4110 if (next_cipher == CIPHER_WARN) {
4111 /* If/when we choose a cipher, warn about it */
4113 } else if (next_cipher == CIPHER_AES) {
4114 /* XXX Probably don't need to mention this. */
4115 logevent("AES not supported in SSH-1, skipping");
4117 switch (next_cipher) {
4118 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4119 cipher_string = "3DES"; break;
4120 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4121 cipher_string = "Blowfish"; break;
4122 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4123 cipher_string = "single-DES"; break;
4125 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4129 if (!cipher_chosen) {
4130 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4131 bombout(("Server violates SSH-1 protocol by not "
4132 "supporting 3DES encryption"));
4134 /* shouldn't happen */
4135 bombout(("No supported ciphers found"));
4139 /* Warn about chosen cipher if necessary. */
4141 ssh_set_frozen(ssh, 1);
4142 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4143 ssh_dialog_callback, ssh);
4144 if (s->dlgret < 0) {
4148 bombout(("Unexpected data from server while waiting"
4149 " for user response"));
4152 } while (pktin || inlen > 0);
4153 s->dlgret = ssh->user_response;
4155 ssh_set_frozen(ssh, 0);
4156 if (s->dlgret == 0) {
4157 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4164 switch (s->cipher_type) {
4165 case SSH_CIPHER_3DES:
4166 logevent("Using 3DES encryption");
4168 case SSH_CIPHER_DES:
4169 logevent("Using single-DES encryption");
4171 case SSH_CIPHER_BLOWFISH:
4172 logevent("Using Blowfish encryption");
4176 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4177 PKT_CHAR, s->cipher_type,
4178 PKT_DATA, cookie, 8,
4179 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4180 PKT_DATA, s->rsabuf, s->len,
4181 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4183 logevent("Trying to enable encryption...");
4187 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4188 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4190 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4191 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4192 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4194 ssh->crcda_ctx = crcda_make_context();
4195 logevent("Installing CRC compensation attack detector");
4197 if (s->servkey.modulus) {
4198 sfree(s->servkey.modulus);
4199 s->servkey.modulus = NULL;
4201 if (s->servkey.exponent) {
4202 sfree(s->servkey.exponent);
4203 s->servkey.exponent = NULL;
4205 if (s->hostkey.modulus) {
4206 sfree(s->hostkey.modulus);
4207 s->hostkey.modulus = NULL;
4209 if (s->hostkey.exponent) {
4210 sfree(s->hostkey.exponent);
4211 s->hostkey.exponent = NULL;
4215 if (pktin->type != SSH1_SMSG_SUCCESS) {
4216 bombout(("Encryption not successfully enabled"));
4220 logevent("Successfully started encryption");
4222 fflush(stdout); /* FIXME eh? */
4224 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4225 int ret; /* need not be kept over crReturn */
4226 s->cur_prompt = new_prompts(ssh->frontend);
4227 s->cur_prompt->to_server = TRUE;
4228 s->cur_prompt->name = dupstr("SSH login name");
4229 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4230 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4233 crWaitUntil(!pktin);
4234 ret = get_userpass_input(s->cur_prompt, in, inlen);
4239 * Failed to get a username. Terminate.
4241 free_prompts(s->cur_prompt);
4242 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4245 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4246 free_prompts(s->cur_prompt);
4249 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4251 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4253 if (flags & FLAG_INTERACTIVE &&
4254 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4255 c_write_str(ssh, userlog);
4256 c_write_str(ssh, "\r\n");
4264 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4265 /* We must not attempt PK auth. Pretend we've already tried it. */
4266 s->tried_publickey = s->tried_agent = 1;
4268 s->tried_publickey = s->tried_agent = 0;
4270 s->tis_auth_refused = s->ccard_auth_refused = 0;
4272 * Load the public half of any configured keyfile for later use.
4274 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4275 if (!filename_is_null(s->keyfile)) {
4277 logeventf(ssh, "Reading key file \"%.150s\"",
4278 filename_to_str(s->keyfile));
4279 keytype = key_type(s->keyfile);
4280 if (keytype == SSH_KEYTYPE_SSH1 ||
4281 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4283 if (rsakey_pubblob(s->keyfile,
4284 &s->publickey_blob, &s->publickey_bloblen,
4285 &s->publickey_comment, &error)) {
4286 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4287 if (!s->privatekey_available)
4288 logeventf(ssh, "Key file contains public key only");
4289 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4293 logeventf(ssh, "Unable to load key (%s)", error);
4294 msgbuf = dupprintf("Unable to load key file "
4295 "\"%.150s\" (%s)\r\n",
4296 filename_to_str(s->keyfile),
4298 c_write_str(ssh, msgbuf);
4300 s->publickey_blob = NULL;
4304 logeventf(ssh, "Unable to use this key file (%s)",
4305 key_type_to_str(keytype));
4306 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4308 filename_to_str(s->keyfile),
4309 key_type_to_str(keytype));
4310 c_write_str(ssh, msgbuf);
4312 s->publickey_blob = NULL;
4315 s->publickey_blob = NULL;
4317 while (pktin->type == SSH1_SMSG_FAILURE) {
4318 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4320 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4322 * Attempt RSA authentication using Pageant.
4328 logevent("Pageant is running. Requesting keys.");
4330 /* Request the keys held by the agent. */
4331 PUT_32BIT(s->request, 1);
4332 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4333 if (!agent_query(s->request, 5, &r, &s->responselen,
4334 ssh_agent_callback, ssh)) {
4338 bombout(("Unexpected data from server while waiting"
4339 " for agent response"));
4342 } while (pktin || inlen > 0);
4343 r = ssh->agent_response;
4344 s->responselen = ssh->agent_response_len;
4346 s->response = (unsigned char *) r;
4347 if (s->response && s->responselen >= 5 &&
4348 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4349 s->p = s->response + 5;
4350 s->nkeys = toint(GET_32BIT(s->p));
4352 logeventf(ssh, "Pageant reported negative key count %d",
4357 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4358 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4359 unsigned char *pkblob = s->p;
4363 do { /* do while (0) to make breaking easy */
4364 n = ssh1_read_bignum
4365 (s->p, toint(s->responselen-(s->p-s->response)),
4370 n = ssh1_read_bignum
4371 (s->p, toint(s->responselen-(s->p-s->response)),
4376 if (s->responselen - (s->p-s->response) < 4)
4378 s->commentlen = toint(GET_32BIT(s->p));
4380 if (s->commentlen < 0 ||
4381 toint(s->responselen - (s->p-s->response)) <
4384 s->commentp = (char *)s->p;
4385 s->p += s->commentlen;
4389 logevent("Pageant key list packet was truncated");
4393 if (s->publickey_blob) {
4394 if (!memcmp(pkblob, s->publickey_blob,
4395 s->publickey_bloblen)) {
4396 logeventf(ssh, "Pageant key #%d matches "
4397 "configured key file", s->keyi);
4398 s->tried_publickey = 1;
4400 /* Skip non-configured key */
4403 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4404 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4405 PKT_BIGNUM, s->key.modulus, PKT_END);
4407 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4408 logevent("Key refused");
4411 logevent("Received RSA challenge");
4412 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4413 bombout(("Server's RSA challenge was badly formatted"));
4418 char *agentreq, *q, *ret;
4421 len = 1 + 4; /* message type, bit count */
4422 len += ssh1_bignum_length(s->key.exponent);
4423 len += ssh1_bignum_length(s->key.modulus);
4424 len += ssh1_bignum_length(s->challenge);
4425 len += 16; /* session id */
4426 len += 4; /* response format */
4427 agentreq = snewn(4 + len, char);
4428 PUT_32BIT(agentreq, len);
4430 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4431 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4433 q += ssh1_write_bignum(q, s->key.exponent);
4434 q += ssh1_write_bignum(q, s->key.modulus);
4435 q += ssh1_write_bignum(q, s->challenge);
4436 memcpy(q, s->session_id, 16);
4438 PUT_32BIT(q, 1); /* response format */
4439 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4440 ssh_agent_callback, ssh)) {
4445 bombout(("Unexpected data from server"
4446 " while waiting for agent"
4450 } while (pktin || inlen > 0);
4451 vret = ssh->agent_response;
4452 retlen = ssh->agent_response_len;
4457 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4458 logevent("Sending Pageant's response");
4459 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4460 PKT_DATA, ret + 5, 16,
4464 if (pktin->type == SSH1_SMSG_SUCCESS) {
4466 ("Pageant's response accepted");
4467 if (flags & FLAG_VERBOSE) {
4468 c_write_str(ssh, "Authenticated using"
4470 c_write(ssh, s->commentp,
4472 c_write_str(ssh, "\" from agent\r\n");
4477 ("Pageant's response not accepted");
4480 ("Pageant failed to answer challenge");
4484 logevent("No reply received from Pageant");
4487 freebn(s->key.exponent);
4488 freebn(s->key.modulus);
4489 freebn(s->challenge);
4494 if (s->publickey_blob && !s->tried_publickey)
4495 logevent("Configured key file not in Pageant");
4497 logevent("Failed to get reply from Pageant");
4502 if (s->publickey_blob && s->privatekey_available &&
4503 !s->tried_publickey) {
4505 * Try public key authentication with the specified
4508 int got_passphrase; /* need not be kept over crReturn */
4509 if (flags & FLAG_VERBOSE)
4510 c_write_str(ssh, "Trying public key authentication.\r\n");
4511 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4512 logeventf(ssh, "Trying public key \"%s\"",
4513 filename_to_str(s->keyfile));
4514 s->tried_publickey = 1;
4515 got_passphrase = FALSE;
4516 while (!got_passphrase) {
4518 * Get a passphrase, if necessary.
4520 char *passphrase = NULL; /* only written after crReturn */
4522 if (!s->privatekey_encrypted) {
4523 if (flags & FLAG_VERBOSE)
4524 c_write_str(ssh, "No passphrase required.\r\n");
4527 int ret; /* need not be kept over crReturn */
4528 s->cur_prompt = new_prompts(ssh->frontend);
4529 s->cur_prompt->to_server = FALSE;
4530 s->cur_prompt->name = dupstr("SSH key passphrase");
4531 add_prompt(s->cur_prompt,
4532 dupprintf("Passphrase for key \"%.100s\": ",
4533 s->publickey_comment), FALSE);
4534 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4537 crWaitUntil(!pktin);
4538 ret = get_userpass_input(s->cur_prompt, in, inlen);
4542 /* Failed to get a passphrase. Terminate. */
4543 free_prompts(s->cur_prompt);
4544 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4548 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4549 free_prompts(s->cur_prompt);
4552 * Try decrypting key with passphrase.
4554 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4555 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4558 smemclr(passphrase, strlen(passphrase));
4562 /* Correct passphrase. */
4563 got_passphrase = TRUE;
4564 } else if (ret == 0) {
4565 c_write_str(ssh, "Couldn't load private key from ");
4566 c_write_str(ssh, filename_to_str(s->keyfile));
4567 c_write_str(ssh, " (");
4568 c_write_str(ssh, error);
4569 c_write_str(ssh, ").\r\n");
4570 got_passphrase = FALSE;
4571 break; /* go and try something else */
4572 } else if (ret == -1) {
4573 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4574 got_passphrase = FALSE;
4577 assert(0 && "unexpected return from loadrsakey()");
4578 got_passphrase = FALSE; /* placate optimisers */
4582 if (got_passphrase) {
4585 * Send a public key attempt.
4587 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4588 PKT_BIGNUM, s->key.modulus, PKT_END);
4591 if (pktin->type == SSH1_SMSG_FAILURE) {
4592 c_write_str(ssh, "Server refused our public key.\r\n");
4593 continue; /* go and try something else */
4595 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4596 bombout(("Bizarre response to offer of public key"));
4602 unsigned char buffer[32];
4603 Bignum challenge, response;
4605 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4606 bombout(("Server's RSA challenge was badly formatted"));
4609 response = rsadecrypt(challenge, &s->key);
4610 freebn(s->key.private_exponent);/* burn the evidence */
4612 for (i = 0; i < 32; i++) {
4613 buffer[i] = bignum_byte(response, 31 - i);
4617 MD5Update(&md5c, buffer, 32);
4618 MD5Update(&md5c, s->session_id, 16);
4619 MD5Final(buffer, &md5c);
4621 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4622 PKT_DATA, buffer, 16, PKT_END);
4629 if (pktin->type == SSH1_SMSG_FAILURE) {
4630 if (flags & FLAG_VERBOSE)
4631 c_write_str(ssh, "Failed to authenticate with"
4632 " our public key.\r\n");
4633 continue; /* go and try something else */
4634 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4635 bombout(("Bizarre response to RSA authentication response"));
4639 break; /* we're through! */
4645 * Otherwise, try various forms of password-like authentication.
4647 s->cur_prompt = new_prompts(ssh->frontend);
4649 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4650 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4651 !s->tis_auth_refused) {
4652 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4653 logevent("Requested TIS authentication");
4654 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4656 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4657 logevent("TIS authentication declined");
4658 if (flags & FLAG_INTERACTIVE)
4659 c_write_str(ssh, "TIS authentication refused.\r\n");
4660 s->tis_auth_refused = 1;
4665 char *instr_suf, *prompt;
4667 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4669 bombout(("TIS challenge packet was badly formed"));
4672 logevent("Received TIS challenge");
4673 s->cur_prompt->to_server = TRUE;
4674 s->cur_prompt->name = dupstr("SSH TIS authentication");
4675 /* Prompt heuristic comes from OpenSSH */
4676 if (memchr(challenge, '\n', challengelen)) {
4677 instr_suf = dupstr("");
4678 prompt = dupprintf("%.*s", challengelen, challenge);
4680 instr_suf = dupprintf("%.*s", challengelen, challenge);
4681 prompt = dupstr("Response: ");
4683 s->cur_prompt->instruction =
4684 dupprintf("Using TIS authentication.%s%s",
4685 (*instr_suf) ? "\n" : "",
4687 s->cur_prompt->instr_reqd = TRUE;
4688 add_prompt(s->cur_prompt, prompt, FALSE);
4692 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4693 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4694 !s->ccard_auth_refused) {
4695 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4696 logevent("Requested CryptoCard authentication");
4697 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4699 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4700 logevent("CryptoCard authentication declined");
4701 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4702 s->ccard_auth_refused = 1;
4707 char *instr_suf, *prompt;
4709 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4711 bombout(("CryptoCard challenge packet was badly formed"));
4714 logevent("Received CryptoCard challenge");
4715 s->cur_prompt->to_server = TRUE;
4716 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4717 s->cur_prompt->name_reqd = FALSE;
4718 /* Prompt heuristic comes from OpenSSH */
4719 if (memchr(challenge, '\n', challengelen)) {
4720 instr_suf = dupstr("");
4721 prompt = dupprintf("%.*s", challengelen, challenge);
4723 instr_suf = dupprintf("%.*s", challengelen, challenge);
4724 prompt = dupstr("Response: ");
4726 s->cur_prompt->instruction =
4727 dupprintf("Using CryptoCard authentication.%s%s",
4728 (*instr_suf) ? "\n" : "",
4730 s->cur_prompt->instr_reqd = TRUE;
4731 add_prompt(s->cur_prompt, prompt, FALSE);
4735 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4736 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4737 bombout(("No supported authentication methods available"));
4740 s->cur_prompt->to_server = TRUE;
4741 s->cur_prompt->name = dupstr("SSH password");
4742 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4743 ssh->username, ssh->savedhost),
4748 * Show password prompt, having first obtained it via a TIS
4749 * or CryptoCard exchange if we're doing TIS or CryptoCard
4753 int ret; /* need not be kept over crReturn */
4754 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4757 crWaitUntil(!pktin);
4758 ret = get_userpass_input(s->cur_prompt, in, inlen);
4763 * Failed to get a password (for example
4764 * because one was supplied on the command line
4765 * which has already failed to work). Terminate.
4767 free_prompts(s->cur_prompt);
4768 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4773 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4775 * Defence against traffic analysis: we send a
4776 * whole bunch of packets containing strings of
4777 * different lengths. One of these strings is the
4778 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4779 * The others are all random data in
4780 * SSH1_MSG_IGNORE packets. This way a passive
4781 * listener can't tell which is the password, and
4782 * hence can't deduce the password length.
4784 * Anybody with a password length greater than 16
4785 * bytes is going to have enough entropy in their
4786 * password that a listener won't find it _that_
4787 * much help to know how long it is. So what we'll
4790 * - if password length < 16, we send 15 packets
4791 * containing string lengths 1 through 15
4793 * - otherwise, we let N be the nearest multiple
4794 * of 8 below the password length, and send 8
4795 * packets containing string lengths N through
4796 * N+7. This won't obscure the order of
4797 * magnitude of the password length, but it will
4798 * introduce a bit of extra uncertainty.
4800 * A few servers can't deal with SSH1_MSG_IGNORE, at
4801 * least in this context. For these servers, we need
4802 * an alternative defence. We make use of the fact
4803 * that the password is interpreted as a C string:
4804 * so we can append a NUL, then some random data.
4806 * A few servers can deal with neither SSH1_MSG_IGNORE
4807 * here _nor_ a padded password string.
4808 * For these servers we are left with no defences
4809 * against password length sniffing.
4811 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4812 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4814 * The server can deal with SSH1_MSG_IGNORE, so
4815 * we can use the primary defence.
4817 int bottom, top, pwlen, i;
4820 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4822 bottom = 0; /* zero length passwords are OK! :-) */
4825 bottom = pwlen & ~7;
4829 assert(pwlen >= bottom && pwlen <= top);
4831 randomstr = snewn(top + 1, char);
4833 for (i = bottom; i <= top; i++) {
4835 defer_packet(ssh, s->pwpkt_type,
4836 PKT_STR,s->cur_prompt->prompts[0]->result,
4839 for (j = 0; j < i; j++) {
4841 randomstr[j] = random_byte();
4842 } while (randomstr[j] == '\0');
4844 randomstr[i] = '\0';
4845 defer_packet(ssh, SSH1_MSG_IGNORE,
4846 PKT_STR, randomstr, PKT_END);
4849 logevent("Sending password with camouflage packets");
4850 ssh_pkt_defersend(ssh);
4853 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4855 * The server can't deal with SSH1_MSG_IGNORE
4856 * but can deal with padded passwords, so we
4857 * can use the secondary defence.
4863 len = strlen(s->cur_prompt->prompts[0]->result);
4864 if (len < sizeof(string)) {
4866 strcpy(string, s->cur_prompt->prompts[0]->result);
4867 len++; /* cover the zero byte */
4868 while (len < sizeof(string)) {
4869 string[len++] = (char) random_byte();
4872 ss = s->cur_prompt->prompts[0]->result;
4874 logevent("Sending length-padded password");
4875 send_packet(ssh, s->pwpkt_type,
4876 PKT_INT, len, PKT_DATA, ss, len,
4880 * The server is believed unable to cope with
4881 * any of our password camouflage methods.
4884 len = strlen(s->cur_prompt->prompts[0]->result);
4885 logevent("Sending unpadded password");
4886 send_packet(ssh, s->pwpkt_type,
4888 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4892 send_packet(ssh, s->pwpkt_type,
4893 PKT_STR, s->cur_prompt->prompts[0]->result,
4896 logevent("Sent password");
4897 free_prompts(s->cur_prompt);
4899 if (pktin->type == SSH1_SMSG_FAILURE) {
4900 if (flags & FLAG_VERBOSE)
4901 c_write_str(ssh, "Access denied\r\n");
4902 logevent("Authentication refused");
4903 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4904 bombout(("Strange packet received, type %d", pktin->type));
4910 if (s->publickey_blob) {
4911 sfree(s->publickey_blob);
4912 sfree(s->publickey_comment);
4915 logevent("Authentication successful");
4920 static void ssh_channel_try_eof(struct ssh_channel *c)
4923 assert(c->pending_eof); /* precondition for calling us */
4925 return; /* can't close: not even opened yet */
4926 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4927 return; /* can't send EOF: pending outgoing data */
4929 c->pending_eof = FALSE; /* we're about to send it */
4930 if (ssh->version == 1) {
4931 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4933 c->closes |= CLOSES_SENT_EOF;
4935 struct Packet *pktout;
4936 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4937 ssh2_pkt_adduint32(pktout, c->remoteid);
4938 ssh2_pkt_send(ssh, pktout);
4939 c->closes |= CLOSES_SENT_EOF;
4940 ssh2_channel_check_close(c);
4944 Conf *sshfwd_get_conf(struct ssh_channel *c)
4950 void sshfwd_write_eof(struct ssh_channel *c)
4954 if (ssh->state == SSH_STATE_CLOSED)
4957 if (c->closes & CLOSES_SENT_EOF)
4960 c->pending_eof = TRUE;
4961 ssh_channel_try_eof(c);
4964 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4968 if (ssh->state == SSH_STATE_CLOSED)
4973 x11_close(c->u.x11.xconn);
4974 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4978 case CHAN_SOCKDATA_DORMANT:
4979 pfd_close(c->u.pfd.pf);
4980 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4983 c->type = CHAN_ZOMBIE;
4984 c->pending_eof = FALSE; /* this will confuse a zombie channel */
4986 ssh2_channel_check_close(c);
4989 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4993 if (ssh->state == SSH_STATE_CLOSED)
4996 if (ssh->version == 1) {
4997 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4998 PKT_INT, c->remoteid,
4999 PKT_INT, len, PKT_DATA, buf, len,
5002 * In SSH-1 we can return 0 here - implying that forwarded
5003 * connections are never individually throttled - because
5004 * the only circumstance that can cause throttling will be
5005 * the whole SSH connection backing up, in which case
5006 * _everything_ will be throttled as a whole.
5010 ssh2_add_channel_data(c, buf, len);
5011 return ssh2_try_send(c);
5015 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
5020 if (ssh->state == SSH_STATE_CLOSED)
5023 if (ssh->version == 1) {
5024 buflimit = SSH1_BUFFER_LIMIT;
5026 buflimit = c->v.v2.locmaxwin;
5027 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
5029 if (c->throttling_conn && bufsize <= buflimit) {
5030 c->throttling_conn = 0;
5031 ssh_throttle_conn(ssh, -1);
5035 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
5037 struct queued_handler *qh = ssh->qhead;
5041 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5044 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5045 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5048 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5049 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5053 ssh->qhead = qh->next;
5055 if (ssh->qhead->msg1 > 0) {
5056 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5057 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5059 if (ssh->qhead->msg2 > 0) {
5060 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5061 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5064 ssh->qhead = ssh->qtail = NULL;
5067 qh->handler(ssh, pktin, qh->ctx);
5072 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5073 chandler_fn_t handler, void *ctx)
5075 struct queued_handler *qh;
5077 qh = snew(struct queued_handler);
5080 qh->handler = handler;
5084 if (ssh->qtail == NULL) {
5088 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5089 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5092 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5093 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5096 ssh->qtail->next = qh;
5101 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5103 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5105 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5106 SSH2_MSG_REQUEST_SUCCESS)) {
5107 logeventf(ssh, "Remote port forwarding from %s enabled",
5110 logeventf(ssh, "Remote port forwarding from %s refused",
5113 rpf = del234(ssh->rportfwds, pf);
5115 pf->pfrec->remote = NULL;
5120 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5123 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5126 pf->share_ctx = share_ctx;
5127 pf->shost = dupstr(shost);
5129 pf->sportdesc = NULL;
5130 if (!ssh->rportfwds) {
5131 assert(ssh->version == 2);
5132 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5134 if (add234(ssh->rportfwds, pf) != pf) {
5142 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5145 share_got_pkt_from_server(ctx, pktin->type,
5146 pktin->body, pktin->length);
5149 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5151 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5152 ssh_sharing_global_request_response, share_ctx);
5155 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5157 struct ssh_portfwd *epf;
5161 if (!ssh->portfwds) {
5162 ssh->portfwds = newtree234(ssh_portcmp);
5165 * Go through the existing port forwardings and tag them
5166 * with status==DESTROY. Any that we want to keep will be
5167 * re-enabled (status==KEEP) as we go through the
5168 * configuration and find out which bits are the same as
5171 struct ssh_portfwd *epf;
5173 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5174 epf->status = DESTROY;
5177 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5179 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5180 char *kp, *kp2, *vp, *vp2;
5181 char address_family, type;
5182 int sport,dport,sserv,dserv;
5183 char *sports, *dports, *saddr, *host;
5187 address_family = 'A';
5189 if (*kp == 'A' || *kp == '4' || *kp == '6')
5190 address_family = *kp++;
5191 if (*kp == 'L' || *kp == 'R')
5194 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5196 * There's a colon in the middle of the source port
5197 * string, which means that the part before it is
5198 * actually a source address.
5200 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5201 saddr = host_strduptrim(saddr_tmp);
5208 sport = atoi(sports);
5212 sport = net_service_lookup(sports);
5214 logeventf(ssh, "Service lookup failed for source"
5215 " port \"%s\"", sports);
5219 if (type == 'L' && !strcmp(val, "D")) {
5220 /* dynamic forwarding */
5227 /* ordinary forwarding */
5229 vp2 = vp + host_strcspn(vp, ":");
5230 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5234 dport = atoi(dports);
5238 dport = net_service_lookup(dports);
5240 logeventf(ssh, "Service lookup failed for destination"
5241 " port \"%s\"", dports);
5246 if (sport && dport) {
5247 /* Set up a description of the source port. */
5248 struct ssh_portfwd *pfrec, *epfrec;
5250 pfrec = snew(struct ssh_portfwd);
5252 pfrec->saddr = saddr;
5253 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5254 pfrec->sport = sport;
5255 pfrec->daddr = host;
5256 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5257 pfrec->dport = dport;
5258 pfrec->local = NULL;
5259 pfrec->remote = NULL;
5260 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5261 address_family == '6' ? ADDRTYPE_IPV6 :
5264 epfrec = add234(ssh->portfwds, pfrec);
5265 if (epfrec != pfrec) {
5266 if (epfrec->status == DESTROY) {
5268 * We already have a port forwarding up and running
5269 * with precisely these parameters. Hence, no need
5270 * to do anything; simply re-tag the existing one
5273 epfrec->status = KEEP;
5276 * Anything else indicates that there was a duplicate
5277 * in our input, which we'll silently ignore.
5279 free_portfwd(pfrec);
5281 pfrec->status = CREATE;
5290 * Now go through and destroy any port forwardings which were
5293 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5294 if (epf->status == DESTROY) {
5297 message = dupprintf("%s port forwarding from %s%s%d",
5298 epf->type == 'L' ? "local" :
5299 epf->type == 'R' ? "remote" : "dynamic",
5300 epf->saddr ? epf->saddr : "",
5301 epf->saddr ? ":" : "",
5304 if (epf->type != 'D') {
5305 char *msg2 = dupprintf("%s to %s:%d", message,
5306 epf->daddr, epf->dport);
5311 logeventf(ssh, "Cancelling %s", message);
5314 /* epf->remote or epf->local may be NULL if setting up a
5315 * forwarding failed. */
5317 struct ssh_rportfwd *rpf = epf->remote;
5318 struct Packet *pktout;
5321 * Cancel the port forwarding at the server
5324 if (ssh->version == 1) {
5326 * We cannot cancel listening ports on the
5327 * server side in SSH-1! There's no message
5328 * to support it. Instead, we simply remove
5329 * the rportfwd record from the local end
5330 * so that any connections the server tries
5331 * to make on it are rejected.
5334 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5335 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5336 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5338 ssh2_pkt_addstring(pktout, epf->saddr);
5339 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5340 /* XXX: rport_acceptall may not represent
5341 * what was used to open the original connection,
5342 * since it's reconfigurable. */
5343 ssh2_pkt_addstring(pktout, "");
5345 ssh2_pkt_addstring(pktout, "localhost");
5347 ssh2_pkt_adduint32(pktout, epf->sport);
5348 ssh2_pkt_send(ssh, pktout);
5351 del234(ssh->rportfwds, rpf);
5353 } else if (epf->local) {
5354 pfl_terminate(epf->local);
5357 delpos234(ssh->portfwds, i);
5359 i--; /* so we don't skip one in the list */
5363 * And finally, set up any new port forwardings (status==CREATE).
5365 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5366 if (epf->status == CREATE) {
5367 char *sportdesc, *dportdesc;
5368 sportdesc = dupprintf("%s%s%s%s%d%s",
5369 epf->saddr ? epf->saddr : "",
5370 epf->saddr ? ":" : "",
5371 epf->sserv ? epf->sserv : "",
5372 epf->sserv ? "(" : "",
5374 epf->sserv ? ")" : "");
5375 if (epf->type == 'D') {
5378 dportdesc = dupprintf("%s:%s%s%d%s",
5380 epf->dserv ? epf->dserv : "",
5381 epf->dserv ? "(" : "",
5383 epf->dserv ? ")" : "");
5386 if (epf->type == 'L') {
5387 char *err = pfl_listen(epf->daddr, epf->dport,
5388 epf->saddr, epf->sport,
5389 ssh, conf, &epf->local,
5390 epf->addressfamily);
5392 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5393 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5394 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5395 sportdesc, dportdesc,
5396 err ? " failed: " : "", err ? err : "");
5399 } else if (epf->type == 'D') {
5400 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5401 ssh, conf, &epf->local,
5402 epf->addressfamily);
5404 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5405 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5406 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5408 err ? " failed: " : "", err ? err : "");
5413 struct ssh_rportfwd *pf;
5416 * Ensure the remote port forwardings tree exists.
5418 if (!ssh->rportfwds) {
5419 if (ssh->version == 1)
5420 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5422 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5425 pf = snew(struct ssh_rportfwd);
5426 pf->share_ctx = NULL;
5427 pf->dhost = dupstr(epf->daddr);
5428 pf->dport = epf->dport;
5430 pf->shost = dupstr(epf->saddr);
5431 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5432 pf->shost = dupstr("");
5434 pf->shost = dupstr("localhost");
5436 pf->sport = epf->sport;
5437 if (add234(ssh->rportfwds, pf) != pf) {
5438 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5439 epf->daddr, epf->dport);
5442 logeventf(ssh, "Requesting remote port %s"
5443 " forward to %s", sportdesc, dportdesc);
5445 pf->sportdesc = sportdesc;
5450 if (ssh->version == 1) {
5451 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5452 PKT_INT, epf->sport,
5453 PKT_STR, epf->daddr,
5454 PKT_INT, epf->dport,
5456 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5458 ssh_rportfwd_succfail, pf);
5460 struct Packet *pktout;
5461 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5462 ssh2_pkt_addstring(pktout, "tcpip-forward");
5463 ssh2_pkt_addbool(pktout, 1);/* want reply */
5464 ssh2_pkt_addstring(pktout, pf->shost);
5465 ssh2_pkt_adduint32(pktout, pf->sport);
5466 ssh2_pkt_send(ssh, pktout);
5468 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5469 SSH2_MSG_REQUEST_FAILURE,
5470 ssh_rportfwd_succfail, pf);
5479 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5482 int stringlen, bufsize;
5484 ssh_pkt_getstring(pktin, &string, &stringlen);
5485 if (string == NULL) {
5486 bombout(("Incoming terminal data packet was badly formed"));
5490 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5492 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5493 ssh->v1_stdout_throttling = 1;
5494 ssh_throttle_conn(ssh, +1);
5498 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5500 /* Remote side is trying to open a channel to talk to our
5501 * X-Server. Give them back a local channel number. */
5502 struct ssh_channel *c;
5503 int remoteid = ssh_pkt_getuint32(pktin);
5505 logevent("Received X11 connect request");
5506 /* Refuse if X11 forwarding is disabled. */
5507 if (!ssh->X11_fwd_enabled) {
5508 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5509 PKT_INT, remoteid, PKT_END);
5510 logevent("Rejected X11 connect request");
5512 c = snew(struct ssh_channel);
5515 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5516 c->remoteid = remoteid;
5517 c->halfopen = FALSE;
5518 c->localid = alloc_channel_id(ssh);
5520 c->pending_eof = FALSE;
5521 c->throttling_conn = 0;
5522 c->type = CHAN_X11; /* identify channel type */
5523 add234(ssh->channels, c);
5524 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5525 PKT_INT, c->remoteid, PKT_INT,
5526 c->localid, PKT_END);
5527 logevent("Opened X11 forward channel");
5531 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5533 /* Remote side is trying to open a channel to talk to our
5534 * agent. Give them back a local channel number. */
5535 struct ssh_channel *c;
5536 int remoteid = ssh_pkt_getuint32(pktin);
5538 /* Refuse if agent forwarding is disabled. */
5539 if (!ssh->agentfwd_enabled) {
5540 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5541 PKT_INT, remoteid, PKT_END);
5543 c = snew(struct ssh_channel);
5545 c->remoteid = remoteid;
5546 c->halfopen = FALSE;
5547 c->localid = alloc_channel_id(ssh);
5549 c->pending_eof = FALSE;
5550 c->throttling_conn = 0;
5551 c->type = CHAN_AGENT; /* identify channel type */
5552 c->u.a.lensofar = 0;
5553 c->u.a.message = NULL;
5554 c->u.a.outstanding_requests = 0;
5555 add234(ssh->channels, c);
5556 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5557 PKT_INT, c->remoteid, PKT_INT, c->localid,
5562 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5564 /* Remote side is trying to open a channel to talk to a
5565 * forwarded port. Give them back a local channel number. */
5566 struct ssh_rportfwd pf, *pfp;
5572 remoteid = ssh_pkt_getuint32(pktin);
5573 ssh_pkt_getstring(pktin, &host, &hostsize);
5574 port = ssh_pkt_getuint32(pktin);
5576 pf.dhost = dupprintf("%.*s", hostsize, host);
5578 pfp = find234(ssh->rportfwds, &pf, NULL);
5581 logeventf(ssh, "Rejected remote port open request for %s:%d",
5583 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5584 PKT_INT, remoteid, PKT_END);
5586 struct ssh_channel *c = snew(struct ssh_channel);
5589 logeventf(ssh, "Received remote port open request for %s:%d",
5591 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5592 c, ssh->conf, pfp->pfrec->addressfamily);
5594 logeventf(ssh, "Port open failed: %s", err);
5597 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5598 PKT_INT, remoteid, PKT_END);
5600 c->remoteid = remoteid;
5601 c->halfopen = FALSE;
5602 c->localid = alloc_channel_id(ssh);
5604 c->pending_eof = FALSE;
5605 c->throttling_conn = 0;
5606 c->type = CHAN_SOCKDATA; /* identify channel type */
5607 add234(ssh->channels, c);
5608 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5609 PKT_INT, c->remoteid, PKT_INT,
5610 c->localid, PKT_END);
5611 logevent("Forwarded port opened successfully");
5618 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5620 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5621 unsigned int localid = ssh_pkt_getuint32(pktin);
5622 struct ssh_channel *c;
5624 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5625 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5626 c->remoteid = localid;
5627 c->halfopen = FALSE;
5628 c->type = CHAN_SOCKDATA;
5629 c->throttling_conn = 0;
5630 pfd_confirm(c->u.pfd.pf);
5633 if (c && c->pending_eof) {
5635 * We have a pending close on this channel,
5636 * which we decided on before the server acked
5637 * the channel open. So now we know the
5638 * remoteid, we can close it again.
5640 ssh_channel_try_eof(c);
5644 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5646 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5647 struct ssh_channel *c;
5649 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5650 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5651 logevent("Forwarded connection refused by server");
5652 pfd_close(c->u.pfd.pf);
5653 del234(ssh->channels, c);
5658 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5660 /* Remote side closes a channel. */
5661 unsigned i = ssh_pkt_getuint32(pktin);
5662 struct ssh_channel *c;
5663 c = find234(ssh->channels, &i, ssh_channelfind);
5664 if (c && !c->halfopen) {
5666 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5667 !(c->closes & CLOSES_RCVD_EOF)) {
5669 * Received CHANNEL_CLOSE, which we translate into
5672 int send_close = FALSE;
5674 c->closes |= CLOSES_RCVD_EOF;
5679 x11_send_eof(c->u.x11.xconn);
5685 pfd_send_eof(c->u.pfd.pf);
5694 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5695 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5697 c->closes |= CLOSES_SENT_EOF;
5701 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5702 !(c->closes & CLOSES_RCVD_CLOSE)) {
5704 if (!(c->closes & CLOSES_SENT_EOF)) {
5705 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5706 " for which we never sent CHANNEL_CLOSE\n", i));
5709 c->closes |= CLOSES_RCVD_CLOSE;
5712 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5713 !(c->closes & CLOSES_SENT_CLOSE)) {
5714 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5715 PKT_INT, c->remoteid, PKT_END);
5716 c->closes |= CLOSES_SENT_CLOSE;
5719 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5720 ssh_channel_destroy(c);
5722 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5723 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5724 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5729 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5731 /* Data sent down one of our channels. */
5732 int i = ssh_pkt_getuint32(pktin);
5735 struct ssh_channel *c;
5737 ssh_pkt_getstring(pktin, &p, &len);
5739 c = find234(ssh->channels, &i, ssh_channelfind);
5744 bufsize = x11_send(c->u.x11.xconn, p, len);
5747 bufsize = pfd_send(c->u.pfd.pf, p, len);
5750 /* Data for an agent message. Buffer it. */
5752 if (c->u.a.lensofar < 4) {
5753 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5754 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5758 c->u.a.lensofar += l;
5760 if (c->u.a.lensofar == 4) {
5762 4 + GET_32BIT(c->u.a.msglen);
5763 c->u.a.message = snewn(c->u.a.totallen,
5765 memcpy(c->u.a.message, c->u.a.msglen, 4);
5767 if (c->u.a.lensofar >= 4 && len > 0) {
5769 min(c->u.a.totallen - c->u.a.lensofar,
5771 memcpy(c->u.a.message + c->u.a.lensofar, p,
5775 c->u.a.lensofar += l;
5777 if (c->u.a.lensofar == c->u.a.totallen) {
5780 c->u.a.outstanding_requests++;
5781 if (agent_query(c->u.a.message,
5784 ssh_agentf_callback, c))
5785 ssh_agentf_callback(c, reply, replylen);
5786 sfree(c->u.a.message);
5787 c->u.a.lensofar = 0;
5790 bufsize = 0; /* agent channels never back up */
5793 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5794 c->throttling_conn = 1;
5795 ssh_throttle_conn(ssh, +1);
5800 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5802 ssh->exitcode = ssh_pkt_getuint32(pktin);
5803 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5804 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5806 * In case `helpful' firewalls or proxies tack
5807 * extra human-readable text on the end of the
5808 * session which we might mistake for another
5809 * encrypted packet, we close the session once
5810 * we've sent EXIT_CONFIRMATION.
5812 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5815 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5816 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5818 struct Packet *pktout = (struct Packet *)data;
5820 unsigned int arg = 0;
5821 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5822 if (i == lenof(ssh_ttymodes)) return;
5823 switch (ssh_ttymodes[i].type) {
5825 arg = ssh_tty_parse_specchar(val);
5828 arg = ssh_tty_parse_boolean(val);
5831 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5832 ssh2_pkt_addbyte(pktout, arg);
5835 int ssh_agent_forwarding_permitted(Ssh ssh)
5837 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5840 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5841 struct Packet *pktin)
5843 crBegin(ssh->do_ssh1_connection_crstate);
5845 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5846 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5847 ssh1_smsg_stdout_stderr_data;
5849 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5850 ssh1_msg_channel_open_confirmation;
5851 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5852 ssh1_msg_channel_open_failure;
5853 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5854 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5855 ssh1_msg_channel_close;
5856 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5857 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5859 if (ssh_agent_forwarding_permitted(ssh)) {
5860 logevent("Requesting agent forwarding");
5861 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5865 if (pktin->type != SSH1_SMSG_SUCCESS
5866 && pktin->type != SSH1_SMSG_FAILURE) {
5867 bombout(("Protocol confusion"));
5869 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5870 logevent("Agent forwarding refused");
5872 logevent("Agent forwarding enabled");
5873 ssh->agentfwd_enabled = TRUE;
5874 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5878 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5880 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5882 if (!ssh->x11disp) {
5883 /* FIXME: return an error message from x11_setup_display */
5884 logevent("X11 forwarding not enabled: unable to"
5885 " initialise X display");
5887 ssh->x11auth = x11_invent_fake_auth
5888 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5889 ssh->x11auth->disp = ssh->x11disp;
5891 logevent("Requesting X11 forwarding");
5892 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5893 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5894 PKT_STR, ssh->x11auth->protoname,
5895 PKT_STR, ssh->x11auth->datastring,
5896 PKT_INT, ssh->x11disp->screennum,
5899 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5900 PKT_STR, ssh->x11auth->protoname,
5901 PKT_STR, ssh->x11auth->datastring,
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 logevent("X11 forwarding refused");
5914 logevent("X11 forwarding enabled");
5915 ssh->X11_fwd_enabled = TRUE;
5916 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5921 ssh_setup_portfwd(ssh, ssh->conf);
5922 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5924 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5926 /* Unpick the terminal-speed string. */
5927 /* XXX perhaps we should allow no speeds to be sent. */
5928 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5929 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5930 /* Send the pty request. */
5931 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5932 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5933 ssh_pkt_adduint32(pkt, ssh->term_height);
5934 ssh_pkt_adduint32(pkt, ssh->term_width);
5935 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5936 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5937 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5938 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5939 ssh_pkt_adduint32(pkt, ssh->ispeed);
5940 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5941 ssh_pkt_adduint32(pkt, ssh->ospeed);
5942 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5944 ssh->state = SSH_STATE_INTERMED;
5948 if (pktin->type != SSH1_SMSG_SUCCESS
5949 && pktin->type != SSH1_SMSG_FAILURE) {
5950 bombout(("Protocol confusion"));
5952 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5953 c_write_str(ssh, "Server refused to allocate pty\r\n");
5954 ssh->editing = ssh->echoing = 1;
5956 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5957 ssh->ospeed, ssh->ispeed);
5958 ssh->got_pty = TRUE;
5961 ssh->editing = ssh->echoing = 1;
5964 if (conf_get_int(ssh->conf, CONF_compression)) {
5965 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5969 if (pktin->type != SSH1_SMSG_SUCCESS
5970 && pktin->type != SSH1_SMSG_FAILURE) {
5971 bombout(("Protocol confusion"));
5973 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5974 c_write_str(ssh, "Server refused to compress\r\n");
5976 logevent("Started compression");
5977 ssh->v1_compressing = TRUE;
5978 ssh->cs_comp_ctx = zlib_compress_init();
5979 logevent("Initialised zlib (RFC1950) compression");
5980 ssh->sc_comp_ctx = zlib_decompress_init();
5981 logevent("Initialised zlib (RFC1950) decompression");
5985 * Start the shell or command.
5987 * Special case: if the first-choice command is an SSH-2
5988 * subsystem (hence not usable here) and the second choice
5989 * exists, we fall straight back to that.
5992 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5994 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5995 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5996 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5997 ssh->fallback_cmd = TRUE;
6000 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
6002 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
6003 logevent("Started session");
6006 ssh->state = SSH_STATE_SESSION;
6007 if (ssh->size_needed)
6008 ssh_size(ssh, ssh->term_width, ssh->term_height);
6009 if (ssh->eof_needed)
6010 ssh_special(ssh, TS_EOF);
6013 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
6015 ssh->channels = newtree234(ssh_channelcmp);
6019 * By this point, most incoming packets are already being
6020 * handled by the dispatch table, and we need only pay
6021 * attention to the unusual ones.
6026 if (pktin->type == SSH1_SMSG_SUCCESS) {
6027 /* may be from EXEC_SHELL on some servers */
6028 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6029 /* may be from EXEC_SHELL on some servers
6030 * if no pty is available or in other odd cases. Ignore */
6032 bombout(("Strange packet received: type %d", pktin->type));
6037 int len = min(inlen, 512);
6038 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
6039 PKT_INT, len, PKT_DATA, in, len,
6051 * Handle the top-level SSH-2 protocol.
6053 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6058 ssh_pkt_getstring(pktin, &msg, &msglen);
6059 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
6062 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6064 /* log reason code in disconnect message */
6068 ssh_pkt_getstring(pktin, &msg, &msglen);
6069 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
6072 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6074 /* Do nothing, because we're ignoring it! Duhh. */
6077 static void ssh1_protocol_setup(Ssh ssh)
6082 * Most messages are handled by the coroutines.
6084 for (i = 0; i < 256; i++)
6085 ssh->packet_dispatch[i] = NULL;
6088 * These special message types we install handlers for.
6090 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6091 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6092 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6095 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6096 struct Packet *pktin)
6098 const unsigned char *in = (const unsigned char *)vin;
6099 if (ssh->state == SSH_STATE_CLOSED)
6102 if (pktin && ssh->packet_dispatch[pktin->type]) {
6103 ssh->packet_dispatch[pktin->type](ssh, pktin);
6107 if (!ssh->protocol_initial_phase_done) {
6108 if (do_ssh1_login(ssh, in, inlen, pktin))
6109 ssh->protocol_initial_phase_done = TRUE;
6114 do_ssh1_connection(ssh, in, inlen, pktin);
6118 * Utility routines for decoding comma-separated strings in KEXINIT.
6120 static int first_in_commasep_string(char const *needle, char const *haystack,
6124 if (!needle || !haystack) /* protect against null pointers */
6126 needlen = strlen(needle);
6128 if (haylen >= needlen && /* haystack is long enough */
6129 !memcmp(needle, haystack, needlen) && /* initial match */
6130 (haylen == needlen || haystack[needlen] == ',')
6131 /* either , or EOS follows */
6137 static int in_commasep_string(char const *needle, char const *haystack,
6142 if (!needle || !haystack) /* protect against null pointers */
6145 * Is it at the start of the string?
6147 if (first_in_commasep_string(needle, haystack, haylen))
6150 * If not, search for the next comma and resume after that.
6151 * If no comma found, terminate.
6153 p = memchr(haystack, ',', haylen);
6155 /* + 1 to skip over comma */
6156 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6160 * Add a value to the comma-separated string at the end of the packet.
6162 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6164 if (pkt->length - pkt->savedpos > 0)
6165 ssh_pkt_addstring_str(pkt, ",");
6166 ssh_pkt_addstring_str(pkt, data);
6171 * SSH-2 key derivation (RFC 4253 section 7.2).
6173 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6174 char chr, int keylen)
6176 const struct ssh_hash *h = ssh->kex->hash;
6184 /* Round up to the next multiple of hash length. */
6185 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6187 key = snewn(keylen_padded, unsigned char);
6189 /* First hlen bytes. */
6191 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6192 hash_mpint(h, s, K);
6193 h->bytes(s, H, h->hlen);
6194 h->bytes(s, &chr, 1);
6195 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6198 /* Subsequent blocks of hlen bytes. */
6199 if (keylen_padded > h->hlen) {
6203 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6204 hash_mpint(h, s, K);
6205 h->bytes(s, H, h->hlen);
6207 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6208 h->bytes(s, key + offset - h->hlen, h->hlen);
6210 h->final(s2, key + offset);
6216 /* Now clear any extra bytes of key material beyond the length
6217 * we're officially returning, because the caller won't know to
6219 if (keylen_padded > keylen)
6220 smemclr(key + keylen, keylen_padded - keylen);
6226 * Structure for constructing KEXINIT algorithm lists.
6228 #define MAXKEXLIST 16
6229 struct kexinit_algorithm {
6233 const struct ssh_kex *kex;
6236 const struct ssh_signkey *hostkey;
6238 const struct ssh2_cipher *cipher;
6242 const struct ssh_mac *mac;
6245 const struct ssh_compress *comp;
6250 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6251 * If the algorithm is already in the list, return a pointer to its
6252 * entry, otherwise return an entry from the end of the list.
6253 * This assumes that every time a particular name is passed in, it
6254 * comes from the same string constant. If this isn't true, this
6255 * function may need to be rewritten to use strcmp() instead.
6257 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6258 *list, const char *name)
6262 for (i = 0; i < MAXKEXLIST; i++)
6263 if (list[i].name == NULL || list[i].name == name) {
6264 list[i].name = name;
6267 assert(!"No space in KEXINIT list");
6272 * Handle the SSH-2 transport layer.
6274 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6275 struct Packet *pktin)
6277 const unsigned char *in = (const unsigned char *)vin;
6279 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6280 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6283 const char * kexlist_descr[NKEXLIST] = {
6284 "key exchange algorithm", "host key algorithm",
6285 "client-to-server cipher", "server-to-client cipher",
6286 "client-to-server MAC", "server-to-client MAC",
6287 "client-to-server compression method",
6288 "server-to-client compression method" };
6289 struct do_ssh2_transport_state {
6291 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
6292 Bignum p, g, e, f, K;
6295 int kex_init_value, kex_reply_value;
6296 const struct ssh_mac **maclist;
6298 const struct ssh2_cipher *cscipher_tobe;
6299 const struct ssh2_cipher *sccipher_tobe;
6300 const struct ssh_mac *csmac_tobe;
6301 const struct ssh_mac *scmac_tobe;
6302 int csmac_etm_tobe, scmac_etm_tobe;
6303 const struct ssh_compress *cscomp_tobe;
6304 const struct ssh_compress *sccomp_tobe;
6305 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6306 int hostkeylen, siglen, rsakeylen;
6307 void *hkey; /* actual host key */
6308 void *rsakey; /* for RSA kex */
6309 void *eckey; /* for ECDH kex */
6310 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6311 int n_preferred_kex;
6312 const struct ssh_kexes *preferred_kex[KEX_MAX];
6313 int n_preferred_ciphers;
6314 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6315 const struct ssh_compress *preferred_comp;
6316 int userauth_succeeded; /* for delayed compression */
6317 int pending_compression;
6318 int got_session_id, activated_authconn;
6319 struct Packet *pktout;
6323 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6325 crState(do_ssh2_transport_state);
6327 assert(!ssh->bare_connection);
6331 s->cscipher_tobe = s->sccipher_tobe = NULL;
6332 s->csmac_tobe = s->scmac_tobe = NULL;
6333 s->cscomp_tobe = s->sccomp_tobe = NULL;
6335 s->got_session_id = s->activated_authconn = FALSE;
6336 s->userauth_succeeded = FALSE;
6337 s->pending_compression = FALSE;
6340 * Be prepared to work around the buggy MAC problem.
6342 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6343 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6345 s->maclist = macs, s->nmacs = lenof(macs);
6348 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6351 struct kexinit_algorithm *alg;
6354 * Set up the preferred key exchange. (NULL => warn below here)
6356 s->n_preferred_kex = 0;
6357 for (i = 0; i < KEX_MAX; i++) {
6358 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6360 s->preferred_kex[s->n_preferred_kex++] =
6361 &ssh_diffiehellman_gex;
6364 s->preferred_kex[s->n_preferred_kex++] =
6365 &ssh_diffiehellman_group14;
6368 s->preferred_kex[s->n_preferred_kex++] =
6369 &ssh_diffiehellman_group1;
6372 s->preferred_kex[s->n_preferred_kex++] =
6376 s->preferred_kex[s->n_preferred_kex++] =
6380 /* Flag for later. Don't bother if it's the last in
6382 if (i < KEX_MAX - 1) {
6383 s->preferred_kex[s->n_preferred_kex++] = NULL;
6390 * Set up the preferred ciphers. (NULL => warn below here)
6392 s->n_preferred_ciphers = 0;
6393 for (i = 0; i < CIPHER_MAX; i++) {
6394 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6395 case CIPHER_BLOWFISH:
6396 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6399 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6400 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6404 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6407 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6409 case CIPHER_ARCFOUR:
6410 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6412 case CIPHER_CHACHA20:
6413 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6416 /* Flag for later. Don't bother if it's the last in
6418 if (i < CIPHER_MAX - 1) {
6419 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6426 * Set up preferred compression.
6428 if (conf_get_int(ssh->conf, CONF_compression))
6429 s->preferred_comp = &ssh_zlib;
6431 s->preferred_comp = &ssh_comp_none;
6434 * Enable queueing of outgoing auth- or connection-layer
6435 * packets while we are in the middle of a key exchange.
6437 ssh->queueing = TRUE;
6440 * Flag that KEX is in progress.
6442 ssh->kex_in_progress = TRUE;
6444 for (i = 0; i < NKEXLIST; i++)
6445 for (j = 0; j < MAXKEXLIST; j++)
6446 s->kexlists[i][j].name = NULL;
6447 /* List key exchange algorithms. */
6449 for (i = 0; i < s->n_preferred_kex; i++) {
6450 const struct ssh_kexes *k = s->preferred_kex[i];
6451 if (!k) warn = TRUE;
6452 else for (j = 0; j < k->nkexes; j++) {
6453 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6455 alg->u.kex.kex = k->list[j];
6456 alg->u.kex.warn = warn;
6459 /* List server host key algorithms. */
6460 if (!s->got_session_id) {
6462 * In the first key exchange, we list all the algorithms
6463 * we're prepared to cope with, but prefer those algorithms
6464 * for which we have a host key for this host.
6466 for (i = 0; i < lenof(hostkey_algs); i++) {
6467 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6468 hostkey_algs[i]->keytype)) {
6469 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6470 hostkey_algs[i]->name);
6471 alg->u.hostkey = hostkey_algs[i];
6474 for (i = 0; i < lenof(hostkey_algs); i++) {
6475 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6476 hostkey_algs[i]->name);
6477 alg->u.hostkey = hostkey_algs[i];
6481 * In subsequent key exchanges, we list only the kex
6482 * algorithm that was selected in the first key exchange,
6483 * so that we keep getting the same host key and hence
6484 * don't have to interrupt the user's session to ask for
6488 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6489 ssh->hostkey->name);
6490 alg->u.hostkey = ssh->hostkey;
6492 /* List encryption algorithms (client->server then server->client). */
6493 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6496 alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6497 alg->u.cipher.cipher = NULL;
6498 alg->u.cipher.warn = warn;
6499 #endif /* FUZZING */
6500 for (i = 0; i < s->n_preferred_ciphers; i++) {
6501 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6502 if (!c) warn = TRUE;
6503 else for (j = 0; j < c->nciphers; j++) {
6504 alg = ssh2_kexinit_addalg(s->kexlists[k],
6506 alg->u.cipher.cipher = c->list[j];
6507 alg->u.cipher.warn = warn;
6511 /* List MAC algorithms (client->server then server->client). */
6512 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6514 alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6515 alg->u.mac.mac = NULL;
6516 alg->u.mac.etm = FALSE;
6517 #endif /* FUZZING */
6518 for (i = 0; i < s->nmacs; i++) {
6519 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6520 alg->u.mac.mac = s->maclist[i];
6521 alg->u.mac.etm = FALSE;
6523 for (i = 0; i < s->nmacs; i++)
6524 /* For each MAC, there may also be an ETM version,
6525 * which we list second. */
6526 if (s->maclist[i]->etm_name) {
6527 alg = ssh2_kexinit_addalg(s->kexlists[j],
6528 s->maclist[i]->etm_name);
6529 alg->u.mac.mac = s->maclist[i];
6530 alg->u.mac.etm = TRUE;
6533 /* List client->server compression algorithms,
6534 * then server->client compression algorithms. (We use the
6535 * same set twice.) */
6536 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6537 assert(lenof(compressions) > 1);
6538 /* Prefer non-delayed versions */
6539 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6540 alg->u.comp = s->preferred_comp;
6541 /* We don't even list delayed versions of algorithms until
6542 * they're allowed to be used, to avoid a race. See the end of
6544 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6545 alg = ssh2_kexinit_addalg(s->kexlists[j],
6546 s->preferred_comp->delayed_name);
6547 alg->u.comp = s->preferred_comp;
6549 for (i = 0; i < lenof(compressions); i++) {
6550 const struct ssh_compress *c = compressions[i];
6551 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6553 if (s->userauth_succeeded && c->delayed_name) {
6554 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6560 * Construct and send our key exchange packet.
6562 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6563 for (i = 0; i < 16; i++)
6564 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6565 for (i = 0; i < NKEXLIST; i++) {
6566 ssh2_pkt_addstring_start(s->pktout);
6567 for (j = 0; j < MAXKEXLIST; j++) {
6568 if (s->kexlists[i][j].name == NULL) break;
6569 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6572 /* List client->server languages. Empty list. */
6573 ssh2_pkt_addstring_start(s->pktout);
6574 /* List server->client languages. Empty list. */
6575 ssh2_pkt_addstring_start(s->pktout);
6576 /* First KEX packet does _not_ follow, because we're not that brave. */
6577 ssh2_pkt_addbool(s->pktout, FALSE);
6579 ssh2_pkt_adduint32(s->pktout, 0);
6582 s->our_kexinitlen = s->pktout->length - 5;
6583 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6584 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6586 ssh2_pkt_send_noqueue(ssh, s->pktout);
6589 crWaitUntilV(pktin);
6592 * Now examine the other side's KEXINIT to see what we're up
6599 if (pktin->type != SSH2_MSG_KEXINIT) {
6600 bombout(("expected key exchange packet from server"));
6604 ssh->hostkey = NULL;
6605 s->cscipher_tobe = NULL;
6606 s->sccipher_tobe = NULL;
6607 s->csmac_tobe = NULL;
6608 s->scmac_tobe = NULL;
6609 s->cscomp_tobe = NULL;
6610 s->sccomp_tobe = NULL;
6611 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
6613 pktin->savedpos += 16; /* skip garbage cookie */
6616 for (i = 0; i < NKEXLIST; i++) {
6617 ssh_pkt_getstring(pktin, &str, &len);
6619 bombout(("KEXINIT packet was incomplete"));
6623 /* If we've already selected a cipher which requires a
6624 * particular MAC, then just select that, and don't even
6625 * bother looking through the server's KEXINIT string for
6627 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6628 s->cscipher_tobe->required_mac) {
6629 s->csmac_tobe = s->cscipher_tobe->required_mac;
6630 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6633 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6634 s->sccipher_tobe->required_mac) {
6635 s->scmac_tobe = s->sccipher_tobe->required_mac;
6636 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6640 for (j = 0; j < MAXKEXLIST; j++) {
6641 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6642 if (alg->name == NULL) break;
6643 if (in_commasep_string(alg->name, str, len)) {
6644 /* We've found a matching algorithm. */
6645 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6646 /* Check if we might need to ignore first kex pkt */
6648 !first_in_commasep_string(alg->name, str, len))
6651 if (i == KEXLIST_KEX) {
6652 ssh->kex = alg->u.kex.kex;
6653 s->warn_kex = alg->u.kex.warn;
6654 } else if (i == KEXLIST_HOSTKEY) {
6655 ssh->hostkey = alg->u.hostkey;
6656 } else if (i == KEXLIST_CSCIPHER) {
6657 s->cscipher_tobe = alg->u.cipher.cipher;
6658 s->warn_cscipher = alg->u.cipher.warn;
6659 } else if (i == KEXLIST_SCCIPHER) {
6660 s->sccipher_tobe = alg->u.cipher.cipher;
6661 s->warn_sccipher = alg->u.cipher.warn;
6662 } else if (i == KEXLIST_CSMAC) {
6663 s->csmac_tobe = alg->u.mac.mac;
6664 s->csmac_etm_tobe = alg->u.mac.etm;
6665 } else if (i == KEXLIST_SCMAC) {
6666 s->scmac_tobe = alg->u.mac.mac;
6667 s->scmac_etm_tobe = alg->u.mac.etm;
6668 } else if (i == KEXLIST_CSCOMP) {
6669 s->cscomp_tobe = alg->u.comp;
6670 } else if (i == KEXLIST_SCCOMP) {
6671 s->sccomp_tobe = alg->u.comp;
6675 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6676 in_commasep_string(alg->u.comp->delayed_name, str, len))
6677 s->pending_compression = TRUE; /* try this later */
6679 bombout(("Couldn't agree a %s ((available: %.*s)",
6680 kexlist_descr[i], len, str));
6685 if (s->pending_compression) {
6686 logevent("Server supports delayed compression; "
6687 "will try this later");
6689 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6690 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6691 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6693 ssh->exhash = ssh->kex->hash->init();
6694 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6695 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6696 hash_string(ssh->kex->hash, ssh->exhash,
6697 s->our_kexinit, s->our_kexinitlen);
6698 sfree(s->our_kexinit);
6699 /* Include the type byte in the hash of server's KEXINIT */
6700 hash_string(ssh->kex->hash, ssh->exhash,
6701 pktin->body - 1, pktin->length + 1);
6704 ssh_set_frozen(ssh, 1);
6705 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6707 ssh_dialog_callback, ssh);
6708 if (s->dlgret < 0) {
6712 bombout(("Unexpected data from server while"
6713 " waiting for user response"));
6716 } while (pktin || inlen > 0);
6717 s->dlgret = ssh->user_response;
6719 ssh_set_frozen(ssh, 0);
6720 if (s->dlgret == 0) {
6721 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6727 if (s->warn_cscipher) {
6728 ssh_set_frozen(ssh, 1);
6729 s->dlgret = askalg(ssh->frontend,
6730 "client-to-server cipher",
6731 s->cscipher_tobe->name,
6732 ssh_dialog_callback, ssh);
6733 if (s->dlgret < 0) {
6737 bombout(("Unexpected data from server while"
6738 " waiting for user response"));
6741 } while (pktin || inlen > 0);
6742 s->dlgret = ssh->user_response;
6744 ssh_set_frozen(ssh, 0);
6745 if (s->dlgret == 0) {
6746 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6752 if (s->warn_sccipher) {
6753 ssh_set_frozen(ssh, 1);
6754 s->dlgret = askalg(ssh->frontend,
6755 "server-to-client cipher",
6756 s->sccipher_tobe->name,
6757 ssh_dialog_callback, ssh);
6758 if (s->dlgret < 0) {
6762 bombout(("Unexpected data from server while"
6763 " waiting for user response"));
6766 } while (pktin || inlen > 0);
6767 s->dlgret = ssh->user_response;
6769 ssh_set_frozen(ssh, 0);
6770 if (s->dlgret == 0) {
6771 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6777 if (s->ignorepkt) /* first_kex_packet_follows */
6778 crWaitUntilV(pktin); /* Ignore packet */
6781 if (ssh->kex->main_type == KEXTYPE_DH) {
6783 * Work out the number of bits of key we will need from the
6784 * key exchange. We start with the maximum key length of
6790 csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6791 scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6792 s->nbits = (csbits > scbits ? csbits : scbits);
6794 /* The keys only have hlen-bit entropy, since they're based on
6795 * a hash. So cap the key size at hlen bits. */
6796 if (s->nbits > ssh->kex->hash->hlen * 8)
6797 s->nbits = ssh->kex->hash->hlen * 8;
6800 * If we're doing Diffie-Hellman group exchange, start by
6801 * requesting a group.
6803 if (dh_is_gex(ssh->kex)) {
6804 logevent("Doing Diffie-Hellman group exchange");
6805 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6807 * Work out how big a DH group we will need to allow that
6810 s->pbits = 512 << ((s->nbits - 1) / 64);
6811 if (s->pbits < DH_MIN_SIZE)
6812 s->pbits = DH_MIN_SIZE;
6813 if (s->pbits > DH_MAX_SIZE)
6814 s->pbits = DH_MAX_SIZE;
6815 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6816 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6817 ssh2_pkt_adduint32(s->pktout, s->pbits);
6819 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6820 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6821 ssh2_pkt_adduint32(s->pktout, s->pbits);
6822 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6824 ssh2_pkt_send_noqueue(ssh, s->pktout);
6826 crWaitUntilV(pktin);
6827 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6828 bombout(("expected key exchange group packet from server"));
6831 s->p = ssh2_pkt_getmp(pktin);
6832 s->g = ssh2_pkt_getmp(pktin);
6833 if (!s->p || !s->g) {
6834 bombout(("unable to read mp-ints from incoming group packet"));
6837 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6838 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6839 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6841 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6842 ssh->kex_ctx = dh_setup_group(ssh->kex);
6843 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6844 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6845 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6846 ssh->kex->groupname);
6849 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6850 ssh->kex->hash->text_name);
6852 * Now generate and send e for Diffie-Hellman.
6854 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6855 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6856 s->pktout = ssh2_pkt_init(s->kex_init_value);
6857 ssh2_pkt_addmp(s->pktout, s->e);
6858 ssh2_pkt_send_noqueue(ssh, s->pktout);
6860 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6861 crWaitUntilV(pktin);
6862 if (pktin->type != s->kex_reply_value) {
6863 bombout(("expected key exchange reply packet from server"));
6866 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6867 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6868 if (!s->hostkeydata) {
6869 bombout(("unable to parse key exchange reply packet"));
6872 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6873 s->hostkeydata, s->hostkeylen);
6874 s->f = ssh2_pkt_getmp(pktin);
6876 bombout(("unable to parse key exchange reply packet"));
6879 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6881 bombout(("unable to parse key exchange reply packet"));
6886 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
6888 bombout(("key exchange reply failed validation: %s", err));
6892 s->K = dh_find_K(ssh->kex_ctx, s->f);
6894 /* We assume everything from now on will be quick, and it might
6895 * involve user interaction. */
6896 set_busy_status(ssh->frontend, BUSY_NOT);
6898 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6899 if (dh_is_gex(ssh->kex)) {
6900 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6901 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
6902 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6903 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6904 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
6905 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6906 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6908 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6909 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6911 dh_cleanup(ssh->kex_ctx);
6913 if (dh_is_gex(ssh->kex)) {
6917 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
6919 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
6920 ssh_ecdhkex_curve_textname(ssh->kex),
6921 ssh->kex->hash->text_name);
6922 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
6924 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
6926 bombout(("Unable to generate key for ECDH"));
6932 int publicPointLength;
6933 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6935 ssh_ecdhkex_freekey(s->eckey);
6936 bombout(("Unable to encode public key for ECDH"));
6939 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
6940 ssh2_pkt_addstring_start(s->pktout);
6941 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
6945 ssh2_pkt_send_noqueue(ssh, s->pktout);
6947 crWaitUntilV(pktin);
6948 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
6949 ssh_ecdhkex_freekey(s->eckey);
6950 bombout(("expected ECDH reply packet from server"));
6954 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6955 if (!s->hostkeydata) {
6956 bombout(("unable to parse ECDH reply packet"));
6959 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6960 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6961 s->hostkeydata, s->hostkeylen);
6965 int publicPointLength;
6966 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6968 ssh_ecdhkex_freekey(s->eckey);
6969 bombout(("Unable to encode public key for ECDH hash"));
6972 hash_string(ssh->kex->hash, ssh->exhash,
6973 publicPoint, publicPointLength);
6980 ssh_pkt_getstring(pktin, &keydata, &keylen);
6982 bombout(("unable to parse ECDH reply packet"));
6985 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
6986 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
6988 ssh_ecdhkex_freekey(s->eckey);
6989 bombout(("point received in ECDH was not valid"));
6994 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6996 bombout(("unable to parse key exchange reply packet"));
7000 ssh_ecdhkex_freekey(s->eckey);
7002 logeventf(ssh, "Doing RSA key exchange with hash %s",
7003 ssh->kex->hash->text_name);
7004 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7006 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7009 crWaitUntilV(pktin);
7010 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7011 bombout(("expected RSA public key packet from server"));
7015 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7016 if (!s->hostkeydata) {
7017 bombout(("unable to parse RSA public key packet"));
7020 hash_string(ssh->kex->hash, ssh->exhash,
7021 s->hostkeydata, s->hostkeylen);
7022 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7023 s->hostkeydata, s->hostkeylen);
7027 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7029 bombout(("unable to parse RSA public key packet"));
7032 s->rsakeydata = snewn(s->rsakeylen, char);
7033 memcpy(s->rsakeydata, keydata, s->rsakeylen);
7036 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7038 sfree(s->rsakeydata);
7039 bombout(("unable to parse RSA public key from server"));
7043 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7046 * Next, set up a shared secret K, of precisely KLEN -
7047 * 2*HLEN - 49 bits, where KLEN is the bit length of the
7048 * RSA key modulus and HLEN is the bit length of the hash
7052 int klen = ssh_rsakex_klen(s->rsakey);
7053 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7055 unsigned char *kstr1, *kstr2, *outstr;
7056 int kstr1len, kstr2len, outstrlen;
7058 s->K = bn_power_2(nbits - 1);
7060 for (i = 0; i < nbits; i++) {
7062 byte = random_byte();
7064 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7068 * Encode this as an mpint.
7070 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7071 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7072 PUT_32BIT(kstr2, kstr1len);
7073 memcpy(kstr2 + 4, kstr1, kstr1len);
7076 * Encrypt it with the given RSA key.
7078 outstrlen = (klen + 7) / 8;
7079 outstr = snewn(outstrlen, unsigned char);
7080 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7081 outstr, outstrlen, s->rsakey);
7084 * And send it off in a return packet.
7086 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7087 ssh2_pkt_addstring_start(s->pktout);
7088 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7089 ssh2_pkt_send_noqueue(ssh, s->pktout);
7091 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7098 ssh_rsakex_freekey(s->rsakey);
7100 crWaitUntilV(pktin);
7101 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7102 sfree(s->rsakeydata);
7103 bombout(("expected signature packet from server"));
7107 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7109 bombout(("unable to parse signature packet"));
7113 sfree(s->rsakeydata);
7116 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7117 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7118 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7120 ssh->kex_ctx = NULL;
7123 debug(("Exchange hash is:\n"));
7124 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7128 bombout(("Server's host key is invalid"));
7132 if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7133 (char *)s->exchange_hash,
7134 ssh->kex->hash->hlen)) {
7136 bombout(("Server's host key did not match the signature supplied"));
7141 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7142 if (!s->got_session_id) {
7144 * Authenticate remote host: verify host key. (We've already
7145 * checked the signature of the exchange hash.)
7147 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7148 logevent("Host key fingerprint is:");
7149 logevent(s->fingerprint);
7150 /* First check against manually configured host keys. */
7151 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7152 ssh->hostkey, s->hkey);
7153 if (s->dlgret == 0) { /* did not match */
7154 bombout(("Host key did not appear in manually configured list"));
7156 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7157 ssh_set_frozen(ssh, 1);
7158 s->dlgret = verify_ssh_host_key(ssh->frontend,
7159 ssh->savedhost, ssh->savedport,
7160 ssh->hostkey->keytype, s->keystr,
7162 ssh_dialog_callback, ssh);
7166 if (s->dlgret < 0) {
7170 bombout(("Unexpected data from server while waiting"
7171 " for user host key response"));
7174 } while (pktin || inlen > 0);
7175 s->dlgret = ssh->user_response;
7177 ssh_set_frozen(ssh, 0);
7178 if (s->dlgret == 0) {
7179 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7184 sfree(s->fingerprint);
7186 * Save this host key, to check against the one presented in
7187 * subsequent rekeys.
7189 ssh->hostkey_str = s->keystr;
7192 * In a rekey, we never present an interactive host key
7193 * verification request to the user. Instead, we simply
7194 * enforce that the key we're seeing this time is identical to
7195 * the one we saw before.
7197 if (strcmp(ssh->hostkey_str, s->keystr)) {
7199 bombout(("Host key was different in repeat key exchange"));
7205 ssh->hostkey->freekey(s->hkey);
7208 * The exchange hash from the very first key exchange is also
7209 * the session id, used in session key construction and
7212 if (!s->got_session_id) {
7213 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7214 memcpy(ssh->v2_session_id, s->exchange_hash,
7215 sizeof(s->exchange_hash));
7216 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7217 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7218 s->got_session_id = TRUE;
7222 * Send SSH2_MSG_NEWKEYS.
7224 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7225 ssh2_pkt_send_noqueue(ssh, s->pktout);
7226 ssh->outgoing_data_size = 0; /* start counting from here */
7229 * We've sent client NEWKEYS, so create and initialise
7230 * client-to-server session keys.
7232 if (ssh->cs_cipher_ctx)
7233 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7234 ssh->cscipher = s->cscipher_tobe;
7235 if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7237 if (ssh->cs_mac_ctx)
7238 ssh->csmac->free_context(ssh->cs_mac_ctx);
7239 ssh->csmac = s->csmac_tobe;
7240 ssh->csmac_etm = s->csmac_etm_tobe;
7242 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7244 if (ssh->cs_comp_ctx)
7245 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7246 ssh->cscomp = s->cscomp_tobe;
7247 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7250 * Set IVs on client-to-server keys. Here we use the exchange
7251 * hash from the _first_ key exchange.
7253 if (ssh->cscipher) {
7256 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7257 ssh->cscipher->padded_keybytes);
7258 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7259 smemclr(key, ssh->cscipher->padded_keybytes);
7262 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7263 ssh->cscipher->blksize);
7264 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7265 smemclr(key, ssh->cscipher->blksize);
7271 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7272 ssh->csmac->keylen);
7273 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7274 smemclr(key, ssh->csmac->keylen);
7279 logeventf(ssh, "Initialised %.200s client->server encryption",
7280 ssh->cscipher->text_name);
7282 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7283 ssh->csmac->text_name,
7284 ssh->csmac_etm ? " (in ETM mode)" : "",
7285 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7286 if (ssh->cscomp->text_name)
7287 logeventf(ssh, "Initialised %s compression",
7288 ssh->cscomp->text_name);
7291 * Now our end of the key exchange is complete, we can send all
7292 * our queued higher-layer packets.
7294 ssh->queueing = FALSE;
7295 ssh2_pkt_queuesend(ssh);
7298 * Expect SSH2_MSG_NEWKEYS from server.
7300 crWaitUntilV(pktin);
7301 if (pktin->type != SSH2_MSG_NEWKEYS) {
7302 bombout(("expected new-keys packet from server"));
7305 ssh->incoming_data_size = 0; /* start counting from here */
7308 * We've seen server NEWKEYS, so create and initialise
7309 * server-to-client session keys.
7311 if (ssh->sc_cipher_ctx)
7312 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7313 if (s->sccipher_tobe) {
7314 ssh->sccipher = s->sccipher_tobe;
7315 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7318 if (ssh->sc_mac_ctx)
7319 ssh->scmac->free_context(ssh->sc_mac_ctx);
7320 if (s->scmac_tobe) {
7321 ssh->scmac = s->scmac_tobe;
7322 ssh->scmac_etm = s->scmac_etm_tobe;
7323 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7326 if (ssh->sc_comp_ctx)
7327 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7328 ssh->sccomp = s->sccomp_tobe;
7329 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7332 * Set IVs on server-to-client keys. Here we use the exchange
7333 * hash from the _first_ key exchange.
7335 if (ssh->sccipher) {
7338 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7339 ssh->sccipher->padded_keybytes);
7340 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7341 smemclr(key, ssh->sccipher->padded_keybytes);
7344 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7345 ssh->sccipher->blksize);
7346 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7347 smemclr(key, ssh->sccipher->blksize);
7353 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7354 ssh->scmac->keylen);
7355 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7356 smemclr(key, ssh->scmac->keylen);
7360 logeventf(ssh, "Initialised %.200s server->client encryption",
7361 ssh->sccipher->text_name);
7363 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7364 ssh->scmac->text_name,
7365 ssh->scmac_etm ? " (in ETM mode)" : "",
7366 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7367 if (ssh->sccomp->text_name)
7368 logeventf(ssh, "Initialised %s decompression",
7369 ssh->sccomp->text_name);
7372 * Free shared secret.
7377 * Key exchange is over. Loop straight back round if we have a
7378 * deferred rekey reason.
7380 if (ssh->deferred_rekey_reason) {
7381 logevent(ssh->deferred_rekey_reason);
7383 ssh->deferred_rekey_reason = NULL;
7384 goto begin_key_exchange;
7388 * Otherwise, schedule a timer for our next rekey.
7390 ssh->kex_in_progress = FALSE;
7391 ssh->last_rekey = GETTICKCOUNT();
7392 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7393 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7397 * Now we're encrypting. Begin returning 1 to the protocol main
7398 * function so that other things can run on top of the
7399 * transport. If we ever see a KEXINIT, we must go back to the
7402 * We _also_ go back to the start if we see pktin==NULL and
7403 * inlen negative, because this is a special signal meaning
7404 * `initiate client-driven rekey', and `in' contains a message
7405 * giving the reason for the rekey.
7407 * inlen==-1 means always initiate a rekey;
7408 * inlen==-2 means that userauth has completed successfully and
7409 * we should consider rekeying (for delayed compression).
7411 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7412 (!pktin && inlen < 0))) {
7414 if (!ssh->protocol_initial_phase_done) {
7415 ssh->protocol_initial_phase_done = TRUE;
7417 * Allow authconn to initialise itself.
7419 do_ssh2_authconn(ssh, NULL, 0, NULL);
7424 logevent("Server initiated key re-exchange");
7428 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7429 * delayed compression, if it's available.
7431 * draft-miller-secsh-compression-delayed-00 says that you
7432 * negotiate delayed compression in the first key exchange, and
7433 * both sides start compressing when the server has sent
7434 * USERAUTH_SUCCESS. This has a race condition -- the server
7435 * can't know when the client has seen it, and thus which incoming
7436 * packets it should treat as compressed.
7438 * Instead, we do the initial key exchange without offering the
7439 * delayed methods, but note if the server offers them; when we
7440 * get here, if a delayed method was available that was higher
7441 * on our list than what we got, we initiate a rekey in which we
7442 * _do_ list the delayed methods (and hopefully get it as a
7443 * result). Subsequent rekeys will do the same.
7445 assert(!s->userauth_succeeded); /* should only happen once */
7446 s->userauth_succeeded = TRUE;
7447 if (!s->pending_compression)
7448 /* Can't see any point rekeying. */
7449 goto wait_for_rekey; /* this is utterly horrid */
7450 /* else fall through to rekey... */
7451 s->pending_compression = FALSE;
7454 * Now we've decided to rekey.
7456 * Special case: if the server bug is set that doesn't
7457 * allow rekeying, we give a different log message and
7458 * continue waiting. (If such a server _initiates_ a rekey,
7459 * we process it anyway!)
7461 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7462 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7464 /* Reset the counters, so that at least this message doesn't
7465 * hit the event log _too_ often. */
7466 ssh->outgoing_data_size = 0;
7467 ssh->incoming_data_size = 0;
7468 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7470 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7473 goto wait_for_rekey; /* this is still utterly horrid */
7475 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7478 goto begin_key_exchange;
7484 * Add data to an SSH-2 channel output buffer.
7486 static void ssh2_add_channel_data(struct ssh_channel *c, const char *buf,
7489 bufchain_add(&c->v.v2.outbuffer, buf, len);
7493 * Attempt to send data on an SSH-2 channel.
7495 static int ssh2_try_send(struct ssh_channel *c)
7498 struct Packet *pktout;
7501 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7504 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7505 if ((unsigned)len > c->v.v2.remwindow)
7506 len = c->v.v2.remwindow;
7507 if ((unsigned)len > c->v.v2.remmaxpkt)
7508 len = c->v.v2.remmaxpkt;
7509 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7510 ssh2_pkt_adduint32(pktout, c->remoteid);
7511 ssh2_pkt_addstring_start(pktout);
7512 ssh2_pkt_addstring_data(pktout, data, len);
7513 ssh2_pkt_send(ssh, pktout);
7514 bufchain_consume(&c->v.v2.outbuffer, len);
7515 c->v.v2.remwindow -= len;
7519 * After having sent as much data as we can, return the amount
7522 ret = bufchain_size(&c->v.v2.outbuffer);
7525 * And if there's no data pending but we need to send an EOF, send
7528 if (!ret && c->pending_eof)
7529 ssh_channel_try_eof(c);
7534 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7537 if (c->closes & CLOSES_SENT_EOF)
7538 return; /* don't send on channels we've EOFed */
7539 bufsize = ssh2_try_send(c);
7542 case CHAN_MAINSESSION:
7543 /* stdin need not receive an unthrottle
7544 * notification since it will be polled */
7547 x11_unthrottle(c->u.x11.xconn);
7550 /* agent sockets are request/response and need no
7551 * buffer management */
7554 pfd_unthrottle(c->u.pfd.pf);
7560 static int ssh_is_simple(Ssh ssh)
7563 * We use the 'simple' variant of the SSH protocol if we're asked
7564 * to, except not if we're also doing connection-sharing (either
7565 * tunnelling our packets over an upstream or expecting to be
7566 * tunnelled over ourselves), since then the assumption that we
7567 * have only one channel to worry about is not true after all.
7569 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7570 !ssh->bare_connection && !ssh->connshare);
7574 * Set up most of a new ssh_channel for SSH-2.
7576 static void ssh2_channel_init(struct ssh_channel *c)
7579 c->localid = alloc_channel_id(ssh);
7581 c->pending_eof = FALSE;
7582 c->throttling_conn = FALSE;
7583 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7584 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7585 c->v.v2.chanreq_head = NULL;
7586 c->v.v2.throttle_state = UNTHROTTLED;
7587 bufchain_init(&c->v.v2.outbuffer);
7591 * Construct the common parts of a CHANNEL_OPEN.
7593 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7596 struct Packet *pktout;
7598 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7599 ssh2_pkt_addstring(pktout, type);
7600 ssh2_pkt_adduint32(pktout, c->localid);
7601 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7602 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7607 * CHANNEL_FAILURE doesn't come with any indication of what message
7608 * caused it, so we have to keep track of the outstanding
7609 * CHANNEL_REQUESTs ourselves.
7611 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7612 cchandler_fn_t handler, void *ctx)
7614 struct outstanding_channel_request *ocr =
7615 snew(struct outstanding_channel_request);
7617 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7618 ocr->handler = handler;
7621 if (!c->v.v2.chanreq_head)
7622 c->v.v2.chanreq_head = ocr;
7624 c->v.v2.chanreq_tail->next = ocr;
7625 c->v.v2.chanreq_tail = ocr;
7629 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7630 * NULL then a reply will be requested and the handler will be called
7631 * when it arrives. The returned packet is ready to have any
7632 * request-specific data added and be sent. Note that if a handler is
7633 * provided, it's essential that the request actually be sent.
7635 * The handler will usually be passed the response packet in pktin. If
7636 * pktin is NULL, this means that no reply will ever be forthcoming
7637 * (e.g. because the entire connection is being destroyed, or because
7638 * the server initiated channel closure before we saw the response)
7639 * and the handler should free any storage it's holding.
7641 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7643 cchandler_fn_t handler, void *ctx)
7645 struct Packet *pktout;
7647 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7648 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7649 ssh2_pkt_adduint32(pktout, c->remoteid);
7650 ssh2_pkt_addstring(pktout, type);
7651 ssh2_pkt_addbool(pktout, handler != NULL);
7652 if (handler != NULL)
7653 ssh2_queue_chanreq_handler(c, handler, ctx);
7658 * Potentially enlarge the window on an SSH-2 channel.
7660 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7662 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7667 * Never send WINDOW_ADJUST for a channel that the remote side has
7668 * already sent EOF on; there's no point, since it won't be
7669 * sending any more data anyway. Ditto if _we've_ already sent
7672 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7676 * Also, never widen the window for an X11 channel when we're
7677 * still waiting to see its initial auth and may yet hand it off
7680 if (c->type == CHAN_X11 && c->u.x11.initial)
7684 * If the remote end has a habit of ignoring maxpkt, limit the
7685 * window so that it has no choice (assuming it doesn't ignore the
7688 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7689 newwin = OUR_V2_MAXPKT;
7692 * Only send a WINDOW_ADJUST if there's significantly more window
7693 * available than the other end thinks there is. This saves us
7694 * sending a WINDOW_ADJUST for every character in a shell session.
7696 * "Significant" is arbitrarily defined as half the window size.
7698 if (newwin / 2 >= c->v.v2.locwindow) {
7699 struct Packet *pktout;
7703 * In order to keep track of how much window the client
7704 * actually has available, we'd like it to acknowledge each
7705 * WINDOW_ADJUST. We can't do that directly, so we accompany
7706 * it with a CHANNEL_REQUEST that has to be acknowledged.
7708 * This is only necessary if we're opening the window wide.
7709 * If we're not, then throughput is being constrained by
7710 * something other than the maximum window size anyway.
7712 if (newwin == c->v.v2.locmaxwin &&
7713 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7714 up = snew(unsigned);
7715 *up = newwin - c->v.v2.locwindow;
7716 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7717 ssh2_handle_winadj_response, up);
7718 ssh2_pkt_send(ssh, pktout);
7720 if (c->v.v2.throttle_state != UNTHROTTLED)
7721 c->v.v2.throttle_state = UNTHROTTLING;
7723 /* Pretend the WINDOW_ADJUST was acked immediately. */
7724 c->v.v2.remlocwin = newwin;
7725 c->v.v2.throttle_state = THROTTLED;
7727 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7728 ssh2_pkt_adduint32(pktout, c->remoteid);
7729 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7730 ssh2_pkt_send(ssh, pktout);
7731 c->v.v2.locwindow = newwin;
7736 * Find the channel associated with a message. If there's no channel,
7737 * or it's not properly open, make a noise about it and return NULL.
7739 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7741 unsigned localid = ssh_pkt_getuint32(pktin);
7742 struct ssh_channel *c;
7744 c = find234(ssh->channels, &localid, ssh_channelfind);
7746 (c->type != CHAN_SHARING && c->halfopen &&
7747 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7748 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7749 char *buf = dupprintf("Received %s for %s channel %u",
7750 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7752 c ? "half-open" : "nonexistent", localid);
7753 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7760 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7761 struct Packet *pktin, void *ctx)
7763 unsigned *sizep = ctx;
7766 * Winadj responses should always be failures. However, at least
7767 * one server ("boks_sshd") is known to return SUCCESS for channel
7768 * requests it's never heard of, such as "winadj@putty". Raised
7769 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7770 * life, we don't worry about what kind of response we got.
7773 c->v.v2.remlocwin += *sizep;
7776 * winadj messages are only sent when the window is fully open, so
7777 * if we get an ack of one, we know any pending unthrottle is
7780 if (c->v.v2.throttle_state == UNTHROTTLING)
7781 c->v.v2.throttle_state = UNTHROTTLED;
7784 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
7786 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
7787 struct outstanding_channel_request *ocr;
7790 if (c->type == CHAN_SHARING) {
7791 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7792 pktin->body, pktin->length);
7795 ocr = c->v.v2.chanreq_head;
7797 ssh2_msg_unexpected(ssh, pktin);
7800 ocr->handler(c, pktin, ocr->ctx);
7801 c->v.v2.chanreq_head = ocr->next;
7804 * We may now initiate channel-closing procedures, if that
7805 * CHANNEL_REQUEST was the last thing outstanding before we send
7808 ssh2_channel_check_close(c);
7811 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
7813 struct ssh_channel *c;
7814 c = ssh2_channel_msg(ssh, pktin);
7817 if (c->type == CHAN_SHARING) {
7818 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7819 pktin->body, pktin->length);
7822 if (!(c->closes & CLOSES_SENT_EOF)) {
7823 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
7824 ssh2_try_send_and_unthrottle(ssh, c);
7828 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
7832 struct ssh_channel *c;
7833 c = ssh2_channel_msg(ssh, pktin);
7836 if (c->type == CHAN_SHARING) {
7837 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7838 pktin->body, pktin->length);
7841 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
7842 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
7843 return; /* extended but not stderr */
7844 ssh_pkt_getstring(pktin, &data, &length);
7847 c->v.v2.locwindow -= length;
7848 c->v.v2.remlocwin -= length;
7850 case CHAN_MAINSESSION:
7852 from_backend(ssh->frontend, pktin->type ==
7853 SSH2_MSG_CHANNEL_EXTENDED_DATA,
7857 bufsize = x11_send(c->u.x11.xconn, data, length);
7860 bufsize = pfd_send(c->u.pfd.pf, data, length);
7863 while (length > 0) {
7864 if (c->u.a.lensofar < 4) {
7865 unsigned int l = min(4 - c->u.a.lensofar,
7867 memcpy(c->u.a.msglen + c->u.a.lensofar,
7871 c->u.a.lensofar += l;
7873 if (c->u.a.lensofar == 4) {
7875 4 + GET_32BIT(c->u.a.msglen);
7876 c->u.a.message = snewn(c->u.a.totallen,
7878 memcpy(c->u.a.message, c->u.a.msglen, 4);
7880 if (c->u.a.lensofar >= 4 && length > 0) {
7882 min(c->u.a.totallen - c->u.a.lensofar,
7884 memcpy(c->u.a.message + c->u.a.lensofar,
7888 c->u.a.lensofar += l;
7890 if (c->u.a.lensofar == c->u.a.totallen) {
7893 c->u.a.outstanding_requests++;
7894 if (agent_query(c->u.a.message,
7897 ssh_agentf_callback, c))
7898 ssh_agentf_callback(c, reply, replylen);
7899 sfree(c->u.a.message);
7900 c->u.a.message = NULL;
7901 c->u.a.lensofar = 0;
7908 * If it looks like the remote end hit the end of its window,
7909 * and we didn't want it to do that, think about using a
7912 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
7913 c->v.v2.locmaxwin < 0x40000000)
7914 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
7916 * If we are not buffering too much data,
7917 * enlarge the window again at the remote side.
7918 * If we are buffering too much, we may still
7919 * need to adjust the window if the server's
7922 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7923 c->v.v2.locmaxwin - bufsize : 0);
7925 * If we're either buffering way too much data, or if we're
7926 * buffering anything at all and we're in "simple" mode,
7927 * throttle the whole channel.
7929 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
7930 && !c->throttling_conn) {
7931 c->throttling_conn = 1;
7932 ssh_throttle_conn(ssh, +1);
7937 static void ssh_check_termination(Ssh ssh)
7939 if (ssh->version == 2 &&
7940 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7941 (ssh->channels && count234(ssh->channels) == 0) &&
7942 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
7944 * We used to send SSH_MSG_DISCONNECT here, because I'd
7945 * believed that _every_ conforming SSH-2 connection had to
7946 * end with a disconnect being sent by at least one side;
7947 * apparently I was wrong and it's perfectly OK to
7948 * unceremoniously slam the connection shut when you're done,
7949 * and indeed OpenSSH feels this is more polite than sending a
7950 * DISCONNECT. So now we don't.
7952 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7956 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
7957 const char *peerinfo)
7960 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
7963 logeventf(ssh, "Connection sharing downstream #%u connected", id);
7966 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
7968 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
7969 ssh_check_termination(ssh);
7972 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
7977 va_start(ap, logfmt);
7978 buf = dupvprintf(logfmt, ap);
7981 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
7983 logeventf(ssh, "Connection sharing: %s", buf);
7987 static void ssh_channel_destroy(struct ssh_channel *c)
7992 case CHAN_MAINSESSION:
7993 ssh->mainchan = NULL;
7994 update_specials_menu(ssh->frontend);
7997 if (c->u.x11.xconn != NULL)
7998 x11_close(c->u.x11.xconn);
7999 logevent("Forwarded X11 connection terminated");
8002 sfree(c->u.a.message);
8005 if (c->u.pfd.pf != NULL)
8006 pfd_close(c->u.pfd.pf);
8007 logevent("Forwarded port closed");
8011 del234(ssh->channels, c);
8012 if (ssh->version == 2) {
8013 bufchain_clear(&c->v.v2.outbuffer);
8014 assert(c->v.v2.chanreq_head == NULL);
8019 * If that was the last channel left open, we might need to
8022 ssh_check_termination(ssh);
8025 static void ssh2_channel_check_close(struct ssh_channel *c)
8028 struct Packet *pktout;
8032 * If we've sent out our own CHANNEL_OPEN but not yet seen
8033 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8034 * it's too early to be sending close messages of any kind.
8039 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8040 c->type == CHAN_ZOMBIE) &&
8041 !c->v.v2.chanreq_head &&
8042 !(c->closes & CLOSES_SENT_CLOSE)) {
8044 * We have both sent and received EOF (or the channel is a
8045 * zombie), and we have no outstanding channel requests, which
8046 * means the channel is in final wind-up. But we haven't sent
8047 * CLOSE, so let's do so now.
8049 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8050 ssh2_pkt_adduint32(pktout, c->remoteid);
8051 ssh2_pkt_send(ssh, pktout);
8052 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8055 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8056 assert(c->v.v2.chanreq_head == NULL);
8058 * We have both sent and received CLOSE, which means we're
8059 * completely done with the channel.
8061 ssh_channel_destroy(c);
8065 static void ssh2_channel_got_eof(struct ssh_channel *c)
8067 if (c->closes & CLOSES_RCVD_EOF)
8068 return; /* already seen EOF */
8069 c->closes |= CLOSES_RCVD_EOF;
8071 if (c->type == CHAN_X11) {
8072 x11_send_eof(c->u.x11.xconn);
8073 } else if (c->type == CHAN_AGENT) {
8074 if (c->u.a.outstanding_requests == 0) {
8075 /* Manufacture an outgoing EOF in response to the incoming one. */
8076 sshfwd_write_eof(c);
8078 } else if (c->type == CHAN_SOCKDATA) {
8079 pfd_send_eof(c->u.pfd.pf);
8080 } else if (c->type == CHAN_MAINSESSION) {
8083 if (!ssh->sent_console_eof &&
8084 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8086 * Either from_backend_eof told us that the front end
8087 * wants us to close the outgoing side of the connection
8088 * as soon as we see EOF from the far end, or else we've
8089 * unilaterally decided to do that because we've allocated
8090 * a remote pty and hence EOF isn't a particularly
8091 * meaningful concept.
8093 sshfwd_write_eof(c);
8095 ssh->sent_console_eof = TRUE;
8098 ssh2_channel_check_close(c);
8101 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8103 struct ssh_channel *c;
8105 c = ssh2_channel_msg(ssh, pktin);
8108 if (c->type == CHAN_SHARING) {
8109 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8110 pktin->body, pktin->length);
8113 ssh2_channel_got_eof(c);
8116 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8118 struct ssh_channel *c;
8120 c = ssh2_channel_msg(ssh, pktin);
8123 if (c->type == CHAN_SHARING) {
8124 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8125 pktin->body, pktin->length);
8130 * When we receive CLOSE on a channel, we assume it comes with an
8131 * implied EOF if we haven't seen EOF yet.
8133 ssh2_channel_got_eof(c);
8135 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8137 * It also means we stop expecting to see replies to any
8138 * outstanding channel requests, so clean those up too.
8139 * (ssh_chanreq_init will enforce by assertion that we don't
8140 * subsequently put anything back on this list.)
8142 while (c->v.v2.chanreq_head) {
8143 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8144 ocr->handler(c, NULL, ocr->ctx);
8145 c->v.v2.chanreq_head = ocr->next;
8151 * And we also send an outgoing EOF, if we haven't already, on the
8152 * assumption that CLOSE is a pretty forceful announcement that
8153 * the remote side is doing away with the entire channel. (If it
8154 * had wanted to send us EOF and continue receiving data from us,
8155 * it would have just sent CHANNEL_EOF.)
8157 if (!(c->closes & CLOSES_SENT_EOF)) {
8159 * Make sure we don't read any more from whatever our local
8160 * data source is for this channel.
8163 case CHAN_MAINSESSION:
8164 ssh->send_ok = 0; /* stop trying to read from stdin */
8167 x11_override_throttle(c->u.x11.xconn, 1);
8170 pfd_override_throttle(c->u.pfd.pf, 1);
8175 * Abandon any buffered data we still wanted to send to this
8176 * channel. Receiving a CHANNEL_CLOSE is an indication that
8177 * the server really wants to get on and _destroy_ this
8178 * channel, and it isn't going to send us any further
8179 * WINDOW_ADJUSTs to permit us to send pending stuff.
8181 bufchain_clear(&c->v.v2.outbuffer);
8184 * Send outgoing EOF.
8186 sshfwd_write_eof(c);
8190 * Now process the actual close.
8192 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8193 c->closes |= CLOSES_RCVD_CLOSE;
8194 ssh2_channel_check_close(c);
8198 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8200 struct ssh_channel *c;
8202 c = ssh2_channel_msg(ssh, pktin);
8205 if (c->type == CHAN_SHARING) {
8206 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8207 pktin->body, pktin->length);
8210 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8211 c->remoteid = ssh_pkt_getuint32(pktin);
8212 c->halfopen = FALSE;
8213 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8214 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8216 if (c->type == CHAN_SOCKDATA_DORMANT) {
8217 c->type = CHAN_SOCKDATA;
8219 pfd_confirm(c->u.pfd.pf);
8220 } else if (c->type == CHAN_ZOMBIE) {
8222 * This case can occur if a local socket error occurred
8223 * between us sending out CHANNEL_OPEN and receiving
8224 * OPEN_CONFIRMATION. In this case, all we can do is
8225 * immediately initiate close proceedings now that we know the
8226 * server's id to put in the close message.
8228 ssh2_channel_check_close(c);
8231 * We never expect to receive OPEN_CONFIRMATION for any
8232 * *other* channel type (since only local-to-remote port
8233 * forwardings cause us to send CHANNEL_OPEN after the main
8234 * channel is live - all other auxiliary channel types are
8235 * initiated from the server end). It's safe to enforce this
8236 * by assertion rather than by ssh_disconnect, because the
8237 * real point is that we never constructed a half-open channel
8238 * structure in the first place with any type other than the
8241 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8245 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8248 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8250 static const char *const reasons[] = {
8251 "<unknown reason code>",
8252 "Administratively prohibited",
8254 "Unknown channel type",
8255 "Resource shortage",
8257 unsigned reason_code;
8258 char *reason_string;
8260 struct ssh_channel *c;
8262 c = ssh2_channel_msg(ssh, pktin);
8265 if (c->type == CHAN_SHARING) {
8266 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8267 pktin->body, pktin->length);
8270 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8272 if (c->type == CHAN_SOCKDATA_DORMANT) {
8273 reason_code = ssh_pkt_getuint32(pktin);
8274 if (reason_code >= lenof(reasons))
8275 reason_code = 0; /* ensure reasons[reason_code] in range */
8276 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8277 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8278 reasons[reason_code], reason_length, reason_string);
8280 pfd_close(c->u.pfd.pf);
8281 } else if (c->type == CHAN_ZOMBIE) {
8283 * This case can occur if a local socket error occurred
8284 * between us sending out CHANNEL_OPEN and receiving
8285 * OPEN_FAILURE. In this case, we need do nothing except allow
8286 * the code below to throw the half-open channel away.
8290 * We never expect to receive OPEN_FAILURE for any *other*
8291 * channel type (since only local-to-remote port forwardings
8292 * cause us to send CHANNEL_OPEN after the main channel is
8293 * live - all other auxiliary channel types are initiated from
8294 * the server end). It's safe to enforce this by assertion
8295 * rather than by ssh_disconnect, because the real point is
8296 * that we never constructed a half-open channel structure in
8297 * the first place with any type other than the above.
8299 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8302 del234(ssh->channels, c);
8306 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8309 int typelen, want_reply;
8310 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8311 struct ssh_channel *c;
8312 struct Packet *pktout;
8314 c = ssh2_channel_msg(ssh, pktin);
8317 if (c->type == CHAN_SHARING) {
8318 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8319 pktin->body, pktin->length);
8322 ssh_pkt_getstring(pktin, &type, &typelen);
8323 want_reply = ssh2_pkt_getbool(pktin);
8325 if (c->closes & CLOSES_SENT_CLOSE) {
8327 * We don't reply to channel requests after we've sent
8328 * CHANNEL_CLOSE for the channel, because our reply might
8329 * cross in the network with the other side's CHANNEL_CLOSE
8330 * and arrive after they have wound the channel up completely.
8336 * Having got the channel number, we now look at
8337 * the request type string to see if it's something
8340 if (c == ssh->mainchan) {
8342 * We recognise "exit-status" and "exit-signal" on
8343 * the primary channel.
8345 if (typelen == 11 &&
8346 !memcmp(type, "exit-status", 11)) {
8348 ssh->exitcode = ssh_pkt_getuint32(pktin);
8349 logeventf(ssh, "Server sent command exit status %d",
8351 reply = SSH2_MSG_CHANNEL_SUCCESS;
8353 } else if (typelen == 11 &&
8354 !memcmp(type, "exit-signal", 11)) {
8356 int is_plausible = TRUE, is_int = FALSE;
8357 char *fmt_sig = NULL, *fmt_msg = NULL;
8359 int msglen = 0, core = FALSE;
8360 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8361 * provide an `int' for the signal, despite its
8362 * having been a `string' in the drafts of RFC 4254 since at
8363 * least 2001. (Fixed in session.c 1.147.) Try to
8364 * infer which we can safely parse it as. */
8366 unsigned char *p = pktin->body +
8368 long len = pktin->length - pktin->savedpos;
8369 unsigned long num = GET_32BIT(p); /* what is it? */
8370 /* If it's 0, it hardly matters; assume string */
8374 int maybe_int = FALSE, maybe_str = FALSE;
8375 #define CHECK_HYPOTHESIS(offset, result) \
8378 int q = toint(offset); \
8379 if (q >= 0 && q+4 <= len) { \
8380 q = toint(q + 4 + GET_32BIT(p+q)); \
8381 if (q >= 0 && q+4 <= len && \
8382 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8387 CHECK_HYPOTHESIS(4+1, maybe_int);
8388 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8389 #undef CHECK_HYPOTHESIS
8390 if (maybe_int && !maybe_str)
8392 else if (!maybe_int && maybe_str)
8395 /* Crikey. Either or neither. Panic. */
8396 is_plausible = FALSE;
8399 ssh->exitcode = 128; /* means `unknown signal' */
8402 /* Old non-standard OpenSSH. */
8403 int signum = ssh_pkt_getuint32(pktin);
8404 fmt_sig = dupprintf(" %d", signum);
8405 ssh->exitcode = 128 + signum;
8407 /* As per RFC 4254. */
8410 ssh_pkt_getstring(pktin, &sig, &siglen);
8411 /* Signal name isn't supposed to be blank, but
8412 * let's cope gracefully if it is. */
8414 fmt_sig = dupprintf(" \"%.*s\"",
8419 * Really hideous method of translating the
8420 * signal description back into a locally
8421 * meaningful number.
8426 #define TRANSLATE_SIGNAL(s) \
8427 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8428 ssh->exitcode = 128 + SIG ## s
8430 TRANSLATE_SIGNAL(ABRT);
8433 TRANSLATE_SIGNAL(ALRM);
8436 TRANSLATE_SIGNAL(FPE);
8439 TRANSLATE_SIGNAL(HUP);
8442 TRANSLATE_SIGNAL(ILL);
8445 TRANSLATE_SIGNAL(INT);
8448 TRANSLATE_SIGNAL(KILL);
8451 TRANSLATE_SIGNAL(PIPE);
8454 TRANSLATE_SIGNAL(QUIT);
8457 TRANSLATE_SIGNAL(SEGV);
8460 TRANSLATE_SIGNAL(TERM);
8463 TRANSLATE_SIGNAL(USR1);
8466 TRANSLATE_SIGNAL(USR2);
8468 #undef TRANSLATE_SIGNAL
8470 ssh->exitcode = 128;
8472 core = ssh2_pkt_getbool(pktin);
8473 ssh_pkt_getstring(pktin, &msg, &msglen);
8475 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8477 /* ignore lang tag */
8478 } /* else don't attempt to parse */
8479 logeventf(ssh, "Server exited on signal%s%s%s",
8480 fmt_sig ? fmt_sig : "",
8481 core ? " (core dumped)" : "",
8482 fmt_msg ? fmt_msg : "");
8485 reply = SSH2_MSG_CHANNEL_SUCCESS;
8490 * This is a channel request we don't know
8491 * about, so we now either ignore the request
8492 * or respond with CHANNEL_FAILURE, depending
8495 reply = SSH2_MSG_CHANNEL_FAILURE;
8498 pktout = ssh2_pkt_init(reply);
8499 ssh2_pkt_adduint32(pktout, c->remoteid);
8500 ssh2_pkt_send(ssh, pktout);
8504 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8507 int typelen, want_reply;
8508 struct Packet *pktout;
8510 ssh_pkt_getstring(pktin, &type, &typelen);
8511 want_reply = ssh2_pkt_getbool(pktin);
8514 * We currently don't support any global requests
8515 * at all, so we either ignore the request or
8516 * respond with REQUEST_FAILURE, depending on
8520 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8521 ssh2_pkt_send(ssh, pktout);
8525 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8529 struct X11FakeAuth *auth;
8532 * Make up a new set of fake X11 auth data, and add it to the tree
8533 * of currently valid ones with an indication of the sharing
8534 * context that it's relevant to.
8536 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8537 auth->share_cs = share_cs;
8538 auth->share_chan = share_chan;
8543 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8545 del234(ssh->x11authtree, auth);
8546 x11_free_fake_auth(auth);
8549 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8556 const char *error = NULL;
8557 struct ssh_channel *c;
8558 unsigned remid, winsize, pktsize;
8559 unsigned our_winsize_override = 0;
8560 struct Packet *pktout;
8562 ssh_pkt_getstring(pktin, &type, &typelen);
8563 c = snew(struct ssh_channel);
8566 remid = ssh_pkt_getuint32(pktin);
8567 winsize = ssh_pkt_getuint32(pktin);
8568 pktsize = ssh_pkt_getuint32(pktin);
8570 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8573 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8574 addrstr = snewn(peeraddrlen+1, char);
8575 memcpy(addrstr, peeraddr, peeraddrlen);
8576 addrstr[peeraddrlen] = '\0';
8577 peerport = ssh_pkt_getuint32(pktin);
8579 logeventf(ssh, "Received X11 connect request from %s:%d",
8582 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8583 error = "X11 forwarding is not enabled";
8585 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8588 c->u.x11.initial = TRUE;
8591 * If we are a connection-sharing upstream, then we should
8592 * initially present a very small window, adequate to take
8593 * the X11 initial authorisation packet but not much more.
8594 * Downstream will then present us a larger window (by
8595 * fiat of the connection-sharing protocol) and we can
8596 * guarantee to send a positive-valued WINDOW_ADJUST.
8599 our_winsize_override = 128;
8601 logevent("Opened X11 forward channel");
8605 } else if (typelen == 15 &&
8606 !memcmp(type, "forwarded-tcpip", 15)) {
8607 struct ssh_rportfwd pf, *realpf;
8610 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8611 pf.shost = dupprintf("%.*s", shostlen, shost);
8612 pf.sport = ssh_pkt_getuint32(pktin);
8613 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8614 peerport = ssh_pkt_getuint32(pktin);
8615 realpf = find234(ssh->rportfwds, &pf, NULL);
8616 logeventf(ssh, "Received remote port %s:%d open request "
8617 "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
8620 if (realpf == NULL) {
8621 error = "Remote port is not recognised";
8625 if (realpf->share_ctx) {
8627 * This port forwarding is on behalf of a
8628 * connection-sharing downstream, so abandon our own
8629 * channel-open procedure and just pass the message on
8632 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8633 pktin->body, pktin->length);
8638 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8639 c, ssh->conf, realpf->pfrec->addressfamily);
8640 logeventf(ssh, "Attempting to forward remote port to "
8641 "%s:%d", realpf->dhost, realpf->dport);
8643 logeventf(ssh, "Port open failed: %s", err);
8645 error = "Port open failed";
8647 logevent("Forwarded port opened successfully");
8648 c->type = CHAN_SOCKDATA;
8651 } else if (typelen == 22 &&
8652 !memcmp(type, "auth-agent@openssh.com", 22)) {
8653 if (!ssh->agentfwd_enabled)
8654 error = "Agent forwarding is not enabled";
8656 c->type = CHAN_AGENT; /* identify channel type */
8657 c->u.a.lensofar = 0;
8658 c->u.a.message = NULL;
8659 c->u.a.outstanding_requests = 0;
8662 error = "Unsupported channel type requested";
8665 c->remoteid = remid;
8666 c->halfopen = FALSE;
8668 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8669 ssh2_pkt_adduint32(pktout, c->remoteid);
8670 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8671 ssh2_pkt_addstring(pktout, error);
8672 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8673 ssh2_pkt_send(ssh, pktout);
8674 logeventf(ssh, "Rejected channel open: %s", error);
8677 ssh2_channel_init(c);
8678 c->v.v2.remwindow = winsize;
8679 c->v.v2.remmaxpkt = pktsize;
8680 if (our_winsize_override) {
8681 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8682 our_winsize_override;
8684 add234(ssh->channels, c);
8685 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8686 ssh2_pkt_adduint32(pktout, c->remoteid);
8687 ssh2_pkt_adduint32(pktout, c->localid);
8688 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8689 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8690 ssh2_pkt_send(ssh, pktout);
8694 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8695 void *share_cs, void *share_chan,
8696 const char *peer_addr, int peer_port,
8697 int endian, int protomajor, int protominor,
8698 const void *initial_data, int initial_len)
8701 * This function is called when we've just discovered that an X
8702 * forwarding channel on which we'd been handling the initial auth
8703 * ourselves turns out to be destined for a connection-sharing
8704 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8705 * that we completely stop tracking windows and buffering data and
8706 * just pass more or less unmodified SSH messages back and forth.
8708 c->type = CHAN_SHARING;
8709 c->u.sharing.ctx = share_cs;
8710 share_setup_x11_channel(share_cs, share_chan,
8711 c->localid, c->remoteid, c->v.v2.remwindow,
8712 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8713 peer_addr, peer_port, endian,
8714 protomajor, protominor,
8715 initial_data, initial_len);
8718 void sshfwd_x11_is_local(struct ssh_channel *c)
8721 * This function is called when we've just discovered that an X
8722 * forwarding channel is _not_ destined for a connection-sharing
8723 * downstream but we're going to handle it ourselves. We stop
8724 * presenting a cautiously small window and go into ordinary data
8727 c->u.x11.initial = FALSE;
8728 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8732 * Buffer banner messages for later display at some convenient point,
8733 * if we're going to display them.
8735 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8737 /* Arbitrary limit to prevent unbounded inflation of buffer */
8738 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8739 bufchain_size(&ssh->banner) <= 131072) {
8740 char *banner = NULL;
8742 ssh_pkt_getstring(pktin, &banner, &size);
8744 bufchain_add(&ssh->banner, banner, size);
8748 /* Helper function to deal with sending tty modes for "pty-req" */
8749 static void ssh2_send_ttymode(void *data, char *mode, char *val)
8751 struct Packet *pktout = (struct Packet *)data;
8753 unsigned int arg = 0;
8754 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
8755 if (i == lenof(ssh_ttymodes)) return;
8756 switch (ssh_ttymodes[i].type) {
8758 arg = ssh_tty_parse_specchar(val);
8761 arg = ssh_tty_parse_boolean(val);
8764 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
8765 ssh2_pkt_adduint32(pktout, arg);
8768 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8771 struct ssh2_setup_x11_state {
8775 struct Packet *pktout;
8776 crStateP(ssh2_setup_x11_state, ctx);
8780 logevent("Requesting X11 forwarding");
8781 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8783 ssh2_pkt_addbool(pktout, 0); /* many connections */
8784 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8785 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8786 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8787 ssh2_pkt_send(ssh, pktout);
8789 /* Wait to be called back with either a response packet, or NULL
8790 * meaning clean up and free our data */
8794 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8795 logevent("X11 forwarding enabled");
8796 ssh->X11_fwd_enabled = TRUE;
8798 logevent("X11 forwarding refused");
8804 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8807 struct ssh2_setup_agent_state {
8811 struct Packet *pktout;
8812 crStateP(ssh2_setup_agent_state, ctx);
8816 logevent("Requesting OpenSSH-style agent forwarding");
8817 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8818 ssh2_setup_agent, s);
8819 ssh2_pkt_send(ssh, pktout);
8821 /* Wait to be called back with either a response packet, or NULL
8822 * meaning clean up and free our data */
8826 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8827 logevent("Agent forwarding enabled");
8828 ssh->agentfwd_enabled = TRUE;
8830 logevent("Agent forwarding refused");
8836 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8839 struct ssh2_setup_pty_state {
8843 struct Packet *pktout;
8844 crStateP(ssh2_setup_pty_state, ctx);
8848 /* Unpick the terminal-speed string. */
8849 /* XXX perhaps we should allow no speeds to be sent. */
8850 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8851 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8852 /* Build the pty request. */
8853 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
8855 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
8856 ssh2_pkt_adduint32(pktout, ssh->term_width);
8857 ssh2_pkt_adduint32(pktout, ssh->term_height);
8858 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
8859 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
8860 ssh2_pkt_addstring_start(pktout);
8861 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
8862 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
8863 ssh2_pkt_adduint32(pktout, ssh->ispeed);
8864 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
8865 ssh2_pkt_adduint32(pktout, ssh->ospeed);
8866 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
8867 ssh2_pkt_send(ssh, pktout);
8868 ssh->state = SSH_STATE_INTERMED;
8870 /* Wait to be called back with either a response packet, or NULL
8871 * meaning clean up and free our data */
8875 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8876 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8877 ssh->ospeed, ssh->ispeed);
8878 ssh->got_pty = TRUE;
8880 c_write_str(ssh, "Server refused to allocate pty\r\n");
8881 ssh->editing = ssh->echoing = 1;
8888 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
8891 struct ssh2_setup_env_state {
8893 int num_env, env_left, env_ok;
8896 struct Packet *pktout;
8897 crStateP(ssh2_setup_env_state, ctx);
8902 * Send environment variables.
8904 * Simplest thing here is to send all the requests at once, and
8905 * then wait for a whole bunch of successes or failures.
8911 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
8913 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
8914 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
8915 ssh2_pkt_addstring(pktout, key);
8916 ssh2_pkt_addstring(pktout, val);
8917 ssh2_pkt_send(ssh, pktout);
8922 logeventf(ssh, "Sent %d environment variables", s->num_env);
8927 s->env_left = s->num_env;
8929 while (s->env_left > 0) {
8930 /* Wait to be called back with either a response packet,
8931 * or NULL meaning clean up and free our data */
8933 if (!pktin) goto out;
8934 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
8939 if (s->env_ok == s->num_env) {
8940 logevent("All environment variables successfully set");
8941 } else if (s->env_ok == 0) {
8942 logevent("All environment variables refused");
8943 c_write_str(ssh, "Server refused to set environment variables\r\n");
8945 logeventf(ssh, "%d environment variables refused",
8946 s->num_env - s->env_ok);
8947 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8955 * Handle the SSH-2 userauth and connection layers.
8957 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
8959 do_ssh2_authconn(ssh, NULL, 0, pktin);
8962 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
8966 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
8969 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
8970 struct Packet *pktin)
8972 struct do_ssh2_authconn_state {
8976 AUTH_TYPE_PUBLICKEY,
8977 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
8978 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
8980 AUTH_TYPE_GSSAPI, /* always QUIET */
8981 AUTH_TYPE_KEYBOARD_INTERACTIVE,
8982 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
8984 int done_service_req;
8985 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
8986 int tried_pubkey_config, done_agent;
8991 int kbd_inter_refused;
8992 int we_are_in, userauth_success;
8993 prompts_t *cur_prompt;
8998 void *publickey_blob;
8999 int publickey_bloblen;
9000 int privatekey_available, privatekey_encrypted;
9001 char *publickey_algorithm;
9002 char *publickey_comment;
9003 unsigned char agent_request[5], *agent_response, *agentp;
9004 int agent_responselen;
9005 unsigned char *pkblob_in_agent;
9007 char *pkblob, *alg, *commentp;
9008 int pklen, alglen, commentlen;
9009 int siglen, retlen, len;
9010 char *q, *agentreq, *ret;
9012 struct Packet *pktout;
9015 struct ssh_gss_library *gsslib;
9016 Ssh_gss_ctx gss_ctx;
9017 Ssh_gss_buf gss_buf;
9018 Ssh_gss_buf gss_rcvtok, gss_sndtok;
9019 Ssh_gss_name gss_srv_name;
9020 Ssh_gss_stat gss_stat;
9023 crState(do_ssh2_authconn_state);
9027 /* Register as a handler for all the messages this coroutine handles. */
9028 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9029 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9030 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9031 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9032 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9033 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9034 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9035 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9036 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9037 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9038 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9039 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9040 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9041 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9042 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9043 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9044 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9045 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9046 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9047 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9049 s->done_service_req = FALSE;
9050 s->we_are_in = s->userauth_success = FALSE;
9051 s->agent_response = NULL;
9053 s->tried_gssapi = FALSE;
9056 if (!ssh->bare_connection) {
9057 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9059 * Request userauth protocol, and await a response to it.
9061 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9062 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9063 ssh2_pkt_send(ssh, s->pktout);
9064 crWaitUntilV(pktin);
9065 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9066 s->done_service_req = TRUE;
9068 if (!s->done_service_req) {
9070 * Request connection protocol directly, without authentication.
9072 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9073 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9074 ssh2_pkt_send(ssh, s->pktout);
9075 crWaitUntilV(pktin);
9076 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9077 s->we_are_in = TRUE; /* no auth required */
9079 bombout(("Server refused service request"));
9084 s->we_are_in = TRUE;
9087 /* Arrange to be able to deal with any BANNERs that come in.
9088 * (We do this now as packets may come in during the next bit.) */
9089 bufchain_init(&ssh->banner);
9090 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9091 ssh2_msg_userauth_banner;
9094 * Misc one-time setup for authentication.
9096 s->publickey_blob = NULL;
9097 if (!s->we_are_in) {
9100 * Load the public half of any configured public key file
9103 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9104 if (!filename_is_null(s->keyfile)) {
9106 logeventf(ssh, "Reading key file \"%.150s\"",
9107 filename_to_str(s->keyfile));
9108 keytype = key_type(s->keyfile);
9109 if (keytype == SSH_KEYTYPE_SSH2 ||
9110 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9111 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9114 ssh2_userkey_loadpub(s->keyfile,
9115 &s->publickey_algorithm,
9116 &s->publickey_bloblen,
9117 &s->publickey_comment, &error);
9118 if (s->publickey_blob) {
9119 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9120 if (!s->privatekey_available)
9121 logeventf(ssh, "Key file contains public key only");
9122 s->privatekey_encrypted =
9123 ssh2_userkey_encrypted(s->keyfile, NULL);
9126 logeventf(ssh, "Unable to load key (%s)",
9128 msgbuf = dupprintf("Unable to load key file "
9129 "\"%.150s\" (%s)\r\n",
9130 filename_to_str(s->keyfile),
9132 c_write_str(ssh, msgbuf);
9137 logeventf(ssh, "Unable to use this key file (%s)",
9138 key_type_to_str(keytype));
9139 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9141 filename_to_str(s->keyfile),
9142 key_type_to_str(keytype));
9143 c_write_str(ssh, msgbuf);
9145 s->publickey_blob = NULL;
9150 * Find out about any keys Pageant has (but if there's a
9151 * public key configured, filter out all others).
9154 s->agent_response = NULL;
9155 s->pkblob_in_agent = NULL;
9156 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9160 logevent("Pageant is running. Requesting keys.");
9162 /* Request the keys held by the agent. */
9163 PUT_32BIT(s->agent_request, 1);
9164 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9165 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9166 ssh_agent_callback, ssh)) {
9170 bombout(("Unexpected data from server while"
9171 " waiting for agent response"));
9174 } while (pktin || inlen > 0);
9175 r = ssh->agent_response;
9176 s->agent_responselen = ssh->agent_response_len;
9178 s->agent_response = (unsigned char *) r;
9179 if (s->agent_response && s->agent_responselen >= 5 &&
9180 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9183 p = s->agent_response + 5;
9184 s->nkeys = toint(GET_32BIT(p));
9187 * Vet the Pageant response to ensure that the key
9188 * count and blob lengths make sense.
9191 logeventf(ssh, "Pageant response contained a negative"
9192 " key count %d", s->nkeys);
9194 goto done_agent_query;
9196 unsigned char *q = p + 4;
9197 int lenleft = s->agent_responselen - 5 - 4;
9199 for (keyi = 0; keyi < s->nkeys; keyi++) {
9200 int bloblen, commentlen;
9202 logeventf(ssh, "Pageant response was truncated");
9204 goto done_agent_query;
9206 bloblen = toint(GET_32BIT(q));
9207 if (bloblen < 0 || bloblen > lenleft) {
9208 logeventf(ssh, "Pageant response was truncated");
9210 goto done_agent_query;
9212 lenleft -= 4 + bloblen;
9214 commentlen = toint(GET_32BIT(q));
9215 if (commentlen < 0 || commentlen > lenleft) {
9216 logeventf(ssh, "Pageant response was truncated");
9218 goto done_agent_query;
9220 lenleft -= 4 + commentlen;
9221 q += 4 + commentlen;
9226 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9227 if (s->publickey_blob) {
9228 /* See if configured key is in agent. */
9229 for (keyi = 0; keyi < s->nkeys; keyi++) {
9230 s->pklen = toint(GET_32BIT(p));
9231 if (s->pklen == s->publickey_bloblen &&
9232 !memcmp(p+4, s->publickey_blob,
9233 s->publickey_bloblen)) {
9234 logeventf(ssh, "Pageant key #%d matches "
9235 "configured key file", keyi);
9237 s->pkblob_in_agent = p;
9241 p += toint(GET_32BIT(p)) + 4; /* comment */
9243 if (!s->pkblob_in_agent) {
9244 logevent("Configured key file not in Pageant");
9249 logevent("Failed to get reply from Pageant");
9257 * We repeat this whole loop, including the username prompt,
9258 * until we manage a successful authentication. If the user
9259 * types the wrong _password_, they can be sent back to the
9260 * beginning to try another username, if this is configured on.
9261 * (If they specify a username in the config, they are never
9262 * asked, even if they do give a wrong password.)
9264 * I think this best serves the needs of
9266 * - the people who have no configuration, no keys, and just
9267 * want to try repeated (username,password) pairs until they
9268 * type both correctly
9270 * - people who have keys and configuration but occasionally
9271 * need to fall back to passwords
9273 * - people with a key held in Pageant, who might not have
9274 * logged in to a particular machine before; so they want to
9275 * type a username, and then _either_ their key will be
9276 * accepted, _or_ they will type a password. If they mistype
9277 * the username they will want to be able to get back and
9280 s->got_username = FALSE;
9281 while (!s->we_are_in) {
9285 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9287 * We got a username last time round this loop, and
9288 * with change_username turned off we don't try to get
9291 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9292 int ret; /* need not be kept over crReturn */
9293 s->cur_prompt = new_prompts(ssh->frontend);
9294 s->cur_prompt->to_server = TRUE;
9295 s->cur_prompt->name = dupstr("SSH login name");
9296 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9297 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9300 crWaitUntilV(!pktin);
9301 ret = get_userpass_input(s->cur_prompt, in, inlen);
9306 * get_userpass_input() failed to get a username.
9309 free_prompts(s->cur_prompt);
9310 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9313 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9314 free_prompts(s->cur_prompt);
9317 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9318 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9319 c_write_str(ssh, stuff);
9323 s->got_username = TRUE;
9326 * Send an authentication request using method "none": (a)
9327 * just in case it succeeds, and (b) so that we know what
9328 * authentication methods we can usefully try next.
9330 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9332 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9333 ssh2_pkt_addstring(s->pktout, ssh->username);
9334 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9335 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9336 ssh2_pkt_send(ssh, s->pktout);
9337 s->type = AUTH_TYPE_NONE;
9339 s->we_are_in = FALSE;
9341 s->tried_pubkey_config = FALSE;
9342 s->kbd_inter_refused = FALSE;
9344 /* Reset agent request state. */
9345 s->done_agent = FALSE;
9346 if (s->agent_response) {
9347 if (s->pkblob_in_agent) {
9348 s->agentp = s->pkblob_in_agent;
9350 s->agentp = s->agent_response + 5 + 4;
9356 char *methods = NULL;
9360 * Wait for the result of the last authentication request.
9363 crWaitUntilV(pktin);
9365 * Now is a convenient point to spew any banner material
9366 * that we've accumulated. (This should ensure that when
9367 * we exit the auth loop, we haven't any left to deal
9371 int size = bufchain_size(&ssh->banner);
9373 * Don't show the banner if we're operating in
9374 * non-verbose non-interactive mode. (It's probably
9375 * a script, which means nobody will read the
9376 * banner _anyway_, and moreover the printing of
9377 * the banner will screw up processing on the
9378 * output of (say) plink.)
9380 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9381 char *banner = snewn(size, char);
9382 bufchain_fetch(&ssh->banner, banner, size);
9383 c_write_untrusted(ssh, banner, size);
9386 bufchain_clear(&ssh->banner);
9388 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9389 logevent("Access granted");
9390 s->we_are_in = s->userauth_success = TRUE;
9394 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9395 bombout(("Strange packet received during authentication: "
9396 "type %d", pktin->type));
9403 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9404 * we can look at the string in it and know what we can
9405 * helpfully try next.
9407 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9408 ssh_pkt_getstring(pktin, &methods, &methlen);
9409 if (!ssh2_pkt_getbool(pktin)) {
9411 * We have received an unequivocal Access
9412 * Denied. This can translate to a variety of
9413 * messages, or no message at all.
9415 * For forms of authentication which are attempted
9416 * implicitly, by which I mean without printing
9417 * anything in the window indicating that we're
9418 * trying them, we should never print 'Access
9421 * If we do print a message saying that we're
9422 * attempting some kind of authentication, it's OK
9423 * to print a followup message saying it failed -
9424 * but the message may sometimes be more specific
9425 * than simply 'Access denied'.
9427 * Additionally, if we'd just tried password
9428 * authentication, we should break out of this
9429 * whole loop so as to go back to the username
9430 * prompt (iff we're configured to allow
9431 * username change attempts).
9433 if (s->type == AUTH_TYPE_NONE) {
9435 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9436 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9437 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9438 c_write_str(ssh, "Server refused our key\r\n");
9439 logevent("Server refused our key");
9440 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9441 /* This _shouldn't_ happen except by a
9442 * protocol bug causing client and server to
9443 * disagree on what is a correct signature. */
9444 c_write_str(ssh, "Server refused public-key signature"
9445 " despite accepting key!\r\n");
9446 logevent("Server refused public-key signature"
9447 " despite accepting key!");
9448 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9449 /* quiet, so no c_write */
9450 logevent("Server refused keyboard-interactive authentication");
9451 } else if (s->type==AUTH_TYPE_GSSAPI) {
9452 /* always quiet, so no c_write */
9453 /* also, the code down in the GSSAPI block has
9454 * already logged this in the Event Log */
9455 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9456 logevent("Keyboard-interactive authentication failed");
9457 c_write_str(ssh, "Access denied\r\n");
9459 assert(s->type == AUTH_TYPE_PASSWORD);
9460 logevent("Password authentication failed");
9461 c_write_str(ssh, "Access denied\r\n");
9463 if (conf_get_int(ssh->conf, CONF_change_username)) {
9464 /* XXX perhaps we should allow
9465 * keyboard-interactive to do this too? */
9466 s->we_are_in = FALSE;
9471 c_write_str(ssh, "Further authentication required\r\n");
9472 logevent("Further authentication required");
9476 in_commasep_string("publickey", methods, methlen);
9478 in_commasep_string("password", methods, methlen);
9479 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9480 in_commasep_string("keyboard-interactive", methods, methlen);
9482 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9483 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9484 /* Try loading the GSS libraries and see if we
9487 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9488 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9490 /* No point in even bothering to try to load the
9491 * GSS libraries, if the user configuration and
9492 * server aren't both prepared to attempt GSSAPI
9493 * auth in the first place. */
9494 s->can_gssapi = FALSE;
9499 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9501 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9504 * Attempt public-key authentication using a key from Pageant.
9507 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9509 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9511 /* Unpack key from agent response */
9512 s->pklen = toint(GET_32BIT(s->agentp));
9514 s->pkblob = (char *)s->agentp;
9515 s->agentp += s->pklen;
9516 s->alglen = toint(GET_32BIT(s->pkblob));
9517 s->alg = s->pkblob + 4;
9518 s->commentlen = toint(GET_32BIT(s->agentp));
9520 s->commentp = (char *)s->agentp;
9521 s->agentp += s->commentlen;
9522 /* s->agentp now points at next key, if any */
9524 /* See if server will accept it */
9525 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9526 ssh2_pkt_addstring(s->pktout, ssh->username);
9527 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9528 /* service requested */
9529 ssh2_pkt_addstring(s->pktout, "publickey");
9531 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9532 ssh2_pkt_addstring_start(s->pktout);
9533 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9534 ssh2_pkt_addstring_start(s->pktout);
9535 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9536 ssh2_pkt_send(ssh, s->pktout);
9537 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9539 crWaitUntilV(pktin);
9540 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9542 /* Offer of key refused. */
9549 if (flags & FLAG_VERBOSE) {
9550 c_write_str(ssh, "Authenticating with "
9552 c_write(ssh, s->commentp, s->commentlen);
9553 c_write_str(ssh, "\" from agent\r\n");
9557 * Server is willing to accept the key.
9558 * Construct a SIGN_REQUEST.
9560 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9561 ssh2_pkt_addstring(s->pktout, ssh->username);
9562 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9563 /* service requested */
9564 ssh2_pkt_addstring(s->pktout, "publickey");
9566 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9567 ssh2_pkt_addstring_start(s->pktout);
9568 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9569 ssh2_pkt_addstring_start(s->pktout);
9570 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9572 /* Ask agent for signature. */
9573 s->siglen = s->pktout->length - 5 + 4 +
9574 ssh->v2_session_id_len;
9575 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9577 s->len = 1; /* message type */
9578 s->len += 4 + s->pklen; /* key blob */
9579 s->len += 4 + s->siglen; /* data to sign */
9580 s->len += 4; /* flags */
9581 s->agentreq = snewn(4 + s->len, char);
9582 PUT_32BIT(s->agentreq, s->len);
9583 s->q = s->agentreq + 4;
9584 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9585 PUT_32BIT(s->q, s->pklen);
9587 memcpy(s->q, s->pkblob, s->pklen);
9589 PUT_32BIT(s->q, s->siglen);
9591 /* Now the data to be signed... */
9592 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9593 PUT_32BIT(s->q, ssh->v2_session_id_len);
9596 memcpy(s->q, ssh->v2_session_id,
9597 ssh->v2_session_id_len);
9598 s->q += ssh->v2_session_id_len;
9599 memcpy(s->q, s->pktout->data + 5,
9600 s->pktout->length - 5);
9601 s->q += s->pktout->length - 5;
9602 /* And finally the (zero) flags word. */
9604 if (!agent_query(s->agentreq, s->len + 4,
9606 ssh_agent_callback, ssh)) {
9610 bombout(("Unexpected data from server"
9611 " while waiting for agent"
9615 } while (pktin || inlen > 0);
9616 vret = ssh->agent_response;
9617 s->retlen = ssh->agent_response_len;
9622 if (s->retlen >= 9 &&
9623 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9624 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9625 logevent("Sending Pageant's response");
9626 ssh2_add_sigblob(ssh, s->pktout,
9627 s->pkblob, s->pklen,
9629 GET_32BIT(s->ret + 5));
9630 ssh2_pkt_send(ssh, s->pktout);
9631 s->type = AUTH_TYPE_PUBLICKEY;
9633 /* FIXME: less drastic response */
9634 bombout(("Pageant failed to answer challenge"));
9640 /* Do we have any keys left to try? */
9641 if (s->pkblob_in_agent) {
9642 s->done_agent = TRUE;
9643 s->tried_pubkey_config = TRUE;
9646 if (s->keyi >= s->nkeys)
9647 s->done_agent = TRUE;
9650 } else if (s->can_pubkey && s->publickey_blob &&
9651 s->privatekey_available && !s->tried_pubkey_config) {
9653 struct ssh2_userkey *key; /* not live over crReturn */
9654 char *passphrase; /* not live over crReturn */
9656 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9658 s->tried_pubkey_config = TRUE;
9661 * Try the public key supplied in the configuration.
9663 * First, offer the public blob to see if the server is
9664 * willing to accept it.
9666 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9667 ssh2_pkt_addstring(s->pktout, ssh->username);
9668 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9669 /* service requested */
9670 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9671 ssh2_pkt_addbool(s->pktout, FALSE);
9672 /* no signature included */
9673 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9674 ssh2_pkt_addstring_start(s->pktout);
9675 ssh2_pkt_addstring_data(s->pktout,
9676 (char *)s->publickey_blob,
9677 s->publickey_bloblen);
9678 ssh2_pkt_send(ssh, s->pktout);
9679 logevent("Offered public key");
9681 crWaitUntilV(pktin);
9682 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9683 /* Key refused. Give up. */
9684 s->gotit = TRUE; /* reconsider message next loop */
9685 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9686 continue; /* process this new message */
9688 logevent("Offer of public key accepted");
9691 * Actually attempt a serious authentication using
9694 if (flags & FLAG_VERBOSE) {
9695 c_write_str(ssh, "Authenticating with public key \"");
9696 c_write_str(ssh, s->publickey_comment);
9697 c_write_str(ssh, "\"\r\n");
9701 const char *error; /* not live over crReturn */
9702 if (s->privatekey_encrypted) {
9704 * Get a passphrase from the user.
9706 int ret; /* need not be kept over crReturn */
9707 s->cur_prompt = new_prompts(ssh->frontend);
9708 s->cur_prompt->to_server = FALSE;
9709 s->cur_prompt->name = dupstr("SSH key passphrase");
9710 add_prompt(s->cur_prompt,
9711 dupprintf("Passphrase for key \"%.100s\": ",
9712 s->publickey_comment),
9714 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9717 crWaitUntilV(!pktin);
9718 ret = get_userpass_input(s->cur_prompt,
9723 /* Failed to get a passphrase. Terminate. */
9724 free_prompts(s->cur_prompt);
9725 ssh_disconnect(ssh, NULL,
9726 "Unable to authenticate",
9727 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9732 dupstr(s->cur_prompt->prompts[0]->result);
9733 free_prompts(s->cur_prompt);
9735 passphrase = NULL; /* no passphrase needed */
9739 * Try decrypting the key.
9741 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9742 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9744 /* burn the evidence */
9745 smemclr(passphrase, strlen(passphrase));
9748 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9750 (key == SSH2_WRONG_PASSPHRASE)) {
9751 c_write_str(ssh, "Wrong passphrase\r\n");
9753 /* and loop again */
9755 c_write_str(ssh, "Unable to load private key (");
9756 c_write_str(ssh, error);
9757 c_write_str(ssh, ")\r\n");
9759 break; /* try something else */
9765 unsigned char *pkblob, *sigblob, *sigdata;
9766 int pkblob_len, sigblob_len, sigdata_len;
9770 * We have loaded the private key and the server
9771 * has announced that it's willing to accept it.
9772 * Hallelujah. Generate a signature and send it.
9774 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9775 ssh2_pkt_addstring(s->pktout, ssh->username);
9776 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9777 /* service requested */
9778 ssh2_pkt_addstring(s->pktout, "publickey");
9780 ssh2_pkt_addbool(s->pktout, TRUE);
9781 /* signature follows */
9782 ssh2_pkt_addstring(s->pktout, key->alg->name);
9783 pkblob = key->alg->public_blob(key->data,
9785 ssh2_pkt_addstring_start(s->pktout);
9786 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9790 * The data to be signed is:
9794 * followed by everything so far placed in the
9797 sigdata_len = s->pktout->length - 5 + 4 +
9798 ssh->v2_session_id_len;
9799 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9801 sigdata = snewn(sigdata_len, unsigned char);
9803 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9804 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9807 memcpy(sigdata+p, ssh->v2_session_id,
9808 ssh->v2_session_id_len);
9809 p += ssh->v2_session_id_len;
9810 memcpy(sigdata+p, s->pktout->data + 5,
9811 s->pktout->length - 5);
9812 p += s->pktout->length - 5;
9813 assert(p == sigdata_len);
9814 sigblob = key->alg->sign(key->data, (char *)sigdata,
9815 sigdata_len, &sigblob_len);
9816 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9817 sigblob, sigblob_len);
9822 ssh2_pkt_send(ssh, s->pktout);
9823 logevent("Sent public key signature");
9824 s->type = AUTH_TYPE_PUBLICKEY;
9825 key->alg->freekey(key->data);
9826 sfree(key->comment);
9831 } else if (s->can_gssapi && !s->tried_gssapi) {
9833 /* GSSAPI Authentication */
9838 s->type = AUTH_TYPE_GSSAPI;
9839 s->tried_gssapi = TRUE;
9841 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9844 * Pick the highest GSS library on the preference
9850 for (i = 0; i < ngsslibs; i++) {
9851 int want_id = conf_get_int_int(ssh->conf,
9852 CONF_ssh_gsslist, i);
9853 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
9854 if (ssh->gsslibs->libraries[j].id == want_id) {
9855 s->gsslib = &ssh->gsslibs->libraries[j];
9856 goto got_gsslib; /* double break */
9861 * We always expect to have found something in
9862 * the above loop: we only came here if there
9863 * was at least one viable GSS library, and the
9864 * preference list should always mention
9865 * everything and only change the order.
9870 if (s->gsslib->gsslogmsg)
9871 logevent(s->gsslib->gsslogmsg);
9873 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
9874 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9875 ssh2_pkt_addstring(s->pktout, ssh->username);
9876 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9877 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
9878 logevent("Attempting GSSAPI authentication");
9880 /* add mechanism info */
9881 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
9883 /* number of GSSAPI mechanisms */
9884 ssh2_pkt_adduint32(s->pktout,1);
9886 /* length of OID + 2 */
9887 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
9888 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
9891 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
9893 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
9895 ssh2_pkt_send(ssh, s->pktout);
9896 crWaitUntilV(pktin);
9897 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
9898 logevent("GSSAPI authentication request refused");
9902 /* check returned packet ... */
9904 ssh_pkt_getstring(pktin, &data, &len);
9905 s->gss_rcvtok.value = data;
9906 s->gss_rcvtok.length = len;
9907 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
9908 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
9909 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
9910 memcmp((char *)s->gss_rcvtok.value + 2,
9911 s->gss_buf.value,s->gss_buf.length) ) {
9912 logevent("GSSAPI authentication - wrong response from server");
9916 /* now start running */
9917 s->gss_stat = s->gsslib->import_name(s->gsslib,
9920 if (s->gss_stat != SSH_GSS_OK) {
9921 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
9922 logevent("GSSAPI import name failed - Bad service name");
9924 logevent("GSSAPI import name failed");
9928 /* fetch TGT into GSS engine */
9929 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
9931 if (s->gss_stat != SSH_GSS_OK) {
9932 logevent("GSSAPI authentication failed to get credentials");
9933 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9937 /* initial tokens are empty */
9938 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
9939 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
9941 /* now enter the loop */
9943 s->gss_stat = s->gsslib->init_sec_context
9947 conf_get_int(ssh->conf, CONF_gssapifwd),
9951 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
9952 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
9953 logevent("GSSAPI authentication initialisation failed");
9955 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
9956 &s->gss_buf) == SSH_GSS_OK) {
9957 logevent(s->gss_buf.value);
9958 sfree(s->gss_buf.value);
9963 logevent("GSSAPI authentication initialised");
9965 /* Client and server now exchange tokens until GSSAPI
9966 * no longer says CONTINUE_NEEDED */
9968 if (s->gss_sndtok.length != 0) {
9969 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
9970 ssh_pkt_addstring_start(s->pktout);
9971 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
9972 ssh2_pkt_send(ssh, s->pktout);
9973 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
9976 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
9977 crWaitUntilV(pktin);
9978 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
9979 logevent("GSSAPI authentication - bad server response");
9980 s->gss_stat = SSH_GSS_FAILURE;
9983 ssh_pkt_getstring(pktin, &data, &len);
9984 s->gss_rcvtok.value = data;
9985 s->gss_rcvtok.length = len;
9987 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
9989 if (s->gss_stat != SSH_GSS_OK) {
9990 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9991 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9994 logevent("GSSAPI authentication loop finished OK");
9996 /* Now send the MIC */
9998 s->pktout = ssh2_pkt_init(0);
9999 micoffset = s->pktout->length;
10000 ssh_pkt_addstring_start(s->pktout);
10001 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10002 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10003 ssh_pkt_addstring(s->pktout, ssh->username);
10004 ssh_pkt_addstring(s->pktout, "ssh-connection");
10005 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10007 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10008 s->gss_buf.length = s->pktout->length - micoffset;
10010 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10011 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10012 ssh_pkt_addstring_start(s->pktout);
10013 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10014 ssh2_pkt_send(ssh, s->pktout);
10015 s->gsslib->free_mic(s->gsslib, &mic);
10019 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10020 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10023 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10026 * Keyboard-interactive authentication.
10029 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10031 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10033 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10034 ssh2_pkt_addstring(s->pktout, ssh->username);
10035 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10036 /* service requested */
10037 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10039 ssh2_pkt_addstring(s->pktout, ""); /* lang */
10040 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
10041 ssh2_pkt_send(ssh, s->pktout);
10043 logevent("Attempting keyboard-interactive authentication");
10045 crWaitUntilV(pktin);
10046 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10047 /* Server is not willing to do keyboard-interactive
10048 * at all (or, bizarrely but legally, accepts the
10049 * user without actually issuing any prompts).
10050 * Give up on it entirely. */
10052 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10053 s->kbd_inter_refused = TRUE; /* don't try it again */
10058 * Loop while the server continues to send INFO_REQUESTs.
10060 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10062 char *name, *inst, *lang;
10063 int name_len, inst_len, lang_len;
10067 * We've got a fresh USERAUTH_INFO_REQUEST.
10068 * Get the preamble and start building a prompt.
10070 ssh_pkt_getstring(pktin, &name, &name_len);
10071 ssh_pkt_getstring(pktin, &inst, &inst_len);
10072 ssh_pkt_getstring(pktin, &lang, &lang_len);
10073 s->cur_prompt = new_prompts(ssh->frontend);
10074 s->cur_prompt->to_server = TRUE;
10077 * Get any prompt(s) from the packet.
10079 s->num_prompts = ssh_pkt_getuint32(pktin);
10080 for (i = 0; i < s->num_prompts; i++) {
10084 static char noprompt[] =
10085 "<server failed to send prompt>: ";
10087 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10088 echo = ssh2_pkt_getbool(pktin);
10091 prompt_len = lenof(noprompt)-1;
10093 add_prompt(s->cur_prompt,
10094 dupprintf("%.*s", prompt_len, prompt),
10099 /* FIXME: better prefix to distinguish from
10100 * local prompts? */
10101 s->cur_prompt->name =
10102 dupprintf("SSH server: %.*s", name_len, name);
10103 s->cur_prompt->name_reqd = TRUE;
10105 s->cur_prompt->name =
10106 dupstr("SSH server authentication");
10107 s->cur_prompt->name_reqd = FALSE;
10109 /* We add a prefix to try to make it clear that a prompt
10110 * has come from the server.
10111 * FIXME: ugly to print "Using..." in prompt _every_
10112 * time round. Can this be done more subtly? */
10113 /* Special case: for reasons best known to themselves,
10114 * some servers send k-i requests with no prompts and
10115 * nothing to display. Keep quiet in this case. */
10116 if (s->num_prompts || name_len || inst_len) {
10117 s->cur_prompt->instruction =
10118 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10119 inst_len ? "\n" : "", inst_len, inst);
10120 s->cur_prompt->instr_reqd = TRUE;
10122 s->cur_prompt->instr_reqd = FALSE;
10126 * Display any instructions, and get the user's
10130 int ret; /* not live over crReturn */
10131 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10134 crWaitUntilV(!pktin);
10135 ret = get_userpass_input(s->cur_prompt, in, inlen);
10140 * Failed to get responses. Terminate.
10142 free_prompts(s->cur_prompt);
10143 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10144 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10151 * Send the response(s) to the server.
10153 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10154 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10155 for (i=0; i < s->num_prompts; i++) {
10156 ssh2_pkt_addstring(s->pktout,
10157 s->cur_prompt->prompts[i]->result);
10159 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10162 * Free the prompts structure from this iteration.
10163 * If there's another, a new one will be allocated
10164 * when we return to the top of this while loop.
10166 free_prompts(s->cur_prompt);
10169 * Get the next packet in case it's another
10172 crWaitUntilV(pktin);
10177 * We should have SUCCESS or FAILURE now.
10181 } else if (s->can_passwd) {
10184 * Plain old password authentication.
10186 int ret; /* not live over crReturn */
10187 int changereq_first_time; /* not live over crReturn */
10189 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10191 s->cur_prompt = new_prompts(ssh->frontend);
10192 s->cur_prompt->to_server = TRUE;
10193 s->cur_prompt->name = dupstr("SSH password");
10194 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10199 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10202 crWaitUntilV(!pktin);
10203 ret = get_userpass_input(s->cur_prompt, in, inlen);
10208 * Failed to get responses. Terminate.
10210 free_prompts(s->cur_prompt);
10211 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10212 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10217 * Squirrel away the password. (We may need it later if
10218 * asked to change it.)
10220 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10221 free_prompts(s->cur_prompt);
10224 * Send the password packet.
10226 * We pad out the password packet to 256 bytes to make
10227 * it harder for an attacker to find the length of the
10230 * Anyone using a password longer than 256 bytes
10231 * probably doesn't have much to worry about from
10232 * people who find out how long their password is!
10234 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10235 ssh2_pkt_addstring(s->pktout, ssh->username);
10236 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10237 /* service requested */
10238 ssh2_pkt_addstring(s->pktout, "password");
10239 ssh2_pkt_addbool(s->pktout, FALSE);
10240 ssh2_pkt_addstring(s->pktout, s->password);
10241 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10242 logevent("Sent password");
10243 s->type = AUTH_TYPE_PASSWORD;
10246 * Wait for next packet, in case it's a password change
10249 crWaitUntilV(pktin);
10250 changereq_first_time = TRUE;
10252 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10255 * We're being asked for a new password
10256 * (perhaps not for the first time).
10257 * Loop until the server accepts it.
10260 int got_new = FALSE; /* not live over crReturn */
10261 char *prompt; /* not live over crReturn */
10262 int prompt_len; /* not live over crReturn */
10266 if (changereq_first_time)
10267 msg = "Server requested password change";
10269 msg = "Server rejected new password";
10271 c_write_str(ssh, msg);
10272 c_write_str(ssh, "\r\n");
10275 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10277 s->cur_prompt = new_prompts(ssh->frontend);
10278 s->cur_prompt->to_server = TRUE;
10279 s->cur_prompt->name = dupstr("New SSH password");
10280 s->cur_prompt->instruction =
10281 dupprintf("%.*s", prompt_len, prompt);
10282 s->cur_prompt->instr_reqd = TRUE;
10284 * There's no explicit requirement in the protocol
10285 * for the "old" passwords in the original and
10286 * password-change messages to be the same, and
10287 * apparently some Cisco kit supports password change
10288 * by the user entering a blank password originally
10289 * and the real password subsequently, so,
10290 * reluctantly, we prompt for the old password again.
10292 * (On the other hand, some servers don't even bother
10293 * to check this field.)
10295 add_prompt(s->cur_prompt,
10296 dupstr("Current password (blank for previously entered password): "),
10298 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10300 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10304 * Loop until the user manages to enter the same
10309 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10312 crWaitUntilV(!pktin);
10313 ret = get_userpass_input(s->cur_prompt, in, inlen);
10318 * Failed to get responses. Terminate.
10320 /* burn the evidence */
10321 free_prompts(s->cur_prompt);
10322 smemclr(s->password, strlen(s->password));
10323 sfree(s->password);
10324 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10325 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10331 * If the user specified a new original password
10332 * (IYSWIM), overwrite any previously specified
10334 * (A side effect is that the user doesn't have to
10335 * re-enter it if they louse up the new password.)
10337 if (s->cur_prompt->prompts[0]->result[0]) {
10338 smemclr(s->password, strlen(s->password));
10339 /* burn the evidence */
10340 sfree(s->password);
10342 dupstr(s->cur_prompt->prompts[0]->result);
10346 * Check the two new passwords match.
10348 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10349 s->cur_prompt->prompts[2]->result)
10352 /* They don't. Silly user. */
10353 c_write_str(ssh, "Passwords do not match\r\n");
10358 * Send the new password (along with the old one).
10359 * (see above for padding rationale)
10361 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10362 ssh2_pkt_addstring(s->pktout, ssh->username);
10363 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10364 /* service requested */
10365 ssh2_pkt_addstring(s->pktout, "password");
10366 ssh2_pkt_addbool(s->pktout, TRUE);
10367 ssh2_pkt_addstring(s->pktout, s->password);
10368 ssh2_pkt_addstring(s->pktout,
10369 s->cur_prompt->prompts[1]->result);
10370 free_prompts(s->cur_prompt);
10371 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10372 logevent("Sent new password");
10375 * Now see what the server has to say about it.
10376 * (If it's CHANGEREQ again, it's not happy with the
10379 crWaitUntilV(pktin);
10380 changereq_first_time = FALSE;
10385 * We need to reexamine the current pktin at the top
10386 * of the loop. Either:
10387 * - we weren't asked to change password at all, in
10388 * which case it's a SUCCESS or FAILURE with the
10390 * - we sent a new password, and the server was
10391 * either OK with it (SUCCESS or FAILURE w/partial
10392 * success) or unhappy with the _old_ password
10393 * (FAILURE w/o partial success)
10394 * In any of these cases, we go back to the top of
10395 * the loop and start again.
10400 * We don't need the old password any more, in any
10401 * case. Burn the evidence.
10403 smemclr(s->password, strlen(s->password));
10404 sfree(s->password);
10407 char *str = dupprintf("No supported authentication methods available"
10408 " (server sent: %.*s)",
10411 ssh_disconnect(ssh, str,
10412 "No supported authentication methods available",
10413 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10423 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10425 /* Clear up various bits and pieces from authentication. */
10426 if (s->publickey_blob) {
10427 sfree(s->publickey_algorithm);
10428 sfree(s->publickey_blob);
10429 sfree(s->publickey_comment);
10431 if (s->agent_response)
10432 sfree(s->agent_response);
10434 if (s->userauth_success && !ssh->bare_connection) {
10436 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10437 * packets since. Signal the transport layer to consider enacting
10438 * delayed compression.
10440 * (Relying on we_are_in is not sufficient, as
10441 * draft-miller-secsh-compression-delayed is quite clear that it
10442 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10443 * become set for other reasons.)
10445 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10448 ssh->channels = newtree234(ssh_channelcmp);
10451 * Set up handlers for some connection protocol messages, so we
10452 * don't have to handle them repeatedly in this coroutine.
10454 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10455 ssh2_msg_channel_window_adjust;
10456 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10457 ssh2_msg_global_request;
10460 * Create the main session channel.
10462 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10463 ssh->mainchan = NULL;
10465 ssh->mainchan = snew(struct ssh_channel);
10466 ssh->mainchan->ssh = ssh;
10467 ssh2_channel_init(ssh->mainchan);
10469 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10471 * Just start a direct-tcpip channel and use it as the main
10474 ssh_send_port_open(ssh->mainchan,
10475 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10476 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10478 ssh->ncmode = TRUE;
10480 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10481 logevent("Opening session as main channel");
10482 ssh2_pkt_send(ssh, s->pktout);
10483 ssh->ncmode = FALSE;
10485 crWaitUntilV(pktin);
10486 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10487 bombout(("Server refused to open channel"));
10489 /* FIXME: error data comes back in FAILURE packet */
10491 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10492 bombout(("Server's channel confirmation cited wrong channel"));
10495 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10496 ssh->mainchan->halfopen = FALSE;
10497 ssh->mainchan->type = CHAN_MAINSESSION;
10498 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10499 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10500 add234(ssh->channels, ssh->mainchan);
10501 update_specials_menu(ssh->frontend);
10502 logevent("Opened main channel");
10506 * Now we have a channel, make dispatch table entries for
10507 * general channel-based messages.
10509 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10510 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10511 ssh2_msg_channel_data;
10512 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10513 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10514 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10515 ssh2_msg_channel_open_confirmation;
10516 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10517 ssh2_msg_channel_open_failure;
10518 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10519 ssh2_msg_channel_request;
10520 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10521 ssh2_msg_channel_open;
10522 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10523 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10526 * Now the connection protocol is properly up and running, with
10527 * all those dispatch table entries, so it's safe to let
10528 * downstreams start trying to open extra channels through us.
10530 if (ssh->connshare)
10531 share_activate(ssh->connshare, ssh->v_s);
10533 if (ssh->mainchan && ssh_is_simple(ssh)) {
10535 * This message indicates to the server that we promise
10536 * not to try to run any other channel in parallel with
10537 * this one, so it's safe for it to advertise a very large
10538 * window and leave the flow control to TCP.
10540 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10541 "simple@putty.projects.tartarus.org",
10543 ssh2_pkt_send(ssh, s->pktout);
10547 * Enable port forwardings.
10549 ssh_setup_portfwd(ssh, ssh->conf);
10551 if (ssh->mainchan && !ssh->ncmode) {
10553 * Send the CHANNEL_REQUESTS for the main session channel.
10554 * Each one is handled by its own little asynchronous
10558 /* Potentially enable X11 forwarding. */
10559 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10561 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10563 if (!ssh->x11disp) {
10564 /* FIXME: return an error message from x11_setup_display */
10565 logevent("X11 forwarding not enabled: unable to"
10566 " initialise X display");
10568 ssh->x11auth = x11_invent_fake_auth
10569 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10570 ssh->x11auth->disp = ssh->x11disp;
10572 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10576 /* Potentially enable agent forwarding. */
10577 if (ssh_agent_forwarding_permitted(ssh))
10578 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10580 /* Now allocate a pty for the session. */
10581 if (!conf_get_int(ssh->conf, CONF_nopty))
10582 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10584 /* Send environment variables. */
10585 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10588 * Start a shell or a remote command. We may have to attempt
10589 * this twice if the config data has provided a second choice
10596 if (ssh->fallback_cmd) {
10597 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10598 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10600 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10601 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10605 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10606 ssh2_response_authconn, NULL);
10607 ssh2_pkt_addstring(s->pktout, cmd);
10609 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10610 ssh2_response_authconn, NULL);
10611 ssh2_pkt_addstring(s->pktout, cmd);
10613 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10614 ssh2_response_authconn, NULL);
10616 ssh2_pkt_send(ssh, s->pktout);
10618 crWaitUntilV(pktin);
10620 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10621 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10622 bombout(("Unexpected response to shell/command request:"
10623 " packet type %d", pktin->type));
10627 * We failed to start the command. If this is the
10628 * fallback command, we really are finished; if it's
10629 * not, and if the fallback command exists, try falling
10630 * back to it before complaining.
10632 if (!ssh->fallback_cmd &&
10633 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10634 logevent("Primary command failed; attempting fallback");
10635 ssh->fallback_cmd = TRUE;
10638 bombout(("Server refused to start a shell/command"));
10641 logevent("Started a shell/command");
10646 ssh->editing = ssh->echoing = TRUE;
10649 ssh->state = SSH_STATE_SESSION;
10650 if (ssh->size_needed)
10651 ssh_size(ssh, ssh->term_width, ssh->term_height);
10652 if (ssh->eof_needed)
10653 ssh_special(ssh, TS_EOF);
10659 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10664 s->try_send = FALSE;
10668 * _All_ the connection-layer packets we expect to
10669 * receive are now handled by the dispatch table.
10670 * Anything that reaches here must be bogus.
10673 bombout(("Strange packet received: type %d", pktin->type));
10675 } else if (ssh->mainchan) {
10677 * We have spare data. Add it to the channel buffer.
10679 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
10680 s->try_send = TRUE;
10684 struct ssh_channel *c;
10686 * Try to send data on all channels if we can.
10688 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
10689 if (c->type != CHAN_SHARING)
10690 ssh2_try_send_and_unthrottle(ssh, c);
10698 * Handlers for SSH-2 messages that might arrive at any moment.
10700 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10702 /* log reason code in disconnect message */
10704 int reason, msglen;
10706 reason = ssh_pkt_getuint32(pktin);
10707 ssh_pkt_getstring(pktin, &msg, &msglen);
10709 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10710 buf = dupprintf("Received disconnect message (%s)",
10711 ssh2_disconnect_reasons[reason]);
10713 buf = dupprintf("Received disconnect message (unknown"
10714 " type %d)", reason);
10718 buf = dupprintf("Disconnection message text: %.*s",
10721 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10723 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10724 ssh2_disconnect_reasons[reason] : "unknown",
10729 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10731 /* log the debug message */
10735 /* XXX maybe we should actually take notice of the return value */
10736 ssh2_pkt_getbool(pktin);
10737 ssh_pkt_getstring(pktin, &msg, &msglen);
10739 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
10742 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10744 do_ssh2_transport(ssh, NULL, 0, pktin);
10748 * Called if we receive a packet that isn't allowed by the protocol.
10749 * This only applies to packets whose meaning PuTTY understands.
10750 * Entirely unknown packets are handled below.
10752 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10754 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10755 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10757 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10761 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10763 struct Packet *pktout;
10764 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10765 ssh2_pkt_adduint32(pktout, pktin->sequence);
10767 * UNIMPLEMENTED messages MUST appear in the same order as the
10768 * messages they respond to. Hence, never queue them.
10770 ssh2_pkt_send_noqueue(ssh, pktout);
10774 * Handle the top-level SSH-2 protocol.
10776 static void ssh2_protocol_setup(Ssh ssh)
10781 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10783 for (i = 0; i < 256; i++)
10784 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10787 * Initially, we only accept transport messages (and a few generic
10788 * ones). do_ssh2_authconn will add more when it starts.
10789 * Messages that are understood but not currently acceptable go to
10790 * ssh2_msg_unexpected.
10792 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10793 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10794 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10795 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10796 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10797 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10798 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10799 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10800 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10801 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10802 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10803 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10804 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10805 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10806 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10807 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10808 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10809 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10810 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10811 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10812 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10813 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10814 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10815 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10816 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10817 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10818 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10819 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10820 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10821 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10822 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10823 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10824 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10827 * These messages have a special handler from the start.
10829 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10830 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10831 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10834 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10839 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10841 for (i = 0; i < 256; i++)
10842 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10845 * Initially, we set all ssh-connection messages to 'unexpected';
10846 * do_ssh2_authconn will fill things in properly. We also handle a
10847 * couple of messages from the transport protocol which aren't
10848 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10851 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10852 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10853 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10854 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10855 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10856 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10857 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10858 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10859 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10860 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10861 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10862 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10863 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10864 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10866 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10869 * These messages have a special handler from the start.
10871 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10872 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
10873 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10876 static void ssh2_timer(void *ctx, unsigned long now)
10878 Ssh ssh = (Ssh)ctx;
10880 if (ssh->state == SSH_STATE_CLOSED)
10883 if (!ssh->kex_in_progress && !ssh->bare_connection &&
10884 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
10885 now == ssh->next_rekey) {
10886 do_ssh2_transport(ssh, "timeout", -1, NULL);
10890 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
10891 struct Packet *pktin)
10893 const unsigned char *in = (const unsigned char *)vin;
10894 if (ssh->state == SSH_STATE_CLOSED)
10898 ssh->incoming_data_size += pktin->encrypted_len;
10899 if (!ssh->kex_in_progress &&
10900 ssh->max_data_size != 0 &&
10901 ssh->incoming_data_size > ssh->max_data_size)
10902 do_ssh2_transport(ssh, "too much data received", -1, NULL);
10906 ssh->packet_dispatch[pktin->type](ssh, pktin);
10907 else if (!ssh->protocol_initial_phase_done)
10908 do_ssh2_transport(ssh, in, inlen, pktin);
10910 do_ssh2_authconn(ssh, in, inlen, pktin);
10913 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
10914 struct Packet *pktin)
10916 const unsigned char *in = (const unsigned char *)vin;
10917 if (ssh->state == SSH_STATE_CLOSED)
10921 ssh->packet_dispatch[pktin->type](ssh, pktin);
10923 do_ssh2_authconn(ssh, in, inlen, pktin);
10926 static void ssh_cache_conf_values(Ssh ssh)
10928 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
10932 * Called to set up the connection.
10934 * Returns an error message, or NULL on success.
10936 static const char *ssh_init(void *frontend_handle, void **backend_handle,
10938 const char *host, int port, char **realhost,
10939 int nodelay, int keepalive)
10944 ssh = snew(struct ssh_tag);
10945 ssh->conf = conf_copy(conf);
10946 ssh_cache_conf_values(ssh);
10947 ssh->version = 0; /* when not ready yet */
10949 ssh->cipher = NULL;
10950 ssh->v1_cipher_ctx = NULL;
10951 ssh->crcda_ctx = NULL;
10952 ssh->cscipher = NULL;
10953 ssh->cs_cipher_ctx = NULL;
10954 ssh->sccipher = NULL;
10955 ssh->sc_cipher_ctx = NULL;
10957 ssh->cs_mac_ctx = NULL;
10959 ssh->sc_mac_ctx = NULL;
10960 ssh->cscomp = NULL;
10961 ssh->cs_comp_ctx = NULL;
10962 ssh->sccomp = NULL;
10963 ssh->sc_comp_ctx = NULL;
10965 ssh->kex_ctx = NULL;
10966 ssh->hostkey = NULL;
10967 ssh->hostkey_str = NULL;
10968 ssh->exitcode = -1;
10969 ssh->close_expected = FALSE;
10970 ssh->clean_exit = FALSE;
10971 ssh->state = SSH_STATE_PREPACKET;
10972 ssh->size_needed = FALSE;
10973 ssh->eof_needed = FALSE;
10975 ssh->logctx = NULL;
10976 ssh->deferred_send_data = NULL;
10977 ssh->deferred_len = 0;
10978 ssh->deferred_size = 0;
10979 ssh->fallback_cmd = 0;
10980 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
10981 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
10982 ssh->x11disp = NULL;
10983 ssh->x11auth = NULL;
10984 ssh->x11authtree = newtree234(x11_authcmp);
10985 ssh->v1_compressing = FALSE;
10986 ssh->v2_outgoing_sequence = 0;
10987 ssh->ssh1_rdpkt_crstate = 0;
10988 ssh->ssh2_rdpkt_crstate = 0;
10989 ssh->ssh2_bare_rdpkt_crstate = 0;
10990 ssh->ssh_gotdata_crstate = 0;
10991 ssh->do_ssh1_connection_crstate = 0;
10992 ssh->do_ssh_init_state = NULL;
10993 ssh->do_ssh_connection_init_state = NULL;
10994 ssh->do_ssh1_login_state = NULL;
10995 ssh->do_ssh2_transport_state = NULL;
10996 ssh->do_ssh2_authconn_state = NULL;
10999 ssh->mainchan = NULL;
11000 ssh->throttled_all = 0;
11001 ssh->v1_stdout_throttling = 0;
11003 ssh->queuelen = ssh->queuesize = 0;
11004 ssh->queueing = FALSE;
11005 ssh->qhead = ssh->qtail = NULL;
11006 ssh->deferred_rekey_reason = NULL;
11007 bufchain_init(&ssh->queued_incoming_data);
11008 ssh->frozen = FALSE;
11009 ssh->username = NULL;
11010 ssh->sent_console_eof = FALSE;
11011 ssh->got_pty = FALSE;
11012 ssh->bare_connection = FALSE;
11013 ssh->X11_fwd_enabled = FALSE;
11014 ssh->connshare = NULL;
11015 ssh->attempting_connshare = FALSE;
11017 *backend_handle = ssh;
11020 if (crypto_startup() == 0)
11021 return "Microsoft high encryption pack not installed!";
11024 ssh->frontend = frontend_handle;
11025 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11026 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11028 ssh->channels = NULL;
11029 ssh->rportfwds = NULL;
11030 ssh->portfwds = NULL;
11035 ssh->conn_throttle_count = 0;
11036 ssh->overall_bufsize = 0;
11037 ssh->fallback_cmd = 0;
11039 ssh->protocol = NULL;
11041 ssh->protocol_initial_phase_done = FALSE;
11043 ssh->pinger = NULL;
11045 ssh->incoming_data_size = ssh->outgoing_data_size =
11046 ssh->deferred_data_size = 0L;
11047 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11048 CONF_ssh_rekey_data));
11049 ssh->kex_in_progress = FALSE;
11052 ssh->gsslibs = NULL;
11055 random_ref(); /* do this now - may be needed by sharing setup code */
11057 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11066 static void ssh_free(void *handle)
11068 Ssh ssh = (Ssh) handle;
11069 struct ssh_channel *c;
11070 struct ssh_rportfwd *pf;
11071 struct X11FakeAuth *auth;
11073 if (ssh->v1_cipher_ctx)
11074 ssh->cipher->free_context(ssh->v1_cipher_ctx);
11075 if (ssh->cs_cipher_ctx)
11076 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11077 if (ssh->sc_cipher_ctx)
11078 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11079 if (ssh->cs_mac_ctx)
11080 ssh->csmac->free_context(ssh->cs_mac_ctx);
11081 if (ssh->sc_mac_ctx)
11082 ssh->scmac->free_context(ssh->sc_mac_ctx);
11083 if (ssh->cs_comp_ctx) {
11085 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11087 zlib_compress_cleanup(ssh->cs_comp_ctx);
11089 if (ssh->sc_comp_ctx) {
11091 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11093 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11096 dh_cleanup(ssh->kex_ctx);
11097 sfree(ssh->savedhost);
11099 while (ssh->queuelen-- > 0)
11100 ssh_free_packet(ssh->queue[ssh->queuelen]);
11103 while (ssh->qhead) {
11104 struct queued_handler *qh = ssh->qhead;
11105 ssh->qhead = qh->next;
11108 ssh->qhead = ssh->qtail = NULL;
11110 if (ssh->channels) {
11111 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11114 if (c->u.x11.xconn != NULL)
11115 x11_close(c->u.x11.xconn);
11117 case CHAN_SOCKDATA:
11118 case CHAN_SOCKDATA_DORMANT:
11119 if (c->u.pfd.pf != NULL)
11120 pfd_close(c->u.pfd.pf);
11123 if (ssh->version == 2) {
11124 struct outstanding_channel_request *ocr, *nocr;
11125 ocr = c->v.v2.chanreq_head;
11127 ocr->handler(c, NULL, ocr->ctx);
11132 bufchain_clear(&c->v.v2.outbuffer);
11136 freetree234(ssh->channels);
11137 ssh->channels = NULL;
11140 if (ssh->connshare)
11141 sharestate_free(ssh->connshare);
11143 if (ssh->rportfwds) {
11144 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11146 freetree234(ssh->rportfwds);
11147 ssh->rportfwds = NULL;
11149 sfree(ssh->deferred_send_data);
11151 x11_free_display(ssh->x11disp);
11152 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11153 x11_free_fake_auth(auth);
11154 freetree234(ssh->x11authtree);
11155 sfree(ssh->do_ssh_init_state);
11156 sfree(ssh->do_ssh1_login_state);
11157 sfree(ssh->do_ssh2_transport_state);
11158 sfree(ssh->do_ssh2_authconn_state);
11161 sfree(ssh->fullhostname);
11162 sfree(ssh->hostkey_str);
11163 if (ssh->crcda_ctx) {
11164 crcda_free_context(ssh->crcda_ctx);
11165 ssh->crcda_ctx = NULL;
11168 ssh_do_close(ssh, TRUE);
11169 expire_timer_context(ssh);
11171 pinger_free(ssh->pinger);
11172 bufchain_clear(&ssh->queued_incoming_data);
11173 sfree(ssh->username);
11174 conf_free(ssh->conf);
11177 ssh_gss_cleanup(ssh->gsslibs);
11185 * Reconfigure the SSH backend.
11187 static void ssh_reconfig(void *handle, Conf *conf)
11189 Ssh ssh = (Ssh) handle;
11190 const char *rekeying = NULL;
11191 int rekey_mandatory = FALSE;
11192 unsigned long old_max_data_size;
11195 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11197 ssh_setup_portfwd(ssh, conf);
11199 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11200 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11202 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11203 unsigned long now = GETTICKCOUNT();
11205 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11206 rekeying = "timeout shortened";
11208 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11212 old_max_data_size = ssh->max_data_size;
11213 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11214 CONF_ssh_rekey_data));
11215 if (old_max_data_size != ssh->max_data_size &&
11216 ssh->max_data_size != 0) {
11217 if (ssh->outgoing_data_size > ssh->max_data_size ||
11218 ssh->incoming_data_size > ssh->max_data_size)
11219 rekeying = "data limit lowered";
11222 if (conf_get_int(ssh->conf, CONF_compression) !=
11223 conf_get_int(conf, CONF_compression)) {
11224 rekeying = "compression setting changed";
11225 rekey_mandatory = TRUE;
11228 for (i = 0; i < CIPHER_MAX; i++)
11229 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11230 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11231 rekeying = "cipher settings changed";
11232 rekey_mandatory = TRUE;
11234 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11235 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11236 rekeying = "cipher settings changed";
11237 rekey_mandatory = TRUE;
11240 conf_free(ssh->conf);
11241 ssh->conf = conf_copy(conf);
11242 ssh_cache_conf_values(ssh);
11244 if (!ssh->bare_connection && rekeying) {
11245 if (!ssh->kex_in_progress) {
11246 do_ssh2_transport(ssh, rekeying, -1, NULL);
11247 } else if (rekey_mandatory) {
11248 ssh->deferred_rekey_reason = rekeying;
11254 * Called to send data down the SSH connection.
11256 static int ssh_send(void *handle, const char *buf, int len)
11258 Ssh ssh = (Ssh) handle;
11260 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11263 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11265 return ssh_sendbuffer(ssh);
11269 * Called to query the current amount of buffered stdin data.
11271 static int ssh_sendbuffer(void *handle)
11273 Ssh ssh = (Ssh) handle;
11274 int override_value;
11276 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11280 * If the SSH socket itself has backed up, add the total backup
11281 * size on that to any individual buffer on the stdin channel.
11283 override_value = 0;
11284 if (ssh->throttled_all)
11285 override_value = ssh->overall_bufsize;
11287 if (ssh->version == 1) {
11288 return override_value;
11289 } else if (ssh->version == 2) {
11290 if (!ssh->mainchan)
11291 return override_value;
11293 return (override_value +
11294 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11301 * Called to set the size of the window from SSH's POV.
11303 static void ssh_size(void *handle, int width, int height)
11305 Ssh ssh = (Ssh) handle;
11306 struct Packet *pktout;
11308 ssh->term_width = width;
11309 ssh->term_height = height;
11311 switch (ssh->state) {
11312 case SSH_STATE_BEFORE_SIZE:
11313 case SSH_STATE_PREPACKET:
11314 case SSH_STATE_CLOSED:
11315 break; /* do nothing */
11316 case SSH_STATE_INTERMED:
11317 ssh->size_needed = TRUE; /* buffer for later */
11319 case SSH_STATE_SESSION:
11320 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11321 if (ssh->version == 1) {
11322 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11323 PKT_INT, ssh->term_height,
11324 PKT_INT, ssh->term_width,
11325 PKT_INT, 0, PKT_INT, 0, PKT_END);
11326 } else if (ssh->mainchan) {
11327 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11329 ssh2_pkt_adduint32(pktout, ssh->term_width);
11330 ssh2_pkt_adduint32(pktout, ssh->term_height);
11331 ssh2_pkt_adduint32(pktout, 0);
11332 ssh2_pkt_adduint32(pktout, 0);
11333 ssh2_pkt_send(ssh, pktout);
11341 * Return a list of the special codes that make sense in this
11344 static const struct telnet_special *ssh_get_specials(void *handle)
11346 static const struct telnet_special ssh1_ignore_special[] = {
11347 {"IGNORE message", TS_NOP}
11349 static const struct telnet_special ssh2_ignore_special[] = {
11350 {"IGNORE message", TS_NOP},
11352 static const struct telnet_special ssh2_rekey_special[] = {
11353 {"Repeat key exchange", TS_REKEY},
11355 static const struct telnet_special ssh2_session_specials[] = {
11358 /* These are the signal names defined by RFC 4254.
11359 * They include all the ISO C signals, but are a subset of the POSIX
11360 * required signals. */
11361 {"SIGINT (Interrupt)", TS_SIGINT},
11362 {"SIGTERM (Terminate)", TS_SIGTERM},
11363 {"SIGKILL (Kill)", TS_SIGKILL},
11364 {"SIGQUIT (Quit)", TS_SIGQUIT},
11365 {"SIGHUP (Hangup)", TS_SIGHUP},
11366 {"More signals", TS_SUBMENU},
11367 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11368 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11369 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11370 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11371 {NULL, TS_EXITMENU}
11373 static const struct telnet_special specials_end[] = {
11374 {NULL, TS_EXITMENU}
11376 /* XXX review this length for any changes: */
11377 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
11378 lenof(ssh2_rekey_special) +
11379 lenof(ssh2_session_specials) +
11380 lenof(specials_end)];
11381 Ssh ssh = (Ssh) handle;
11383 #define ADD_SPECIALS(name) \
11385 assert((i + lenof(name)) <= lenof(ssh_specials)); \
11386 memcpy(&ssh_specials[i], name, sizeof name); \
11387 i += lenof(name); \
11390 if (ssh->version == 1) {
11391 /* Don't bother offering IGNORE if we've decided the remote
11392 * won't cope with it, since we wouldn't bother sending it if
11394 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11395 ADD_SPECIALS(ssh1_ignore_special);
11396 } else if (ssh->version == 2) {
11397 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11398 ADD_SPECIALS(ssh2_ignore_special);
11399 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11400 ADD_SPECIALS(ssh2_rekey_special);
11402 ADD_SPECIALS(ssh2_session_specials);
11403 } /* else we're not ready yet */
11406 ADD_SPECIALS(specials_end);
11407 return ssh_specials;
11411 #undef ADD_SPECIALS
11415 * Send special codes. TS_EOF is useful for `plink', so you
11416 * can send an EOF and collect resulting output (e.g. `plink
11419 static void ssh_special(void *handle, Telnet_Special code)
11421 Ssh ssh = (Ssh) handle;
11422 struct Packet *pktout;
11424 if (code == TS_EOF) {
11425 if (ssh->state != SSH_STATE_SESSION) {
11427 * Buffer the EOF in case we are pre-SESSION, so we can
11428 * send it as soon as we reach SESSION.
11430 if (code == TS_EOF)
11431 ssh->eof_needed = TRUE;
11434 if (ssh->version == 1) {
11435 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11436 } else if (ssh->mainchan) {
11437 sshfwd_write_eof(ssh->mainchan);
11438 ssh->send_ok = 0; /* now stop trying to read from stdin */
11440 logevent("Sent EOF message");
11441 } else if (code == TS_PING || code == TS_NOP) {
11442 if (ssh->state == SSH_STATE_CLOSED
11443 || ssh->state == SSH_STATE_PREPACKET) return;
11444 if (ssh->version == 1) {
11445 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11446 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11448 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11449 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11450 ssh2_pkt_addstring_start(pktout);
11451 ssh2_pkt_send_noqueue(ssh, pktout);
11454 } else if (code == TS_REKEY) {
11455 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11456 ssh->version == 2) {
11457 do_ssh2_transport(ssh, "at user request", -1, NULL);
11459 } else if (code == TS_BRK) {
11460 if (ssh->state == SSH_STATE_CLOSED
11461 || ssh->state == SSH_STATE_PREPACKET) return;
11462 if (ssh->version == 1) {
11463 logevent("Unable to send BREAK signal in SSH-1");
11464 } else if (ssh->mainchan) {
11465 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11466 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11467 ssh2_pkt_send(ssh, pktout);
11470 /* Is is a POSIX signal? */
11471 const char *signame = NULL;
11472 if (code == TS_SIGABRT) signame = "ABRT";
11473 if (code == TS_SIGALRM) signame = "ALRM";
11474 if (code == TS_SIGFPE) signame = "FPE";
11475 if (code == TS_SIGHUP) signame = "HUP";
11476 if (code == TS_SIGILL) signame = "ILL";
11477 if (code == TS_SIGINT) signame = "INT";
11478 if (code == TS_SIGKILL) signame = "KILL";
11479 if (code == TS_SIGPIPE) signame = "PIPE";
11480 if (code == TS_SIGQUIT) signame = "QUIT";
11481 if (code == TS_SIGSEGV) signame = "SEGV";
11482 if (code == TS_SIGTERM) signame = "TERM";
11483 if (code == TS_SIGUSR1) signame = "USR1";
11484 if (code == TS_SIGUSR2) signame = "USR2";
11485 /* The SSH-2 protocol does in principle support arbitrary named
11486 * signals, including signame@domain, but we don't support those. */
11488 /* It's a signal. */
11489 if (ssh->version == 2 && ssh->mainchan) {
11490 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11491 ssh2_pkt_addstring(pktout, signame);
11492 ssh2_pkt_send(ssh, pktout);
11493 logeventf(ssh, "Sent signal SIG%s", signame);
11496 /* Never heard of it. Do nothing */
11501 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11503 Ssh ssh = (Ssh) handle;
11504 struct ssh_channel *c;
11505 c = snew(struct ssh_channel);
11508 ssh2_channel_init(c);
11509 c->halfopen = TRUE;
11510 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11512 add234(ssh->channels, c);
11516 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11518 struct ssh_channel *c;
11519 c = snew(struct ssh_channel);
11522 ssh2_channel_init(c);
11523 c->type = CHAN_SHARING;
11524 c->u.sharing.ctx = sharing_ctx;
11525 add234(ssh->channels, c);
11529 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11531 struct ssh_channel *c;
11533 c = find234(ssh->channels, &localid, ssh_channelfind);
11535 ssh_channel_destroy(c);
11538 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11539 const void *data, int datalen,
11540 const char *additional_log_text)
11542 struct Packet *pkt;
11544 pkt = ssh2_pkt_init(type);
11545 pkt->downstream_id = id;
11546 pkt->additional_log_text = additional_log_text;
11547 ssh2_pkt_adddata(pkt, data, datalen);
11548 ssh2_pkt_send(ssh, pkt);
11552 * This is called when stdout/stderr (the entity to which
11553 * from_backend sends data) manages to clear some backlog.
11555 static void ssh_unthrottle(void *handle, int bufsize)
11557 Ssh ssh = (Ssh) handle;
11560 if (ssh->version == 1) {
11561 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11562 ssh->v1_stdout_throttling = 0;
11563 ssh_throttle_conn(ssh, -1);
11566 if (ssh->mainchan) {
11567 ssh2_set_window(ssh->mainchan,
11568 bufsize < ssh->mainchan->v.v2.locmaxwin ?
11569 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11570 if (ssh_is_simple(ssh))
11573 buflimit = ssh->mainchan->v.v2.locmaxwin;
11574 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11575 ssh->mainchan->throttling_conn = 0;
11576 ssh_throttle_conn(ssh, -1);
11582 * Now process any SSH connection data that was stashed in our
11583 * queue while we were frozen.
11585 ssh_process_queued_incoming_data(ssh);
11588 void ssh_send_port_open(void *channel, const char *hostname, int port,
11591 struct ssh_channel *c = (struct ssh_channel *)channel;
11593 struct Packet *pktout;
11595 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11597 if (ssh->version == 1) {
11598 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11599 PKT_INT, c->localid,
11602 /* PKT_STR, <org:orgport>, */
11605 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11607 char *trimmed_host = host_strduptrim(hostname);
11608 ssh2_pkt_addstring(pktout, trimmed_host);
11609 sfree(trimmed_host);
11611 ssh2_pkt_adduint32(pktout, port);
11613 * We make up values for the originator data; partly it's
11614 * too much hassle to keep track, and partly I'm not
11615 * convinced the server should be told details like that
11616 * about my local network configuration.
11617 * The "originator IP address" is syntactically a numeric
11618 * IP address, and some servers (e.g., Tectia) get upset
11619 * if it doesn't match this syntax.
11621 ssh2_pkt_addstring(pktout, "0.0.0.0");
11622 ssh2_pkt_adduint32(pktout, 0);
11623 ssh2_pkt_send(ssh, pktout);
11627 static int ssh_connected(void *handle)
11629 Ssh ssh = (Ssh) handle;
11630 return ssh->s != NULL;
11633 static int ssh_sendok(void *handle)
11635 Ssh ssh = (Ssh) handle;
11636 return ssh->send_ok;
11639 static int ssh_ldisc(void *handle, int option)
11641 Ssh ssh = (Ssh) handle;
11642 if (option == LD_ECHO)
11643 return ssh->echoing;
11644 if (option == LD_EDIT)
11645 return ssh->editing;
11649 static void ssh_provide_ldisc(void *handle, void *ldisc)
11651 Ssh ssh = (Ssh) handle;
11652 ssh->ldisc = ldisc;
11655 static void ssh_provide_logctx(void *handle, void *logctx)
11657 Ssh ssh = (Ssh) handle;
11658 ssh->logctx = logctx;
11661 static int ssh_return_exitcode(void *handle)
11663 Ssh ssh = (Ssh) handle;
11664 if (ssh->s != NULL)
11667 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11671 * cfg_info for SSH is the protocol running in this session.
11672 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11673 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11675 static int ssh_cfg_info(void *handle)
11677 Ssh ssh = (Ssh) handle;
11678 if (ssh->version == 0)
11679 return 0; /* don't know yet */
11680 else if (ssh->bare_connection)
11683 return ssh->version;
11687 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11688 * that fails. This variable is the means by which scp.c can reach
11689 * into the SSH code and find out which one it got.
11691 extern int ssh_fallback_cmd(void *handle)
11693 Ssh ssh = (Ssh) handle;
11694 return ssh->fallback_cmd;
11697 Backend ssh_backend = {
11707 ssh_return_exitcode,
11711 ssh_provide_logctx,
11714 ssh_test_for_upstream,