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 logeventf(ssh, "Looking up host \"%s\"%s", host,
3678 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3679 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3680 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3681 if ((err = sk_addr_error(addr)) != NULL) {
3685 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3687 ssh->s = new_connection(addr, *realhost, port,
3688 0, 1, nodelay, keepalive,
3689 (Plug) ssh, ssh->conf);
3690 if ((err = sk_socket_error(ssh->s)) != NULL) {
3692 notify_remote_exit(ssh->frontend);
3698 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3699 * send the version string too.
3701 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3704 if (sshprot == 3 && !ssh->bare_connection) {
3706 ssh_send_verstring(ssh, "SSH-", NULL);
3710 * loghost, if configured, overrides realhost.
3714 *realhost = dupstr(loghost);
3721 * Throttle or unthrottle the SSH connection.
3723 static void ssh_throttle_conn(Ssh ssh, int adjust)
3725 int old_count = ssh->conn_throttle_count;
3726 ssh->conn_throttle_count += adjust;
3727 assert(ssh->conn_throttle_count >= 0);
3728 if (ssh->conn_throttle_count && !old_count) {
3729 ssh_set_frozen(ssh, 1);
3730 } else if (!ssh->conn_throttle_count && old_count) {
3731 ssh_set_frozen(ssh, 0);
3736 * Throttle or unthrottle _all_ local data streams (for when sends
3737 * on the SSH connection itself back up).
3739 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3742 struct ssh_channel *c;
3744 if (enable == ssh->throttled_all)
3746 ssh->throttled_all = enable;
3747 ssh->overall_bufsize = bufsize;
3750 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3752 case CHAN_MAINSESSION:
3754 * This is treated separately, outside the switch.
3758 x11_override_throttle(c->u.x11.xconn, enable);
3761 /* Agent channels require no buffer management. */
3764 pfd_override_throttle(c->u.pfd.pf, enable);
3770 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3772 Ssh ssh = (Ssh) sshv;
3774 ssh->agent_response = reply;
3775 ssh->agent_response_len = replylen;
3777 if (ssh->version == 1)
3778 do_ssh1_login(ssh, NULL, -1, NULL);
3780 do_ssh2_authconn(ssh, NULL, -1, NULL);
3783 static void ssh_dialog_callback(void *sshv, int ret)
3785 Ssh ssh = (Ssh) sshv;
3787 ssh->user_response = ret;
3789 if (ssh->version == 1)
3790 do_ssh1_login(ssh, NULL, -1, NULL);
3792 do_ssh2_transport(ssh, NULL, -1, NULL);
3795 * This may have unfrozen the SSH connection, so do a
3798 ssh_process_queued_incoming_data(ssh);
3801 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3803 struct ssh_channel *c = (struct ssh_channel *)cv;
3805 const void *sentreply = reply;
3807 c->u.a.outstanding_requests--;
3809 /* Fake SSH_AGENT_FAILURE. */
3810 sentreply = "\0\0\0\1\5";
3813 if (ssh->version == 2) {
3814 ssh2_add_channel_data(c, sentreply, replylen);
3817 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3818 PKT_INT, c->remoteid,
3820 PKT_DATA, sentreply, replylen,
3826 * If we've already seen an incoming EOF but haven't sent an
3827 * outgoing one, this may be the moment to send it.
3829 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3830 sshfwd_write_eof(c);
3834 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3835 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3836 * => log `wire_reason'.
3838 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3839 const char *wire_reason,
3840 int code, int clean_exit)
3844 client_reason = wire_reason;
3846 error = dupprintf("Disconnected: %s", client_reason);
3848 error = dupstr("Disconnected");
3850 if (ssh->version == 1) {
3851 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3853 } else if (ssh->version == 2) {
3854 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3855 ssh2_pkt_adduint32(pktout, code);
3856 ssh2_pkt_addstring(pktout, wire_reason);
3857 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3858 ssh2_pkt_send_noqueue(ssh, pktout);
3861 ssh->close_expected = TRUE;
3862 ssh->clean_exit = clean_exit;
3863 ssh_closing((Plug)ssh, error, 0, 0);
3867 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3868 const struct ssh_signkey *ssh2keytype,
3871 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3872 return -1; /* no manual keys configured */
3877 * The fingerprint string we've been given will have things
3878 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3879 * narrow down to just the colon-separated hex block at the
3880 * end of the string.
3882 const char *p = strrchr(fingerprint, ' ');
3883 fingerprint = p ? p+1 : fingerprint;
3884 /* Quick sanity checks, including making sure it's in lowercase */
3885 assert(strlen(fingerprint) == 16*3 - 1);
3886 assert(fingerprint[2] == ':');
3887 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3889 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3891 return 1; /* success */
3896 * Construct the base64-encoded public key blob and see if
3899 unsigned char *binblob;
3901 int binlen, atoms, i;
3902 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3903 atoms = (binlen + 2) / 3;
3904 base64blob = snewn(atoms * 4 + 1, char);
3905 for (i = 0; i < atoms; i++)
3906 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3907 base64blob[atoms * 4] = '\0';
3909 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3912 return 1; /* success */
3921 * Handle the key exchange and user authentication phases.
3923 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
3924 struct Packet *pktin)
3927 unsigned char cookie[8], *ptr;
3928 struct MD5Context md5c;
3929 struct do_ssh1_login_state {
3932 unsigned char *rsabuf;
3933 const unsigned char *keystr1, *keystr2;
3934 unsigned long supported_ciphers_mask, supported_auths_mask;
3935 int tried_publickey, tried_agent;
3936 int tis_auth_refused, ccard_auth_refused;
3937 unsigned char session_id[16];
3939 void *publickey_blob;
3940 int publickey_bloblen;
3941 char *publickey_comment;
3942 int privatekey_available, privatekey_encrypted;
3943 prompts_t *cur_prompt;
3946 unsigned char request[5], *response, *p;
3956 struct RSAKey servkey, hostkey;
3958 crState(do_ssh1_login_state);
3965 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3966 bombout(("Public key packet not received"));
3970 logevent("Received public keys");
3972 ptr = ssh_pkt_getdata(pktin, 8);
3974 bombout(("SSH-1 public key packet stopped before random cookie"));
3977 memcpy(cookie, ptr, 8);
3979 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3980 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3981 bombout(("Failed to read SSH-1 public keys from public key packet"));
3986 * Log the host key fingerprint.
3990 logevent("Host key fingerprint is:");
3991 strcpy(logmsg, " ");
3992 s->hostkey.comment = NULL;
3993 rsa_fingerprint(logmsg + strlen(logmsg),
3994 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3998 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3999 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
4000 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
4001 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
4002 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
4004 ssh->v1_local_protoflags =
4005 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
4006 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
4009 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
4010 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
4011 MD5Update(&md5c, cookie, 8);
4012 MD5Final(s->session_id, &md5c);
4014 for (i = 0; i < 32; i++)
4015 ssh->session_key[i] = random_byte();
4018 * Verify that the `bits' and `bytes' parameters match.
4020 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
4021 s->servkey.bits > s->servkey.bytes * 8) {
4022 bombout(("SSH-1 public keys were badly formatted"));
4026 s->len = (s->hostkey.bytes > s->servkey.bytes ?
4027 s->hostkey.bytes : s->servkey.bytes);
4029 s->rsabuf = snewn(s->len, unsigned char);
4032 * Verify the host key.
4036 * First format the key into a string.
4038 int len = rsastr_len(&s->hostkey);
4039 char fingerprint[100];
4040 char *keystr = snewn(len, char);
4041 rsastr_fmt(keystr, &s->hostkey);
4042 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4044 /* First check against manually configured host keys. */
4045 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4046 if (s->dlgret == 0) { /* did not match */
4047 bombout(("Host key did not appear in manually configured list"));
4050 } else if (s->dlgret < 0) { /* none configured; use standard handling */
4051 ssh_set_frozen(ssh, 1);
4052 s->dlgret = verify_ssh_host_key(ssh->frontend,
4053 ssh->savedhost, ssh->savedport,
4054 "rsa", keystr, fingerprint,
4055 ssh_dialog_callback, ssh);
4060 if (s->dlgret < 0) {
4064 bombout(("Unexpected data from server while waiting"
4065 " for user host key response"));
4068 } while (pktin || inlen > 0);
4069 s->dlgret = ssh->user_response;
4071 ssh_set_frozen(ssh, 0);
4073 if (s->dlgret == 0) {
4074 ssh_disconnect(ssh, "User aborted at host key verification",
4083 for (i = 0; i < 32; i++) {
4084 s->rsabuf[i] = ssh->session_key[i];
4086 s->rsabuf[i] ^= s->session_id[i];
4089 if (s->hostkey.bytes > s->servkey.bytes) {
4090 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4092 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4094 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4096 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4099 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4103 logevent("Encrypted session key");
4106 int cipher_chosen = 0, warn = 0;
4107 const char *cipher_string = NULL;
4109 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4110 int next_cipher = conf_get_int_int(ssh->conf,
4111 CONF_ssh_cipherlist, i);
4112 if (next_cipher == CIPHER_WARN) {
4113 /* If/when we choose a cipher, warn about it */
4115 } else if (next_cipher == CIPHER_AES) {
4116 /* XXX Probably don't need to mention this. */
4117 logevent("AES not supported in SSH-1, skipping");
4119 switch (next_cipher) {
4120 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4121 cipher_string = "3DES"; break;
4122 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4123 cipher_string = "Blowfish"; break;
4124 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4125 cipher_string = "single-DES"; break;
4127 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4131 if (!cipher_chosen) {
4132 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4133 bombout(("Server violates SSH-1 protocol by not "
4134 "supporting 3DES encryption"));
4136 /* shouldn't happen */
4137 bombout(("No supported ciphers found"));
4141 /* Warn about chosen cipher if necessary. */
4143 ssh_set_frozen(ssh, 1);
4144 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4145 ssh_dialog_callback, ssh);
4146 if (s->dlgret < 0) {
4150 bombout(("Unexpected data from server while waiting"
4151 " for user response"));
4154 } while (pktin || inlen > 0);
4155 s->dlgret = ssh->user_response;
4157 ssh_set_frozen(ssh, 0);
4158 if (s->dlgret == 0) {
4159 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4166 switch (s->cipher_type) {
4167 case SSH_CIPHER_3DES:
4168 logevent("Using 3DES encryption");
4170 case SSH_CIPHER_DES:
4171 logevent("Using single-DES encryption");
4173 case SSH_CIPHER_BLOWFISH:
4174 logevent("Using Blowfish encryption");
4178 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4179 PKT_CHAR, s->cipher_type,
4180 PKT_DATA, cookie, 8,
4181 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4182 PKT_DATA, s->rsabuf, s->len,
4183 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4185 logevent("Trying to enable encryption...");
4189 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4190 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4192 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4193 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4194 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4196 ssh->crcda_ctx = crcda_make_context();
4197 logevent("Installing CRC compensation attack detector");
4199 if (s->servkey.modulus) {
4200 sfree(s->servkey.modulus);
4201 s->servkey.modulus = NULL;
4203 if (s->servkey.exponent) {
4204 sfree(s->servkey.exponent);
4205 s->servkey.exponent = NULL;
4207 if (s->hostkey.modulus) {
4208 sfree(s->hostkey.modulus);
4209 s->hostkey.modulus = NULL;
4211 if (s->hostkey.exponent) {
4212 sfree(s->hostkey.exponent);
4213 s->hostkey.exponent = NULL;
4217 if (pktin->type != SSH1_SMSG_SUCCESS) {
4218 bombout(("Encryption not successfully enabled"));
4222 logevent("Successfully started encryption");
4224 fflush(stdout); /* FIXME eh? */
4226 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4227 int ret; /* need not be kept over crReturn */
4228 s->cur_prompt = new_prompts(ssh->frontend);
4229 s->cur_prompt->to_server = TRUE;
4230 s->cur_prompt->name = dupstr("SSH login name");
4231 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4232 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4235 crWaitUntil(!pktin);
4236 ret = get_userpass_input(s->cur_prompt, in, inlen);
4241 * Failed to get a username. Terminate.
4243 free_prompts(s->cur_prompt);
4244 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4247 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4248 free_prompts(s->cur_prompt);
4251 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4253 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4255 if (flags & FLAG_INTERACTIVE &&
4256 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4257 c_write_str(ssh, userlog);
4258 c_write_str(ssh, "\r\n");
4266 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4267 /* We must not attempt PK auth. Pretend we've already tried it. */
4268 s->tried_publickey = s->tried_agent = 1;
4270 s->tried_publickey = s->tried_agent = 0;
4272 s->tis_auth_refused = s->ccard_auth_refused = 0;
4274 * Load the public half of any configured keyfile for later use.
4276 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4277 if (!filename_is_null(s->keyfile)) {
4279 logeventf(ssh, "Reading key file \"%.150s\"",
4280 filename_to_str(s->keyfile));
4281 keytype = key_type(s->keyfile);
4282 if (keytype == SSH_KEYTYPE_SSH1 ||
4283 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4285 if (rsakey_pubblob(s->keyfile,
4286 &s->publickey_blob, &s->publickey_bloblen,
4287 &s->publickey_comment, &error)) {
4288 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4289 if (!s->privatekey_available)
4290 logeventf(ssh, "Key file contains public key only");
4291 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4295 logeventf(ssh, "Unable to load key (%s)", error);
4296 msgbuf = dupprintf("Unable to load key file "
4297 "\"%.150s\" (%s)\r\n",
4298 filename_to_str(s->keyfile),
4300 c_write_str(ssh, msgbuf);
4302 s->publickey_blob = NULL;
4306 logeventf(ssh, "Unable to use this key file (%s)",
4307 key_type_to_str(keytype));
4308 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4310 filename_to_str(s->keyfile),
4311 key_type_to_str(keytype));
4312 c_write_str(ssh, msgbuf);
4314 s->publickey_blob = NULL;
4317 s->publickey_blob = NULL;
4319 while (pktin->type == SSH1_SMSG_FAILURE) {
4320 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4322 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4324 * Attempt RSA authentication using Pageant.
4330 logevent("Pageant is running. Requesting keys.");
4332 /* Request the keys held by the agent. */
4333 PUT_32BIT(s->request, 1);
4334 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4335 if (!agent_query(s->request, 5, &r, &s->responselen,
4336 ssh_agent_callback, ssh)) {
4340 bombout(("Unexpected data from server while waiting"
4341 " for agent response"));
4344 } while (pktin || inlen > 0);
4345 r = ssh->agent_response;
4346 s->responselen = ssh->agent_response_len;
4348 s->response = (unsigned char *) r;
4349 if (s->response && s->responselen >= 5 &&
4350 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4351 s->p = s->response + 5;
4352 s->nkeys = toint(GET_32BIT(s->p));
4354 logeventf(ssh, "Pageant reported negative key count %d",
4359 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4360 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4361 unsigned char *pkblob = s->p;
4365 do { /* do while (0) to make breaking easy */
4366 n = ssh1_read_bignum
4367 (s->p, toint(s->responselen-(s->p-s->response)),
4372 n = ssh1_read_bignum
4373 (s->p, toint(s->responselen-(s->p-s->response)),
4378 if (s->responselen - (s->p-s->response) < 4)
4380 s->commentlen = toint(GET_32BIT(s->p));
4382 if (s->commentlen < 0 ||
4383 toint(s->responselen - (s->p-s->response)) <
4386 s->commentp = (char *)s->p;
4387 s->p += s->commentlen;
4391 logevent("Pageant key list packet was truncated");
4395 if (s->publickey_blob) {
4396 if (!memcmp(pkblob, s->publickey_blob,
4397 s->publickey_bloblen)) {
4398 logeventf(ssh, "Pageant key #%d matches "
4399 "configured key file", s->keyi);
4400 s->tried_publickey = 1;
4402 /* Skip non-configured key */
4405 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4406 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4407 PKT_BIGNUM, s->key.modulus, PKT_END);
4409 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4410 logevent("Key refused");
4413 logevent("Received RSA challenge");
4414 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4415 bombout(("Server's RSA challenge was badly formatted"));
4420 char *agentreq, *q, *ret;
4423 len = 1 + 4; /* message type, bit count */
4424 len += ssh1_bignum_length(s->key.exponent);
4425 len += ssh1_bignum_length(s->key.modulus);
4426 len += ssh1_bignum_length(s->challenge);
4427 len += 16; /* session id */
4428 len += 4; /* response format */
4429 agentreq = snewn(4 + len, char);
4430 PUT_32BIT(agentreq, len);
4432 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4433 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4435 q += ssh1_write_bignum(q, s->key.exponent);
4436 q += ssh1_write_bignum(q, s->key.modulus);
4437 q += ssh1_write_bignum(q, s->challenge);
4438 memcpy(q, s->session_id, 16);
4440 PUT_32BIT(q, 1); /* response format */
4441 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4442 ssh_agent_callback, ssh)) {
4447 bombout(("Unexpected data from server"
4448 " while waiting for agent"
4452 } while (pktin || inlen > 0);
4453 vret = ssh->agent_response;
4454 retlen = ssh->agent_response_len;
4459 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4460 logevent("Sending Pageant's response");
4461 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4462 PKT_DATA, ret + 5, 16,
4466 if (pktin->type == SSH1_SMSG_SUCCESS) {
4468 ("Pageant's response accepted");
4469 if (flags & FLAG_VERBOSE) {
4470 c_write_str(ssh, "Authenticated using"
4472 c_write(ssh, s->commentp,
4474 c_write_str(ssh, "\" from agent\r\n");
4479 ("Pageant's response not accepted");
4482 ("Pageant failed to answer challenge");
4486 logevent("No reply received from Pageant");
4489 freebn(s->key.exponent);
4490 freebn(s->key.modulus);
4491 freebn(s->challenge);
4496 if (s->publickey_blob && !s->tried_publickey)
4497 logevent("Configured key file not in Pageant");
4499 logevent("Failed to get reply from Pageant");
4504 if (s->publickey_blob && s->privatekey_available &&
4505 !s->tried_publickey) {
4507 * Try public key authentication with the specified
4510 int got_passphrase; /* need not be kept over crReturn */
4511 if (flags & FLAG_VERBOSE)
4512 c_write_str(ssh, "Trying public key authentication.\r\n");
4513 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4514 logeventf(ssh, "Trying public key \"%s\"",
4515 filename_to_str(s->keyfile));
4516 s->tried_publickey = 1;
4517 got_passphrase = FALSE;
4518 while (!got_passphrase) {
4520 * Get a passphrase, if necessary.
4522 char *passphrase = NULL; /* only written after crReturn */
4524 if (!s->privatekey_encrypted) {
4525 if (flags & FLAG_VERBOSE)
4526 c_write_str(ssh, "No passphrase required.\r\n");
4529 int ret; /* need not be kept over crReturn */
4530 s->cur_prompt = new_prompts(ssh->frontend);
4531 s->cur_prompt->to_server = FALSE;
4532 s->cur_prompt->name = dupstr("SSH key passphrase");
4533 add_prompt(s->cur_prompt,
4534 dupprintf("Passphrase for key \"%.100s\": ",
4535 s->publickey_comment), FALSE);
4536 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4539 crWaitUntil(!pktin);
4540 ret = get_userpass_input(s->cur_prompt, in, inlen);
4544 /* Failed to get a passphrase. Terminate. */
4545 free_prompts(s->cur_prompt);
4546 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4550 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4551 free_prompts(s->cur_prompt);
4554 * Try decrypting key with passphrase.
4556 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4557 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4560 smemclr(passphrase, strlen(passphrase));
4564 /* Correct passphrase. */
4565 got_passphrase = TRUE;
4566 } else if (ret == 0) {
4567 c_write_str(ssh, "Couldn't load private key from ");
4568 c_write_str(ssh, filename_to_str(s->keyfile));
4569 c_write_str(ssh, " (");
4570 c_write_str(ssh, error);
4571 c_write_str(ssh, ").\r\n");
4572 got_passphrase = FALSE;
4573 break; /* go and try something else */
4574 } else if (ret == -1) {
4575 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4576 got_passphrase = FALSE;
4579 assert(0 && "unexpected return from loadrsakey()");
4580 got_passphrase = FALSE; /* placate optimisers */
4584 if (got_passphrase) {
4587 * Send a public key attempt.
4589 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4590 PKT_BIGNUM, s->key.modulus, PKT_END);
4593 if (pktin->type == SSH1_SMSG_FAILURE) {
4594 c_write_str(ssh, "Server refused our public key.\r\n");
4595 continue; /* go and try something else */
4597 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4598 bombout(("Bizarre response to offer of public key"));
4604 unsigned char buffer[32];
4605 Bignum challenge, response;
4607 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4608 bombout(("Server's RSA challenge was badly formatted"));
4611 response = rsadecrypt(challenge, &s->key);
4612 freebn(s->key.private_exponent);/* burn the evidence */
4614 for (i = 0; i < 32; i++) {
4615 buffer[i] = bignum_byte(response, 31 - i);
4619 MD5Update(&md5c, buffer, 32);
4620 MD5Update(&md5c, s->session_id, 16);
4621 MD5Final(buffer, &md5c);
4623 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4624 PKT_DATA, buffer, 16, PKT_END);
4631 if (pktin->type == SSH1_SMSG_FAILURE) {
4632 if (flags & FLAG_VERBOSE)
4633 c_write_str(ssh, "Failed to authenticate with"
4634 " our public key.\r\n");
4635 continue; /* go and try something else */
4636 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4637 bombout(("Bizarre response to RSA authentication response"));
4641 break; /* we're through! */
4647 * Otherwise, try various forms of password-like authentication.
4649 s->cur_prompt = new_prompts(ssh->frontend);
4651 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4652 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4653 !s->tis_auth_refused) {
4654 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4655 logevent("Requested TIS authentication");
4656 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4658 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4659 logevent("TIS authentication declined");
4660 if (flags & FLAG_INTERACTIVE)
4661 c_write_str(ssh, "TIS authentication refused.\r\n");
4662 s->tis_auth_refused = 1;
4667 char *instr_suf, *prompt;
4669 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4671 bombout(("TIS challenge packet was badly formed"));
4674 logevent("Received TIS challenge");
4675 s->cur_prompt->to_server = TRUE;
4676 s->cur_prompt->name = dupstr("SSH TIS authentication");
4677 /* Prompt heuristic comes from OpenSSH */
4678 if (memchr(challenge, '\n', challengelen)) {
4679 instr_suf = dupstr("");
4680 prompt = dupprintf("%.*s", challengelen, challenge);
4682 instr_suf = dupprintf("%.*s", challengelen, challenge);
4683 prompt = dupstr("Response: ");
4685 s->cur_prompt->instruction =
4686 dupprintf("Using TIS authentication.%s%s",
4687 (*instr_suf) ? "\n" : "",
4689 s->cur_prompt->instr_reqd = TRUE;
4690 add_prompt(s->cur_prompt, prompt, FALSE);
4694 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4695 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4696 !s->ccard_auth_refused) {
4697 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4698 logevent("Requested CryptoCard authentication");
4699 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4701 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4702 logevent("CryptoCard authentication declined");
4703 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4704 s->ccard_auth_refused = 1;
4709 char *instr_suf, *prompt;
4711 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4713 bombout(("CryptoCard challenge packet was badly formed"));
4716 logevent("Received CryptoCard challenge");
4717 s->cur_prompt->to_server = TRUE;
4718 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4719 s->cur_prompt->name_reqd = FALSE;
4720 /* Prompt heuristic comes from OpenSSH */
4721 if (memchr(challenge, '\n', challengelen)) {
4722 instr_suf = dupstr("");
4723 prompt = dupprintf("%.*s", challengelen, challenge);
4725 instr_suf = dupprintf("%.*s", challengelen, challenge);
4726 prompt = dupstr("Response: ");
4728 s->cur_prompt->instruction =
4729 dupprintf("Using CryptoCard authentication.%s%s",
4730 (*instr_suf) ? "\n" : "",
4732 s->cur_prompt->instr_reqd = TRUE;
4733 add_prompt(s->cur_prompt, prompt, FALSE);
4737 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4738 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4739 bombout(("No supported authentication methods available"));
4742 s->cur_prompt->to_server = TRUE;
4743 s->cur_prompt->name = dupstr("SSH password");
4744 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4745 ssh->username, ssh->savedhost),
4750 * Show password prompt, having first obtained it via a TIS
4751 * or CryptoCard exchange if we're doing TIS or CryptoCard
4755 int ret; /* need not be kept over crReturn */
4756 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4759 crWaitUntil(!pktin);
4760 ret = get_userpass_input(s->cur_prompt, in, inlen);
4765 * Failed to get a password (for example
4766 * because one was supplied on the command line
4767 * which has already failed to work). Terminate.
4769 free_prompts(s->cur_prompt);
4770 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4775 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4777 * Defence against traffic analysis: we send a
4778 * whole bunch of packets containing strings of
4779 * different lengths. One of these strings is the
4780 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4781 * The others are all random data in
4782 * SSH1_MSG_IGNORE packets. This way a passive
4783 * listener can't tell which is the password, and
4784 * hence can't deduce the password length.
4786 * Anybody with a password length greater than 16
4787 * bytes is going to have enough entropy in their
4788 * password that a listener won't find it _that_
4789 * much help to know how long it is. So what we'll
4792 * - if password length < 16, we send 15 packets
4793 * containing string lengths 1 through 15
4795 * - otherwise, we let N be the nearest multiple
4796 * of 8 below the password length, and send 8
4797 * packets containing string lengths N through
4798 * N+7. This won't obscure the order of
4799 * magnitude of the password length, but it will
4800 * introduce a bit of extra uncertainty.
4802 * A few servers can't deal with SSH1_MSG_IGNORE, at
4803 * least in this context. For these servers, we need
4804 * an alternative defence. We make use of the fact
4805 * that the password is interpreted as a C string:
4806 * so we can append a NUL, then some random data.
4808 * A few servers can deal with neither SSH1_MSG_IGNORE
4809 * here _nor_ a padded password string.
4810 * For these servers we are left with no defences
4811 * against password length sniffing.
4813 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4814 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4816 * The server can deal with SSH1_MSG_IGNORE, so
4817 * we can use the primary defence.
4819 int bottom, top, pwlen, i;
4822 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4824 bottom = 0; /* zero length passwords are OK! :-) */
4827 bottom = pwlen & ~7;
4831 assert(pwlen >= bottom && pwlen <= top);
4833 randomstr = snewn(top + 1, char);
4835 for (i = bottom; i <= top; i++) {
4837 defer_packet(ssh, s->pwpkt_type,
4838 PKT_STR,s->cur_prompt->prompts[0]->result,
4841 for (j = 0; j < i; j++) {
4843 randomstr[j] = random_byte();
4844 } while (randomstr[j] == '\0');
4846 randomstr[i] = '\0';
4847 defer_packet(ssh, SSH1_MSG_IGNORE,
4848 PKT_STR, randomstr, PKT_END);
4851 logevent("Sending password with camouflage packets");
4852 ssh_pkt_defersend(ssh);
4855 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4857 * The server can't deal with SSH1_MSG_IGNORE
4858 * but can deal with padded passwords, so we
4859 * can use the secondary defence.
4865 len = strlen(s->cur_prompt->prompts[0]->result);
4866 if (len < sizeof(string)) {
4868 strcpy(string, s->cur_prompt->prompts[0]->result);
4869 len++; /* cover the zero byte */
4870 while (len < sizeof(string)) {
4871 string[len++] = (char) random_byte();
4874 ss = s->cur_prompt->prompts[0]->result;
4876 logevent("Sending length-padded password");
4877 send_packet(ssh, s->pwpkt_type,
4878 PKT_INT, len, PKT_DATA, ss, len,
4882 * The server is believed unable to cope with
4883 * any of our password camouflage methods.
4886 len = strlen(s->cur_prompt->prompts[0]->result);
4887 logevent("Sending unpadded password");
4888 send_packet(ssh, s->pwpkt_type,
4890 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4894 send_packet(ssh, s->pwpkt_type,
4895 PKT_STR, s->cur_prompt->prompts[0]->result,
4898 logevent("Sent password");
4899 free_prompts(s->cur_prompt);
4901 if (pktin->type == SSH1_SMSG_FAILURE) {
4902 if (flags & FLAG_VERBOSE)
4903 c_write_str(ssh, "Access denied\r\n");
4904 logevent("Authentication refused");
4905 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4906 bombout(("Strange packet received, type %d", pktin->type));
4912 if (s->publickey_blob) {
4913 sfree(s->publickey_blob);
4914 sfree(s->publickey_comment);
4917 logevent("Authentication successful");
4922 static void ssh_channel_try_eof(struct ssh_channel *c)
4925 assert(c->pending_eof); /* precondition for calling us */
4927 return; /* can't close: not even opened yet */
4928 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4929 return; /* can't send EOF: pending outgoing data */
4931 c->pending_eof = FALSE; /* we're about to send it */
4932 if (ssh->version == 1) {
4933 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4935 c->closes |= CLOSES_SENT_EOF;
4937 struct Packet *pktout;
4938 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4939 ssh2_pkt_adduint32(pktout, c->remoteid);
4940 ssh2_pkt_send(ssh, pktout);
4941 c->closes |= CLOSES_SENT_EOF;
4942 ssh2_channel_check_close(c);
4946 Conf *sshfwd_get_conf(struct ssh_channel *c)
4952 void sshfwd_write_eof(struct ssh_channel *c)
4956 if (ssh->state == SSH_STATE_CLOSED)
4959 if (c->closes & CLOSES_SENT_EOF)
4962 c->pending_eof = TRUE;
4963 ssh_channel_try_eof(c);
4966 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4970 if (ssh->state == SSH_STATE_CLOSED)
4975 x11_close(c->u.x11.xconn);
4976 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4980 case CHAN_SOCKDATA_DORMANT:
4981 pfd_close(c->u.pfd.pf);
4982 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4985 c->type = CHAN_ZOMBIE;
4986 c->pending_eof = FALSE; /* this will confuse a zombie channel */
4988 ssh2_channel_check_close(c);
4991 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4995 if (ssh->state == SSH_STATE_CLOSED)
4998 if (ssh->version == 1) {
4999 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
5000 PKT_INT, c->remoteid,
5001 PKT_INT, len, PKT_DATA, buf, len,
5004 * In SSH-1 we can return 0 here - implying that forwarded
5005 * connections are never individually throttled - because
5006 * the only circumstance that can cause throttling will be
5007 * the whole SSH connection backing up, in which case
5008 * _everything_ will be throttled as a whole.
5012 ssh2_add_channel_data(c, buf, len);
5013 return ssh2_try_send(c);
5017 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
5022 if (ssh->state == SSH_STATE_CLOSED)
5025 if (ssh->version == 1) {
5026 buflimit = SSH1_BUFFER_LIMIT;
5028 buflimit = c->v.v2.locmaxwin;
5029 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
5031 if (c->throttling_conn && bufsize <= buflimit) {
5032 c->throttling_conn = 0;
5033 ssh_throttle_conn(ssh, -1);
5037 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
5039 struct queued_handler *qh = ssh->qhead;
5043 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5046 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5047 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5050 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5051 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5055 ssh->qhead = qh->next;
5057 if (ssh->qhead->msg1 > 0) {
5058 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5059 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5061 if (ssh->qhead->msg2 > 0) {
5062 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5063 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5066 ssh->qhead = ssh->qtail = NULL;
5069 qh->handler(ssh, pktin, qh->ctx);
5074 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5075 chandler_fn_t handler, void *ctx)
5077 struct queued_handler *qh;
5079 qh = snew(struct queued_handler);
5082 qh->handler = handler;
5086 if (ssh->qtail == NULL) {
5090 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5091 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5094 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5095 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5098 ssh->qtail->next = qh;
5103 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5105 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5107 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5108 SSH2_MSG_REQUEST_SUCCESS)) {
5109 logeventf(ssh, "Remote port forwarding from %s enabled",
5112 logeventf(ssh, "Remote port forwarding from %s refused",
5115 rpf = del234(ssh->rportfwds, pf);
5117 pf->pfrec->remote = NULL;
5122 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5125 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5128 pf->share_ctx = share_ctx;
5129 pf->shost = dupstr(shost);
5131 pf->sportdesc = NULL;
5132 if (!ssh->rportfwds) {
5133 assert(ssh->version == 2);
5134 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5136 if (add234(ssh->rportfwds, pf) != pf) {
5144 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5147 share_got_pkt_from_server(ctx, pktin->type,
5148 pktin->body, pktin->length);
5151 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5153 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5154 ssh_sharing_global_request_response, share_ctx);
5157 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5159 struct ssh_portfwd *epf;
5163 if (!ssh->portfwds) {
5164 ssh->portfwds = newtree234(ssh_portcmp);
5167 * Go through the existing port forwardings and tag them
5168 * with status==DESTROY. Any that we want to keep will be
5169 * re-enabled (status==KEEP) as we go through the
5170 * configuration and find out which bits are the same as
5173 struct ssh_portfwd *epf;
5175 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5176 epf->status = DESTROY;
5179 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5181 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5182 char *kp, *kp2, *vp, *vp2;
5183 char address_family, type;
5184 int sport,dport,sserv,dserv;
5185 char *sports, *dports, *saddr, *host;
5189 address_family = 'A';
5191 if (*kp == 'A' || *kp == '4' || *kp == '6')
5192 address_family = *kp++;
5193 if (*kp == 'L' || *kp == 'R')
5196 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5198 * There's a colon in the middle of the source port
5199 * string, which means that the part before it is
5200 * actually a source address.
5202 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5203 saddr = host_strduptrim(saddr_tmp);
5210 sport = atoi(sports);
5214 sport = net_service_lookup(sports);
5216 logeventf(ssh, "Service lookup failed for source"
5217 " port \"%s\"", sports);
5221 if (type == 'L' && !strcmp(val, "D")) {
5222 /* dynamic forwarding */
5229 /* ordinary forwarding */
5231 vp2 = vp + host_strcspn(vp, ":");
5232 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5236 dport = atoi(dports);
5240 dport = net_service_lookup(dports);
5242 logeventf(ssh, "Service lookup failed for destination"
5243 " port \"%s\"", dports);
5248 if (sport && dport) {
5249 /* Set up a description of the source port. */
5250 struct ssh_portfwd *pfrec, *epfrec;
5252 pfrec = snew(struct ssh_portfwd);
5254 pfrec->saddr = saddr;
5255 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5256 pfrec->sport = sport;
5257 pfrec->daddr = host;
5258 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5259 pfrec->dport = dport;
5260 pfrec->local = NULL;
5261 pfrec->remote = NULL;
5262 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5263 address_family == '6' ? ADDRTYPE_IPV6 :
5266 epfrec = add234(ssh->portfwds, pfrec);
5267 if (epfrec != pfrec) {
5268 if (epfrec->status == DESTROY) {
5270 * We already have a port forwarding up and running
5271 * with precisely these parameters. Hence, no need
5272 * to do anything; simply re-tag the existing one
5275 epfrec->status = KEEP;
5278 * Anything else indicates that there was a duplicate
5279 * in our input, which we'll silently ignore.
5281 free_portfwd(pfrec);
5283 pfrec->status = CREATE;
5292 * Now go through and destroy any port forwardings which were
5295 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5296 if (epf->status == DESTROY) {
5299 message = dupprintf("%s port forwarding from %s%s%d",
5300 epf->type == 'L' ? "local" :
5301 epf->type == 'R' ? "remote" : "dynamic",
5302 epf->saddr ? epf->saddr : "",
5303 epf->saddr ? ":" : "",
5306 if (epf->type != 'D') {
5307 char *msg2 = dupprintf("%s to %s:%d", message,
5308 epf->daddr, epf->dport);
5313 logeventf(ssh, "Cancelling %s", message);
5316 /* epf->remote or epf->local may be NULL if setting up a
5317 * forwarding failed. */
5319 struct ssh_rportfwd *rpf = epf->remote;
5320 struct Packet *pktout;
5323 * Cancel the port forwarding at the server
5326 if (ssh->version == 1) {
5328 * We cannot cancel listening ports on the
5329 * server side in SSH-1! There's no message
5330 * to support it. Instead, we simply remove
5331 * the rportfwd record from the local end
5332 * so that any connections the server tries
5333 * to make on it are rejected.
5336 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5337 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5338 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5340 ssh2_pkt_addstring(pktout, epf->saddr);
5341 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5342 /* XXX: rport_acceptall may not represent
5343 * what was used to open the original connection,
5344 * since it's reconfigurable. */
5345 ssh2_pkt_addstring(pktout, "");
5347 ssh2_pkt_addstring(pktout, "localhost");
5349 ssh2_pkt_adduint32(pktout, epf->sport);
5350 ssh2_pkt_send(ssh, pktout);
5353 del234(ssh->rportfwds, rpf);
5355 } else if (epf->local) {
5356 pfl_terminate(epf->local);
5359 delpos234(ssh->portfwds, i);
5361 i--; /* so we don't skip one in the list */
5365 * And finally, set up any new port forwardings (status==CREATE).
5367 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5368 if (epf->status == CREATE) {
5369 char *sportdesc, *dportdesc;
5370 sportdesc = dupprintf("%s%s%s%s%d%s",
5371 epf->saddr ? epf->saddr : "",
5372 epf->saddr ? ":" : "",
5373 epf->sserv ? epf->sserv : "",
5374 epf->sserv ? "(" : "",
5376 epf->sserv ? ")" : "");
5377 if (epf->type == 'D') {
5380 dportdesc = dupprintf("%s:%s%s%d%s",
5382 epf->dserv ? epf->dserv : "",
5383 epf->dserv ? "(" : "",
5385 epf->dserv ? ")" : "");
5388 if (epf->type == 'L') {
5389 char *err = pfl_listen(epf->daddr, epf->dport,
5390 epf->saddr, epf->sport,
5391 ssh, conf, &epf->local,
5392 epf->addressfamily);
5394 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5395 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5396 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5397 sportdesc, dportdesc,
5398 err ? " failed: " : "", err ? err : "");
5401 } else if (epf->type == 'D') {
5402 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5403 ssh, conf, &epf->local,
5404 epf->addressfamily);
5406 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5407 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5408 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5410 err ? " failed: " : "", err ? err : "");
5415 struct ssh_rportfwd *pf;
5418 * Ensure the remote port forwardings tree exists.
5420 if (!ssh->rportfwds) {
5421 if (ssh->version == 1)
5422 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5424 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5427 pf = snew(struct ssh_rportfwd);
5428 pf->share_ctx = NULL;
5429 pf->dhost = dupstr(epf->daddr);
5430 pf->dport = epf->dport;
5432 pf->shost = dupstr(epf->saddr);
5433 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5434 pf->shost = dupstr("");
5436 pf->shost = dupstr("localhost");
5438 pf->sport = epf->sport;
5439 if (add234(ssh->rportfwds, pf) != pf) {
5440 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5441 epf->daddr, epf->dport);
5444 logeventf(ssh, "Requesting remote port %s"
5445 " forward to %s", sportdesc, dportdesc);
5447 pf->sportdesc = sportdesc;
5452 if (ssh->version == 1) {
5453 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5454 PKT_INT, epf->sport,
5455 PKT_STR, epf->daddr,
5456 PKT_INT, epf->dport,
5458 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5460 ssh_rportfwd_succfail, pf);
5462 struct Packet *pktout;
5463 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5464 ssh2_pkt_addstring(pktout, "tcpip-forward");
5465 ssh2_pkt_addbool(pktout, 1);/* want reply */
5466 ssh2_pkt_addstring(pktout, pf->shost);
5467 ssh2_pkt_adduint32(pktout, pf->sport);
5468 ssh2_pkt_send(ssh, pktout);
5470 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5471 SSH2_MSG_REQUEST_FAILURE,
5472 ssh_rportfwd_succfail, pf);
5481 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5484 int stringlen, bufsize;
5486 ssh_pkt_getstring(pktin, &string, &stringlen);
5487 if (string == NULL) {
5488 bombout(("Incoming terminal data packet was badly formed"));
5492 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5494 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5495 ssh->v1_stdout_throttling = 1;
5496 ssh_throttle_conn(ssh, +1);
5500 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5502 /* Remote side is trying to open a channel to talk to our
5503 * X-Server. Give them back a local channel number. */
5504 struct ssh_channel *c;
5505 int remoteid = ssh_pkt_getuint32(pktin);
5507 logevent("Received X11 connect request");
5508 /* Refuse if X11 forwarding is disabled. */
5509 if (!ssh->X11_fwd_enabled) {
5510 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5511 PKT_INT, remoteid, PKT_END);
5512 logevent("Rejected X11 connect request");
5514 c = snew(struct ssh_channel);
5517 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5518 c->remoteid = remoteid;
5519 c->halfopen = FALSE;
5520 c->localid = alloc_channel_id(ssh);
5522 c->pending_eof = FALSE;
5523 c->throttling_conn = 0;
5524 c->type = CHAN_X11; /* identify channel type */
5525 add234(ssh->channels, c);
5526 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5527 PKT_INT, c->remoteid, PKT_INT,
5528 c->localid, PKT_END);
5529 logevent("Opened X11 forward channel");
5533 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5535 /* Remote side is trying to open a channel to talk to our
5536 * agent. Give them back a local channel number. */
5537 struct ssh_channel *c;
5538 int remoteid = ssh_pkt_getuint32(pktin);
5540 /* Refuse if agent forwarding is disabled. */
5541 if (!ssh->agentfwd_enabled) {
5542 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5543 PKT_INT, remoteid, PKT_END);
5545 c = snew(struct ssh_channel);
5547 c->remoteid = remoteid;
5548 c->halfopen = FALSE;
5549 c->localid = alloc_channel_id(ssh);
5551 c->pending_eof = FALSE;
5552 c->throttling_conn = 0;
5553 c->type = CHAN_AGENT; /* identify channel type */
5554 c->u.a.lensofar = 0;
5555 c->u.a.message = NULL;
5556 c->u.a.outstanding_requests = 0;
5557 add234(ssh->channels, c);
5558 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5559 PKT_INT, c->remoteid, PKT_INT, c->localid,
5564 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5566 /* Remote side is trying to open a channel to talk to a
5567 * forwarded port. Give them back a local channel number. */
5568 struct ssh_rportfwd pf, *pfp;
5574 remoteid = ssh_pkt_getuint32(pktin);
5575 ssh_pkt_getstring(pktin, &host, &hostsize);
5576 port = ssh_pkt_getuint32(pktin);
5578 pf.dhost = dupprintf("%.*s", hostsize, host);
5580 pfp = find234(ssh->rportfwds, &pf, NULL);
5583 logeventf(ssh, "Rejected remote port open request for %s:%d",
5585 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5586 PKT_INT, remoteid, PKT_END);
5588 struct ssh_channel *c = snew(struct ssh_channel);
5591 logeventf(ssh, "Received remote port open request for %s:%d",
5593 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5594 c, ssh->conf, pfp->pfrec->addressfamily);
5596 logeventf(ssh, "Port open failed: %s", err);
5599 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5600 PKT_INT, remoteid, PKT_END);
5602 c->remoteid = remoteid;
5603 c->halfopen = FALSE;
5604 c->localid = alloc_channel_id(ssh);
5606 c->pending_eof = FALSE;
5607 c->throttling_conn = 0;
5608 c->type = CHAN_SOCKDATA; /* identify channel type */
5609 add234(ssh->channels, c);
5610 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5611 PKT_INT, c->remoteid, PKT_INT,
5612 c->localid, PKT_END);
5613 logevent("Forwarded port opened successfully");
5620 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5622 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5623 unsigned int localid = ssh_pkt_getuint32(pktin);
5624 struct ssh_channel *c;
5626 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5627 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5628 c->remoteid = localid;
5629 c->halfopen = FALSE;
5630 c->type = CHAN_SOCKDATA;
5631 c->throttling_conn = 0;
5632 pfd_confirm(c->u.pfd.pf);
5635 if (c && c->pending_eof) {
5637 * We have a pending close on this channel,
5638 * which we decided on before the server acked
5639 * the channel open. So now we know the
5640 * remoteid, we can close it again.
5642 ssh_channel_try_eof(c);
5646 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5648 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5649 struct ssh_channel *c;
5651 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5652 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5653 logevent("Forwarded connection refused by server");
5654 pfd_close(c->u.pfd.pf);
5655 del234(ssh->channels, c);
5660 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5662 /* Remote side closes a channel. */
5663 unsigned i = ssh_pkt_getuint32(pktin);
5664 struct ssh_channel *c;
5665 c = find234(ssh->channels, &i, ssh_channelfind);
5666 if (c && !c->halfopen) {
5668 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5669 !(c->closes & CLOSES_RCVD_EOF)) {
5671 * Received CHANNEL_CLOSE, which we translate into
5674 int send_close = FALSE;
5676 c->closes |= CLOSES_RCVD_EOF;
5681 x11_send_eof(c->u.x11.xconn);
5687 pfd_send_eof(c->u.pfd.pf);
5696 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5697 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5699 c->closes |= CLOSES_SENT_EOF;
5703 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5704 !(c->closes & CLOSES_RCVD_CLOSE)) {
5706 if (!(c->closes & CLOSES_SENT_EOF)) {
5707 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5708 " for which we never sent CHANNEL_CLOSE\n", i));
5711 c->closes |= CLOSES_RCVD_CLOSE;
5714 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5715 !(c->closes & CLOSES_SENT_CLOSE)) {
5716 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5717 PKT_INT, c->remoteid, PKT_END);
5718 c->closes |= CLOSES_SENT_CLOSE;
5721 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5722 ssh_channel_destroy(c);
5724 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5725 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5726 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5731 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5733 /* Data sent down one of our channels. */
5734 int i = ssh_pkt_getuint32(pktin);
5737 struct ssh_channel *c;
5739 ssh_pkt_getstring(pktin, &p, &len);
5741 c = find234(ssh->channels, &i, ssh_channelfind);
5746 bufsize = x11_send(c->u.x11.xconn, p, len);
5749 bufsize = pfd_send(c->u.pfd.pf, p, len);
5752 /* Data for an agent message. Buffer it. */
5754 if (c->u.a.lensofar < 4) {
5755 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5756 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5760 c->u.a.lensofar += l;
5762 if (c->u.a.lensofar == 4) {
5764 4 + GET_32BIT(c->u.a.msglen);
5765 c->u.a.message = snewn(c->u.a.totallen,
5767 memcpy(c->u.a.message, c->u.a.msglen, 4);
5769 if (c->u.a.lensofar >= 4 && len > 0) {
5771 min(c->u.a.totallen - c->u.a.lensofar,
5773 memcpy(c->u.a.message + c->u.a.lensofar, p,
5777 c->u.a.lensofar += l;
5779 if (c->u.a.lensofar == c->u.a.totallen) {
5782 c->u.a.outstanding_requests++;
5783 if (agent_query(c->u.a.message,
5786 ssh_agentf_callback, c))
5787 ssh_agentf_callback(c, reply, replylen);
5788 sfree(c->u.a.message);
5789 c->u.a.lensofar = 0;
5792 bufsize = 0; /* agent channels never back up */
5795 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5796 c->throttling_conn = 1;
5797 ssh_throttle_conn(ssh, +1);
5802 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5804 ssh->exitcode = ssh_pkt_getuint32(pktin);
5805 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5806 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5808 * In case `helpful' firewalls or proxies tack
5809 * extra human-readable text on the end of the
5810 * session which we might mistake for another
5811 * encrypted packet, we close the session once
5812 * we've sent EXIT_CONFIRMATION.
5814 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5817 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5818 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5820 struct Packet *pktout = (struct Packet *)data;
5822 unsigned int arg = 0;
5823 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5824 if (i == lenof(ssh_ttymodes)) return;
5825 switch (ssh_ttymodes[i].type) {
5827 arg = ssh_tty_parse_specchar(val);
5830 arg = ssh_tty_parse_boolean(val);
5833 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5834 ssh2_pkt_addbyte(pktout, arg);
5837 int ssh_agent_forwarding_permitted(Ssh ssh)
5839 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5842 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5843 struct Packet *pktin)
5845 crBegin(ssh->do_ssh1_connection_crstate);
5847 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5848 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5849 ssh1_smsg_stdout_stderr_data;
5851 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5852 ssh1_msg_channel_open_confirmation;
5853 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5854 ssh1_msg_channel_open_failure;
5855 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5856 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5857 ssh1_msg_channel_close;
5858 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5859 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5861 if (ssh_agent_forwarding_permitted(ssh)) {
5862 logevent("Requesting agent forwarding");
5863 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5867 if (pktin->type != SSH1_SMSG_SUCCESS
5868 && pktin->type != SSH1_SMSG_FAILURE) {
5869 bombout(("Protocol confusion"));
5871 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5872 logevent("Agent forwarding refused");
5874 logevent("Agent forwarding enabled");
5875 ssh->agentfwd_enabled = TRUE;
5876 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5880 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5882 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5884 if (!ssh->x11disp) {
5885 /* FIXME: return an error message from x11_setup_display */
5886 logevent("X11 forwarding not enabled: unable to"
5887 " initialise X display");
5889 ssh->x11auth = x11_invent_fake_auth
5890 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5891 ssh->x11auth->disp = ssh->x11disp;
5893 logevent("Requesting X11 forwarding");
5894 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5895 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5896 PKT_STR, ssh->x11auth->protoname,
5897 PKT_STR, ssh->x11auth->datastring,
5898 PKT_INT, ssh->x11disp->screennum,
5901 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5902 PKT_STR, ssh->x11auth->protoname,
5903 PKT_STR, ssh->x11auth->datastring,
5909 if (pktin->type != SSH1_SMSG_SUCCESS
5910 && pktin->type != SSH1_SMSG_FAILURE) {
5911 bombout(("Protocol confusion"));
5913 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5914 logevent("X11 forwarding refused");
5916 logevent("X11 forwarding enabled");
5917 ssh->X11_fwd_enabled = TRUE;
5918 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5923 ssh_setup_portfwd(ssh, ssh->conf);
5924 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5926 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5928 /* Unpick the terminal-speed string. */
5929 /* XXX perhaps we should allow no speeds to be sent. */
5930 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5931 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5932 /* Send the pty request. */
5933 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5934 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5935 ssh_pkt_adduint32(pkt, ssh->term_height);
5936 ssh_pkt_adduint32(pkt, ssh->term_width);
5937 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5938 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5939 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5940 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5941 ssh_pkt_adduint32(pkt, ssh->ispeed);
5942 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5943 ssh_pkt_adduint32(pkt, ssh->ospeed);
5944 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5946 ssh->state = SSH_STATE_INTERMED;
5950 if (pktin->type != SSH1_SMSG_SUCCESS
5951 && pktin->type != SSH1_SMSG_FAILURE) {
5952 bombout(("Protocol confusion"));
5954 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5955 c_write_str(ssh, "Server refused to allocate pty\r\n");
5956 ssh->editing = ssh->echoing = 1;
5958 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5959 ssh->ospeed, ssh->ispeed);
5960 ssh->got_pty = TRUE;
5963 ssh->editing = ssh->echoing = 1;
5966 if (conf_get_int(ssh->conf, CONF_compression)) {
5967 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5971 if (pktin->type != SSH1_SMSG_SUCCESS
5972 && pktin->type != SSH1_SMSG_FAILURE) {
5973 bombout(("Protocol confusion"));
5975 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5976 c_write_str(ssh, "Server refused to compress\r\n");
5978 logevent("Started compression");
5979 ssh->v1_compressing = TRUE;
5980 ssh->cs_comp_ctx = zlib_compress_init();
5981 logevent("Initialised zlib (RFC1950) compression");
5982 ssh->sc_comp_ctx = zlib_decompress_init();
5983 logevent("Initialised zlib (RFC1950) decompression");
5987 * Start the shell or command.
5989 * Special case: if the first-choice command is an SSH-2
5990 * subsystem (hence not usable here) and the second choice
5991 * exists, we fall straight back to that.
5994 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5996 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5997 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5998 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5999 ssh->fallback_cmd = TRUE;
6002 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
6004 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
6005 logevent("Started session");
6008 ssh->state = SSH_STATE_SESSION;
6009 if (ssh->size_needed)
6010 ssh_size(ssh, ssh->term_width, ssh->term_height);
6011 if (ssh->eof_needed)
6012 ssh_special(ssh, TS_EOF);
6015 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
6017 ssh->channels = newtree234(ssh_channelcmp);
6021 * By this point, most incoming packets are already being
6022 * handled by the dispatch table, and we need only pay
6023 * attention to the unusual ones.
6028 if (pktin->type == SSH1_SMSG_SUCCESS) {
6029 /* may be from EXEC_SHELL on some servers */
6030 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6031 /* may be from EXEC_SHELL on some servers
6032 * if no pty is available or in other odd cases. Ignore */
6034 bombout(("Strange packet received: type %d", pktin->type));
6039 int len = min(inlen, 512);
6040 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
6041 PKT_INT, len, PKT_DATA, in, len,
6053 * Handle the top-level SSH-2 protocol.
6055 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6060 ssh_pkt_getstring(pktin, &msg, &msglen);
6061 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
6064 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6066 /* log reason code in disconnect message */
6070 ssh_pkt_getstring(pktin, &msg, &msglen);
6071 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
6074 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6076 /* Do nothing, because we're ignoring it! Duhh. */
6079 static void ssh1_protocol_setup(Ssh ssh)
6084 * Most messages are handled by the coroutines.
6086 for (i = 0; i < 256; i++)
6087 ssh->packet_dispatch[i] = NULL;
6090 * These special message types we install handlers for.
6092 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6093 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6094 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6097 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6098 struct Packet *pktin)
6100 const unsigned char *in = (const unsigned char *)vin;
6101 if (ssh->state == SSH_STATE_CLOSED)
6104 if (pktin && ssh->packet_dispatch[pktin->type]) {
6105 ssh->packet_dispatch[pktin->type](ssh, pktin);
6109 if (!ssh->protocol_initial_phase_done) {
6110 if (do_ssh1_login(ssh, in, inlen, pktin))
6111 ssh->protocol_initial_phase_done = TRUE;
6116 do_ssh1_connection(ssh, in, inlen, pktin);
6120 * Utility routines for decoding comma-separated strings in KEXINIT.
6122 static int first_in_commasep_string(char const *needle, char const *haystack,
6126 if (!needle || !haystack) /* protect against null pointers */
6128 needlen = strlen(needle);
6130 if (haylen >= needlen && /* haystack is long enough */
6131 !memcmp(needle, haystack, needlen) && /* initial match */
6132 (haylen == needlen || haystack[needlen] == ',')
6133 /* either , or EOS follows */
6139 static int in_commasep_string(char const *needle, char const *haystack,
6144 if (!needle || !haystack) /* protect against null pointers */
6147 * Is it at the start of the string?
6149 if (first_in_commasep_string(needle, haystack, haylen))
6152 * If not, search for the next comma and resume after that.
6153 * If no comma found, terminate.
6155 p = memchr(haystack, ',', haylen);
6157 /* + 1 to skip over comma */
6158 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6162 * Add a value to the comma-separated string at the end of the packet.
6164 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6166 if (pkt->length - pkt->savedpos > 0)
6167 ssh_pkt_addstring_str(pkt, ",");
6168 ssh_pkt_addstring_str(pkt, data);
6173 * SSH-2 key derivation (RFC 4253 section 7.2).
6175 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6176 char chr, int keylen)
6178 const struct ssh_hash *h = ssh->kex->hash;
6186 /* Round up to the next multiple of hash length. */
6187 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6189 key = snewn(keylen_padded, unsigned char);
6191 /* First hlen bytes. */
6193 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6194 hash_mpint(h, s, K);
6195 h->bytes(s, H, h->hlen);
6196 h->bytes(s, &chr, 1);
6197 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6200 /* Subsequent blocks of hlen bytes. */
6201 if (keylen_padded > h->hlen) {
6205 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6206 hash_mpint(h, s, K);
6207 h->bytes(s, H, h->hlen);
6209 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6210 h->bytes(s, key + offset - h->hlen, h->hlen);
6212 h->final(s2, key + offset);
6218 /* Now clear any extra bytes of key material beyond the length
6219 * we're officially returning, because the caller won't know to
6221 if (keylen_padded > keylen)
6222 smemclr(key + keylen, keylen_padded - keylen);
6228 * Structure for constructing KEXINIT algorithm lists.
6230 #define MAXKEXLIST 16
6231 struct kexinit_algorithm {
6235 const struct ssh_kex *kex;
6238 const struct ssh_signkey *hostkey;
6240 const struct ssh2_cipher *cipher;
6244 const struct ssh_mac *mac;
6247 const struct ssh_compress *comp;
6252 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6253 * If the algorithm is already in the list, return a pointer to its
6254 * entry, otherwise return an entry from the end of the list.
6255 * This assumes that every time a particular name is passed in, it
6256 * comes from the same string constant. If this isn't true, this
6257 * function may need to be rewritten to use strcmp() instead.
6259 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6260 *list, const char *name)
6264 for (i = 0; i < MAXKEXLIST; i++)
6265 if (list[i].name == NULL || list[i].name == name) {
6266 list[i].name = name;
6269 assert(!"No space in KEXINIT list");
6274 * Handle the SSH-2 transport layer.
6276 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6277 struct Packet *pktin)
6279 const unsigned char *in = (const unsigned char *)vin;
6281 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6282 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6285 const char * kexlist_descr[NKEXLIST] = {
6286 "key exchange algorithm", "host key algorithm",
6287 "client-to-server cipher", "server-to-client cipher",
6288 "client-to-server MAC", "server-to-client MAC",
6289 "client-to-server compression method",
6290 "server-to-client compression method" };
6291 struct do_ssh2_transport_state {
6293 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
6294 Bignum p, g, e, f, K;
6297 int kex_init_value, kex_reply_value;
6298 const struct ssh_mac **maclist;
6300 const struct ssh2_cipher *cscipher_tobe;
6301 const struct ssh2_cipher *sccipher_tobe;
6302 const struct ssh_mac *csmac_tobe;
6303 const struct ssh_mac *scmac_tobe;
6304 int csmac_etm_tobe, scmac_etm_tobe;
6305 const struct ssh_compress *cscomp_tobe;
6306 const struct ssh_compress *sccomp_tobe;
6307 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6308 int hostkeylen, siglen, rsakeylen;
6309 void *hkey; /* actual host key */
6310 void *rsakey; /* for RSA kex */
6311 void *eckey; /* for ECDH kex */
6312 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6313 int n_preferred_kex;
6314 const struct ssh_kexes *preferred_kex[KEX_MAX];
6315 int n_preferred_ciphers;
6316 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6317 const struct ssh_compress *preferred_comp;
6318 int userauth_succeeded; /* for delayed compression */
6319 int pending_compression;
6320 int got_session_id, activated_authconn;
6321 struct Packet *pktout;
6325 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6327 crState(do_ssh2_transport_state);
6329 assert(!ssh->bare_connection);
6333 s->cscipher_tobe = s->sccipher_tobe = NULL;
6334 s->csmac_tobe = s->scmac_tobe = NULL;
6335 s->cscomp_tobe = s->sccomp_tobe = NULL;
6337 s->got_session_id = s->activated_authconn = FALSE;
6338 s->userauth_succeeded = FALSE;
6339 s->pending_compression = FALSE;
6342 * Be prepared to work around the buggy MAC problem.
6344 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6345 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6347 s->maclist = macs, s->nmacs = lenof(macs);
6350 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6353 struct kexinit_algorithm *alg;
6356 * Set up the preferred key exchange. (NULL => warn below here)
6358 s->n_preferred_kex = 0;
6359 for (i = 0; i < KEX_MAX; i++) {
6360 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6362 s->preferred_kex[s->n_preferred_kex++] =
6363 &ssh_diffiehellman_gex;
6366 s->preferred_kex[s->n_preferred_kex++] =
6367 &ssh_diffiehellman_group14;
6370 s->preferred_kex[s->n_preferred_kex++] =
6371 &ssh_diffiehellman_group1;
6374 s->preferred_kex[s->n_preferred_kex++] =
6378 s->preferred_kex[s->n_preferred_kex++] =
6382 /* Flag for later. Don't bother if it's the last in
6384 if (i < KEX_MAX - 1) {
6385 s->preferred_kex[s->n_preferred_kex++] = NULL;
6392 * Set up the preferred ciphers. (NULL => warn below here)
6394 s->n_preferred_ciphers = 0;
6395 for (i = 0; i < CIPHER_MAX; i++) {
6396 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6397 case CIPHER_BLOWFISH:
6398 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6401 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6402 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6406 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6409 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6411 case CIPHER_ARCFOUR:
6412 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6414 case CIPHER_CHACHA20:
6415 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6418 /* Flag for later. Don't bother if it's the last in
6420 if (i < CIPHER_MAX - 1) {
6421 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6428 * Set up preferred compression.
6430 if (conf_get_int(ssh->conf, CONF_compression))
6431 s->preferred_comp = &ssh_zlib;
6433 s->preferred_comp = &ssh_comp_none;
6436 * Enable queueing of outgoing auth- or connection-layer
6437 * packets while we are in the middle of a key exchange.
6439 ssh->queueing = TRUE;
6442 * Flag that KEX is in progress.
6444 ssh->kex_in_progress = TRUE;
6446 for (i = 0; i < NKEXLIST; i++)
6447 for (j = 0; j < MAXKEXLIST; j++)
6448 s->kexlists[i][j].name = NULL;
6449 /* List key exchange algorithms. */
6451 for (i = 0; i < s->n_preferred_kex; i++) {
6452 const struct ssh_kexes *k = s->preferred_kex[i];
6453 if (!k) warn = TRUE;
6454 else for (j = 0; j < k->nkexes; j++) {
6455 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6457 alg->u.kex.kex = k->list[j];
6458 alg->u.kex.warn = warn;
6461 /* List server host key algorithms. */
6462 if (!s->got_session_id) {
6464 * In the first key exchange, we list all the algorithms
6465 * we're prepared to cope with, but prefer those algorithms
6466 * for which we have a host key for this host.
6468 for (i = 0; i < lenof(hostkey_algs); i++) {
6469 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6470 hostkey_algs[i]->keytype)) {
6471 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6472 hostkey_algs[i]->name);
6473 alg->u.hostkey = hostkey_algs[i];
6476 for (i = 0; i < lenof(hostkey_algs); i++) {
6477 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6478 hostkey_algs[i]->name);
6479 alg->u.hostkey = hostkey_algs[i];
6483 * In subsequent key exchanges, we list only the kex
6484 * algorithm that was selected in the first key exchange,
6485 * so that we keep getting the same host key and hence
6486 * don't have to interrupt the user's session to ask for
6490 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6491 ssh->hostkey->name);
6492 alg->u.hostkey = ssh->hostkey;
6494 /* List encryption algorithms (client->server then server->client). */
6495 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6498 alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6499 alg->u.cipher.cipher = NULL;
6500 alg->u.cipher.warn = warn;
6501 #endif /* FUZZING */
6502 for (i = 0; i < s->n_preferred_ciphers; i++) {
6503 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6504 if (!c) warn = TRUE;
6505 else for (j = 0; j < c->nciphers; j++) {
6506 alg = ssh2_kexinit_addalg(s->kexlists[k],
6508 alg->u.cipher.cipher = c->list[j];
6509 alg->u.cipher.warn = warn;
6513 /* List MAC algorithms (client->server then server->client). */
6514 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6516 alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6517 alg->u.mac.mac = NULL;
6518 alg->u.mac.etm = FALSE;
6519 #endif /* FUZZING */
6520 for (i = 0; i < s->nmacs; i++) {
6521 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6522 alg->u.mac.mac = s->maclist[i];
6523 alg->u.mac.etm = FALSE;
6525 for (i = 0; i < s->nmacs; i++)
6526 /* For each MAC, there may also be an ETM version,
6527 * which we list second. */
6528 if (s->maclist[i]->etm_name) {
6529 alg = ssh2_kexinit_addalg(s->kexlists[j],
6530 s->maclist[i]->etm_name);
6531 alg->u.mac.mac = s->maclist[i];
6532 alg->u.mac.etm = TRUE;
6535 /* List client->server compression algorithms,
6536 * then server->client compression algorithms. (We use the
6537 * same set twice.) */
6538 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6539 assert(lenof(compressions) > 1);
6540 /* Prefer non-delayed versions */
6541 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6542 alg->u.comp = s->preferred_comp;
6543 /* We don't even list delayed versions of algorithms until
6544 * they're allowed to be used, to avoid a race. See the end of
6546 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6547 alg = ssh2_kexinit_addalg(s->kexlists[j],
6548 s->preferred_comp->delayed_name);
6549 alg->u.comp = s->preferred_comp;
6551 for (i = 0; i < lenof(compressions); i++) {
6552 const struct ssh_compress *c = compressions[i];
6553 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6555 if (s->userauth_succeeded && c->delayed_name) {
6556 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6562 * Construct and send our key exchange packet.
6564 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6565 for (i = 0; i < 16; i++)
6566 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6567 for (i = 0; i < NKEXLIST; i++) {
6568 ssh2_pkt_addstring_start(s->pktout);
6569 for (j = 0; j < MAXKEXLIST; j++) {
6570 if (s->kexlists[i][j].name == NULL) break;
6571 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6574 /* List client->server languages. Empty list. */
6575 ssh2_pkt_addstring_start(s->pktout);
6576 /* List server->client languages. Empty list. */
6577 ssh2_pkt_addstring_start(s->pktout);
6578 /* First KEX packet does _not_ follow, because we're not that brave. */
6579 ssh2_pkt_addbool(s->pktout, FALSE);
6581 ssh2_pkt_adduint32(s->pktout, 0);
6584 s->our_kexinitlen = s->pktout->length - 5;
6585 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6586 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6588 ssh2_pkt_send_noqueue(ssh, s->pktout);
6591 crWaitUntilV(pktin);
6594 * Now examine the other side's KEXINIT to see what we're up
6601 if (pktin->type != SSH2_MSG_KEXINIT) {
6602 bombout(("expected key exchange packet from server"));
6606 ssh->hostkey = NULL;
6607 s->cscipher_tobe = NULL;
6608 s->sccipher_tobe = NULL;
6609 s->csmac_tobe = NULL;
6610 s->scmac_tobe = NULL;
6611 s->cscomp_tobe = NULL;
6612 s->sccomp_tobe = NULL;
6613 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
6615 pktin->savedpos += 16; /* skip garbage cookie */
6618 for (i = 0; i < NKEXLIST; i++) {
6619 ssh_pkt_getstring(pktin, &str, &len);
6621 bombout(("KEXINIT packet was incomplete"));
6625 /* If we've already selected a cipher which requires a
6626 * particular MAC, then just select that, and don't even
6627 * bother looking through the server's KEXINIT string for
6629 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6630 s->cscipher_tobe->required_mac) {
6631 s->csmac_tobe = s->cscipher_tobe->required_mac;
6632 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6635 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6636 s->sccipher_tobe->required_mac) {
6637 s->scmac_tobe = s->sccipher_tobe->required_mac;
6638 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6642 for (j = 0; j < MAXKEXLIST; j++) {
6643 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6644 if (alg->name == NULL) break;
6645 if (in_commasep_string(alg->name, str, len)) {
6646 /* We've found a matching algorithm. */
6647 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6648 /* Check if we might need to ignore first kex pkt */
6650 !first_in_commasep_string(alg->name, str, len))
6653 if (i == KEXLIST_KEX) {
6654 ssh->kex = alg->u.kex.kex;
6655 s->warn_kex = alg->u.kex.warn;
6656 } else if (i == KEXLIST_HOSTKEY) {
6657 ssh->hostkey = alg->u.hostkey;
6658 } else if (i == KEXLIST_CSCIPHER) {
6659 s->cscipher_tobe = alg->u.cipher.cipher;
6660 s->warn_cscipher = alg->u.cipher.warn;
6661 } else if (i == KEXLIST_SCCIPHER) {
6662 s->sccipher_tobe = alg->u.cipher.cipher;
6663 s->warn_sccipher = alg->u.cipher.warn;
6664 } else if (i == KEXLIST_CSMAC) {
6665 s->csmac_tobe = alg->u.mac.mac;
6666 s->csmac_etm_tobe = alg->u.mac.etm;
6667 } else if (i == KEXLIST_SCMAC) {
6668 s->scmac_tobe = alg->u.mac.mac;
6669 s->scmac_etm_tobe = alg->u.mac.etm;
6670 } else if (i == KEXLIST_CSCOMP) {
6671 s->cscomp_tobe = alg->u.comp;
6672 } else if (i == KEXLIST_SCCOMP) {
6673 s->sccomp_tobe = alg->u.comp;
6677 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6678 in_commasep_string(alg->u.comp->delayed_name, str, len))
6679 s->pending_compression = TRUE; /* try this later */
6681 bombout(("Couldn't agree a %s ((available: %.*s)",
6682 kexlist_descr[i], len, str));
6687 if (s->pending_compression) {
6688 logevent("Server supports delayed compression; "
6689 "will try this later");
6691 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6692 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6693 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6695 ssh->exhash = ssh->kex->hash->init();
6696 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6697 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6698 hash_string(ssh->kex->hash, ssh->exhash,
6699 s->our_kexinit, s->our_kexinitlen);
6700 sfree(s->our_kexinit);
6701 /* Include the type byte in the hash of server's KEXINIT */
6702 hash_string(ssh->kex->hash, ssh->exhash,
6703 pktin->body - 1, pktin->length + 1);
6706 ssh_set_frozen(ssh, 1);
6707 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6709 ssh_dialog_callback, ssh);
6710 if (s->dlgret < 0) {
6714 bombout(("Unexpected data from server while"
6715 " waiting for user response"));
6718 } while (pktin || inlen > 0);
6719 s->dlgret = ssh->user_response;
6721 ssh_set_frozen(ssh, 0);
6722 if (s->dlgret == 0) {
6723 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6729 if (s->warn_cscipher) {
6730 ssh_set_frozen(ssh, 1);
6731 s->dlgret = askalg(ssh->frontend,
6732 "client-to-server cipher",
6733 s->cscipher_tobe->name,
6734 ssh_dialog_callback, ssh);
6735 if (s->dlgret < 0) {
6739 bombout(("Unexpected data from server while"
6740 " waiting for user response"));
6743 } while (pktin || inlen > 0);
6744 s->dlgret = ssh->user_response;
6746 ssh_set_frozen(ssh, 0);
6747 if (s->dlgret == 0) {
6748 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6754 if (s->warn_sccipher) {
6755 ssh_set_frozen(ssh, 1);
6756 s->dlgret = askalg(ssh->frontend,
6757 "server-to-client cipher",
6758 s->sccipher_tobe->name,
6759 ssh_dialog_callback, ssh);
6760 if (s->dlgret < 0) {
6764 bombout(("Unexpected data from server while"
6765 " waiting for user response"));
6768 } while (pktin || inlen > 0);
6769 s->dlgret = ssh->user_response;
6771 ssh_set_frozen(ssh, 0);
6772 if (s->dlgret == 0) {
6773 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6779 if (s->ignorepkt) /* first_kex_packet_follows */
6780 crWaitUntilV(pktin); /* Ignore packet */
6783 if (ssh->kex->main_type == KEXTYPE_DH) {
6785 * Work out the number of bits of key we will need from the
6786 * key exchange. We start with the maximum key length of
6792 csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6793 scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6794 s->nbits = (csbits > scbits ? csbits : scbits);
6796 /* The keys only have hlen-bit entropy, since they're based on
6797 * a hash. So cap the key size at hlen bits. */
6798 if (s->nbits > ssh->kex->hash->hlen * 8)
6799 s->nbits = ssh->kex->hash->hlen * 8;
6802 * If we're doing Diffie-Hellman group exchange, start by
6803 * requesting a group.
6805 if (dh_is_gex(ssh->kex)) {
6806 logevent("Doing Diffie-Hellman group exchange");
6807 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6809 * Work out how big a DH group we will need to allow that
6812 s->pbits = 512 << ((s->nbits - 1) / 64);
6813 if (s->pbits < DH_MIN_SIZE)
6814 s->pbits = DH_MIN_SIZE;
6815 if (s->pbits > DH_MAX_SIZE)
6816 s->pbits = DH_MAX_SIZE;
6817 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6818 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6819 ssh2_pkt_adduint32(s->pktout, s->pbits);
6821 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6822 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6823 ssh2_pkt_adduint32(s->pktout, s->pbits);
6824 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6826 ssh2_pkt_send_noqueue(ssh, s->pktout);
6828 crWaitUntilV(pktin);
6829 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6830 bombout(("expected key exchange group packet from server"));
6833 s->p = ssh2_pkt_getmp(pktin);
6834 s->g = ssh2_pkt_getmp(pktin);
6835 if (!s->p || !s->g) {
6836 bombout(("unable to read mp-ints from incoming group packet"));
6839 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6840 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6841 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6843 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6844 ssh->kex_ctx = dh_setup_group(ssh->kex);
6845 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6846 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6847 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6848 ssh->kex->groupname);
6851 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6852 ssh->kex->hash->text_name);
6854 * Now generate and send e for Diffie-Hellman.
6856 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6857 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6858 s->pktout = ssh2_pkt_init(s->kex_init_value);
6859 ssh2_pkt_addmp(s->pktout, s->e);
6860 ssh2_pkt_send_noqueue(ssh, s->pktout);
6862 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6863 crWaitUntilV(pktin);
6864 if (pktin->type != s->kex_reply_value) {
6865 bombout(("expected key exchange reply packet from server"));
6868 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6869 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6870 if (!s->hostkeydata) {
6871 bombout(("unable to parse key exchange reply packet"));
6874 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6875 s->hostkeydata, s->hostkeylen);
6876 s->f = ssh2_pkt_getmp(pktin);
6878 bombout(("unable to parse key exchange reply packet"));
6881 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6883 bombout(("unable to parse key exchange reply packet"));
6888 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
6890 bombout(("key exchange reply failed validation: %s", err));
6894 s->K = dh_find_K(ssh->kex_ctx, s->f);
6896 /* We assume everything from now on will be quick, and it might
6897 * involve user interaction. */
6898 set_busy_status(ssh->frontend, BUSY_NOT);
6900 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6901 if (dh_is_gex(ssh->kex)) {
6902 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6903 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
6904 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6905 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6906 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
6907 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6908 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6910 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6911 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6913 dh_cleanup(ssh->kex_ctx);
6915 if (dh_is_gex(ssh->kex)) {
6919 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
6921 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
6922 ssh_ecdhkex_curve_textname(ssh->kex),
6923 ssh->kex->hash->text_name);
6924 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
6926 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
6928 bombout(("Unable to generate key for ECDH"));
6934 int publicPointLength;
6935 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6937 ssh_ecdhkex_freekey(s->eckey);
6938 bombout(("Unable to encode public key for ECDH"));
6941 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
6942 ssh2_pkt_addstring_start(s->pktout);
6943 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
6947 ssh2_pkt_send_noqueue(ssh, s->pktout);
6949 crWaitUntilV(pktin);
6950 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
6951 ssh_ecdhkex_freekey(s->eckey);
6952 bombout(("expected ECDH reply packet from server"));
6956 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6957 if (!s->hostkeydata) {
6958 bombout(("unable to parse ECDH reply packet"));
6961 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6962 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6963 s->hostkeydata, s->hostkeylen);
6967 int publicPointLength;
6968 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6970 ssh_ecdhkex_freekey(s->eckey);
6971 bombout(("Unable to encode public key for ECDH hash"));
6974 hash_string(ssh->kex->hash, ssh->exhash,
6975 publicPoint, publicPointLength);
6982 ssh_pkt_getstring(pktin, &keydata, &keylen);
6984 bombout(("unable to parse ECDH reply packet"));
6987 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
6988 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
6990 ssh_ecdhkex_freekey(s->eckey);
6991 bombout(("point received in ECDH was not valid"));
6996 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6998 bombout(("unable to parse key exchange reply packet"));
7002 ssh_ecdhkex_freekey(s->eckey);
7004 logeventf(ssh, "Doing RSA key exchange with hash %s",
7005 ssh->kex->hash->text_name);
7006 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7008 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7011 crWaitUntilV(pktin);
7012 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7013 bombout(("expected RSA public key packet from server"));
7017 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7018 if (!s->hostkeydata) {
7019 bombout(("unable to parse RSA public key packet"));
7022 hash_string(ssh->kex->hash, ssh->exhash,
7023 s->hostkeydata, s->hostkeylen);
7024 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7025 s->hostkeydata, s->hostkeylen);
7029 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7031 bombout(("unable to parse RSA public key packet"));
7034 s->rsakeydata = snewn(s->rsakeylen, char);
7035 memcpy(s->rsakeydata, keydata, s->rsakeylen);
7038 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7040 sfree(s->rsakeydata);
7041 bombout(("unable to parse RSA public key from server"));
7045 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7048 * Next, set up a shared secret K, of precisely KLEN -
7049 * 2*HLEN - 49 bits, where KLEN is the bit length of the
7050 * RSA key modulus and HLEN is the bit length of the hash
7054 int klen = ssh_rsakex_klen(s->rsakey);
7055 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7057 unsigned char *kstr1, *kstr2, *outstr;
7058 int kstr1len, kstr2len, outstrlen;
7060 s->K = bn_power_2(nbits - 1);
7062 for (i = 0; i < nbits; i++) {
7064 byte = random_byte();
7066 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7070 * Encode this as an mpint.
7072 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7073 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7074 PUT_32BIT(kstr2, kstr1len);
7075 memcpy(kstr2 + 4, kstr1, kstr1len);
7078 * Encrypt it with the given RSA key.
7080 outstrlen = (klen + 7) / 8;
7081 outstr = snewn(outstrlen, unsigned char);
7082 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7083 outstr, outstrlen, s->rsakey);
7086 * And send it off in a return packet.
7088 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7089 ssh2_pkt_addstring_start(s->pktout);
7090 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7091 ssh2_pkt_send_noqueue(ssh, s->pktout);
7093 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7100 ssh_rsakex_freekey(s->rsakey);
7102 crWaitUntilV(pktin);
7103 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7104 sfree(s->rsakeydata);
7105 bombout(("expected signature packet from server"));
7109 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7111 bombout(("unable to parse signature packet"));
7115 sfree(s->rsakeydata);
7118 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7119 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7120 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7122 ssh->kex_ctx = NULL;
7125 debug(("Exchange hash is:\n"));
7126 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7130 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7131 (char *)s->exchange_hash,
7132 ssh->kex->hash->hlen)) {
7134 bombout(("Server's host key did not match the signature supplied"));
7139 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7140 if (!s->got_session_id) {
7142 * Authenticate remote host: verify host key. (We've already
7143 * checked the signature of the exchange hash.)
7145 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7146 logevent("Host key fingerprint is:");
7147 logevent(s->fingerprint);
7148 /* First check against manually configured host keys. */
7149 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7150 ssh->hostkey, s->hkey);
7151 if (s->dlgret == 0) { /* did not match */
7152 bombout(("Host key did not appear in manually configured list"));
7154 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7155 ssh_set_frozen(ssh, 1);
7156 s->dlgret = verify_ssh_host_key(ssh->frontend,
7157 ssh->savedhost, ssh->savedport,
7158 ssh->hostkey->keytype, s->keystr,
7160 ssh_dialog_callback, ssh);
7164 if (s->dlgret < 0) {
7168 bombout(("Unexpected data from server while waiting"
7169 " for user host key response"));
7172 } while (pktin || inlen > 0);
7173 s->dlgret = ssh->user_response;
7175 ssh_set_frozen(ssh, 0);
7176 if (s->dlgret == 0) {
7177 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7182 sfree(s->fingerprint);
7184 * Save this host key, to check against the one presented in
7185 * subsequent rekeys.
7187 ssh->hostkey_str = s->keystr;
7190 * In a rekey, we never present an interactive host key
7191 * verification request to the user. Instead, we simply
7192 * enforce that the key we're seeing this time is identical to
7193 * the one we saw before.
7195 if (strcmp(ssh->hostkey_str, s->keystr)) {
7197 bombout(("Host key was different in repeat key exchange"));
7203 ssh->hostkey->freekey(s->hkey);
7206 * The exchange hash from the very first key exchange is also
7207 * the session id, used in session key construction and
7210 if (!s->got_session_id) {
7211 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7212 memcpy(ssh->v2_session_id, s->exchange_hash,
7213 sizeof(s->exchange_hash));
7214 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7215 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7216 s->got_session_id = TRUE;
7220 * Send SSH2_MSG_NEWKEYS.
7222 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7223 ssh2_pkt_send_noqueue(ssh, s->pktout);
7224 ssh->outgoing_data_size = 0; /* start counting from here */
7227 * We've sent client NEWKEYS, so create and initialise
7228 * client-to-server session keys.
7230 if (ssh->cs_cipher_ctx)
7231 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7232 ssh->cscipher = s->cscipher_tobe;
7233 if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7235 if (ssh->cs_mac_ctx)
7236 ssh->csmac->free_context(ssh->cs_mac_ctx);
7237 ssh->csmac = s->csmac_tobe;
7238 ssh->csmac_etm = s->csmac_etm_tobe;
7240 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7242 if (ssh->cs_comp_ctx)
7243 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7244 ssh->cscomp = s->cscomp_tobe;
7245 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7248 * Set IVs on client-to-server keys. Here we use the exchange
7249 * hash from the _first_ key exchange.
7251 if (ssh->cscipher) {
7254 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7255 ssh->cscipher->padded_keybytes);
7256 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7257 smemclr(key, ssh->cscipher->padded_keybytes);
7260 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7261 ssh->cscipher->blksize);
7262 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7263 smemclr(key, ssh->cscipher->blksize);
7269 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7270 ssh->csmac->keylen);
7271 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7272 smemclr(key, ssh->csmac->keylen);
7277 logeventf(ssh, "Initialised %.200s client->server encryption",
7278 ssh->cscipher->text_name);
7280 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7281 ssh->csmac->text_name,
7282 ssh->csmac_etm ? " (in ETM mode)" : "",
7283 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7284 if (ssh->cscomp->text_name)
7285 logeventf(ssh, "Initialised %s compression",
7286 ssh->cscomp->text_name);
7289 * Now our end of the key exchange is complete, we can send all
7290 * our queued higher-layer packets.
7292 ssh->queueing = FALSE;
7293 ssh2_pkt_queuesend(ssh);
7296 * Expect SSH2_MSG_NEWKEYS from server.
7298 crWaitUntilV(pktin);
7299 if (pktin->type != SSH2_MSG_NEWKEYS) {
7300 bombout(("expected new-keys packet from server"));
7303 ssh->incoming_data_size = 0; /* start counting from here */
7306 * We've seen server NEWKEYS, so create and initialise
7307 * server-to-client session keys.
7309 if (ssh->sc_cipher_ctx)
7310 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7311 if (ssh->sccipher) {
7312 ssh->sccipher = s->sccipher_tobe;
7313 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7316 if (ssh->sc_mac_ctx)
7317 ssh->scmac->free_context(ssh->sc_mac_ctx);
7319 ssh->scmac = s->scmac_tobe;
7320 ssh->scmac_etm = s->scmac_etm_tobe;
7321 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7324 if (ssh->sc_comp_ctx)
7325 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7326 ssh->sccomp = s->sccomp_tobe;
7327 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7330 * Set IVs on server-to-client keys. Here we use the exchange
7331 * hash from the _first_ key exchange.
7333 if (ssh->sccipher) {
7336 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7337 ssh->sccipher->padded_keybytes);
7338 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7339 smemclr(key, ssh->sccipher->padded_keybytes);
7342 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7343 ssh->sccipher->blksize);
7344 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7345 smemclr(key, ssh->sccipher->blksize);
7351 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7352 ssh->scmac->keylen);
7353 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7354 smemclr(key, ssh->scmac->keylen);
7358 logeventf(ssh, "Initialised %.200s server->client encryption",
7359 ssh->sccipher->text_name);
7361 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7362 ssh->scmac->text_name,
7363 ssh->scmac_etm ? " (in ETM mode)" : "",
7364 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7365 if (ssh->sccomp->text_name)
7366 logeventf(ssh, "Initialised %s decompression",
7367 ssh->sccomp->text_name);
7370 * Free shared secret.
7375 * Key exchange is over. Loop straight back round if we have a
7376 * deferred rekey reason.
7378 if (ssh->deferred_rekey_reason) {
7379 logevent(ssh->deferred_rekey_reason);
7381 ssh->deferred_rekey_reason = NULL;
7382 goto begin_key_exchange;
7386 * Otherwise, schedule a timer for our next rekey.
7388 ssh->kex_in_progress = FALSE;
7389 ssh->last_rekey = GETTICKCOUNT();
7390 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7391 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7395 * Now we're encrypting. Begin returning 1 to the protocol main
7396 * function so that other things can run on top of the
7397 * transport. If we ever see a KEXINIT, we must go back to the
7400 * We _also_ go back to the start if we see pktin==NULL and
7401 * inlen negative, because this is a special signal meaning
7402 * `initiate client-driven rekey', and `in' contains a message
7403 * giving the reason for the rekey.
7405 * inlen==-1 means always initiate a rekey;
7406 * inlen==-2 means that userauth has completed successfully and
7407 * we should consider rekeying (for delayed compression).
7409 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7410 (!pktin && inlen < 0))) {
7412 if (!ssh->protocol_initial_phase_done) {
7413 ssh->protocol_initial_phase_done = TRUE;
7415 * Allow authconn to initialise itself.
7417 do_ssh2_authconn(ssh, NULL, 0, NULL);
7422 logevent("Server initiated key re-exchange");
7426 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7427 * delayed compression, if it's available.
7429 * draft-miller-secsh-compression-delayed-00 says that you
7430 * negotiate delayed compression in the first key exchange, and
7431 * both sides start compressing when the server has sent
7432 * USERAUTH_SUCCESS. This has a race condition -- the server
7433 * can't know when the client has seen it, and thus which incoming
7434 * packets it should treat as compressed.
7436 * Instead, we do the initial key exchange without offering the
7437 * delayed methods, but note if the server offers them; when we
7438 * get here, if a delayed method was available that was higher
7439 * on our list than what we got, we initiate a rekey in which we
7440 * _do_ list the delayed methods (and hopefully get it as a
7441 * result). Subsequent rekeys will do the same.
7443 assert(!s->userauth_succeeded); /* should only happen once */
7444 s->userauth_succeeded = TRUE;
7445 if (!s->pending_compression)
7446 /* Can't see any point rekeying. */
7447 goto wait_for_rekey; /* this is utterly horrid */
7448 /* else fall through to rekey... */
7449 s->pending_compression = FALSE;
7452 * Now we've decided to rekey.
7454 * Special case: if the server bug is set that doesn't
7455 * allow rekeying, we give a different log message and
7456 * continue waiting. (If such a server _initiates_ a rekey,
7457 * we process it anyway!)
7459 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7460 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7462 /* Reset the counters, so that at least this message doesn't
7463 * hit the event log _too_ often. */
7464 ssh->outgoing_data_size = 0;
7465 ssh->incoming_data_size = 0;
7466 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7468 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7471 goto wait_for_rekey; /* this is still utterly horrid */
7473 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7476 goto begin_key_exchange;
7482 * Add data to an SSH-2 channel output buffer.
7484 static void ssh2_add_channel_data(struct ssh_channel *c, const char *buf,
7487 bufchain_add(&c->v.v2.outbuffer, buf, len);
7491 * Attempt to send data on an SSH-2 channel.
7493 static int ssh2_try_send(struct ssh_channel *c)
7496 struct Packet *pktout;
7499 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7502 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7503 if ((unsigned)len > c->v.v2.remwindow)
7504 len = c->v.v2.remwindow;
7505 if ((unsigned)len > c->v.v2.remmaxpkt)
7506 len = c->v.v2.remmaxpkt;
7507 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7508 ssh2_pkt_adduint32(pktout, c->remoteid);
7509 ssh2_pkt_addstring_start(pktout);
7510 ssh2_pkt_addstring_data(pktout, data, len);
7511 ssh2_pkt_send(ssh, pktout);
7512 bufchain_consume(&c->v.v2.outbuffer, len);
7513 c->v.v2.remwindow -= len;
7517 * After having sent as much data as we can, return the amount
7520 ret = bufchain_size(&c->v.v2.outbuffer);
7523 * And if there's no data pending but we need to send an EOF, send
7526 if (!ret && c->pending_eof)
7527 ssh_channel_try_eof(c);
7532 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7535 if (c->closes & CLOSES_SENT_EOF)
7536 return; /* don't send on channels we've EOFed */
7537 bufsize = ssh2_try_send(c);
7540 case CHAN_MAINSESSION:
7541 /* stdin need not receive an unthrottle
7542 * notification since it will be polled */
7545 x11_unthrottle(c->u.x11.xconn);
7548 /* agent sockets are request/response and need no
7549 * buffer management */
7552 pfd_unthrottle(c->u.pfd.pf);
7558 static int ssh_is_simple(Ssh ssh)
7561 * We use the 'simple' variant of the SSH protocol if we're asked
7562 * to, except not if we're also doing connection-sharing (either
7563 * tunnelling our packets over an upstream or expecting to be
7564 * tunnelled over ourselves), since then the assumption that we
7565 * have only one channel to worry about is not true after all.
7567 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7568 !ssh->bare_connection && !ssh->connshare);
7572 * Set up most of a new ssh_channel for SSH-2.
7574 static void ssh2_channel_init(struct ssh_channel *c)
7577 c->localid = alloc_channel_id(ssh);
7579 c->pending_eof = FALSE;
7580 c->throttling_conn = FALSE;
7581 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7582 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7583 c->v.v2.chanreq_head = NULL;
7584 c->v.v2.throttle_state = UNTHROTTLED;
7585 bufchain_init(&c->v.v2.outbuffer);
7589 * Construct the common parts of a CHANNEL_OPEN.
7591 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7594 struct Packet *pktout;
7596 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7597 ssh2_pkt_addstring(pktout, type);
7598 ssh2_pkt_adduint32(pktout, c->localid);
7599 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7600 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7605 * CHANNEL_FAILURE doesn't come with any indication of what message
7606 * caused it, so we have to keep track of the outstanding
7607 * CHANNEL_REQUESTs ourselves.
7609 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7610 cchandler_fn_t handler, void *ctx)
7612 struct outstanding_channel_request *ocr =
7613 snew(struct outstanding_channel_request);
7615 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7616 ocr->handler = handler;
7619 if (!c->v.v2.chanreq_head)
7620 c->v.v2.chanreq_head = ocr;
7622 c->v.v2.chanreq_tail->next = ocr;
7623 c->v.v2.chanreq_tail = ocr;
7627 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7628 * NULL then a reply will be requested and the handler will be called
7629 * when it arrives. The returned packet is ready to have any
7630 * request-specific data added and be sent. Note that if a handler is
7631 * provided, it's essential that the request actually be sent.
7633 * The handler will usually be passed the response packet in pktin. If
7634 * pktin is NULL, this means that no reply will ever be forthcoming
7635 * (e.g. because the entire connection is being destroyed, or because
7636 * the server initiated channel closure before we saw the response)
7637 * and the handler should free any storage it's holding.
7639 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7641 cchandler_fn_t handler, void *ctx)
7643 struct Packet *pktout;
7645 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7646 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7647 ssh2_pkt_adduint32(pktout, c->remoteid);
7648 ssh2_pkt_addstring(pktout, type);
7649 ssh2_pkt_addbool(pktout, handler != NULL);
7650 if (handler != NULL)
7651 ssh2_queue_chanreq_handler(c, handler, ctx);
7656 * Potentially enlarge the window on an SSH-2 channel.
7658 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7660 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7665 * Never send WINDOW_ADJUST for a channel that the remote side has
7666 * already sent EOF on; there's no point, since it won't be
7667 * sending any more data anyway. Ditto if _we've_ already sent
7670 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7674 * Also, never widen the window for an X11 channel when we're
7675 * still waiting to see its initial auth and may yet hand it off
7678 if (c->type == CHAN_X11 && c->u.x11.initial)
7682 * If the remote end has a habit of ignoring maxpkt, limit the
7683 * window so that it has no choice (assuming it doesn't ignore the
7686 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7687 newwin = OUR_V2_MAXPKT;
7690 * Only send a WINDOW_ADJUST if there's significantly more window
7691 * available than the other end thinks there is. This saves us
7692 * sending a WINDOW_ADJUST for every character in a shell session.
7694 * "Significant" is arbitrarily defined as half the window size.
7696 if (newwin / 2 >= c->v.v2.locwindow) {
7697 struct Packet *pktout;
7701 * In order to keep track of how much window the client
7702 * actually has available, we'd like it to acknowledge each
7703 * WINDOW_ADJUST. We can't do that directly, so we accompany
7704 * it with a CHANNEL_REQUEST that has to be acknowledged.
7706 * This is only necessary if we're opening the window wide.
7707 * If we're not, then throughput is being constrained by
7708 * something other than the maximum window size anyway.
7710 if (newwin == c->v.v2.locmaxwin &&
7711 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7712 up = snew(unsigned);
7713 *up = newwin - c->v.v2.locwindow;
7714 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7715 ssh2_handle_winadj_response, up);
7716 ssh2_pkt_send(ssh, pktout);
7718 if (c->v.v2.throttle_state != UNTHROTTLED)
7719 c->v.v2.throttle_state = UNTHROTTLING;
7721 /* Pretend the WINDOW_ADJUST was acked immediately. */
7722 c->v.v2.remlocwin = newwin;
7723 c->v.v2.throttle_state = THROTTLED;
7725 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7726 ssh2_pkt_adduint32(pktout, c->remoteid);
7727 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7728 ssh2_pkt_send(ssh, pktout);
7729 c->v.v2.locwindow = newwin;
7734 * Find the channel associated with a message. If there's no channel,
7735 * or it's not properly open, make a noise about it and return NULL.
7737 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7739 unsigned localid = ssh_pkt_getuint32(pktin);
7740 struct ssh_channel *c;
7742 c = find234(ssh->channels, &localid, ssh_channelfind);
7744 (c->type != CHAN_SHARING && c->halfopen &&
7745 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7746 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7747 char *buf = dupprintf("Received %s for %s channel %u",
7748 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7750 c ? "half-open" : "nonexistent", localid);
7751 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7758 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7759 struct Packet *pktin, void *ctx)
7761 unsigned *sizep = ctx;
7764 * Winadj responses should always be failures. However, at least
7765 * one server ("boks_sshd") is known to return SUCCESS for channel
7766 * requests it's never heard of, such as "winadj@putty". Raised
7767 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7768 * life, we don't worry about what kind of response we got.
7771 c->v.v2.remlocwin += *sizep;
7774 * winadj messages are only sent when the window is fully open, so
7775 * if we get an ack of one, we know any pending unthrottle is
7778 if (c->v.v2.throttle_state == UNTHROTTLING)
7779 c->v.v2.throttle_state = UNTHROTTLED;
7782 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
7784 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
7785 struct outstanding_channel_request *ocr;
7788 if (c->type == CHAN_SHARING) {
7789 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7790 pktin->body, pktin->length);
7793 ocr = c->v.v2.chanreq_head;
7795 ssh2_msg_unexpected(ssh, pktin);
7798 ocr->handler(c, pktin, ocr->ctx);
7799 c->v.v2.chanreq_head = ocr->next;
7802 * We may now initiate channel-closing procedures, if that
7803 * CHANNEL_REQUEST was the last thing outstanding before we send
7806 ssh2_channel_check_close(c);
7809 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
7811 struct ssh_channel *c;
7812 c = ssh2_channel_msg(ssh, pktin);
7815 if (c->type == CHAN_SHARING) {
7816 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7817 pktin->body, pktin->length);
7820 if (!(c->closes & CLOSES_SENT_EOF)) {
7821 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
7822 ssh2_try_send_and_unthrottle(ssh, c);
7826 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
7830 struct ssh_channel *c;
7831 c = ssh2_channel_msg(ssh, pktin);
7834 if (c->type == CHAN_SHARING) {
7835 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7836 pktin->body, pktin->length);
7839 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
7840 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
7841 return; /* extended but not stderr */
7842 ssh_pkt_getstring(pktin, &data, &length);
7845 c->v.v2.locwindow -= length;
7846 c->v.v2.remlocwin -= length;
7848 case CHAN_MAINSESSION:
7850 from_backend(ssh->frontend, pktin->type ==
7851 SSH2_MSG_CHANNEL_EXTENDED_DATA,
7855 bufsize = x11_send(c->u.x11.xconn, data, length);
7858 bufsize = pfd_send(c->u.pfd.pf, data, length);
7861 while (length > 0) {
7862 if (c->u.a.lensofar < 4) {
7863 unsigned int l = min(4 - c->u.a.lensofar,
7865 memcpy(c->u.a.msglen + c->u.a.lensofar,
7869 c->u.a.lensofar += l;
7871 if (c->u.a.lensofar == 4) {
7873 4 + GET_32BIT(c->u.a.msglen);
7874 c->u.a.message = snewn(c->u.a.totallen,
7876 memcpy(c->u.a.message, c->u.a.msglen, 4);
7878 if (c->u.a.lensofar >= 4 && length > 0) {
7880 min(c->u.a.totallen - c->u.a.lensofar,
7882 memcpy(c->u.a.message + c->u.a.lensofar,
7886 c->u.a.lensofar += l;
7888 if (c->u.a.lensofar == c->u.a.totallen) {
7891 c->u.a.outstanding_requests++;
7892 if (agent_query(c->u.a.message,
7895 ssh_agentf_callback, c))
7896 ssh_agentf_callback(c, reply, replylen);
7897 sfree(c->u.a.message);
7898 c->u.a.message = NULL;
7899 c->u.a.lensofar = 0;
7906 * If it looks like the remote end hit the end of its window,
7907 * and we didn't want it to do that, think about using a
7910 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
7911 c->v.v2.locmaxwin < 0x40000000)
7912 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
7914 * If we are not buffering too much data,
7915 * enlarge the window again at the remote side.
7916 * If we are buffering too much, we may still
7917 * need to adjust the window if the server's
7920 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7921 c->v.v2.locmaxwin - bufsize : 0);
7923 * If we're either buffering way too much data, or if we're
7924 * buffering anything at all and we're in "simple" mode,
7925 * throttle the whole channel.
7927 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
7928 && !c->throttling_conn) {
7929 c->throttling_conn = 1;
7930 ssh_throttle_conn(ssh, +1);
7935 static void ssh_check_termination(Ssh ssh)
7937 if (ssh->version == 2 &&
7938 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7939 (ssh->channels && count234(ssh->channels) == 0) &&
7940 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
7942 * We used to send SSH_MSG_DISCONNECT here, because I'd
7943 * believed that _every_ conforming SSH-2 connection had to
7944 * end with a disconnect being sent by at least one side;
7945 * apparently I was wrong and it's perfectly OK to
7946 * unceremoniously slam the connection shut when you're done,
7947 * and indeed OpenSSH feels this is more polite than sending a
7948 * DISCONNECT. So now we don't.
7950 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7954 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
7955 const char *peerinfo)
7958 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
7961 logeventf(ssh, "Connection sharing downstream #%u connected", id);
7964 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
7966 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
7967 ssh_check_termination(ssh);
7970 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
7975 va_start(ap, logfmt);
7976 buf = dupvprintf(logfmt, ap);
7979 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
7981 logeventf(ssh, "Connection sharing: %s", buf);
7985 static void ssh_channel_destroy(struct ssh_channel *c)
7990 case CHAN_MAINSESSION:
7991 ssh->mainchan = NULL;
7992 update_specials_menu(ssh->frontend);
7995 if (c->u.x11.xconn != NULL)
7996 x11_close(c->u.x11.xconn);
7997 logevent("Forwarded X11 connection terminated");
8000 sfree(c->u.a.message);
8003 if (c->u.pfd.pf != NULL)
8004 pfd_close(c->u.pfd.pf);
8005 logevent("Forwarded port closed");
8009 del234(ssh->channels, c);
8010 if (ssh->version == 2) {
8011 bufchain_clear(&c->v.v2.outbuffer);
8012 assert(c->v.v2.chanreq_head == NULL);
8017 * If that was the last channel left open, we might need to
8020 ssh_check_termination(ssh);
8023 static void ssh2_channel_check_close(struct ssh_channel *c)
8026 struct Packet *pktout;
8030 * If we've sent out our own CHANNEL_OPEN but not yet seen
8031 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8032 * it's too early to be sending close messages of any kind.
8037 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8038 c->type == CHAN_ZOMBIE) &&
8039 !c->v.v2.chanreq_head &&
8040 !(c->closes & CLOSES_SENT_CLOSE)) {
8042 * We have both sent and received EOF (or the channel is a
8043 * zombie), and we have no outstanding channel requests, which
8044 * means the channel is in final wind-up. But we haven't sent
8045 * CLOSE, so let's do so now.
8047 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8048 ssh2_pkt_adduint32(pktout, c->remoteid);
8049 ssh2_pkt_send(ssh, pktout);
8050 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8053 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8054 assert(c->v.v2.chanreq_head == NULL);
8056 * We have both sent and received CLOSE, which means we're
8057 * completely done with the channel.
8059 ssh_channel_destroy(c);
8063 static void ssh2_channel_got_eof(struct ssh_channel *c)
8065 if (c->closes & CLOSES_RCVD_EOF)
8066 return; /* already seen EOF */
8067 c->closes |= CLOSES_RCVD_EOF;
8069 if (c->type == CHAN_X11) {
8070 x11_send_eof(c->u.x11.xconn);
8071 } else if (c->type == CHAN_AGENT) {
8072 if (c->u.a.outstanding_requests == 0) {
8073 /* Manufacture an outgoing EOF in response to the incoming one. */
8074 sshfwd_write_eof(c);
8076 } else if (c->type == CHAN_SOCKDATA) {
8077 pfd_send_eof(c->u.pfd.pf);
8078 } else if (c->type == CHAN_MAINSESSION) {
8081 if (!ssh->sent_console_eof &&
8082 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8084 * Either from_backend_eof told us that the front end
8085 * wants us to close the outgoing side of the connection
8086 * as soon as we see EOF from the far end, or else we've
8087 * unilaterally decided to do that because we've allocated
8088 * a remote pty and hence EOF isn't a particularly
8089 * meaningful concept.
8091 sshfwd_write_eof(c);
8093 ssh->sent_console_eof = TRUE;
8096 ssh2_channel_check_close(c);
8099 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8101 struct ssh_channel *c;
8103 c = ssh2_channel_msg(ssh, pktin);
8106 if (c->type == CHAN_SHARING) {
8107 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8108 pktin->body, pktin->length);
8111 ssh2_channel_got_eof(c);
8114 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8116 struct ssh_channel *c;
8118 c = ssh2_channel_msg(ssh, pktin);
8121 if (c->type == CHAN_SHARING) {
8122 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8123 pktin->body, pktin->length);
8128 * When we receive CLOSE on a channel, we assume it comes with an
8129 * implied EOF if we haven't seen EOF yet.
8131 ssh2_channel_got_eof(c);
8133 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8135 * It also means we stop expecting to see replies to any
8136 * outstanding channel requests, so clean those up too.
8137 * (ssh_chanreq_init will enforce by assertion that we don't
8138 * subsequently put anything back on this list.)
8140 while (c->v.v2.chanreq_head) {
8141 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8142 ocr->handler(c, NULL, ocr->ctx);
8143 c->v.v2.chanreq_head = ocr->next;
8149 * And we also send an outgoing EOF, if we haven't already, on the
8150 * assumption that CLOSE is a pretty forceful announcement that
8151 * the remote side is doing away with the entire channel. (If it
8152 * had wanted to send us EOF and continue receiving data from us,
8153 * it would have just sent CHANNEL_EOF.)
8155 if (!(c->closes & CLOSES_SENT_EOF)) {
8157 * Make sure we don't read any more from whatever our local
8158 * data source is for this channel.
8161 case CHAN_MAINSESSION:
8162 ssh->send_ok = 0; /* stop trying to read from stdin */
8165 x11_override_throttle(c->u.x11.xconn, 1);
8168 pfd_override_throttle(c->u.pfd.pf, 1);
8173 * Abandon any buffered data we still wanted to send to this
8174 * channel. Receiving a CHANNEL_CLOSE is an indication that
8175 * the server really wants to get on and _destroy_ this
8176 * channel, and it isn't going to send us any further
8177 * WINDOW_ADJUSTs to permit us to send pending stuff.
8179 bufchain_clear(&c->v.v2.outbuffer);
8182 * Send outgoing EOF.
8184 sshfwd_write_eof(c);
8188 * Now process the actual close.
8190 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8191 c->closes |= CLOSES_RCVD_CLOSE;
8192 ssh2_channel_check_close(c);
8196 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8198 struct ssh_channel *c;
8200 c = ssh2_channel_msg(ssh, pktin);
8203 if (c->type == CHAN_SHARING) {
8204 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8205 pktin->body, pktin->length);
8208 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8209 c->remoteid = ssh_pkt_getuint32(pktin);
8210 c->halfopen = FALSE;
8211 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8212 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8214 if (c->type == CHAN_SOCKDATA_DORMANT) {
8215 c->type = CHAN_SOCKDATA;
8217 pfd_confirm(c->u.pfd.pf);
8218 } else if (c->type == CHAN_ZOMBIE) {
8220 * This case can occur if a local socket error occurred
8221 * between us sending out CHANNEL_OPEN and receiving
8222 * OPEN_CONFIRMATION. In this case, all we can do is
8223 * immediately initiate close proceedings now that we know the
8224 * server's id to put in the close message.
8226 ssh2_channel_check_close(c);
8229 * We never expect to receive OPEN_CONFIRMATION for any
8230 * *other* channel type (since only local-to-remote port
8231 * forwardings cause us to send CHANNEL_OPEN after the main
8232 * channel is live - all other auxiliary channel types are
8233 * initiated from the server end). It's safe to enforce this
8234 * by assertion rather than by ssh_disconnect, because the
8235 * real point is that we never constructed a half-open channel
8236 * structure in the first place with any type other than the
8239 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8243 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8246 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8248 static const char *const reasons[] = {
8249 "<unknown reason code>",
8250 "Administratively prohibited",
8252 "Unknown channel type",
8253 "Resource shortage",
8255 unsigned reason_code;
8256 char *reason_string;
8258 struct ssh_channel *c;
8260 c = ssh2_channel_msg(ssh, pktin);
8263 if (c->type == CHAN_SHARING) {
8264 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8265 pktin->body, pktin->length);
8268 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8270 if (c->type == CHAN_SOCKDATA_DORMANT) {
8271 reason_code = ssh_pkt_getuint32(pktin);
8272 if (reason_code >= lenof(reasons))
8273 reason_code = 0; /* ensure reasons[reason_code] in range */
8274 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8275 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8276 reasons[reason_code], reason_length, reason_string);
8278 pfd_close(c->u.pfd.pf);
8279 } else if (c->type == CHAN_ZOMBIE) {
8281 * This case can occur if a local socket error occurred
8282 * between us sending out CHANNEL_OPEN and receiving
8283 * OPEN_FAILURE. In this case, we need do nothing except allow
8284 * the code below to throw the half-open channel away.
8288 * We never expect to receive OPEN_FAILURE for any *other*
8289 * channel type (since only local-to-remote port forwardings
8290 * cause us to send CHANNEL_OPEN after the main channel is
8291 * live - all other auxiliary channel types are initiated from
8292 * the server end). It's safe to enforce this by assertion
8293 * rather than by ssh_disconnect, because the real point is
8294 * that we never constructed a half-open channel structure in
8295 * the first place with any type other than the above.
8297 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8300 del234(ssh->channels, c);
8304 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8307 int typelen, want_reply;
8308 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8309 struct ssh_channel *c;
8310 struct Packet *pktout;
8312 c = ssh2_channel_msg(ssh, pktin);
8315 if (c->type == CHAN_SHARING) {
8316 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8317 pktin->body, pktin->length);
8320 ssh_pkt_getstring(pktin, &type, &typelen);
8321 want_reply = ssh2_pkt_getbool(pktin);
8323 if (c->closes & CLOSES_SENT_CLOSE) {
8325 * We don't reply to channel requests after we've sent
8326 * CHANNEL_CLOSE for the channel, because our reply might
8327 * cross in the network with the other side's CHANNEL_CLOSE
8328 * and arrive after they have wound the channel up completely.
8334 * Having got the channel number, we now look at
8335 * the request type string to see if it's something
8338 if (c == ssh->mainchan) {
8340 * We recognise "exit-status" and "exit-signal" on
8341 * the primary channel.
8343 if (typelen == 11 &&
8344 !memcmp(type, "exit-status", 11)) {
8346 ssh->exitcode = ssh_pkt_getuint32(pktin);
8347 logeventf(ssh, "Server sent command exit status %d",
8349 reply = SSH2_MSG_CHANNEL_SUCCESS;
8351 } else if (typelen == 11 &&
8352 !memcmp(type, "exit-signal", 11)) {
8354 int is_plausible = TRUE, is_int = FALSE;
8355 char *fmt_sig = NULL, *fmt_msg = NULL;
8357 int msglen = 0, core = FALSE;
8358 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8359 * provide an `int' for the signal, despite its
8360 * having been a `string' in the drafts of RFC 4254 since at
8361 * least 2001. (Fixed in session.c 1.147.) Try to
8362 * infer which we can safely parse it as. */
8364 unsigned char *p = pktin->body +
8366 long len = pktin->length - pktin->savedpos;
8367 unsigned long num = GET_32BIT(p); /* what is it? */
8368 /* If it's 0, it hardly matters; assume string */
8372 int maybe_int = FALSE, maybe_str = FALSE;
8373 #define CHECK_HYPOTHESIS(offset, result) \
8376 int q = toint(offset); \
8377 if (q >= 0 && q+4 <= len) { \
8378 q = toint(q + 4 + GET_32BIT(p+q)); \
8379 if (q >= 0 && q+4 <= len && \
8380 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8385 CHECK_HYPOTHESIS(4+1, maybe_int);
8386 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8387 #undef CHECK_HYPOTHESIS
8388 if (maybe_int && !maybe_str)
8390 else if (!maybe_int && maybe_str)
8393 /* Crikey. Either or neither. Panic. */
8394 is_plausible = FALSE;
8397 ssh->exitcode = 128; /* means `unknown signal' */
8400 /* Old non-standard OpenSSH. */
8401 int signum = ssh_pkt_getuint32(pktin);
8402 fmt_sig = dupprintf(" %d", signum);
8403 ssh->exitcode = 128 + signum;
8405 /* As per RFC 4254. */
8408 ssh_pkt_getstring(pktin, &sig, &siglen);
8409 /* Signal name isn't supposed to be blank, but
8410 * let's cope gracefully if it is. */
8412 fmt_sig = dupprintf(" \"%.*s\"",
8417 * Really hideous method of translating the
8418 * signal description back into a locally
8419 * meaningful number.
8424 #define TRANSLATE_SIGNAL(s) \
8425 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8426 ssh->exitcode = 128 + SIG ## s
8428 TRANSLATE_SIGNAL(ABRT);
8431 TRANSLATE_SIGNAL(ALRM);
8434 TRANSLATE_SIGNAL(FPE);
8437 TRANSLATE_SIGNAL(HUP);
8440 TRANSLATE_SIGNAL(ILL);
8443 TRANSLATE_SIGNAL(INT);
8446 TRANSLATE_SIGNAL(KILL);
8449 TRANSLATE_SIGNAL(PIPE);
8452 TRANSLATE_SIGNAL(QUIT);
8455 TRANSLATE_SIGNAL(SEGV);
8458 TRANSLATE_SIGNAL(TERM);
8461 TRANSLATE_SIGNAL(USR1);
8464 TRANSLATE_SIGNAL(USR2);
8466 #undef TRANSLATE_SIGNAL
8468 ssh->exitcode = 128;
8470 core = ssh2_pkt_getbool(pktin);
8471 ssh_pkt_getstring(pktin, &msg, &msglen);
8473 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8475 /* ignore lang tag */
8476 } /* else don't attempt to parse */
8477 logeventf(ssh, "Server exited on signal%s%s%s",
8478 fmt_sig ? fmt_sig : "",
8479 core ? " (core dumped)" : "",
8480 fmt_msg ? fmt_msg : "");
8483 reply = SSH2_MSG_CHANNEL_SUCCESS;
8488 * This is a channel request we don't know
8489 * about, so we now either ignore the request
8490 * or respond with CHANNEL_FAILURE, depending
8493 reply = SSH2_MSG_CHANNEL_FAILURE;
8496 pktout = ssh2_pkt_init(reply);
8497 ssh2_pkt_adduint32(pktout, c->remoteid);
8498 ssh2_pkt_send(ssh, pktout);
8502 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8505 int typelen, want_reply;
8506 struct Packet *pktout;
8508 ssh_pkt_getstring(pktin, &type, &typelen);
8509 want_reply = ssh2_pkt_getbool(pktin);
8512 * We currently don't support any global requests
8513 * at all, so we either ignore the request or
8514 * respond with REQUEST_FAILURE, depending on
8518 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8519 ssh2_pkt_send(ssh, pktout);
8523 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8527 struct X11FakeAuth *auth;
8530 * Make up a new set of fake X11 auth data, and add it to the tree
8531 * of currently valid ones with an indication of the sharing
8532 * context that it's relevant to.
8534 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8535 auth->share_cs = share_cs;
8536 auth->share_chan = share_chan;
8541 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8543 del234(ssh->x11authtree, auth);
8544 x11_free_fake_auth(auth);
8547 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8554 const char *error = NULL;
8555 struct ssh_channel *c;
8556 unsigned remid, winsize, pktsize;
8557 unsigned our_winsize_override = 0;
8558 struct Packet *pktout;
8560 ssh_pkt_getstring(pktin, &type, &typelen);
8561 c = snew(struct ssh_channel);
8564 remid = ssh_pkt_getuint32(pktin);
8565 winsize = ssh_pkt_getuint32(pktin);
8566 pktsize = ssh_pkt_getuint32(pktin);
8568 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8571 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8572 addrstr = snewn(peeraddrlen+1, char);
8573 memcpy(addrstr, peeraddr, peeraddrlen);
8574 addrstr[peeraddrlen] = '\0';
8575 peerport = ssh_pkt_getuint32(pktin);
8577 logeventf(ssh, "Received X11 connect request from %s:%d",
8580 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8581 error = "X11 forwarding is not enabled";
8583 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8586 c->u.x11.initial = TRUE;
8589 * If we are a connection-sharing upstream, then we should
8590 * initially present a very small window, adequate to take
8591 * the X11 initial authorisation packet but not much more.
8592 * Downstream will then present us a larger window (by
8593 * fiat of the connection-sharing protocol) and we can
8594 * guarantee to send a positive-valued WINDOW_ADJUST.
8597 our_winsize_override = 128;
8599 logevent("Opened X11 forward channel");
8603 } else if (typelen == 15 &&
8604 !memcmp(type, "forwarded-tcpip", 15)) {
8605 struct ssh_rportfwd pf, *realpf;
8608 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8609 pf.shost = dupprintf("%.*s", shostlen, shost);
8610 pf.sport = ssh_pkt_getuint32(pktin);
8611 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8612 peerport = ssh_pkt_getuint32(pktin);
8613 realpf = find234(ssh->rportfwds, &pf, NULL);
8614 logeventf(ssh, "Received remote port %s:%d open request "
8615 "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
8618 if (realpf == NULL) {
8619 error = "Remote port is not recognised";
8623 if (realpf->share_ctx) {
8625 * This port forwarding is on behalf of a
8626 * connection-sharing downstream, so abandon our own
8627 * channel-open procedure and just pass the message on
8630 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8631 pktin->body, pktin->length);
8636 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8637 c, ssh->conf, realpf->pfrec->addressfamily);
8638 logeventf(ssh, "Attempting to forward remote port to "
8639 "%s:%d", realpf->dhost, realpf->dport);
8641 logeventf(ssh, "Port open failed: %s", err);
8643 error = "Port open failed";
8645 logevent("Forwarded port opened successfully");
8646 c->type = CHAN_SOCKDATA;
8649 } else if (typelen == 22 &&
8650 !memcmp(type, "auth-agent@openssh.com", 22)) {
8651 if (!ssh->agentfwd_enabled)
8652 error = "Agent forwarding is not enabled";
8654 c->type = CHAN_AGENT; /* identify channel type */
8655 c->u.a.lensofar = 0;
8656 c->u.a.message = NULL;
8657 c->u.a.outstanding_requests = 0;
8660 error = "Unsupported channel type requested";
8663 c->remoteid = remid;
8664 c->halfopen = FALSE;
8666 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8667 ssh2_pkt_adduint32(pktout, c->remoteid);
8668 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8669 ssh2_pkt_addstring(pktout, error);
8670 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8671 ssh2_pkt_send(ssh, pktout);
8672 logeventf(ssh, "Rejected channel open: %s", error);
8675 ssh2_channel_init(c);
8676 c->v.v2.remwindow = winsize;
8677 c->v.v2.remmaxpkt = pktsize;
8678 if (our_winsize_override) {
8679 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8680 our_winsize_override;
8682 add234(ssh->channels, c);
8683 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8684 ssh2_pkt_adduint32(pktout, c->remoteid);
8685 ssh2_pkt_adduint32(pktout, c->localid);
8686 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8687 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8688 ssh2_pkt_send(ssh, pktout);
8692 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8693 void *share_cs, void *share_chan,
8694 const char *peer_addr, int peer_port,
8695 int endian, int protomajor, int protominor,
8696 const void *initial_data, int initial_len)
8699 * This function is called when we've just discovered that an X
8700 * forwarding channel on which we'd been handling the initial auth
8701 * ourselves turns out to be destined for a connection-sharing
8702 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8703 * that we completely stop tracking windows and buffering data and
8704 * just pass more or less unmodified SSH messages back and forth.
8706 c->type = CHAN_SHARING;
8707 c->u.sharing.ctx = share_cs;
8708 share_setup_x11_channel(share_cs, share_chan,
8709 c->localid, c->remoteid, c->v.v2.remwindow,
8710 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8711 peer_addr, peer_port, endian,
8712 protomajor, protominor,
8713 initial_data, initial_len);
8716 void sshfwd_x11_is_local(struct ssh_channel *c)
8719 * This function is called when we've just discovered that an X
8720 * forwarding channel is _not_ destined for a connection-sharing
8721 * downstream but we're going to handle it ourselves. We stop
8722 * presenting a cautiously small window and go into ordinary data
8725 c->u.x11.initial = FALSE;
8726 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8730 * Buffer banner messages for later display at some convenient point,
8731 * if we're going to display them.
8733 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8735 /* Arbitrary limit to prevent unbounded inflation of buffer */
8736 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8737 bufchain_size(&ssh->banner) <= 131072) {
8738 char *banner = NULL;
8740 ssh_pkt_getstring(pktin, &banner, &size);
8742 bufchain_add(&ssh->banner, banner, size);
8746 /* Helper function to deal with sending tty modes for "pty-req" */
8747 static void ssh2_send_ttymode(void *data, char *mode, char *val)
8749 struct Packet *pktout = (struct Packet *)data;
8751 unsigned int arg = 0;
8752 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
8753 if (i == lenof(ssh_ttymodes)) return;
8754 switch (ssh_ttymodes[i].type) {
8756 arg = ssh_tty_parse_specchar(val);
8759 arg = ssh_tty_parse_boolean(val);
8762 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
8763 ssh2_pkt_adduint32(pktout, arg);
8766 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8769 struct ssh2_setup_x11_state {
8773 struct Packet *pktout;
8774 crStateP(ssh2_setup_x11_state, ctx);
8778 logevent("Requesting X11 forwarding");
8779 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8781 ssh2_pkt_addbool(pktout, 0); /* many connections */
8782 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8783 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8784 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8785 ssh2_pkt_send(ssh, pktout);
8787 /* Wait to be called back with either a response packet, or NULL
8788 * meaning clean up and free our data */
8792 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8793 logevent("X11 forwarding enabled");
8794 ssh->X11_fwd_enabled = TRUE;
8796 logevent("X11 forwarding refused");
8802 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8805 struct ssh2_setup_agent_state {
8809 struct Packet *pktout;
8810 crStateP(ssh2_setup_agent_state, ctx);
8814 logevent("Requesting OpenSSH-style agent forwarding");
8815 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8816 ssh2_setup_agent, s);
8817 ssh2_pkt_send(ssh, pktout);
8819 /* Wait to be called back with either a response packet, or NULL
8820 * meaning clean up and free our data */
8824 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8825 logevent("Agent forwarding enabled");
8826 ssh->agentfwd_enabled = TRUE;
8828 logevent("Agent forwarding refused");
8834 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8837 struct ssh2_setup_pty_state {
8841 struct Packet *pktout;
8842 crStateP(ssh2_setup_pty_state, ctx);
8846 /* Unpick the terminal-speed string. */
8847 /* XXX perhaps we should allow no speeds to be sent. */
8848 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8849 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8850 /* Build the pty request. */
8851 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
8853 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
8854 ssh2_pkt_adduint32(pktout, ssh->term_width);
8855 ssh2_pkt_adduint32(pktout, ssh->term_height);
8856 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
8857 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
8858 ssh2_pkt_addstring_start(pktout);
8859 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
8860 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
8861 ssh2_pkt_adduint32(pktout, ssh->ispeed);
8862 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
8863 ssh2_pkt_adduint32(pktout, ssh->ospeed);
8864 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
8865 ssh2_pkt_send(ssh, pktout);
8866 ssh->state = SSH_STATE_INTERMED;
8868 /* Wait to be called back with either a response packet, or NULL
8869 * meaning clean up and free our data */
8873 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8874 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8875 ssh->ospeed, ssh->ispeed);
8876 ssh->got_pty = TRUE;
8878 c_write_str(ssh, "Server refused to allocate pty\r\n");
8879 ssh->editing = ssh->echoing = 1;
8886 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
8889 struct ssh2_setup_env_state {
8891 int num_env, env_left, env_ok;
8894 struct Packet *pktout;
8895 crStateP(ssh2_setup_env_state, ctx);
8900 * Send environment variables.
8902 * Simplest thing here is to send all the requests at once, and
8903 * then wait for a whole bunch of successes or failures.
8909 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
8911 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
8912 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
8913 ssh2_pkt_addstring(pktout, key);
8914 ssh2_pkt_addstring(pktout, val);
8915 ssh2_pkt_send(ssh, pktout);
8920 logeventf(ssh, "Sent %d environment variables", s->num_env);
8925 s->env_left = s->num_env;
8927 while (s->env_left > 0) {
8928 /* Wait to be called back with either a response packet,
8929 * or NULL meaning clean up and free our data */
8931 if (!pktin) goto out;
8932 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
8937 if (s->env_ok == s->num_env) {
8938 logevent("All environment variables successfully set");
8939 } else if (s->env_ok == 0) {
8940 logevent("All environment variables refused");
8941 c_write_str(ssh, "Server refused to set environment variables\r\n");
8943 logeventf(ssh, "%d environment variables refused",
8944 s->num_env - s->env_ok);
8945 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8953 * Handle the SSH-2 userauth and connection layers.
8955 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
8957 do_ssh2_authconn(ssh, NULL, 0, pktin);
8960 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
8964 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
8967 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
8968 struct Packet *pktin)
8970 struct do_ssh2_authconn_state {
8974 AUTH_TYPE_PUBLICKEY,
8975 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
8976 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
8978 AUTH_TYPE_GSSAPI, /* always QUIET */
8979 AUTH_TYPE_KEYBOARD_INTERACTIVE,
8980 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
8982 int done_service_req;
8983 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
8984 int tried_pubkey_config, done_agent;
8989 int kbd_inter_refused;
8990 int we_are_in, userauth_success;
8991 prompts_t *cur_prompt;
8996 void *publickey_blob;
8997 int publickey_bloblen;
8998 int privatekey_available, privatekey_encrypted;
8999 char *publickey_algorithm;
9000 char *publickey_comment;
9001 unsigned char agent_request[5], *agent_response, *agentp;
9002 int agent_responselen;
9003 unsigned char *pkblob_in_agent;
9005 char *pkblob, *alg, *commentp;
9006 int pklen, alglen, commentlen;
9007 int siglen, retlen, len;
9008 char *q, *agentreq, *ret;
9010 struct Packet *pktout;
9013 struct ssh_gss_library *gsslib;
9014 Ssh_gss_ctx gss_ctx;
9015 Ssh_gss_buf gss_buf;
9016 Ssh_gss_buf gss_rcvtok, gss_sndtok;
9017 Ssh_gss_name gss_srv_name;
9018 Ssh_gss_stat gss_stat;
9021 crState(do_ssh2_authconn_state);
9025 /* Register as a handler for all the messages this coroutine handles. */
9026 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9027 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9028 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9029 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9030 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9031 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9032 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9033 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9034 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9035 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9036 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9037 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9038 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9039 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9040 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9041 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9042 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9043 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9044 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9045 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9047 s->done_service_req = FALSE;
9048 s->we_are_in = s->userauth_success = FALSE;
9049 s->agent_response = NULL;
9051 s->tried_gssapi = FALSE;
9054 if (!ssh->bare_connection) {
9055 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9057 * Request userauth protocol, and await a response to it.
9059 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9060 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9061 ssh2_pkt_send(ssh, s->pktout);
9062 crWaitUntilV(pktin);
9063 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9064 s->done_service_req = TRUE;
9066 if (!s->done_service_req) {
9068 * Request connection protocol directly, without authentication.
9070 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9071 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9072 ssh2_pkt_send(ssh, s->pktout);
9073 crWaitUntilV(pktin);
9074 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9075 s->we_are_in = TRUE; /* no auth required */
9077 bombout(("Server refused service request"));
9082 s->we_are_in = TRUE;
9085 /* Arrange to be able to deal with any BANNERs that come in.
9086 * (We do this now as packets may come in during the next bit.) */
9087 bufchain_init(&ssh->banner);
9088 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9089 ssh2_msg_userauth_banner;
9092 * Misc one-time setup for authentication.
9094 s->publickey_blob = NULL;
9095 if (!s->we_are_in) {
9098 * Load the public half of any configured public key file
9101 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9102 if (!filename_is_null(s->keyfile)) {
9104 logeventf(ssh, "Reading key file \"%.150s\"",
9105 filename_to_str(s->keyfile));
9106 keytype = key_type(s->keyfile);
9107 if (keytype == SSH_KEYTYPE_SSH2 ||
9108 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9109 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9112 ssh2_userkey_loadpub(s->keyfile,
9113 &s->publickey_algorithm,
9114 &s->publickey_bloblen,
9115 &s->publickey_comment, &error);
9116 if (s->publickey_blob) {
9117 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9118 if (!s->privatekey_available)
9119 logeventf(ssh, "Key file contains public key only");
9120 s->privatekey_encrypted =
9121 ssh2_userkey_encrypted(s->keyfile, NULL);
9124 logeventf(ssh, "Unable to load key (%s)",
9126 msgbuf = dupprintf("Unable to load key file "
9127 "\"%.150s\" (%s)\r\n",
9128 filename_to_str(s->keyfile),
9130 c_write_str(ssh, msgbuf);
9135 logeventf(ssh, "Unable to use this key file (%s)",
9136 key_type_to_str(keytype));
9137 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9139 filename_to_str(s->keyfile),
9140 key_type_to_str(keytype));
9141 c_write_str(ssh, msgbuf);
9143 s->publickey_blob = NULL;
9148 * Find out about any keys Pageant has (but if there's a
9149 * public key configured, filter out all others).
9152 s->agent_response = NULL;
9153 s->pkblob_in_agent = NULL;
9154 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9158 logevent("Pageant is running. Requesting keys.");
9160 /* Request the keys held by the agent. */
9161 PUT_32BIT(s->agent_request, 1);
9162 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9163 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9164 ssh_agent_callback, ssh)) {
9168 bombout(("Unexpected data from server while"
9169 " waiting for agent response"));
9172 } while (pktin || inlen > 0);
9173 r = ssh->agent_response;
9174 s->agent_responselen = ssh->agent_response_len;
9176 s->agent_response = (unsigned char *) r;
9177 if (s->agent_response && s->agent_responselen >= 5 &&
9178 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9181 p = s->agent_response + 5;
9182 s->nkeys = toint(GET_32BIT(p));
9185 * Vet the Pageant response to ensure that the key
9186 * count and blob lengths make sense.
9189 logeventf(ssh, "Pageant response contained a negative"
9190 " key count %d", s->nkeys);
9192 goto done_agent_query;
9194 unsigned char *q = p + 4;
9195 int lenleft = s->agent_responselen - 5 - 4;
9197 for (keyi = 0; keyi < s->nkeys; keyi++) {
9198 int bloblen, commentlen;
9200 logeventf(ssh, "Pageant response was truncated");
9202 goto done_agent_query;
9204 bloblen = toint(GET_32BIT(q));
9205 if (bloblen < 0 || bloblen > lenleft) {
9206 logeventf(ssh, "Pageant response was truncated");
9208 goto done_agent_query;
9210 lenleft -= 4 + bloblen;
9212 commentlen = toint(GET_32BIT(q));
9213 if (commentlen < 0 || commentlen > lenleft) {
9214 logeventf(ssh, "Pageant response was truncated");
9216 goto done_agent_query;
9218 lenleft -= 4 + commentlen;
9219 q += 4 + commentlen;
9224 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9225 if (s->publickey_blob) {
9226 /* See if configured key is in agent. */
9227 for (keyi = 0; keyi < s->nkeys; keyi++) {
9228 s->pklen = toint(GET_32BIT(p));
9229 if (s->pklen == s->publickey_bloblen &&
9230 !memcmp(p+4, s->publickey_blob,
9231 s->publickey_bloblen)) {
9232 logeventf(ssh, "Pageant key #%d matches "
9233 "configured key file", keyi);
9235 s->pkblob_in_agent = p;
9239 p += toint(GET_32BIT(p)) + 4; /* comment */
9241 if (!s->pkblob_in_agent) {
9242 logevent("Configured key file not in Pageant");
9247 logevent("Failed to get reply from Pageant");
9255 * We repeat this whole loop, including the username prompt,
9256 * until we manage a successful authentication. If the user
9257 * types the wrong _password_, they can be sent back to the
9258 * beginning to try another username, if this is configured on.
9259 * (If they specify a username in the config, they are never
9260 * asked, even if they do give a wrong password.)
9262 * I think this best serves the needs of
9264 * - the people who have no configuration, no keys, and just
9265 * want to try repeated (username,password) pairs until they
9266 * type both correctly
9268 * - people who have keys and configuration but occasionally
9269 * need to fall back to passwords
9271 * - people with a key held in Pageant, who might not have
9272 * logged in to a particular machine before; so they want to
9273 * type a username, and then _either_ their key will be
9274 * accepted, _or_ they will type a password. If they mistype
9275 * the username they will want to be able to get back and
9278 s->got_username = FALSE;
9279 while (!s->we_are_in) {
9283 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9285 * We got a username last time round this loop, and
9286 * with change_username turned off we don't try to get
9289 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9290 int ret; /* need not be kept over crReturn */
9291 s->cur_prompt = new_prompts(ssh->frontend);
9292 s->cur_prompt->to_server = TRUE;
9293 s->cur_prompt->name = dupstr("SSH login name");
9294 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9295 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9298 crWaitUntilV(!pktin);
9299 ret = get_userpass_input(s->cur_prompt, in, inlen);
9304 * get_userpass_input() failed to get a username.
9307 free_prompts(s->cur_prompt);
9308 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9311 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9312 free_prompts(s->cur_prompt);
9315 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9316 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9317 c_write_str(ssh, stuff);
9321 s->got_username = TRUE;
9324 * Send an authentication request using method "none": (a)
9325 * just in case it succeeds, and (b) so that we know what
9326 * authentication methods we can usefully try next.
9328 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9330 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9331 ssh2_pkt_addstring(s->pktout, ssh->username);
9332 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9333 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9334 ssh2_pkt_send(ssh, s->pktout);
9335 s->type = AUTH_TYPE_NONE;
9337 s->we_are_in = FALSE;
9339 s->tried_pubkey_config = FALSE;
9340 s->kbd_inter_refused = FALSE;
9342 /* Reset agent request state. */
9343 s->done_agent = FALSE;
9344 if (s->agent_response) {
9345 if (s->pkblob_in_agent) {
9346 s->agentp = s->pkblob_in_agent;
9348 s->agentp = s->agent_response + 5 + 4;
9354 char *methods = NULL;
9358 * Wait for the result of the last authentication request.
9361 crWaitUntilV(pktin);
9363 * Now is a convenient point to spew any banner material
9364 * that we've accumulated. (This should ensure that when
9365 * we exit the auth loop, we haven't any left to deal
9369 int size = bufchain_size(&ssh->banner);
9371 * Don't show the banner if we're operating in
9372 * non-verbose non-interactive mode. (It's probably
9373 * a script, which means nobody will read the
9374 * banner _anyway_, and moreover the printing of
9375 * the banner will screw up processing on the
9376 * output of (say) plink.)
9378 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9379 char *banner = snewn(size, char);
9380 bufchain_fetch(&ssh->banner, banner, size);
9381 c_write_untrusted(ssh, banner, size);
9384 bufchain_clear(&ssh->banner);
9386 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9387 logevent("Access granted");
9388 s->we_are_in = s->userauth_success = TRUE;
9392 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9393 bombout(("Strange packet received during authentication: "
9394 "type %d", pktin->type));
9401 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9402 * we can look at the string in it and know what we can
9403 * helpfully try next.
9405 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9406 ssh_pkt_getstring(pktin, &methods, &methlen);
9407 if (!ssh2_pkt_getbool(pktin)) {
9409 * We have received an unequivocal Access
9410 * Denied. This can translate to a variety of
9411 * messages, or no message at all.
9413 * For forms of authentication which are attempted
9414 * implicitly, by which I mean without printing
9415 * anything in the window indicating that we're
9416 * trying them, we should never print 'Access
9419 * If we do print a message saying that we're
9420 * attempting some kind of authentication, it's OK
9421 * to print a followup message saying it failed -
9422 * but the message may sometimes be more specific
9423 * than simply 'Access denied'.
9425 * Additionally, if we'd just tried password
9426 * authentication, we should break out of this
9427 * whole loop so as to go back to the username
9428 * prompt (iff we're configured to allow
9429 * username change attempts).
9431 if (s->type == AUTH_TYPE_NONE) {
9433 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9434 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9435 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9436 c_write_str(ssh, "Server refused our key\r\n");
9437 logevent("Server refused our key");
9438 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9439 /* This _shouldn't_ happen except by a
9440 * protocol bug causing client and server to
9441 * disagree on what is a correct signature. */
9442 c_write_str(ssh, "Server refused public-key signature"
9443 " despite accepting key!\r\n");
9444 logevent("Server refused public-key signature"
9445 " despite accepting key!");
9446 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9447 /* quiet, so no c_write */
9448 logevent("Server refused keyboard-interactive authentication");
9449 } else if (s->type==AUTH_TYPE_GSSAPI) {
9450 /* always quiet, so no c_write */
9451 /* also, the code down in the GSSAPI block has
9452 * already logged this in the Event Log */
9453 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9454 logevent("Keyboard-interactive authentication failed");
9455 c_write_str(ssh, "Access denied\r\n");
9457 assert(s->type == AUTH_TYPE_PASSWORD);
9458 logevent("Password authentication failed");
9459 c_write_str(ssh, "Access denied\r\n");
9461 if (conf_get_int(ssh->conf, CONF_change_username)) {
9462 /* XXX perhaps we should allow
9463 * keyboard-interactive to do this too? */
9464 s->we_are_in = FALSE;
9469 c_write_str(ssh, "Further authentication required\r\n");
9470 logevent("Further authentication required");
9474 in_commasep_string("publickey", methods, methlen);
9476 in_commasep_string("password", methods, methlen);
9477 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9478 in_commasep_string("keyboard-interactive", methods, methlen);
9480 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9481 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9482 /* Try loading the GSS libraries and see if we
9485 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9486 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9488 /* No point in even bothering to try to load the
9489 * GSS libraries, if the user configuration and
9490 * server aren't both prepared to attempt GSSAPI
9491 * auth in the first place. */
9492 s->can_gssapi = FALSE;
9497 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9499 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9502 * Attempt public-key authentication using a key from Pageant.
9505 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9507 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9509 /* Unpack key from agent response */
9510 s->pklen = toint(GET_32BIT(s->agentp));
9512 s->pkblob = (char *)s->agentp;
9513 s->agentp += s->pklen;
9514 s->alglen = toint(GET_32BIT(s->pkblob));
9515 s->alg = s->pkblob + 4;
9516 s->commentlen = toint(GET_32BIT(s->agentp));
9518 s->commentp = (char *)s->agentp;
9519 s->agentp += s->commentlen;
9520 /* s->agentp now points at next key, if any */
9522 /* See if server will accept it */
9523 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9524 ssh2_pkt_addstring(s->pktout, ssh->username);
9525 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9526 /* service requested */
9527 ssh2_pkt_addstring(s->pktout, "publickey");
9529 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9530 ssh2_pkt_addstring_start(s->pktout);
9531 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9532 ssh2_pkt_addstring_start(s->pktout);
9533 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9534 ssh2_pkt_send(ssh, s->pktout);
9535 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9537 crWaitUntilV(pktin);
9538 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9540 /* Offer of key refused. */
9547 if (flags & FLAG_VERBOSE) {
9548 c_write_str(ssh, "Authenticating with "
9550 c_write(ssh, s->commentp, s->commentlen);
9551 c_write_str(ssh, "\" from agent\r\n");
9555 * Server is willing to accept the key.
9556 * Construct a SIGN_REQUEST.
9558 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9559 ssh2_pkt_addstring(s->pktout, ssh->username);
9560 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9561 /* service requested */
9562 ssh2_pkt_addstring(s->pktout, "publickey");
9564 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9565 ssh2_pkt_addstring_start(s->pktout);
9566 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9567 ssh2_pkt_addstring_start(s->pktout);
9568 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9570 /* Ask agent for signature. */
9571 s->siglen = s->pktout->length - 5 + 4 +
9572 ssh->v2_session_id_len;
9573 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9575 s->len = 1; /* message type */
9576 s->len += 4 + s->pklen; /* key blob */
9577 s->len += 4 + s->siglen; /* data to sign */
9578 s->len += 4; /* flags */
9579 s->agentreq = snewn(4 + s->len, char);
9580 PUT_32BIT(s->agentreq, s->len);
9581 s->q = s->agentreq + 4;
9582 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9583 PUT_32BIT(s->q, s->pklen);
9585 memcpy(s->q, s->pkblob, s->pklen);
9587 PUT_32BIT(s->q, s->siglen);
9589 /* Now the data to be signed... */
9590 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9591 PUT_32BIT(s->q, ssh->v2_session_id_len);
9594 memcpy(s->q, ssh->v2_session_id,
9595 ssh->v2_session_id_len);
9596 s->q += ssh->v2_session_id_len;
9597 memcpy(s->q, s->pktout->data + 5,
9598 s->pktout->length - 5);
9599 s->q += s->pktout->length - 5;
9600 /* And finally the (zero) flags word. */
9602 if (!agent_query(s->agentreq, s->len + 4,
9604 ssh_agent_callback, ssh)) {
9608 bombout(("Unexpected data from server"
9609 " while waiting for agent"
9613 } while (pktin || inlen > 0);
9614 vret = ssh->agent_response;
9615 s->retlen = ssh->agent_response_len;
9620 if (s->retlen >= 9 &&
9621 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9622 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9623 logevent("Sending Pageant's response");
9624 ssh2_add_sigblob(ssh, s->pktout,
9625 s->pkblob, s->pklen,
9627 GET_32BIT(s->ret + 5));
9628 ssh2_pkt_send(ssh, s->pktout);
9629 s->type = AUTH_TYPE_PUBLICKEY;
9631 /* FIXME: less drastic response */
9632 bombout(("Pageant failed to answer challenge"));
9638 /* Do we have any keys left to try? */
9639 if (s->pkblob_in_agent) {
9640 s->done_agent = TRUE;
9641 s->tried_pubkey_config = TRUE;
9644 if (s->keyi >= s->nkeys)
9645 s->done_agent = TRUE;
9648 } else if (s->can_pubkey && s->publickey_blob &&
9649 s->privatekey_available && !s->tried_pubkey_config) {
9651 struct ssh2_userkey *key; /* not live over crReturn */
9652 char *passphrase; /* not live over crReturn */
9654 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9656 s->tried_pubkey_config = TRUE;
9659 * Try the public key supplied in the configuration.
9661 * First, offer the public blob to see if the server is
9662 * willing to accept it.
9664 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9665 ssh2_pkt_addstring(s->pktout, ssh->username);
9666 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9667 /* service requested */
9668 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9669 ssh2_pkt_addbool(s->pktout, FALSE);
9670 /* no signature included */
9671 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9672 ssh2_pkt_addstring_start(s->pktout);
9673 ssh2_pkt_addstring_data(s->pktout,
9674 (char *)s->publickey_blob,
9675 s->publickey_bloblen);
9676 ssh2_pkt_send(ssh, s->pktout);
9677 logevent("Offered public key");
9679 crWaitUntilV(pktin);
9680 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9681 /* Key refused. Give up. */
9682 s->gotit = TRUE; /* reconsider message next loop */
9683 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9684 continue; /* process this new message */
9686 logevent("Offer of public key accepted");
9689 * Actually attempt a serious authentication using
9692 if (flags & FLAG_VERBOSE) {
9693 c_write_str(ssh, "Authenticating with public key \"");
9694 c_write_str(ssh, s->publickey_comment);
9695 c_write_str(ssh, "\"\r\n");
9699 const char *error; /* not live over crReturn */
9700 if (s->privatekey_encrypted) {
9702 * Get a passphrase from the user.
9704 int ret; /* need not be kept over crReturn */
9705 s->cur_prompt = new_prompts(ssh->frontend);
9706 s->cur_prompt->to_server = FALSE;
9707 s->cur_prompt->name = dupstr("SSH key passphrase");
9708 add_prompt(s->cur_prompt,
9709 dupprintf("Passphrase for key \"%.100s\": ",
9710 s->publickey_comment),
9712 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9715 crWaitUntilV(!pktin);
9716 ret = get_userpass_input(s->cur_prompt,
9721 /* Failed to get a passphrase. Terminate. */
9722 free_prompts(s->cur_prompt);
9723 ssh_disconnect(ssh, NULL,
9724 "Unable to authenticate",
9725 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9730 dupstr(s->cur_prompt->prompts[0]->result);
9731 free_prompts(s->cur_prompt);
9733 passphrase = NULL; /* no passphrase needed */
9737 * Try decrypting the key.
9739 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9740 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9742 /* burn the evidence */
9743 smemclr(passphrase, strlen(passphrase));
9746 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9748 (key == SSH2_WRONG_PASSPHRASE)) {
9749 c_write_str(ssh, "Wrong passphrase\r\n");
9751 /* and loop again */
9753 c_write_str(ssh, "Unable to load private key (");
9754 c_write_str(ssh, error);
9755 c_write_str(ssh, ")\r\n");
9757 break; /* try something else */
9763 unsigned char *pkblob, *sigblob, *sigdata;
9764 int pkblob_len, sigblob_len, sigdata_len;
9768 * We have loaded the private key and the server
9769 * has announced that it's willing to accept it.
9770 * Hallelujah. Generate a signature and send it.
9772 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9773 ssh2_pkt_addstring(s->pktout, ssh->username);
9774 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9775 /* service requested */
9776 ssh2_pkt_addstring(s->pktout, "publickey");
9778 ssh2_pkt_addbool(s->pktout, TRUE);
9779 /* signature follows */
9780 ssh2_pkt_addstring(s->pktout, key->alg->name);
9781 pkblob = key->alg->public_blob(key->data,
9783 ssh2_pkt_addstring_start(s->pktout);
9784 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9788 * The data to be signed is:
9792 * followed by everything so far placed in the
9795 sigdata_len = s->pktout->length - 5 + 4 +
9796 ssh->v2_session_id_len;
9797 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9799 sigdata = snewn(sigdata_len, unsigned char);
9801 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9802 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9805 memcpy(sigdata+p, ssh->v2_session_id,
9806 ssh->v2_session_id_len);
9807 p += ssh->v2_session_id_len;
9808 memcpy(sigdata+p, s->pktout->data + 5,
9809 s->pktout->length - 5);
9810 p += s->pktout->length - 5;
9811 assert(p == sigdata_len);
9812 sigblob = key->alg->sign(key->data, (char *)sigdata,
9813 sigdata_len, &sigblob_len);
9814 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9815 sigblob, sigblob_len);
9820 ssh2_pkt_send(ssh, s->pktout);
9821 logevent("Sent public key signature");
9822 s->type = AUTH_TYPE_PUBLICKEY;
9823 key->alg->freekey(key->data);
9824 sfree(key->comment);
9829 } else if (s->can_gssapi && !s->tried_gssapi) {
9831 /* GSSAPI Authentication */
9836 s->type = AUTH_TYPE_GSSAPI;
9837 s->tried_gssapi = TRUE;
9839 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9842 * Pick the highest GSS library on the preference
9848 for (i = 0; i < ngsslibs; i++) {
9849 int want_id = conf_get_int_int(ssh->conf,
9850 CONF_ssh_gsslist, i);
9851 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
9852 if (ssh->gsslibs->libraries[j].id == want_id) {
9853 s->gsslib = &ssh->gsslibs->libraries[j];
9854 goto got_gsslib; /* double break */
9859 * We always expect to have found something in
9860 * the above loop: we only came here if there
9861 * was at least one viable GSS library, and the
9862 * preference list should always mention
9863 * everything and only change the order.
9868 if (s->gsslib->gsslogmsg)
9869 logevent(s->gsslib->gsslogmsg);
9871 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
9872 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9873 ssh2_pkt_addstring(s->pktout, ssh->username);
9874 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9875 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
9876 logevent("Attempting GSSAPI authentication");
9878 /* add mechanism info */
9879 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
9881 /* number of GSSAPI mechanisms */
9882 ssh2_pkt_adduint32(s->pktout,1);
9884 /* length of OID + 2 */
9885 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
9886 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
9889 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
9891 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
9893 ssh2_pkt_send(ssh, s->pktout);
9894 crWaitUntilV(pktin);
9895 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
9896 logevent("GSSAPI authentication request refused");
9900 /* check returned packet ... */
9902 ssh_pkt_getstring(pktin, &data, &len);
9903 s->gss_rcvtok.value = data;
9904 s->gss_rcvtok.length = len;
9905 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
9906 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
9907 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
9908 memcmp((char *)s->gss_rcvtok.value + 2,
9909 s->gss_buf.value,s->gss_buf.length) ) {
9910 logevent("GSSAPI authentication - wrong response from server");
9914 /* now start running */
9915 s->gss_stat = s->gsslib->import_name(s->gsslib,
9918 if (s->gss_stat != SSH_GSS_OK) {
9919 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
9920 logevent("GSSAPI import name failed - Bad service name");
9922 logevent("GSSAPI import name failed");
9926 /* fetch TGT into GSS engine */
9927 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
9929 if (s->gss_stat != SSH_GSS_OK) {
9930 logevent("GSSAPI authentication failed to get credentials");
9931 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9935 /* initial tokens are empty */
9936 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
9937 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
9939 /* now enter the loop */
9941 s->gss_stat = s->gsslib->init_sec_context
9945 conf_get_int(ssh->conf, CONF_gssapifwd),
9949 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
9950 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
9951 logevent("GSSAPI authentication initialisation failed");
9953 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
9954 &s->gss_buf) == SSH_GSS_OK) {
9955 logevent(s->gss_buf.value);
9956 sfree(s->gss_buf.value);
9961 logevent("GSSAPI authentication initialised");
9963 /* Client and server now exchange tokens until GSSAPI
9964 * no longer says CONTINUE_NEEDED */
9966 if (s->gss_sndtok.length != 0) {
9967 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
9968 ssh_pkt_addstring_start(s->pktout);
9969 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
9970 ssh2_pkt_send(ssh, s->pktout);
9971 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
9974 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
9975 crWaitUntilV(pktin);
9976 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
9977 logevent("GSSAPI authentication - bad server response");
9978 s->gss_stat = SSH_GSS_FAILURE;
9981 ssh_pkt_getstring(pktin, &data, &len);
9982 s->gss_rcvtok.value = data;
9983 s->gss_rcvtok.length = len;
9985 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
9987 if (s->gss_stat != SSH_GSS_OK) {
9988 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9989 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9992 logevent("GSSAPI authentication loop finished OK");
9994 /* Now send the MIC */
9996 s->pktout = ssh2_pkt_init(0);
9997 micoffset = s->pktout->length;
9998 ssh_pkt_addstring_start(s->pktout);
9999 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10000 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10001 ssh_pkt_addstring(s->pktout, ssh->username);
10002 ssh_pkt_addstring(s->pktout, "ssh-connection");
10003 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10005 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10006 s->gss_buf.length = s->pktout->length - micoffset;
10008 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10009 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10010 ssh_pkt_addstring_start(s->pktout);
10011 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10012 ssh2_pkt_send(ssh, s->pktout);
10013 s->gsslib->free_mic(s->gsslib, &mic);
10017 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10018 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10021 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10024 * Keyboard-interactive authentication.
10027 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10029 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10031 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10032 ssh2_pkt_addstring(s->pktout, ssh->username);
10033 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10034 /* service requested */
10035 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10037 ssh2_pkt_addstring(s->pktout, ""); /* lang */
10038 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
10039 ssh2_pkt_send(ssh, s->pktout);
10041 logevent("Attempting keyboard-interactive authentication");
10043 crWaitUntilV(pktin);
10044 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10045 /* Server is not willing to do keyboard-interactive
10046 * at all (or, bizarrely but legally, accepts the
10047 * user without actually issuing any prompts).
10048 * Give up on it entirely. */
10050 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10051 s->kbd_inter_refused = TRUE; /* don't try it again */
10056 * Loop while the server continues to send INFO_REQUESTs.
10058 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10060 char *name, *inst, *lang;
10061 int name_len, inst_len, lang_len;
10065 * We've got a fresh USERAUTH_INFO_REQUEST.
10066 * Get the preamble and start building a prompt.
10068 ssh_pkt_getstring(pktin, &name, &name_len);
10069 ssh_pkt_getstring(pktin, &inst, &inst_len);
10070 ssh_pkt_getstring(pktin, &lang, &lang_len);
10071 s->cur_prompt = new_prompts(ssh->frontend);
10072 s->cur_prompt->to_server = TRUE;
10075 * Get any prompt(s) from the packet.
10077 s->num_prompts = ssh_pkt_getuint32(pktin);
10078 for (i = 0; i < s->num_prompts; i++) {
10082 static char noprompt[] =
10083 "<server failed to send prompt>: ";
10085 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10086 echo = ssh2_pkt_getbool(pktin);
10089 prompt_len = lenof(noprompt)-1;
10091 add_prompt(s->cur_prompt,
10092 dupprintf("%.*s", prompt_len, prompt),
10097 /* FIXME: better prefix to distinguish from
10098 * local prompts? */
10099 s->cur_prompt->name =
10100 dupprintf("SSH server: %.*s", name_len, name);
10101 s->cur_prompt->name_reqd = TRUE;
10103 s->cur_prompt->name =
10104 dupstr("SSH server authentication");
10105 s->cur_prompt->name_reqd = FALSE;
10107 /* We add a prefix to try to make it clear that a prompt
10108 * has come from the server.
10109 * FIXME: ugly to print "Using..." in prompt _every_
10110 * time round. Can this be done more subtly? */
10111 /* Special case: for reasons best known to themselves,
10112 * some servers send k-i requests with no prompts and
10113 * nothing to display. Keep quiet in this case. */
10114 if (s->num_prompts || name_len || inst_len) {
10115 s->cur_prompt->instruction =
10116 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10117 inst_len ? "\n" : "", inst_len, inst);
10118 s->cur_prompt->instr_reqd = TRUE;
10120 s->cur_prompt->instr_reqd = FALSE;
10124 * Display any instructions, and get the user's
10128 int ret; /* not live over crReturn */
10129 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10132 crWaitUntilV(!pktin);
10133 ret = get_userpass_input(s->cur_prompt, in, inlen);
10138 * Failed to get responses. Terminate.
10140 free_prompts(s->cur_prompt);
10141 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10142 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10149 * Send the response(s) to the server.
10151 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10152 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10153 for (i=0; i < s->num_prompts; i++) {
10154 ssh2_pkt_addstring(s->pktout,
10155 s->cur_prompt->prompts[i]->result);
10157 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10160 * Free the prompts structure from this iteration.
10161 * If there's another, a new one will be allocated
10162 * when we return to the top of this while loop.
10164 free_prompts(s->cur_prompt);
10167 * Get the next packet in case it's another
10170 crWaitUntilV(pktin);
10175 * We should have SUCCESS or FAILURE now.
10179 } else if (s->can_passwd) {
10182 * Plain old password authentication.
10184 int ret; /* not live over crReturn */
10185 int changereq_first_time; /* not live over crReturn */
10187 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10189 s->cur_prompt = new_prompts(ssh->frontend);
10190 s->cur_prompt->to_server = TRUE;
10191 s->cur_prompt->name = dupstr("SSH password");
10192 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10197 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10200 crWaitUntilV(!pktin);
10201 ret = get_userpass_input(s->cur_prompt, in, inlen);
10206 * Failed to get responses. Terminate.
10208 free_prompts(s->cur_prompt);
10209 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10210 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10215 * Squirrel away the password. (We may need it later if
10216 * asked to change it.)
10218 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10219 free_prompts(s->cur_prompt);
10222 * Send the password packet.
10224 * We pad out the password packet to 256 bytes to make
10225 * it harder for an attacker to find the length of the
10228 * Anyone using a password longer than 256 bytes
10229 * probably doesn't have much to worry about from
10230 * people who find out how long their password is!
10232 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10233 ssh2_pkt_addstring(s->pktout, ssh->username);
10234 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10235 /* service requested */
10236 ssh2_pkt_addstring(s->pktout, "password");
10237 ssh2_pkt_addbool(s->pktout, FALSE);
10238 ssh2_pkt_addstring(s->pktout, s->password);
10239 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10240 logevent("Sent password");
10241 s->type = AUTH_TYPE_PASSWORD;
10244 * Wait for next packet, in case it's a password change
10247 crWaitUntilV(pktin);
10248 changereq_first_time = TRUE;
10250 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10253 * We're being asked for a new password
10254 * (perhaps not for the first time).
10255 * Loop until the server accepts it.
10258 int got_new = FALSE; /* not live over crReturn */
10259 char *prompt; /* not live over crReturn */
10260 int prompt_len; /* not live over crReturn */
10264 if (changereq_first_time)
10265 msg = "Server requested password change";
10267 msg = "Server rejected new password";
10269 c_write_str(ssh, msg);
10270 c_write_str(ssh, "\r\n");
10273 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10275 s->cur_prompt = new_prompts(ssh->frontend);
10276 s->cur_prompt->to_server = TRUE;
10277 s->cur_prompt->name = dupstr("New SSH password");
10278 s->cur_prompt->instruction =
10279 dupprintf("%.*s", prompt_len, prompt);
10280 s->cur_prompt->instr_reqd = TRUE;
10282 * There's no explicit requirement in the protocol
10283 * for the "old" passwords in the original and
10284 * password-change messages to be the same, and
10285 * apparently some Cisco kit supports password change
10286 * by the user entering a blank password originally
10287 * and the real password subsequently, so,
10288 * reluctantly, we prompt for the old password again.
10290 * (On the other hand, some servers don't even bother
10291 * to check this field.)
10293 add_prompt(s->cur_prompt,
10294 dupstr("Current password (blank for previously entered password): "),
10296 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10298 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10302 * Loop until the user manages to enter the same
10307 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10310 crWaitUntilV(!pktin);
10311 ret = get_userpass_input(s->cur_prompt, in, inlen);
10316 * Failed to get responses. Terminate.
10318 /* burn the evidence */
10319 free_prompts(s->cur_prompt);
10320 smemclr(s->password, strlen(s->password));
10321 sfree(s->password);
10322 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10323 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10329 * If the user specified a new original password
10330 * (IYSWIM), overwrite any previously specified
10332 * (A side effect is that the user doesn't have to
10333 * re-enter it if they louse up the new password.)
10335 if (s->cur_prompt->prompts[0]->result[0]) {
10336 smemclr(s->password, strlen(s->password));
10337 /* burn the evidence */
10338 sfree(s->password);
10340 dupstr(s->cur_prompt->prompts[0]->result);
10344 * Check the two new passwords match.
10346 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10347 s->cur_prompt->prompts[2]->result)
10350 /* They don't. Silly user. */
10351 c_write_str(ssh, "Passwords do not match\r\n");
10356 * Send the new password (along with the old one).
10357 * (see above for padding rationale)
10359 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10360 ssh2_pkt_addstring(s->pktout, ssh->username);
10361 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10362 /* service requested */
10363 ssh2_pkt_addstring(s->pktout, "password");
10364 ssh2_pkt_addbool(s->pktout, TRUE);
10365 ssh2_pkt_addstring(s->pktout, s->password);
10366 ssh2_pkt_addstring(s->pktout,
10367 s->cur_prompt->prompts[1]->result);
10368 free_prompts(s->cur_prompt);
10369 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10370 logevent("Sent new password");
10373 * Now see what the server has to say about it.
10374 * (If it's CHANGEREQ again, it's not happy with the
10377 crWaitUntilV(pktin);
10378 changereq_first_time = FALSE;
10383 * We need to reexamine the current pktin at the top
10384 * of the loop. Either:
10385 * - we weren't asked to change password at all, in
10386 * which case it's a SUCCESS or FAILURE with the
10388 * - we sent a new password, and the server was
10389 * either OK with it (SUCCESS or FAILURE w/partial
10390 * success) or unhappy with the _old_ password
10391 * (FAILURE w/o partial success)
10392 * In any of these cases, we go back to the top of
10393 * the loop and start again.
10398 * We don't need the old password any more, in any
10399 * case. Burn the evidence.
10401 smemclr(s->password, strlen(s->password));
10402 sfree(s->password);
10405 char *str = dupprintf("No supported authentication methods available"
10406 " (server sent: %.*s)",
10409 ssh_disconnect(ssh, str,
10410 "No supported authentication methods available",
10411 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10421 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10423 /* Clear up various bits and pieces from authentication. */
10424 if (s->publickey_blob) {
10425 sfree(s->publickey_algorithm);
10426 sfree(s->publickey_blob);
10427 sfree(s->publickey_comment);
10429 if (s->agent_response)
10430 sfree(s->agent_response);
10432 if (s->userauth_success && !ssh->bare_connection) {
10434 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10435 * packets since. Signal the transport layer to consider enacting
10436 * delayed compression.
10438 * (Relying on we_are_in is not sufficient, as
10439 * draft-miller-secsh-compression-delayed is quite clear that it
10440 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10441 * become set for other reasons.)
10443 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10446 ssh->channels = newtree234(ssh_channelcmp);
10449 * Set up handlers for some connection protocol messages, so we
10450 * don't have to handle them repeatedly in this coroutine.
10452 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10453 ssh2_msg_channel_window_adjust;
10454 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10455 ssh2_msg_global_request;
10458 * Create the main session channel.
10460 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10461 ssh->mainchan = NULL;
10463 ssh->mainchan = snew(struct ssh_channel);
10464 ssh->mainchan->ssh = ssh;
10465 ssh2_channel_init(ssh->mainchan);
10467 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10469 * Just start a direct-tcpip channel and use it as the main
10472 ssh_send_port_open(ssh->mainchan,
10473 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10474 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10476 ssh->ncmode = TRUE;
10478 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10479 logevent("Opening session as main channel");
10480 ssh2_pkt_send(ssh, s->pktout);
10481 ssh->ncmode = FALSE;
10483 crWaitUntilV(pktin);
10484 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10485 bombout(("Server refused to open channel"));
10487 /* FIXME: error data comes back in FAILURE packet */
10489 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10490 bombout(("Server's channel confirmation cited wrong channel"));
10493 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10494 ssh->mainchan->halfopen = FALSE;
10495 ssh->mainchan->type = CHAN_MAINSESSION;
10496 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10497 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10498 add234(ssh->channels, ssh->mainchan);
10499 update_specials_menu(ssh->frontend);
10500 logevent("Opened main channel");
10504 * Now we have a channel, make dispatch table entries for
10505 * general channel-based messages.
10507 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10508 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10509 ssh2_msg_channel_data;
10510 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10511 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10512 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10513 ssh2_msg_channel_open_confirmation;
10514 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10515 ssh2_msg_channel_open_failure;
10516 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10517 ssh2_msg_channel_request;
10518 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10519 ssh2_msg_channel_open;
10520 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10521 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10524 * Now the connection protocol is properly up and running, with
10525 * all those dispatch table entries, so it's safe to let
10526 * downstreams start trying to open extra channels through us.
10528 if (ssh->connshare)
10529 share_activate(ssh->connshare, ssh->v_s);
10531 if (ssh->mainchan && ssh_is_simple(ssh)) {
10533 * This message indicates to the server that we promise
10534 * not to try to run any other channel in parallel with
10535 * this one, so it's safe for it to advertise a very large
10536 * window and leave the flow control to TCP.
10538 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10539 "simple@putty.projects.tartarus.org",
10541 ssh2_pkt_send(ssh, s->pktout);
10545 * Enable port forwardings.
10547 ssh_setup_portfwd(ssh, ssh->conf);
10549 if (ssh->mainchan && !ssh->ncmode) {
10551 * Send the CHANNEL_REQUESTS for the main session channel.
10552 * Each one is handled by its own little asynchronous
10556 /* Potentially enable X11 forwarding. */
10557 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10559 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10561 if (!ssh->x11disp) {
10562 /* FIXME: return an error message from x11_setup_display */
10563 logevent("X11 forwarding not enabled: unable to"
10564 " initialise X display");
10566 ssh->x11auth = x11_invent_fake_auth
10567 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10568 ssh->x11auth->disp = ssh->x11disp;
10570 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10574 /* Potentially enable agent forwarding. */
10575 if (ssh_agent_forwarding_permitted(ssh))
10576 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10578 /* Now allocate a pty for the session. */
10579 if (!conf_get_int(ssh->conf, CONF_nopty))
10580 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10582 /* Send environment variables. */
10583 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10586 * Start a shell or a remote command. We may have to attempt
10587 * this twice if the config data has provided a second choice
10594 if (ssh->fallback_cmd) {
10595 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10596 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10598 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10599 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10603 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10604 ssh2_response_authconn, NULL);
10605 ssh2_pkt_addstring(s->pktout, cmd);
10607 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10608 ssh2_response_authconn, NULL);
10609 ssh2_pkt_addstring(s->pktout, cmd);
10611 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10612 ssh2_response_authconn, NULL);
10614 ssh2_pkt_send(ssh, s->pktout);
10616 crWaitUntilV(pktin);
10618 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10619 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10620 bombout(("Unexpected response to shell/command request:"
10621 " packet type %d", pktin->type));
10625 * We failed to start the command. If this is the
10626 * fallback command, we really are finished; if it's
10627 * not, and if the fallback command exists, try falling
10628 * back to it before complaining.
10630 if (!ssh->fallback_cmd &&
10631 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10632 logevent("Primary command failed; attempting fallback");
10633 ssh->fallback_cmd = TRUE;
10636 bombout(("Server refused to start a shell/command"));
10639 logevent("Started a shell/command");
10644 ssh->editing = ssh->echoing = TRUE;
10647 ssh->state = SSH_STATE_SESSION;
10648 if (ssh->size_needed)
10649 ssh_size(ssh, ssh->term_width, ssh->term_height);
10650 if (ssh->eof_needed)
10651 ssh_special(ssh, TS_EOF);
10657 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10662 s->try_send = FALSE;
10666 * _All_ the connection-layer packets we expect to
10667 * receive are now handled by the dispatch table.
10668 * Anything that reaches here must be bogus.
10671 bombout(("Strange packet received: type %d", pktin->type));
10673 } else if (ssh->mainchan) {
10675 * We have spare data. Add it to the channel buffer.
10677 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
10678 s->try_send = TRUE;
10682 struct ssh_channel *c;
10684 * Try to send data on all channels if we can.
10686 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
10687 if (c->type != CHAN_SHARING)
10688 ssh2_try_send_and_unthrottle(ssh, c);
10696 * Handlers for SSH-2 messages that might arrive at any moment.
10698 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10700 /* log reason code in disconnect message */
10702 int reason, msglen;
10704 reason = ssh_pkt_getuint32(pktin);
10705 ssh_pkt_getstring(pktin, &msg, &msglen);
10707 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10708 buf = dupprintf("Received disconnect message (%s)",
10709 ssh2_disconnect_reasons[reason]);
10711 buf = dupprintf("Received disconnect message (unknown"
10712 " type %d)", reason);
10716 buf = dupprintf("Disconnection message text: %.*s",
10719 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10721 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10722 ssh2_disconnect_reasons[reason] : "unknown",
10727 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10729 /* log the debug message */
10733 /* XXX maybe we should actually take notice of the return value */
10734 ssh2_pkt_getbool(pktin);
10735 ssh_pkt_getstring(pktin, &msg, &msglen);
10737 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
10740 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10742 do_ssh2_transport(ssh, NULL, 0, pktin);
10746 * Called if we receive a packet that isn't allowed by the protocol.
10747 * This only applies to packets whose meaning PuTTY understands.
10748 * Entirely unknown packets are handled below.
10750 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10752 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10753 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10755 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10759 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10761 struct Packet *pktout;
10762 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10763 ssh2_pkt_adduint32(pktout, pktin->sequence);
10765 * UNIMPLEMENTED messages MUST appear in the same order as the
10766 * messages they respond to. Hence, never queue them.
10768 ssh2_pkt_send_noqueue(ssh, pktout);
10772 * Handle the top-level SSH-2 protocol.
10774 static void ssh2_protocol_setup(Ssh ssh)
10779 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10781 for (i = 0; i < 256; i++)
10782 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10785 * Initially, we only accept transport messages (and a few generic
10786 * ones). do_ssh2_authconn will add more when it starts.
10787 * Messages that are understood but not currently acceptable go to
10788 * ssh2_msg_unexpected.
10790 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10791 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10792 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10793 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10794 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10795 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10796 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10797 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10798 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10799 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10800 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10801 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10802 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10803 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10804 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10805 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10806 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10807 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10808 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10809 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10810 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10811 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10812 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10813 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10814 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10815 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10816 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10817 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10818 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10819 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10820 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10821 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10822 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10825 * These messages have a special handler from the start.
10827 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10828 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10829 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10832 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10837 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10839 for (i = 0; i < 256; i++)
10840 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10843 * Initially, we set all ssh-connection messages to 'unexpected';
10844 * do_ssh2_authconn will fill things in properly. We also handle a
10845 * couple of messages from the transport protocol which aren't
10846 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10849 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10850 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10851 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10852 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10853 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10854 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10855 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10856 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10857 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10858 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10859 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10860 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10861 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10862 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10864 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10867 * These messages have a special handler from the start.
10869 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10870 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
10871 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10874 static void ssh2_timer(void *ctx, unsigned long now)
10876 Ssh ssh = (Ssh)ctx;
10878 if (ssh->state == SSH_STATE_CLOSED)
10881 if (!ssh->kex_in_progress && !ssh->bare_connection &&
10882 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
10883 now == ssh->next_rekey) {
10884 do_ssh2_transport(ssh, "timeout", -1, NULL);
10888 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
10889 struct Packet *pktin)
10891 const unsigned char *in = (const unsigned char *)vin;
10892 if (ssh->state == SSH_STATE_CLOSED)
10896 ssh->incoming_data_size += pktin->encrypted_len;
10897 if (!ssh->kex_in_progress &&
10898 ssh->max_data_size != 0 &&
10899 ssh->incoming_data_size > ssh->max_data_size)
10900 do_ssh2_transport(ssh, "too much data received", -1, NULL);
10904 ssh->packet_dispatch[pktin->type](ssh, pktin);
10905 else if (!ssh->protocol_initial_phase_done)
10906 do_ssh2_transport(ssh, in, inlen, pktin);
10908 do_ssh2_authconn(ssh, in, inlen, pktin);
10911 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
10912 struct Packet *pktin)
10914 const unsigned char *in = (const unsigned char *)vin;
10915 if (ssh->state == SSH_STATE_CLOSED)
10919 ssh->packet_dispatch[pktin->type](ssh, pktin);
10921 do_ssh2_authconn(ssh, in, inlen, pktin);
10924 static void ssh_cache_conf_values(Ssh ssh)
10926 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
10930 * Called to set up the connection.
10932 * Returns an error message, or NULL on success.
10934 static const char *ssh_init(void *frontend_handle, void **backend_handle,
10936 const char *host, int port, char **realhost,
10937 int nodelay, int keepalive)
10942 ssh = snew(struct ssh_tag);
10943 ssh->conf = conf_copy(conf);
10944 ssh_cache_conf_values(ssh);
10945 ssh->version = 0; /* when not ready yet */
10947 ssh->cipher = NULL;
10948 ssh->v1_cipher_ctx = NULL;
10949 ssh->crcda_ctx = NULL;
10950 ssh->cscipher = NULL;
10951 ssh->cs_cipher_ctx = NULL;
10952 ssh->sccipher = NULL;
10953 ssh->sc_cipher_ctx = NULL;
10955 ssh->cs_mac_ctx = NULL;
10957 ssh->sc_mac_ctx = NULL;
10958 ssh->cscomp = NULL;
10959 ssh->cs_comp_ctx = NULL;
10960 ssh->sccomp = NULL;
10961 ssh->sc_comp_ctx = NULL;
10963 ssh->kex_ctx = NULL;
10964 ssh->hostkey = NULL;
10965 ssh->hostkey_str = NULL;
10966 ssh->exitcode = -1;
10967 ssh->close_expected = FALSE;
10968 ssh->clean_exit = FALSE;
10969 ssh->state = SSH_STATE_PREPACKET;
10970 ssh->size_needed = FALSE;
10971 ssh->eof_needed = FALSE;
10973 ssh->logctx = NULL;
10974 ssh->deferred_send_data = NULL;
10975 ssh->deferred_len = 0;
10976 ssh->deferred_size = 0;
10977 ssh->fallback_cmd = 0;
10978 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
10979 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
10980 ssh->x11disp = NULL;
10981 ssh->x11auth = NULL;
10982 ssh->x11authtree = newtree234(x11_authcmp);
10983 ssh->v1_compressing = FALSE;
10984 ssh->v2_outgoing_sequence = 0;
10985 ssh->ssh1_rdpkt_crstate = 0;
10986 ssh->ssh2_rdpkt_crstate = 0;
10987 ssh->ssh2_bare_rdpkt_crstate = 0;
10988 ssh->ssh_gotdata_crstate = 0;
10989 ssh->do_ssh1_connection_crstate = 0;
10990 ssh->do_ssh_init_state = NULL;
10991 ssh->do_ssh_connection_init_state = NULL;
10992 ssh->do_ssh1_login_state = NULL;
10993 ssh->do_ssh2_transport_state = NULL;
10994 ssh->do_ssh2_authconn_state = NULL;
10997 ssh->mainchan = NULL;
10998 ssh->throttled_all = 0;
10999 ssh->v1_stdout_throttling = 0;
11001 ssh->queuelen = ssh->queuesize = 0;
11002 ssh->queueing = FALSE;
11003 ssh->qhead = ssh->qtail = NULL;
11004 ssh->deferred_rekey_reason = NULL;
11005 bufchain_init(&ssh->queued_incoming_data);
11006 ssh->frozen = FALSE;
11007 ssh->username = NULL;
11008 ssh->sent_console_eof = FALSE;
11009 ssh->got_pty = FALSE;
11010 ssh->bare_connection = FALSE;
11011 ssh->X11_fwd_enabled = FALSE;
11012 ssh->connshare = NULL;
11013 ssh->attempting_connshare = FALSE;
11015 *backend_handle = ssh;
11018 if (crypto_startup() == 0)
11019 return "Microsoft high encryption pack not installed!";
11022 ssh->frontend = frontend_handle;
11023 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11024 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11026 ssh->channels = NULL;
11027 ssh->rportfwds = NULL;
11028 ssh->portfwds = NULL;
11033 ssh->conn_throttle_count = 0;
11034 ssh->overall_bufsize = 0;
11035 ssh->fallback_cmd = 0;
11037 ssh->protocol = NULL;
11039 ssh->protocol_initial_phase_done = FALSE;
11041 ssh->pinger = NULL;
11043 ssh->incoming_data_size = ssh->outgoing_data_size =
11044 ssh->deferred_data_size = 0L;
11045 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11046 CONF_ssh_rekey_data));
11047 ssh->kex_in_progress = FALSE;
11050 ssh->gsslibs = NULL;
11053 random_ref(); /* do this now - may be needed by sharing setup code */
11055 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11064 static void ssh_free(void *handle)
11066 Ssh ssh = (Ssh) handle;
11067 struct ssh_channel *c;
11068 struct ssh_rportfwd *pf;
11069 struct X11FakeAuth *auth;
11071 if (ssh->v1_cipher_ctx)
11072 ssh->cipher->free_context(ssh->v1_cipher_ctx);
11073 if (ssh->cs_cipher_ctx)
11074 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11075 if (ssh->sc_cipher_ctx)
11076 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11077 if (ssh->cs_mac_ctx)
11078 ssh->csmac->free_context(ssh->cs_mac_ctx);
11079 if (ssh->sc_mac_ctx)
11080 ssh->scmac->free_context(ssh->sc_mac_ctx);
11081 if (ssh->cs_comp_ctx) {
11083 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11085 zlib_compress_cleanup(ssh->cs_comp_ctx);
11087 if (ssh->sc_comp_ctx) {
11089 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11091 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11094 dh_cleanup(ssh->kex_ctx);
11095 sfree(ssh->savedhost);
11097 while (ssh->queuelen-- > 0)
11098 ssh_free_packet(ssh->queue[ssh->queuelen]);
11101 while (ssh->qhead) {
11102 struct queued_handler *qh = ssh->qhead;
11103 ssh->qhead = qh->next;
11106 ssh->qhead = ssh->qtail = NULL;
11108 if (ssh->channels) {
11109 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11112 if (c->u.x11.xconn != NULL)
11113 x11_close(c->u.x11.xconn);
11115 case CHAN_SOCKDATA:
11116 case CHAN_SOCKDATA_DORMANT:
11117 if (c->u.pfd.pf != NULL)
11118 pfd_close(c->u.pfd.pf);
11121 if (ssh->version == 2) {
11122 struct outstanding_channel_request *ocr, *nocr;
11123 ocr = c->v.v2.chanreq_head;
11125 ocr->handler(c, NULL, ocr->ctx);
11130 bufchain_clear(&c->v.v2.outbuffer);
11134 freetree234(ssh->channels);
11135 ssh->channels = NULL;
11138 if (ssh->connshare)
11139 sharestate_free(ssh->connshare);
11141 if (ssh->rportfwds) {
11142 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11144 freetree234(ssh->rportfwds);
11145 ssh->rportfwds = NULL;
11147 sfree(ssh->deferred_send_data);
11149 x11_free_display(ssh->x11disp);
11150 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11151 x11_free_fake_auth(auth);
11152 freetree234(ssh->x11authtree);
11153 sfree(ssh->do_ssh_init_state);
11154 sfree(ssh->do_ssh1_login_state);
11155 sfree(ssh->do_ssh2_transport_state);
11156 sfree(ssh->do_ssh2_authconn_state);
11159 sfree(ssh->fullhostname);
11160 sfree(ssh->hostkey_str);
11161 if (ssh->crcda_ctx) {
11162 crcda_free_context(ssh->crcda_ctx);
11163 ssh->crcda_ctx = NULL;
11166 ssh_do_close(ssh, TRUE);
11167 expire_timer_context(ssh);
11169 pinger_free(ssh->pinger);
11170 bufchain_clear(&ssh->queued_incoming_data);
11171 sfree(ssh->username);
11172 conf_free(ssh->conf);
11175 ssh_gss_cleanup(ssh->gsslibs);
11183 * Reconfigure the SSH backend.
11185 static void ssh_reconfig(void *handle, Conf *conf)
11187 Ssh ssh = (Ssh) handle;
11188 const char *rekeying = NULL;
11189 int rekey_mandatory = FALSE;
11190 unsigned long old_max_data_size;
11193 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11195 ssh_setup_portfwd(ssh, conf);
11197 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11198 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11200 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11201 unsigned long now = GETTICKCOUNT();
11203 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11204 rekeying = "timeout shortened";
11206 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11210 old_max_data_size = ssh->max_data_size;
11211 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11212 CONF_ssh_rekey_data));
11213 if (old_max_data_size != ssh->max_data_size &&
11214 ssh->max_data_size != 0) {
11215 if (ssh->outgoing_data_size > ssh->max_data_size ||
11216 ssh->incoming_data_size > ssh->max_data_size)
11217 rekeying = "data limit lowered";
11220 if (conf_get_int(ssh->conf, CONF_compression) !=
11221 conf_get_int(conf, CONF_compression)) {
11222 rekeying = "compression setting changed";
11223 rekey_mandatory = TRUE;
11226 for (i = 0; i < CIPHER_MAX; i++)
11227 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11228 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11229 rekeying = "cipher settings changed";
11230 rekey_mandatory = TRUE;
11232 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11233 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11234 rekeying = "cipher settings changed";
11235 rekey_mandatory = TRUE;
11238 conf_free(ssh->conf);
11239 ssh->conf = conf_copy(conf);
11240 ssh_cache_conf_values(ssh);
11242 if (!ssh->bare_connection && rekeying) {
11243 if (!ssh->kex_in_progress) {
11244 do_ssh2_transport(ssh, rekeying, -1, NULL);
11245 } else if (rekey_mandatory) {
11246 ssh->deferred_rekey_reason = rekeying;
11252 * Called to send data down the SSH connection.
11254 static int ssh_send(void *handle, const char *buf, int len)
11256 Ssh ssh = (Ssh) handle;
11258 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11261 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11263 return ssh_sendbuffer(ssh);
11267 * Called to query the current amount of buffered stdin data.
11269 static int ssh_sendbuffer(void *handle)
11271 Ssh ssh = (Ssh) handle;
11272 int override_value;
11274 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11278 * If the SSH socket itself has backed up, add the total backup
11279 * size on that to any individual buffer on the stdin channel.
11281 override_value = 0;
11282 if (ssh->throttled_all)
11283 override_value = ssh->overall_bufsize;
11285 if (ssh->version == 1) {
11286 return override_value;
11287 } else if (ssh->version == 2) {
11288 if (!ssh->mainchan)
11289 return override_value;
11291 return (override_value +
11292 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11299 * Called to set the size of the window from SSH's POV.
11301 static void ssh_size(void *handle, int width, int height)
11303 Ssh ssh = (Ssh) handle;
11304 struct Packet *pktout;
11306 ssh->term_width = width;
11307 ssh->term_height = height;
11309 switch (ssh->state) {
11310 case SSH_STATE_BEFORE_SIZE:
11311 case SSH_STATE_PREPACKET:
11312 case SSH_STATE_CLOSED:
11313 break; /* do nothing */
11314 case SSH_STATE_INTERMED:
11315 ssh->size_needed = TRUE; /* buffer for later */
11317 case SSH_STATE_SESSION:
11318 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11319 if (ssh->version == 1) {
11320 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11321 PKT_INT, ssh->term_height,
11322 PKT_INT, ssh->term_width,
11323 PKT_INT, 0, PKT_INT, 0, PKT_END);
11324 } else if (ssh->mainchan) {
11325 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11327 ssh2_pkt_adduint32(pktout, ssh->term_width);
11328 ssh2_pkt_adduint32(pktout, ssh->term_height);
11329 ssh2_pkt_adduint32(pktout, 0);
11330 ssh2_pkt_adduint32(pktout, 0);
11331 ssh2_pkt_send(ssh, pktout);
11339 * Return a list of the special codes that make sense in this
11342 static const struct telnet_special *ssh_get_specials(void *handle)
11344 static const struct telnet_special ssh1_ignore_special[] = {
11345 {"IGNORE message", TS_NOP}
11347 static const struct telnet_special ssh2_ignore_special[] = {
11348 {"IGNORE message", TS_NOP},
11350 static const struct telnet_special ssh2_rekey_special[] = {
11351 {"Repeat key exchange", TS_REKEY},
11353 static const struct telnet_special ssh2_session_specials[] = {
11356 /* These are the signal names defined by RFC 4254.
11357 * They include all the ISO C signals, but are a subset of the POSIX
11358 * required signals. */
11359 {"SIGINT (Interrupt)", TS_SIGINT},
11360 {"SIGTERM (Terminate)", TS_SIGTERM},
11361 {"SIGKILL (Kill)", TS_SIGKILL},
11362 {"SIGQUIT (Quit)", TS_SIGQUIT},
11363 {"SIGHUP (Hangup)", TS_SIGHUP},
11364 {"More signals", TS_SUBMENU},
11365 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11366 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11367 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11368 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11369 {NULL, TS_EXITMENU}
11371 static const struct telnet_special specials_end[] = {
11372 {NULL, TS_EXITMENU}
11374 /* XXX review this length for any changes: */
11375 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
11376 lenof(ssh2_rekey_special) +
11377 lenof(ssh2_session_specials) +
11378 lenof(specials_end)];
11379 Ssh ssh = (Ssh) handle;
11381 #define ADD_SPECIALS(name) \
11383 assert((i + lenof(name)) <= lenof(ssh_specials)); \
11384 memcpy(&ssh_specials[i], name, sizeof name); \
11385 i += lenof(name); \
11388 if (ssh->version == 1) {
11389 /* Don't bother offering IGNORE if we've decided the remote
11390 * won't cope with it, since we wouldn't bother sending it if
11392 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11393 ADD_SPECIALS(ssh1_ignore_special);
11394 } else if (ssh->version == 2) {
11395 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11396 ADD_SPECIALS(ssh2_ignore_special);
11397 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11398 ADD_SPECIALS(ssh2_rekey_special);
11400 ADD_SPECIALS(ssh2_session_specials);
11401 } /* else we're not ready yet */
11404 ADD_SPECIALS(specials_end);
11405 return ssh_specials;
11409 #undef ADD_SPECIALS
11413 * Send special codes. TS_EOF is useful for `plink', so you
11414 * can send an EOF and collect resulting output (e.g. `plink
11417 static void ssh_special(void *handle, Telnet_Special code)
11419 Ssh ssh = (Ssh) handle;
11420 struct Packet *pktout;
11422 if (code == TS_EOF) {
11423 if (ssh->state != SSH_STATE_SESSION) {
11425 * Buffer the EOF in case we are pre-SESSION, so we can
11426 * send it as soon as we reach SESSION.
11428 if (code == TS_EOF)
11429 ssh->eof_needed = TRUE;
11432 if (ssh->version == 1) {
11433 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11434 } else if (ssh->mainchan) {
11435 sshfwd_write_eof(ssh->mainchan);
11436 ssh->send_ok = 0; /* now stop trying to read from stdin */
11438 logevent("Sent EOF message");
11439 } else if (code == TS_PING || code == TS_NOP) {
11440 if (ssh->state == SSH_STATE_CLOSED
11441 || ssh->state == SSH_STATE_PREPACKET) return;
11442 if (ssh->version == 1) {
11443 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11444 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11446 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11447 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11448 ssh2_pkt_addstring_start(pktout);
11449 ssh2_pkt_send_noqueue(ssh, pktout);
11452 } else if (code == TS_REKEY) {
11453 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11454 ssh->version == 2) {
11455 do_ssh2_transport(ssh, "at user request", -1, NULL);
11457 } else if (code == TS_BRK) {
11458 if (ssh->state == SSH_STATE_CLOSED
11459 || ssh->state == SSH_STATE_PREPACKET) return;
11460 if (ssh->version == 1) {
11461 logevent("Unable to send BREAK signal in SSH-1");
11462 } else if (ssh->mainchan) {
11463 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11464 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11465 ssh2_pkt_send(ssh, pktout);
11468 /* Is is a POSIX signal? */
11469 const char *signame = NULL;
11470 if (code == TS_SIGABRT) signame = "ABRT";
11471 if (code == TS_SIGALRM) signame = "ALRM";
11472 if (code == TS_SIGFPE) signame = "FPE";
11473 if (code == TS_SIGHUP) signame = "HUP";
11474 if (code == TS_SIGILL) signame = "ILL";
11475 if (code == TS_SIGINT) signame = "INT";
11476 if (code == TS_SIGKILL) signame = "KILL";
11477 if (code == TS_SIGPIPE) signame = "PIPE";
11478 if (code == TS_SIGQUIT) signame = "QUIT";
11479 if (code == TS_SIGSEGV) signame = "SEGV";
11480 if (code == TS_SIGTERM) signame = "TERM";
11481 if (code == TS_SIGUSR1) signame = "USR1";
11482 if (code == TS_SIGUSR2) signame = "USR2";
11483 /* The SSH-2 protocol does in principle support arbitrary named
11484 * signals, including signame@domain, but we don't support those. */
11486 /* It's a signal. */
11487 if (ssh->version == 2 && ssh->mainchan) {
11488 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11489 ssh2_pkt_addstring(pktout, signame);
11490 ssh2_pkt_send(ssh, pktout);
11491 logeventf(ssh, "Sent signal SIG%s", signame);
11494 /* Never heard of it. Do nothing */
11499 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11501 Ssh ssh = (Ssh) handle;
11502 struct ssh_channel *c;
11503 c = snew(struct ssh_channel);
11506 ssh2_channel_init(c);
11507 c->halfopen = TRUE;
11508 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11510 add234(ssh->channels, c);
11514 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11516 struct ssh_channel *c;
11517 c = snew(struct ssh_channel);
11520 ssh2_channel_init(c);
11521 c->type = CHAN_SHARING;
11522 c->u.sharing.ctx = sharing_ctx;
11523 add234(ssh->channels, c);
11527 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11529 struct ssh_channel *c;
11531 c = find234(ssh->channels, &localid, ssh_channelfind);
11533 ssh_channel_destroy(c);
11536 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11537 const void *data, int datalen,
11538 const char *additional_log_text)
11540 struct Packet *pkt;
11542 pkt = ssh2_pkt_init(type);
11543 pkt->downstream_id = id;
11544 pkt->additional_log_text = additional_log_text;
11545 ssh2_pkt_adddata(pkt, data, datalen);
11546 ssh2_pkt_send(ssh, pkt);
11550 * This is called when stdout/stderr (the entity to which
11551 * from_backend sends data) manages to clear some backlog.
11553 static void ssh_unthrottle(void *handle, int bufsize)
11555 Ssh ssh = (Ssh) handle;
11558 if (ssh->version == 1) {
11559 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11560 ssh->v1_stdout_throttling = 0;
11561 ssh_throttle_conn(ssh, -1);
11564 if (ssh->mainchan) {
11565 ssh2_set_window(ssh->mainchan,
11566 bufsize < ssh->mainchan->v.v2.locmaxwin ?
11567 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11568 if (ssh_is_simple(ssh))
11571 buflimit = ssh->mainchan->v.v2.locmaxwin;
11572 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11573 ssh->mainchan->throttling_conn = 0;
11574 ssh_throttle_conn(ssh, -1);
11580 * Now process any SSH connection data that was stashed in our
11581 * queue while we were frozen.
11583 ssh_process_queued_incoming_data(ssh);
11586 void ssh_send_port_open(void *channel, const char *hostname, int port,
11589 struct ssh_channel *c = (struct ssh_channel *)channel;
11591 struct Packet *pktout;
11593 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11595 if (ssh->version == 1) {
11596 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11597 PKT_INT, c->localid,
11600 /* PKT_STR, <org:orgport>, */
11603 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11605 char *trimmed_host = host_strduptrim(hostname);
11606 ssh2_pkt_addstring(pktout, trimmed_host);
11607 sfree(trimmed_host);
11609 ssh2_pkt_adduint32(pktout, port);
11611 * We make up values for the originator data; partly it's
11612 * too much hassle to keep track, and partly I'm not
11613 * convinced the server should be told details like that
11614 * about my local network configuration.
11615 * The "originator IP address" is syntactically a numeric
11616 * IP address, and some servers (e.g., Tectia) get upset
11617 * if it doesn't match this syntax.
11619 ssh2_pkt_addstring(pktout, "0.0.0.0");
11620 ssh2_pkt_adduint32(pktout, 0);
11621 ssh2_pkt_send(ssh, pktout);
11625 static int ssh_connected(void *handle)
11627 Ssh ssh = (Ssh) handle;
11628 return ssh->s != NULL;
11631 static int ssh_sendok(void *handle)
11633 Ssh ssh = (Ssh) handle;
11634 return ssh->send_ok;
11637 static int ssh_ldisc(void *handle, int option)
11639 Ssh ssh = (Ssh) handle;
11640 if (option == LD_ECHO)
11641 return ssh->echoing;
11642 if (option == LD_EDIT)
11643 return ssh->editing;
11647 static void ssh_provide_ldisc(void *handle, void *ldisc)
11649 Ssh ssh = (Ssh) handle;
11650 ssh->ldisc = ldisc;
11653 static void ssh_provide_logctx(void *handle, void *logctx)
11655 Ssh ssh = (Ssh) handle;
11656 ssh->logctx = logctx;
11659 static int ssh_return_exitcode(void *handle)
11661 Ssh ssh = (Ssh) handle;
11662 if (ssh->s != NULL)
11665 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11669 * cfg_info for SSH is the protocol running in this session.
11670 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11671 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11673 static int ssh_cfg_info(void *handle)
11675 Ssh ssh = (Ssh) handle;
11676 if (ssh->version == 0)
11677 return 0; /* don't know yet */
11678 else if (ssh->bare_connection)
11681 return ssh->version;
11685 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11686 * that fails. This variable is the means by which scp.c can reach
11687 * into the SSH code and find out which one it got.
11689 extern int ssh_fallback_cmd(void *handle)
11691 Ssh ssh = (Ssh) handle;
11692 return ssh->fallback_cmd;
11695 Backend ssh_backend = {
11705 ssh_return_exitcode,
11709 ssh_provide_logctx,
11712 ssh_test_for_upstream,