28 * Packet type contexts, so that ssh2_pkt_type can correctly decode
29 * the ambiguous type numbers back into the correct type strings.
40 SSH2_PKTCTX_PUBLICKEY,
46 static const char *const ssh2_disconnect_reasons[] = {
48 "host not allowed to connect",
50 "key exchange failed",
51 "host authentication failed",
54 "service not available",
55 "protocol version not supported",
56 "host key not verifiable",
59 "too many connections",
60 "auth cancelled by user",
61 "no more auth methods available",
66 * Various remote-bug flags.
68 #define BUG_CHOKES_ON_SSH1_IGNORE 1
69 #define BUG_SSH2_HMAC 2
70 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
71 #define BUG_CHOKES_ON_RSA 8
72 #define BUG_SSH2_RSA_PADDING 16
73 #define BUG_SSH2_DERIVEKEY 32
74 #define BUG_SSH2_REKEY 64
75 #define BUG_SSH2_PK_SESSIONID 128
76 #define BUG_SSH2_MAXPKT 256
77 #define BUG_CHOKES_ON_SSH2_IGNORE 512
78 #define BUG_CHOKES_ON_WINADJ 1024
79 #define BUG_SENDS_LATE_REQUEST_REPLY 2048
80 #define BUG_SSH2_OLDGEX 4096
82 #define DH_MIN_SIZE 1024
83 #define DH_MAX_SIZE 8192
86 * Codes for terminal modes.
87 * Most of these are the same in SSH-1 and SSH-2.
88 * This list is derived from RFC 4254 and
92 const char* const mode;
94 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
96 /* "V" prefix discarded for special characters relative to SSH specs */
97 { "INTR", 1, TTY_OP_CHAR },
98 { "QUIT", 2, TTY_OP_CHAR },
99 { "ERASE", 3, TTY_OP_CHAR },
100 { "KILL", 4, TTY_OP_CHAR },
101 { "EOF", 5, TTY_OP_CHAR },
102 { "EOL", 6, TTY_OP_CHAR },
103 { "EOL2", 7, TTY_OP_CHAR },
104 { "START", 8, TTY_OP_CHAR },
105 { "STOP", 9, TTY_OP_CHAR },
106 { "SUSP", 10, TTY_OP_CHAR },
107 { "DSUSP", 11, TTY_OP_CHAR },
108 { "REPRINT", 12, TTY_OP_CHAR },
109 { "WERASE", 13, TTY_OP_CHAR },
110 { "LNEXT", 14, TTY_OP_CHAR },
111 { "FLUSH", 15, TTY_OP_CHAR },
112 { "SWTCH", 16, TTY_OP_CHAR },
113 { "STATUS", 17, TTY_OP_CHAR },
114 { "DISCARD", 18, TTY_OP_CHAR },
115 { "IGNPAR", 30, TTY_OP_BOOL },
116 { "PARMRK", 31, TTY_OP_BOOL },
117 { "INPCK", 32, TTY_OP_BOOL },
118 { "ISTRIP", 33, TTY_OP_BOOL },
119 { "INLCR", 34, TTY_OP_BOOL },
120 { "IGNCR", 35, TTY_OP_BOOL },
121 { "ICRNL", 36, TTY_OP_BOOL },
122 { "IUCLC", 37, TTY_OP_BOOL },
123 { "IXON", 38, TTY_OP_BOOL },
124 { "IXANY", 39, TTY_OP_BOOL },
125 { "IXOFF", 40, TTY_OP_BOOL },
126 { "IMAXBEL", 41, TTY_OP_BOOL },
127 { "ISIG", 50, TTY_OP_BOOL },
128 { "ICANON", 51, TTY_OP_BOOL },
129 { "XCASE", 52, TTY_OP_BOOL },
130 { "ECHO", 53, TTY_OP_BOOL },
131 { "ECHOE", 54, TTY_OP_BOOL },
132 { "ECHOK", 55, TTY_OP_BOOL },
133 { "ECHONL", 56, TTY_OP_BOOL },
134 { "NOFLSH", 57, TTY_OP_BOOL },
135 { "TOSTOP", 58, TTY_OP_BOOL },
136 { "IEXTEN", 59, TTY_OP_BOOL },
137 { "ECHOCTL", 60, TTY_OP_BOOL },
138 { "ECHOKE", 61, TTY_OP_BOOL },
139 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
140 { "OPOST", 70, TTY_OP_BOOL },
141 { "OLCUC", 71, TTY_OP_BOOL },
142 { "ONLCR", 72, TTY_OP_BOOL },
143 { "OCRNL", 73, TTY_OP_BOOL },
144 { "ONOCR", 74, TTY_OP_BOOL },
145 { "ONLRET", 75, TTY_OP_BOOL },
146 { "CS7", 90, TTY_OP_BOOL },
147 { "CS8", 91, TTY_OP_BOOL },
148 { "PARENB", 92, TTY_OP_BOOL },
149 { "PARODD", 93, TTY_OP_BOOL }
152 /* Miscellaneous other tty-related constants. */
153 #define SSH_TTY_OP_END 0
154 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
155 #define SSH1_TTY_OP_ISPEED 192
156 #define SSH1_TTY_OP_OSPEED 193
157 #define SSH2_TTY_OP_ISPEED 128
158 #define SSH2_TTY_OP_OSPEED 129
160 /* Helper functions for parsing tty-related config. */
161 static unsigned int ssh_tty_parse_specchar(char *s)
166 ret = ctrlparse(s, &next);
167 if (!next) ret = s[0];
169 ret = 255; /* special value meaning "don't set" */
173 static unsigned int ssh_tty_parse_boolean(char *s)
175 if (stricmp(s, "yes") == 0 ||
176 stricmp(s, "on") == 0 ||
177 stricmp(s, "true") == 0 ||
178 stricmp(s, "+") == 0)
180 else if (stricmp(s, "no") == 0 ||
181 stricmp(s, "off") == 0 ||
182 stricmp(s, "false") == 0 ||
183 stricmp(s, "-") == 0)
184 return 0; /* false */
186 return (atoi(s) != 0);
189 #define translate(x) if (type == x) return #x
190 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
191 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
192 static char *ssh1_pkt_type(int type)
194 translate(SSH1_MSG_DISCONNECT);
195 translate(SSH1_SMSG_PUBLIC_KEY);
196 translate(SSH1_CMSG_SESSION_KEY);
197 translate(SSH1_CMSG_USER);
198 translate(SSH1_CMSG_AUTH_RSA);
199 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
200 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
201 translate(SSH1_CMSG_AUTH_PASSWORD);
202 translate(SSH1_CMSG_REQUEST_PTY);
203 translate(SSH1_CMSG_WINDOW_SIZE);
204 translate(SSH1_CMSG_EXEC_SHELL);
205 translate(SSH1_CMSG_EXEC_CMD);
206 translate(SSH1_SMSG_SUCCESS);
207 translate(SSH1_SMSG_FAILURE);
208 translate(SSH1_CMSG_STDIN_DATA);
209 translate(SSH1_SMSG_STDOUT_DATA);
210 translate(SSH1_SMSG_STDERR_DATA);
211 translate(SSH1_CMSG_EOF);
212 translate(SSH1_SMSG_EXIT_STATUS);
213 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
214 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
215 translate(SSH1_MSG_CHANNEL_DATA);
216 translate(SSH1_MSG_CHANNEL_CLOSE);
217 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
218 translate(SSH1_SMSG_X11_OPEN);
219 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
220 translate(SSH1_MSG_PORT_OPEN);
221 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
222 translate(SSH1_SMSG_AGENT_OPEN);
223 translate(SSH1_MSG_IGNORE);
224 translate(SSH1_CMSG_EXIT_CONFIRMATION);
225 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
226 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
227 translate(SSH1_MSG_DEBUG);
228 translate(SSH1_CMSG_REQUEST_COMPRESSION);
229 translate(SSH1_CMSG_AUTH_TIS);
230 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
231 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
232 translate(SSH1_CMSG_AUTH_CCARD);
233 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
234 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
237 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
239 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
240 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
241 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
242 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
243 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
244 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
245 translate(SSH2_MSG_DISCONNECT);
246 translate(SSH2_MSG_IGNORE);
247 translate(SSH2_MSG_UNIMPLEMENTED);
248 translate(SSH2_MSG_DEBUG);
249 translate(SSH2_MSG_SERVICE_REQUEST);
250 translate(SSH2_MSG_SERVICE_ACCEPT);
251 translate(SSH2_MSG_KEXINIT);
252 translate(SSH2_MSG_NEWKEYS);
253 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
254 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
255 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD, SSH2_PKTCTX_DHGEX);
256 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
257 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
258 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
259 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
260 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
261 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
262 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
263 translatek(SSH2_MSG_KEX_ECDH_INIT, SSH2_PKTCTX_ECDHKEX);
264 translatek(SSH2_MSG_KEX_ECDH_REPLY, SSH2_PKTCTX_ECDHKEX);
265 translate(SSH2_MSG_USERAUTH_REQUEST);
266 translate(SSH2_MSG_USERAUTH_FAILURE);
267 translate(SSH2_MSG_USERAUTH_SUCCESS);
268 translate(SSH2_MSG_USERAUTH_BANNER);
269 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
270 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
271 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
272 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
273 translate(SSH2_MSG_GLOBAL_REQUEST);
274 translate(SSH2_MSG_REQUEST_SUCCESS);
275 translate(SSH2_MSG_REQUEST_FAILURE);
276 translate(SSH2_MSG_CHANNEL_OPEN);
277 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
278 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
279 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
280 translate(SSH2_MSG_CHANNEL_DATA);
281 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
282 translate(SSH2_MSG_CHANNEL_EOF);
283 translate(SSH2_MSG_CHANNEL_CLOSE);
284 translate(SSH2_MSG_CHANNEL_REQUEST);
285 translate(SSH2_MSG_CHANNEL_SUCCESS);
286 translate(SSH2_MSG_CHANNEL_FAILURE);
292 /* Enumeration values for fields in SSH-1 packets */
294 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
298 * Coroutine mechanics for the sillier bits of the code. If these
299 * macros look impenetrable to you, you might find it helpful to
302 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
304 * which explains the theory behind these macros.
306 * In particular, if you are getting `case expression not constant'
307 * errors when building with MS Visual Studio, this is because MS's
308 * Edit and Continue debugging feature causes their compiler to
309 * violate ANSI C. To disable Edit and Continue debugging:
311 * - right-click ssh.c in the FileView
313 * - select the C/C++ tab and the General category
314 * - under `Debug info:', select anything _other_ than `Program
315 * Database for Edit and Continue'.
317 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
318 #define crBeginState crBegin(s->crLine)
319 #define crStateP(t, v) \
321 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
323 #define crState(t) crStateP(t, ssh->t)
324 #define crFinish(z) } *crLine = 0; return (z); }
325 #define crFinishV } *crLine = 0; return; }
326 #define crFinishFree(z) } sfree(s); return (z); }
327 #define crFinishFreeV } sfree(s); return; }
328 #define crReturn(z) \
330 *crLine =__LINE__; return (z); case __LINE__:;\
334 *crLine=__LINE__; return; case __LINE__:;\
336 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
337 #define crStopV do{ *crLine = 0; return; }while(0)
338 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
339 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
343 static struct Packet *ssh1_pkt_init(int pkt_type);
344 static struct Packet *ssh2_pkt_init(int pkt_type);
345 static void ssh_pkt_ensure(struct Packet *, int length);
346 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
347 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
348 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
349 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
350 static void ssh_pkt_addstring_start(struct Packet *);
351 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
352 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
353 static void ssh_pkt_addstring(struct Packet *, const char *data);
354 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
355 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
356 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
357 static int ssh2_pkt_construct(Ssh, struct Packet *);
358 static void ssh2_pkt_send(Ssh, struct Packet *);
359 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
360 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
361 struct Packet *pktin);
362 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
363 struct Packet *pktin);
364 static void ssh2_channel_check_close(struct ssh_channel *c);
365 static void ssh_channel_destroy(struct ssh_channel *c);
368 * Buffer management constants. There are several of these for
369 * various different purposes:
371 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
372 * on a local data stream before we throttle the whole SSH
373 * connection (in SSH-1 only). Throttling the whole connection is
374 * pretty drastic so we set this high in the hope it won't
377 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
378 * on the SSH connection itself before we defensively throttle
379 * _all_ local data streams. This is pretty drastic too (though
380 * thankfully unlikely in SSH-2 since the window mechanism should
381 * ensure that the server never has any need to throttle its end
382 * of the connection), so we set this high as well.
384 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
387 * - OUR_V2_BIGWIN is the window size we advertise for the only
388 * channel in a simple connection. It must be <= INT_MAX.
390 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
391 * to the remote side. This actually has nothing to do with the
392 * size of the _packet_, but is instead a limit on the amount
393 * of data we're willing to receive in a single SSH2 channel
396 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
397 * _packet_ we're prepared to cope with. It must be a multiple
398 * of the cipher block size, and must be at least 35000.
401 #define SSH1_BUFFER_LIMIT 32768
402 #define SSH_MAX_BACKLOG 32768
403 #define OUR_V2_WINSIZE 16384
404 #define OUR_V2_BIGWIN 0x7fffffff
405 #define OUR_V2_MAXPKT 0x4000UL
406 #define OUR_V2_PACKETLIMIT 0x9000UL
408 const static struct ssh_signkey *hostkey_algs[] = {
410 &ssh_ecdsa_nistp256, &ssh_ecdsa_nistp384, &ssh_ecdsa_nistp521,
414 const static struct ssh_mac *macs[] = {
415 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
417 const static struct ssh_mac *buggymacs[] = {
418 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
421 static void *ssh_comp_none_init(void)
425 static void ssh_comp_none_cleanup(void *handle)
428 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
429 unsigned char **outblock, int *outlen)
433 static int ssh_comp_none_disable(void *handle)
437 const static struct ssh_compress ssh_comp_none = {
439 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
440 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
441 ssh_comp_none_disable, NULL
443 extern const struct ssh_compress ssh_zlib;
444 const static struct ssh_compress *compressions[] = {
445 &ssh_zlib, &ssh_comp_none
448 enum { /* channel types */
453 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
455 * CHAN_SHARING indicates a channel which is tracked here on
456 * behalf of a connection-sharing downstream. We do almost nothing
457 * with these channels ourselves: all messages relating to them
458 * get thrown straight to sshshare.c and passed on almost
459 * unmodified to downstream.
463 * CHAN_ZOMBIE is used to indicate a channel for which we've
464 * already destroyed the local data source: for instance, if a
465 * forwarded port experiences a socket error on the local side, we
466 * immediately destroy its local socket and turn the SSH channel
472 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
473 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
474 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
477 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
480 struct outstanding_channel_request {
481 cchandler_fn_t handler;
483 struct outstanding_channel_request *next;
487 * 2-3-4 tree storing channels.
490 Ssh ssh; /* pointer back to main context */
491 unsigned remoteid, localid;
493 /* True if we opened this channel but server hasn't confirmed. */
496 * In SSH-1, this value contains four bits:
498 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
499 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
500 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
501 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
503 * A channel is completely finished with when all four bits are set.
505 * In SSH-2, the four bits mean:
507 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
508 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
509 * 4 We have received SSH2_MSG_CHANNEL_EOF.
510 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
512 * A channel is completely finished with when we have both sent
513 * and received CLOSE.
515 * The symbolic constants below use the SSH-2 terminology, which
516 * is a bit confusing in SSH-1, but we have to use _something_.
518 #define CLOSES_SENT_EOF 1
519 #define CLOSES_SENT_CLOSE 2
520 #define CLOSES_RCVD_EOF 4
521 #define CLOSES_RCVD_CLOSE 8
525 * This flag indicates that an EOF is pending on the outgoing side
526 * of the channel: that is, wherever we're getting the data for
527 * this channel has sent us some data followed by EOF. We can't
528 * actually send the EOF until we've finished sending the data, so
529 * we set this flag instead to remind us to do so once our buffer
535 * True if this channel is causing the underlying connection to be
540 struct ssh2_data_channel {
542 unsigned remwindow, remmaxpkt;
543 /* locwindow is signed so we can cope with excess data. */
544 int locwindow, locmaxwin;
546 * remlocwin is the amount of local window that we think
547 * the remote end had available to it after it sent the
548 * last data packet or window adjust ack.
552 * These store the list of channel requests that haven't
555 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
556 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
560 struct ssh_agent_channel {
561 unsigned char *message;
562 unsigned char msglen[4];
563 unsigned lensofar, totallen;
564 int outstanding_requests;
566 struct ssh_x11_channel {
567 struct X11Connection *xconn;
570 struct ssh_pfd_channel {
571 struct PortForwarding *pf;
573 struct ssh_sharing_channel {
580 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
581 * use this structure in different ways, reflecting SSH-2's
582 * altogether saner approach to port forwarding.
584 * In SSH-1, you arrange a remote forwarding by sending the server
585 * the remote port number, and the local destination host:port.
586 * When a connection comes in, the server sends you back that
587 * host:port pair, and you connect to it. This is a ready-made
588 * security hole if you're not on the ball: a malicious server
589 * could send you back _any_ host:port pair, so if you trustingly
590 * connect to the address it gives you then you've just opened the
591 * entire inside of your corporate network just by connecting
592 * through it to a dodgy SSH server. Hence, we must store a list of
593 * host:port pairs we _are_ trying to forward to, and reject a
594 * connection request from the server if it's not in the list.
596 * In SSH-2, each side of the connection minds its own business and
597 * doesn't send unnecessary information to the other. You arrange a
598 * remote forwarding by sending the server just the remote port
599 * number. When a connection comes in, the server tells you which
600 * of its ports was connected to; and _you_ have to remember what
601 * local host:port pair went with that port number.
603 * Hence, in SSH-1 this structure is indexed by destination
604 * host:port pair, whereas in SSH-2 it is indexed by source port.
606 struct ssh_portfwd; /* forward declaration */
608 struct ssh_rportfwd {
609 unsigned sport, dport;
613 struct ssh_portfwd *pfrec;
616 static void free_rportfwd(struct ssh_rportfwd *pf)
619 sfree(pf->sportdesc);
627 * Separately to the rportfwd tree (which is for looking up port
628 * open requests from the server), a tree of _these_ structures is
629 * used to keep track of all the currently open port forwardings,
630 * so that we can reconfigure in mid-session if the user requests
634 enum { DESTROY, KEEP, CREATE } status;
636 unsigned sport, dport;
639 struct ssh_rportfwd *remote;
641 struct PortListener *local;
643 #define free_portfwd(pf) ( \
644 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
645 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
648 long length; /* length of packet: see below */
649 long forcepad; /* SSH-2: force padding to at least this length */
650 int type; /* only used for incoming packets */
651 unsigned long sequence; /* SSH-2 incoming sequence number */
652 unsigned char *data; /* allocated storage */
653 unsigned char *body; /* offset of payload within `data' */
654 long savedpos; /* dual-purpose saved packet position: see below */
655 long maxlen; /* amount of storage allocated for `data' */
656 long encrypted_len; /* for SSH-2 total-size counting */
659 * A note on the 'length' and 'savedpos' fields above.
661 * Incoming packets are set up so that pkt->length is measured
662 * relative to pkt->body, which itself points to a few bytes after
663 * pkt->data (skipping some uninteresting header fields including
664 * the packet type code). The ssh_pkt_get* functions all expect
665 * this setup, and they also use pkt->savedpos to indicate how far
666 * through the packet being decoded they've got - and that, too,
667 * is an offset from pkt->body rather than pkt->data.
669 * During construction of an outgoing packet, however, pkt->length
670 * is measured relative to the base pointer pkt->data, and
671 * pkt->body is not really used for anything until the packet is
672 * ready for sending. In this mode, pkt->savedpos is reused as a
673 * temporary variable by the addstring functions, which write out
674 * a string length field and then keep going back and updating it
675 * as more data is appended to the subsequent string data field;
676 * pkt->savedpos stores the offset (again relative to pkt->data)
677 * of the start of the string data field.
680 /* Extra metadata used in SSH packet logging mode, allowing us to
681 * log in the packet header line that the packet came from a
682 * connection-sharing downstream and what if anything unusual was
683 * done to it. The additional_log_text field is expected to be a
684 * static string - it will not be freed. */
685 unsigned downstream_id;
686 const char *additional_log_text;
689 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
690 struct Packet *pktin);
691 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
692 struct Packet *pktin);
693 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
694 struct Packet *pktin);
695 static void ssh1_protocol_setup(Ssh ssh);
696 static void ssh2_protocol_setup(Ssh ssh);
697 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
698 static void ssh_size(void *handle, int width, int height);
699 static void ssh_special(void *handle, Telnet_Special);
700 static int ssh2_try_send(struct ssh_channel *c);
701 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
702 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
703 static void ssh2_set_window(struct ssh_channel *c, int newwin);
704 static int ssh_sendbuffer(void *handle);
705 static int ssh_do_close(Ssh ssh, int notify_exit);
706 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
707 static int ssh2_pkt_getbool(struct Packet *pkt);
708 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
709 static void ssh2_timer(void *ctx, unsigned long now);
710 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
711 struct Packet *pktin);
712 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
714 struct rdpkt1_state_tag {
715 long len, pad, biglen, to_read;
716 unsigned long realcrc, gotcrc;
720 struct Packet *pktin;
723 struct rdpkt2_state_tag {
724 long len, pad, payload, packetlen, maclen;
727 unsigned long incoming_sequence;
728 struct Packet *pktin;
731 struct rdpkt2_bare_state_tag {
735 unsigned long incoming_sequence;
736 struct Packet *pktin;
739 struct queued_handler;
740 struct queued_handler {
742 chandler_fn_t handler;
744 struct queued_handler *next;
748 const struct plug_function_table *fn;
749 /* the above field _must_ be first in the structure */
759 unsigned char session_key[32];
761 int v1_remote_protoflags;
762 int v1_local_protoflags;
763 int agentfwd_enabled;
766 const struct ssh_cipher *cipher;
769 const struct ssh2_cipher *cscipher, *sccipher;
770 void *cs_cipher_ctx, *sc_cipher_ctx;
771 const struct ssh_mac *csmac, *scmac;
772 int csmac_etm, scmac_etm;
773 void *cs_mac_ctx, *sc_mac_ctx;
774 const struct ssh_compress *cscomp, *sccomp;
775 void *cs_comp_ctx, *sc_comp_ctx;
776 const struct ssh_kex *kex;
777 const struct ssh_signkey *hostkey;
778 char *hostkey_str; /* string representation, for easy checking in rekeys */
779 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
780 int v2_session_id_len;
784 int attempting_connshare;
790 int echoing, editing;
794 int ospeed, ispeed; /* temporaries */
795 int term_width, term_height;
797 tree234 *channels; /* indexed by local id */
798 struct ssh_channel *mainchan; /* primary session channel */
799 int ncmode; /* is primary channel direct-tcpip? */
804 tree234 *rportfwds, *portfwds;
808 SSH_STATE_BEFORE_SIZE,
814 int size_needed, eof_needed;
815 int sent_console_eof;
816 int got_pty; /* affects EOF behaviour on main channel */
818 struct Packet **queue;
819 int queuelen, queuesize;
821 unsigned char *deferred_send_data;
822 int deferred_len, deferred_size;
825 * Gross hack: pscp will try to start SFTP but fall back to
826 * scp1 if that fails. This variable is the means by which
827 * scp.c can reach into the SSH code and find out which one it
832 bufchain banner; /* accumulates banners during do_ssh2_authconn */
837 struct X11Display *x11disp;
838 struct X11FakeAuth *x11auth;
839 tree234 *x11authtree;
842 int conn_throttle_count;
845 int v1_stdout_throttling;
846 unsigned long v2_outgoing_sequence;
848 int ssh1_rdpkt_crstate;
849 int ssh2_rdpkt_crstate;
850 int ssh2_bare_rdpkt_crstate;
851 int ssh_gotdata_crstate;
852 int do_ssh1_connection_crstate;
854 void *do_ssh_init_state;
855 void *do_ssh1_login_state;
856 void *do_ssh2_transport_state;
857 void *do_ssh2_authconn_state;
858 void *do_ssh_connection_init_state;
860 struct rdpkt1_state_tag rdpkt1_state;
861 struct rdpkt2_state_tag rdpkt2_state;
862 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
864 /* SSH-1 and SSH-2 use this for different things, but both use it */
865 int protocol_initial_phase_done;
867 void (*protocol) (Ssh ssh, void *vin, int inlen,
869 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
870 int (*do_ssh_init)(Ssh ssh, unsigned char c);
873 * We maintain our own copy of a Conf structure here. That way,
874 * when we're passed a new one for reconfiguration, we can check
875 * the differences and potentially reconfigure port forwardings
876 * etc in mid-session.
881 * Values cached out of conf so as to avoid the tree234 lookup
882 * cost every time they're used.
887 * Dynamically allocated username string created during SSH
888 * login. Stored in here rather than in the coroutine state so
889 * that it'll be reliably freed if we shut down the SSH session
890 * at some unexpected moment.
895 * Used to transfer data back from async callbacks.
897 void *agent_response;
898 int agent_response_len;
902 * The SSH connection can be set as `frozen', meaning we are
903 * not currently accepting incoming data from the network. This
904 * is slightly more serious than setting the _socket_ as
905 * frozen, because we may already have had data passed to us
906 * from the network which we need to delay processing until
907 * after the freeze is lifted, so we also need a bufchain to
911 bufchain queued_incoming_data;
914 * Dispatch table for packet types that we may have to deal
917 handler_fn_t packet_dispatch[256];
920 * Queues of one-off handler functions for success/failure
921 * indications from a request.
923 struct queued_handler *qhead, *qtail;
924 handler_fn_t q_saved_handler1, q_saved_handler2;
927 * This module deals with sending keepalives.
932 * Track incoming and outgoing data sizes and time, for
935 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
936 unsigned long max_data_size;
938 unsigned long next_rekey, last_rekey;
939 char *deferred_rekey_reason; /* points to STATIC string; don't free */
942 * Fully qualified host name, which we need if doing GSSAPI.
948 * GSSAPI libraries for this session.
950 struct ssh_gss_liblist *gsslibs;
954 #define logevent(s) logevent(ssh->frontend, s)
956 /* logevent, only printf-formatted. */
957 static void logeventf(Ssh ssh, const char *fmt, ...)
963 buf = dupvprintf(fmt, ap);
969 static void bomb_out(Ssh ssh, char *text)
971 ssh_do_close(ssh, FALSE);
973 connection_fatal(ssh->frontend, "%s", text);
977 #define bombout(msg) bomb_out(ssh, dupprintf msg)
979 /* Helper function for common bits of parsing ttymodes. */
980 static void parse_ttymodes(Ssh ssh,
981 void (*do_mode)(void *data, char *mode, char *val),
986 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
988 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
990 * val[0] is either 'V', indicating that an explicit value
991 * follows it, or 'A' indicating that we should pass the
992 * value through from the local environment via get_ttymode.
995 val = get_ttymode(ssh->frontend, key);
997 do_mode(data, key, val);
1001 do_mode(data, key, val + 1); /* skip the 'V' */
1005 static int ssh_channelcmp(void *av, void *bv)
1007 struct ssh_channel *a = (struct ssh_channel *) av;
1008 struct ssh_channel *b = (struct ssh_channel *) bv;
1009 if (a->localid < b->localid)
1011 if (a->localid > b->localid)
1015 static int ssh_channelfind(void *av, void *bv)
1017 unsigned *a = (unsigned *) av;
1018 struct ssh_channel *b = (struct ssh_channel *) bv;
1019 if (*a < b->localid)
1021 if (*a > b->localid)
1026 static int ssh_rportcmp_ssh1(void *av, void *bv)
1028 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1029 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1031 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1032 return i < 0 ? -1 : +1;
1033 if (a->dport > b->dport)
1035 if (a->dport < b->dport)
1040 static int ssh_rportcmp_ssh2(void *av, void *bv)
1042 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1043 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1045 if ( (i = strcmp(a->shost, b->shost)) != 0)
1046 return i < 0 ? -1 : +1;
1047 if (a->sport > b->sport)
1049 if (a->sport < b->sport)
1055 * Special form of strcmp which can cope with NULL inputs. NULL is
1056 * defined to sort before even the empty string.
1058 static int nullstrcmp(const char *a, const char *b)
1060 if (a == NULL && b == NULL)
1066 return strcmp(a, b);
1069 static int ssh_portcmp(void *av, void *bv)
1071 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1072 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1074 if (a->type > b->type)
1076 if (a->type < b->type)
1078 if (a->addressfamily > b->addressfamily)
1080 if (a->addressfamily < b->addressfamily)
1082 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1083 return i < 0 ? -1 : +1;
1084 if (a->sport > b->sport)
1086 if (a->sport < b->sport)
1088 if (a->type != 'D') {
1089 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1090 return i < 0 ? -1 : +1;
1091 if (a->dport > b->dport)
1093 if (a->dport < b->dport)
1099 static int alloc_channel_id(Ssh ssh)
1101 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1102 unsigned low, high, mid;
1104 struct ssh_channel *c;
1107 * First-fit allocation of channel numbers: always pick the
1108 * lowest unused one. To do this, binary-search using the
1109 * counted B-tree to find the largest channel ID which is in a
1110 * contiguous sequence from the beginning. (Precisely
1111 * everything in that sequence must have ID equal to its tree
1112 * index plus CHANNEL_NUMBER_OFFSET.)
1114 tsize = count234(ssh->channels);
1118 while (high - low > 1) {
1119 mid = (high + low) / 2;
1120 c = index234(ssh->channels, mid);
1121 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1122 low = mid; /* this one is fine */
1124 high = mid; /* this one is past it */
1127 * Now low points to either -1, or the tree index of the
1128 * largest ID in the initial sequence.
1131 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1132 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1134 return low + 1 + CHANNEL_NUMBER_OFFSET;
1137 static void c_write_stderr(int trusted, const char *buf, int len)
1140 for (i = 0; i < len; i++)
1141 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1142 fputc(buf[i], stderr);
1145 static void c_write(Ssh ssh, const char *buf, int len)
1147 if (flags & FLAG_STDERR)
1148 c_write_stderr(1, buf, len);
1150 from_backend(ssh->frontend, 1, buf, len);
1153 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1155 if (flags & FLAG_STDERR)
1156 c_write_stderr(0, buf, len);
1158 from_backend_untrusted(ssh->frontend, buf, len);
1161 static void c_write_str(Ssh ssh, const char *buf)
1163 c_write(ssh, buf, strlen(buf));
1166 static void ssh_free_packet(struct Packet *pkt)
1171 static struct Packet *ssh_new_packet(void)
1173 struct Packet *pkt = snew(struct Packet);
1175 pkt->body = pkt->data = NULL;
1181 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1184 struct logblank_t blanks[4];
1190 if (ssh->logomitdata &&
1191 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1192 pkt->type == SSH1_SMSG_STDERR_DATA ||
1193 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1194 /* "Session data" packets - omit the data string. */
1195 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1196 ssh_pkt_getuint32(pkt); /* skip channel id */
1197 blanks[nblanks].offset = pkt->savedpos + 4;
1198 blanks[nblanks].type = PKTLOG_OMIT;
1199 ssh_pkt_getstring(pkt, &str, &slen);
1201 blanks[nblanks].len = slen;
1205 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1206 ssh1_pkt_type(pkt->type),
1207 pkt->body, pkt->length, nblanks, blanks, NULL,
1211 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1214 struct logblank_t blanks[4];
1219 * For outgoing packets, pkt->length represents the length of the
1220 * whole packet starting at pkt->data (including some header), and
1221 * pkt->body refers to the point within that where the log-worthy
1222 * payload begins. However, incoming packets expect pkt->length to
1223 * represent only the payload length (that is, it's measured from
1224 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1225 * packet to conform to the incoming-packet semantics, so that we
1226 * can analyse it with the ssh_pkt_get functions.
1228 pkt->length -= (pkt->body - pkt->data);
1231 if (ssh->logomitdata &&
1232 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1233 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1234 /* "Session data" packets - omit the data string. */
1235 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1236 ssh_pkt_getuint32(pkt); /* skip channel id */
1237 blanks[nblanks].offset = pkt->savedpos + 4;
1238 blanks[nblanks].type = PKTLOG_OMIT;
1239 ssh_pkt_getstring(pkt, &str, &slen);
1241 blanks[nblanks].len = slen;
1246 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1247 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1248 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1249 conf_get_int(ssh->conf, CONF_logomitpass)) {
1250 /* If this is a password or similar packet, blank the password(s). */
1251 blanks[nblanks].offset = 0;
1252 blanks[nblanks].len = pkt->length;
1253 blanks[nblanks].type = PKTLOG_BLANK;
1255 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1256 conf_get_int(ssh->conf, CONF_logomitpass)) {
1258 * If this is an X forwarding request packet, blank the fake
1261 * Note that while we blank the X authentication data here, we
1262 * don't take any special action to blank the start of an X11
1263 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1264 * an X connection without having session blanking enabled is
1265 * likely to leak your cookie into the log.
1268 ssh_pkt_getstring(pkt, &str, &slen);
1269 blanks[nblanks].offset = pkt->savedpos;
1270 blanks[nblanks].type = PKTLOG_BLANK;
1271 ssh_pkt_getstring(pkt, &str, &slen);
1273 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1278 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1279 ssh1_pkt_type(pkt->data[12]),
1280 pkt->body, pkt->length,
1281 nblanks, blanks, NULL, 0, NULL);
1284 * Undo the above adjustment of pkt->length, to put the packet
1285 * back in the state we found it.
1287 pkt->length += (pkt->body - pkt->data);
1291 * Collect incoming data in the incoming packet buffer.
1292 * Decipher and verify the packet when it is completely read.
1293 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1294 * Update the *data and *datalen variables.
1295 * Return a Packet structure when a packet is completed.
1297 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1299 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1301 crBegin(ssh->ssh1_rdpkt_crstate);
1303 st->pktin = ssh_new_packet();
1305 st->pktin->type = 0;
1306 st->pktin->length = 0;
1308 for (st->i = st->len = 0; st->i < 4; st->i++) {
1309 while ((*datalen) == 0)
1311 st->len = (st->len << 8) + **data;
1312 (*data)++, (*datalen)--;
1315 st->pad = 8 - (st->len % 8);
1316 st->biglen = st->len + st->pad;
1317 st->pktin->length = st->len - 5;
1319 if (st->biglen < 0) {
1320 bombout(("Extremely large packet length from server suggests"
1321 " data stream corruption"));
1322 ssh_free_packet(st->pktin);
1326 st->pktin->maxlen = st->biglen;
1327 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1329 st->to_read = st->biglen;
1330 st->p = st->pktin->data;
1331 while (st->to_read > 0) {
1332 st->chunk = st->to_read;
1333 while ((*datalen) == 0)
1335 if (st->chunk > (*datalen))
1336 st->chunk = (*datalen);
1337 memcpy(st->p, *data, st->chunk);
1339 *datalen -= st->chunk;
1341 st->to_read -= st->chunk;
1344 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1345 st->biglen, NULL)) {
1346 bombout(("Network attack (CRC compensation) detected!"));
1347 ssh_free_packet(st->pktin);
1352 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1354 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1355 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1356 if (st->gotcrc != st->realcrc) {
1357 bombout(("Incorrect CRC received on packet"));
1358 ssh_free_packet(st->pktin);
1362 st->pktin->body = st->pktin->data + st->pad + 1;
1364 if (ssh->v1_compressing) {
1365 unsigned char *decompblk;
1367 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1368 st->pktin->body - 1, st->pktin->length + 1,
1369 &decompblk, &decomplen)) {
1370 bombout(("Zlib decompression encountered invalid data"));
1371 ssh_free_packet(st->pktin);
1375 if (st->pktin->maxlen < st->pad + decomplen) {
1376 st->pktin->maxlen = st->pad + decomplen;
1377 st->pktin->data = sresize(st->pktin->data,
1378 st->pktin->maxlen + APIEXTRA,
1380 st->pktin->body = st->pktin->data + st->pad + 1;
1383 memcpy(st->pktin->body - 1, decompblk, decomplen);
1385 st->pktin->length = decomplen - 1;
1388 st->pktin->type = st->pktin->body[-1];
1391 * Now pktin->body and pktin->length identify the semantic content
1392 * of the packet, excluding the initial type byte.
1396 ssh1_log_incoming_packet(ssh, st->pktin);
1398 st->pktin->savedpos = 0;
1400 crFinish(st->pktin);
1403 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1406 struct logblank_t blanks[4];
1412 if (ssh->logomitdata &&
1413 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1414 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1415 /* "Session data" packets - omit the data string. */
1416 ssh_pkt_getuint32(pkt); /* skip channel id */
1417 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1418 ssh_pkt_getuint32(pkt); /* skip extended data type */
1419 blanks[nblanks].offset = pkt->savedpos + 4;
1420 blanks[nblanks].type = PKTLOG_OMIT;
1421 ssh_pkt_getstring(pkt, &str, &slen);
1423 blanks[nblanks].len = slen;
1428 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1429 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1430 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1434 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1437 struct logblank_t blanks[4];
1442 * For outgoing packets, pkt->length represents the length of the
1443 * whole packet starting at pkt->data (including some header), and
1444 * pkt->body refers to the point within that where the log-worthy
1445 * payload begins. However, incoming packets expect pkt->length to
1446 * represent only the payload length (that is, it's measured from
1447 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1448 * packet to conform to the incoming-packet semantics, so that we
1449 * can analyse it with the ssh_pkt_get functions.
1451 pkt->length -= (pkt->body - pkt->data);
1454 if (ssh->logomitdata &&
1455 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1456 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1457 /* "Session data" packets - omit the data string. */
1458 ssh_pkt_getuint32(pkt); /* skip channel id */
1459 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1460 ssh_pkt_getuint32(pkt); /* skip extended data type */
1461 blanks[nblanks].offset = pkt->savedpos + 4;
1462 blanks[nblanks].type = PKTLOG_OMIT;
1463 ssh_pkt_getstring(pkt, &str, &slen);
1465 blanks[nblanks].len = slen;
1470 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1471 conf_get_int(ssh->conf, CONF_logomitpass)) {
1472 /* If this is a password packet, blank the password(s). */
1474 ssh_pkt_getstring(pkt, &str, &slen);
1475 ssh_pkt_getstring(pkt, &str, &slen);
1476 ssh_pkt_getstring(pkt, &str, &slen);
1477 if (slen == 8 && !memcmp(str, "password", 8)) {
1478 ssh2_pkt_getbool(pkt);
1479 /* Blank the password field. */
1480 blanks[nblanks].offset = pkt->savedpos;
1481 blanks[nblanks].type = PKTLOG_BLANK;
1482 ssh_pkt_getstring(pkt, &str, &slen);
1484 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1486 /* If there's another password field beyond it (change of
1487 * password), blank that too. */
1488 ssh_pkt_getstring(pkt, &str, &slen);
1490 blanks[nblanks-1].len =
1491 pkt->savedpos - blanks[nblanks].offset;
1494 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1495 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1496 conf_get_int(ssh->conf, CONF_logomitpass)) {
1497 /* If this is a keyboard-interactive response packet, blank
1500 ssh_pkt_getuint32(pkt);
1501 blanks[nblanks].offset = pkt->savedpos;
1502 blanks[nblanks].type = PKTLOG_BLANK;
1504 ssh_pkt_getstring(pkt, &str, &slen);
1508 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1510 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1511 conf_get_int(ssh->conf, CONF_logomitpass)) {
1513 * If this is an X forwarding request packet, blank the fake
1516 * Note that while we blank the X authentication data here, we
1517 * don't take any special action to blank the start of an X11
1518 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1519 * an X connection without having session blanking enabled is
1520 * likely to leak your cookie into the log.
1523 ssh_pkt_getuint32(pkt);
1524 ssh_pkt_getstring(pkt, &str, &slen);
1525 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1526 ssh2_pkt_getbool(pkt);
1527 ssh2_pkt_getbool(pkt);
1528 ssh_pkt_getstring(pkt, &str, &slen);
1529 blanks[nblanks].offset = pkt->savedpos;
1530 blanks[nblanks].type = PKTLOG_BLANK;
1531 ssh_pkt_getstring(pkt, &str, &slen);
1533 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1539 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1540 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1541 pkt->body, pkt->length, nblanks, blanks,
1542 &ssh->v2_outgoing_sequence,
1543 pkt->downstream_id, pkt->additional_log_text);
1546 * Undo the above adjustment of pkt->length, to put the packet
1547 * back in the state we found it.
1549 pkt->length += (pkt->body - pkt->data);
1552 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1554 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1556 crBegin(ssh->ssh2_rdpkt_crstate);
1558 st->pktin = ssh_new_packet();
1560 st->pktin->type = 0;
1561 st->pktin->length = 0;
1563 st->cipherblk = ssh->sccipher->blksize;
1566 if (st->cipherblk < 8)
1568 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1570 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1571 ssh->scmac && !ssh->scmac_etm) {
1573 * When dealing with a CBC-mode cipher, we want to avoid the
1574 * possibility of an attacker's tweaking the ciphertext stream
1575 * so as to cause us to feed the same block to the block
1576 * cipher more than once and thus leak information
1577 * (VU#958563). The way we do this is not to take any
1578 * decisions on the basis of anything we've decrypted until
1579 * we've verified it with a MAC. That includes the packet
1580 * length, so we just read data and check the MAC repeatedly,
1581 * and when the MAC passes, see if the length we've got is
1584 * This defence is unnecessary in OpenSSH ETM mode, because
1585 * the whole point of ETM mode is that the attacker can't
1586 * tweak the ciphertext stream at all without the MAC
1587 * detecting it before we decrypt anything.
1590 /* May as well allocate the whole lot now. */
1591 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1594 /* Read an amount corresponding to the MAC. */
1595 for (st->i = 0; st->i < st->maclen; st->i++) {
1596 while ((*datalen) == 0)
1598 st->pktin->data[st->i] = *(*data)++;
1604 unsigned char seq[4];
1605 ssh->scmac->start(ssh->sc_mac_ctx);
1606 PUT_32BIT(seq, st->incoming_sequence);
1607 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1610 for (;;) { /* Once around this loop per cipher block. */
1611 /* Read another cipher-block's worth, and tack it onto the end. */
1612 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1613 while ((*datalen) == 0)
1615 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1618 /* Decrypt one more block (a little further back in the stream). */
1619 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1620 st->pktin->data + st->packetlen,
1622 /* Feed that block to the MAC. */
1623 ssh->scmac->bytes(ssh->sc_mac_ctx,
1624 st->pktin->data + st->packetlen, st->cipherblk);
1625 st->packetlen += st->cipherblk;
1626 /* See if that gives us a valid packet. */
1627 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1628 st->pktin->data + st->packetlen) &&
1629 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1632 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1633 bombout(("No valid incoming packet found"));
1634 ssh_free_packet(st->pktin);
1638 st->pktin->maxlen = st->packetlen + st->maclen;
1639 st->pktin->data = sresize(st->pktin->data,
1640 st->pktin->maxlen + APIEXTRA,
1642 } else if (ssh->scmac && ssh->scmac_etm) {
1643 st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1646 * OpenSSH encrypt-then-MAC mode: the packet length is
1649 for (st->i = st->len = 0; st->i < 4; st->i++) {
1650 while ((*datalen) == 0)
1652 st->pktin->data[st->i] = *(*data)++;
1655 st->len = toint(GET_32BIT(st->pktin->data));
1658 * _Completely_ silly lengths should be stomped on before they
1659 * do us any more damage.
1661 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1662 st->len % st->cipherblk != 0) {
1663 bombout(("Incoming packet length field was garbled"));
1664 ssh_free_packet(st->pktin);
1669 * So now we can work out the total packet length.
1671 st->packetlen = st->len + 4;
1674 * Allocate memory for the rest of the packet.
1676 st->pktin->maxlen = st->packetlen + st->maclen;
1677 st->pktin->data = sresize(st->pktin->data,
1678 st->pktin->maxlen + APIEXTRA,
1682 * Read the remainder of the packet.
1684 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1685 while ((*datalen) == 0)
1687 st->pktin->data[st->i] = *(*data)++;
1695 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1696 st->len + 4, st->incoming_sequence)) {
1697 bombout(("Incorrect MAC received on packet"));
1698 ssh_free_packet(st->pktin);
1702 /* Decrypt everything between the length field and the MAC. */
1704 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1705 st->pktin->data + 4,
1708 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1711 * Acquire and decrypt the first block of the packet. This will
1712 * contain the length and padding details.
1714 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1715 while ((*datalen) == 0)
1717 st->pktin->data[st->i] = *(*data)++;
1722 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1723 st->pktin->data, st->cipherblk);
1726 * Now get the length figure.
1728 st->len = toint(GET_32BIT(st->pktin->data));
1731 * _Completely_ silly lengths should be stomped on before they
1732 * do us any more damage.
1734 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1735 (st->len + 4) % st->cipherblk != 0) {
1736 bombout(("Incoming packet was garbled on decryption"));
1737 ssh_free_packet(st->pktin);
1742 * So now we can work out the total packet length.
1744 st->packetlen = st->len + 4;
1747 * Allocate memory for the rest of the packet.
1749 st->pktin->maxlen = st->packetlen + st->maclen;
1750 st->pktin->data = sresize(st->pktin->data,
1751 st->pktin->maxlen + APIEXTRA,
1755 * Read and decrypt the remainder of the packet.
1757 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1759 while ((*datalen) == 0)
1761 st->pktin->data[st->i] = *(*data)++;
1764 /* Decrypt everything _except_ the MAC. */
1766 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1767 st->pktin->data + st->cipherblk,
1768 st->packetlen - st->cipherblk);
1774 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1775 st->len + 4, st->incoming_sequence)) {
1776 bombout(("Incorrect MAC received on packet"));
1777 ssh_free_packet(st->pktin);
1781 /* Get and sanity-check the amount of random padding. */
1782 st->pad = st->pktin->data[4];
1783 if (st->pad < 4 || st->len - st->pad < 1) {
1784 bombout(("Invalid padding length on received packet"));
1785 ssh_free_packet(st->pktin);
1789 * This enables us to deduce the payload length.
1791 st->payload = st->len - st->pad - 1;
1793 st->pktin->length = st->payload + 5;
1794 st->pktin->encrypted_len = st->packetlen;
1796 st->pktin->sequence = st->incoming_sequence++;
1798 st->pktin->length = st->packetlen - st->pad;
1799 assert(st->pktin->length >= 0);
1802 * Decompress packet payload.
1805 unsigned char *newpayload;
1808 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1809 st->pktin->data + 5, st->pktin->length - 5,
1810 &newpayload, &newlen)) {
1811 if (st->pktin->maxlen < newlen + 5) {
1812 st->pktin->maxlen = newlen + 5;
1813 st->pktin->data = sresize(st->pktin->data,
1814 st->pktin->maxlen + APIEXTRA,
1817 st->pktin->length = 5 + newlen;
1818 memcpy(st->pktin->data + 5, newpayload, newlen);
1824 * pktin->body and pktin->length should identify the semantic
1825 * content of the packet, excluding the initial type byte.
1827 st->pktin->type = st->pktin->data[5];
1828 st->pktin->body = st->pktin->data + 6;
1829 st->pktin->length -= 6;
1830 assert(st->pktin->length >= 0); /* one last double-check */
1833 ssh2_log_incoming_packet(ssh, st->pktin);
1835 st->pktin->savedpos = 0;
1837 crFinish(st->pktin);
1840 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh, unsigned char **data,
1843 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1845 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1848 * Read the packet length field.
1850 for (st->i = 0; st->i < 4; st->i++) {
1851 while ((*datalen) == 0)
1853 st->length[st->i] = *(*data)++;
1857 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1858 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1859 bombout(("Invalid packet length received"));
1863 st->pktin = ssh_new_packet();
1864 st->pktin->data = snewn(st->packetlen, unsigned char);
1866 st->pktin->encrypted_len = st->packetlen;
1868 st->pktin->sequence = st->incoming_sequence++;
1871 * Read the remainder of the packet.
1873 for (st->i = 0; st->i < st->packetlen; st->i++) {
1874 while ((*datalen) == 0)
1876 st->pktin->data[st->i] = *(*data)++;
1881 * pktin->body and pktin->length should identify the semantic
1882 * content of the packet, excluding the initial type byte.
1884 st->pktin->type = st->pktin->data[0];
1885 st->pktin->body = st->pktin->data + 1;
1886 st->pktin->length = st->packetlen - 1;
1889 * Log incoming packet, possibly omitting sensitive fields.
1892 ssh2_log_incoming_packet(ssh, st->pktin);
1894 st->pktin->savedpos = 0;
1896 crFinish(st->pktin);
1899 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1901 int pad, biglen, i, pktoffs;
1905 * XXX various versions of SC (including 8.8.4) screw up the
1906 * register allocation in this function and use the same register
1907 * (D6) for len and as a temporary, with predictable results. The
1908 * following sledgehammer prevents this.
1915 ssh1_log_outgoing_packet(ssh, pkt);
1917 if (ssh->v1_compressing) {
1918 unsigned char *compblk;
1920 zlib_compress_block(ssh->cs_comp_ctx,
1921 pkt->data + 12, pkt->length - 12,
1922 &compblk, &complen);
1923 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1924 memcpy(pkt->data + 12, compblk, complen);
1926 pkt->length = complen + 12;
1929 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1931 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1932 pad = 8 - (len % 8);
1934 biglen = len + pad; /* len(padding+type+data+CRC) */
1936 for (i = pktoffs; i < 4+8; i++)
1937 pkt->data[i] = random_byte();
1938 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1939 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1940 PUT_32BIT(pkt->data + pktoffs, len);
1943 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1944 pkt->data + pktoffs + 4, biglen);
1946 if (offset_p) *offset_p = pktoffs;
1947 return biglen + 4; /* len(length+padding+type+data+CRC) */
1950 static int s_write(Ssh ssh, void *data, int len)
1953 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1954 0, NULL, NULL, 0, NULL);
1957 return sk_write(ssh->s, (char *)data, len);
1960 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1962 int len, backlog, offset;
1963 len = s_wrpkt_prepare(ssh, pkt, &offset);
1964 backlog = s_write(ssh, pkt->data + offset, len);
1965 if (backlog > SSH_MAX_BACKLOG)
1966 ssh_throttle_all(ssh, 1, backlog);
1967 ssh_free_packet(pkt);
1970 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1973 len = s_wrpkt_prepare(ssh, pkt, &offset);
1974 if (ssh->deferred_len + len > ssh->deferred_size) {
1975 ssh->deferred_size = ssh->deferred_len + len + 128;
1976 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1980 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1981 pkt->data + offset, len);
1982 ssh->deferred_len += len;
1983 ssh_free_packet(pkt);
1987 * Construct a SSH-1 packet with the specified contents.
1988 * (This all-at-once interface used to be the only one, but now SSH-1
1989 * packets can also be constructed incrementally.)
1991 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1997 pkt = ssh1_pkt_init(pkttype);
1999 while ((argtype = va_arg(ap, int)) != PKT_END) {
2000 unsigned char *argp, argchar;
2002 unsigned long argint;
2005 /* Actual fields in the packet */
2007 argint = va_arg(ap, int);
2008 ssh_pkt_adduint32(pkt, argint);
2011 argchar = (unsigned char) va_arg(ap, int);
2012 ssh_pkt_addbyte(pkt, argchar);
2015 argp = va_arg(ap, unsigned char *);
2016 arglen = va_arg(ap, int);
2017 ssh_pkt_adddata(pkt, argp, arglen);
2020 sargp = va_arg(ap, char *);
2021 ssh_pkt_addstring(pkt, sargp);
2024 bn = va_arg(ap, Bignum);
2025 ssh1_pkt_addmp(pkt, bn);
2033 static void send_packet(Ssh ssh, int pkttype, ...)
2037 va_start(ap, pkttype);
2038 pkt = construct_packet(ssh, pkttype, ap);
2043 static void defer_packet(Ssh ssh, int pkttype, ...)
2047 va_start(ap, pkttype);
2048 pkt = construct_packet(ssh, pkttype, ap);
2050 s_wrpkt_defer(ssh, pkt);
2053 static int ssh_versioncmp(char *a, char *b)
2056 unsigned long av, bv;
2058 av = strtoul(a, &ae, 10);
2059 bv = strtoul(b, &be, 10);
2061 return (av < bv ? -1 : +1);
2066 av = strtoul(ae, &ae, 10);
2067 bv = strtoul(be, &be, 10);
2069 return (av < bv ? -1 : +1);
2074 * Utility routines for putting an SSH-protocol `string' and
2075 * `uint32' into a hash state.
2077 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2079 unsigned char lenblk[4];
2080 PUT_32BIT(lenblk, len);
2081 h->bytes(s, lenblk, 4);
2082 h->bytes(s, str, len);
2085 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2087 unsigned char intblk[4];
2088 PUT_32BIT(intblk, i);
2089 h->bytes(s, intblk, 4);
2093 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2095 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2097 if (pkt->maxlen < length) {
2098 unsigned char *body = pkt->body;
2099 int offset = body ? body - pkt->data : 0;
2100 pkt->maxlen = length + 256;
2101 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2102 if (body) pkt->body = pkt->data + offset;
2105 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2108 ssh_pkt_ensure(pkt, pkt->length);
2109 memcpy(pkt->data + pkt->length - len, data, len);
2111 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2113 ssh_pkt_adddata(pkt, &byte, 1);
2115 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2117 ssh_pkt_adddata(pkt, &value, 1);
2119 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2122 PUT_32BIT(x, value);
2123 ssh_pkt_adddata(pkt, x, 4);
2125 static void ssh_pkt_addstring_start(struct Packet *pkt)
2127 ssh_pkt_adduint32(pkt, 0);
2128 pkt->savedpos = pkt->length;
2130 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2132 ssh_pkt_adddata(pkt, data, strlen(data));
2133 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2135 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2138 ssh_pkt_adddata(pkt, data, len);
2139 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2141 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2143 ssh_pkt_addstring_start(pkt);
2144 ssh_pkt_addstring_str(pkt, data);
2146 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2148 int len = ssh1_bignum_length(b);
2149 unsigned char *data = snewn(len, unsigned char);
2150 (void) ssh1_write_bignum(data, b);
2151 ssh_pkt_adddata(pkt, data, len);
2154 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2157 int i, n = (bignum_bitcount(b) + 7) / 8;
2158 p = snewn(n + 1, unsigned char);
2160 for (i = 1; i <= n; i++)
2161 p[i] = bignum_byte(b, n - i);
2163 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2165 memmove(p, p + i, n + 1 - i);
2169 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2173 p = ssh2_mpint_fmt(b, &len);
2174 ssh_pkt_addstring_start(pkt);
2175 ssh_pkt_addstring_data(pkt, (char *)p, len);
2179 static struct Packet *ssh1_pkt_init(int pkt_type)
2181 struct Packet *pkt = ssh_new_packet();
2182 pkt->length = 4 + 8; /* space for length + max padding */
2183 ssh_pkt_addbyte(pkt, pkt_type);
2184 pkt->body = pkt->data + pkt->length;
2185 pkt->type = pkt_type;
2186 pkt->downstream_id = 0;
2187 pkt->additional_log_text = NULL;
2191 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2192 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2193 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2194 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2195 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2196 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2197 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2198 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2199 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2201 static struct Packet *ssh2_pkt_init(int pkt_type)
2203 struct Packet *pkt = ssh_new_packet();
2204 pkt->length = 5; /* space for packet length + padding length */
2206 pkt->type = pkt_type;
2207 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2208 pkt->body = pkt->data + pkt->length; /* after packet type */
2209 pkt->downstream_id = 0;
2210 pkt->additional_log_text = NULL;
2215 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2216 * put the MAC on it. Final packet, ready to be sent, is stored in
2217 * pkt->data. Total length is returned.
2219 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2221 int cipherblk, maclen, padding, unencrypted_prefix, i;
2224 ssh2_log_outgoing_packet(ssh, pkt);
2226 if (ssh->bare_connection) {
2228 * Trivial packet construction for the bare connection
2231 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2232 pkt->body = pkt->data + 1;
2233 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2234 return pkt->length - 1;
2238 * Compress packet payload.
2241 unsigned char *newpayload;
2244 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2246 &newpayload, &newlen)) {
2248 ssh2_pkt_adddata(pkt, newpayload, newlen);
2254 * Add padding. At least four bytes, and must also bring total
2255 * length (minus MAC) up to a multiple of the block size.
2256 * If pkt->forcepad is set, make sure the packet is at least that size
2259 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2260 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2262 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2263 if (pkt->length + padding < pkt->forcepad)
2264 padding = pkt->forcepad - pkt->length;
2266 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2268 assert(padding <= 255);
2269 maclen = ssh->csmac ? ssh->csmac->len : 0;
2270 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2271 pkt->data[4] = padding;
2272 for (i = 0; i < padding; i++)
2273 pkt->data[pkt->length + i] = random_byte();
2274 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2275 if (ssh->csmac && ssh->csmac_etm) {
2277 * OpenSSH-defined encrypt-then-MAC protocol.
2280 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2281 pkt->data + 4, pkt->length + padding - 4);
2282 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2283 pkt->length + padding,
2284 ssh->v2_outgoing_sequence);
2287 * SSH-2 standard protocol.
2290 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2291 pkt->length + padding,
2292 ssh->v2_outgoing_sequence);
2294 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2295 pkt->data, pkt->length + padding);
2298 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2299 pkt->encrypted_len = pkt->length + padding;
2301 /* Ready-to-send packet starts at pkt->data. We return length. */
2302 pkt->body = pkt->data;
2303 return pkt->length + padding + maclen;
2307 * Routines called from the main SSH code to send packets. There
2308 * are quite a few of these, because we have two separate
2309 * mechanisms for delaying the sending of packets:
2311 * - In order to send an IGNORE message and a password message in
2312 * a single fixed-length blob, we require the ability to
2313 * concatenate the encrypted forms of those two packets _into_ a
2314 * single blob and then pass it to our <network.h> transport
2315 * layer in one go. Hence, there's a deferment mechanism which
2316 * works after packet encryption.
2318 * - In order to avoid sending any connection-layer messages
2319 * during repeat key exchange, we have to queue up any such
2320 * outgoing messages _before_ they are encrypted (and in
2321 * particular before they're allocated sequence numbers), and
2322 * then send them once we've finished.
2324 * I call these mechanisms `defer' and `queue' respectively, so as
2325 * to distinguish them reasonably easily.
2327 * The functions send_noqueue() and defer_noqueue() free the packet
2328 * structure they are passed. Every outgoing packet goes through
2329 * precisely one of these functions in its life; packets passed to
2330 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2331 * these or get queued, and then when the queue is later emptied
2332 * the packets are all passed to defer_noqueue().
2334 * When using a CBC-mode cipher, it's necessary to ensure that an
2335 * attacker can't provide data to be encrypted using an IV that they
2336 * know. We ensure this by prefixing each packet that might contain
2337 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2338 * mechanism, so in this case send_noqueue() ends up redirecting to
2339 * defer_noqueue(). If you don't like this inefficiency, don't use
2343 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2344 static void ssh_pkt_defersend(Ssh);
2347 * Send an SSH-2 packet immediately, without queuing or deferring.
2349 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2353 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2354 /* We need to send two packets, so use the deferral mechanism. */
2355 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2356 ssh_pkt_defersend(ssh);
2359 len = ssh2_pkt_construct(ssh, pkt);
2360 backlog = s_write(ssh, pkt->body, len);
2361 if (backlog > SSH_MAX_BACKLOG)
2362 ssh_throttle_all(ssh, 1, backlog);
2364 ssh->outgoing_data_size += pkt->encrypted_len;
2365 if (!ssh->kex_in_progress &&
2366 !ssh->bare_connection &&
2367 ssh->max_data_size != 0 &&
2368 ssh->outgoing_data_size > ssh->max_data_size)
2369 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2371 ssh_free_packet(pkt);
2375 * Defer an SSH-2 packet.
2377 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2380 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2381 ssh->deferred_len == 0 && !noignore &&
2382 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2384 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2385 * get encrypted with a known IV.
2387 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2388 ssh2_pkt_addstring_start(ipkt);
2389 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2391 len = ssh2_pkt_construct(ssh, pkt);
2392 if (ssh->deferred_len + len > ssh->deferred_size) {
2393 ssh->deferred_size = ssh->deferred_len + len + 128;
2394 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2398 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2399 ssh->deferred_len += len;
2400 ssh->deferred_data_size += pkt->encrypted_len;
2401 ssh_free_packet(pkt);
2405 * Queue an SSH-2 packet.
2407 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2409 assert(ssh->queueing);
2411 if (ssh->queuelen >= ssh->queuesize) {
2412 ssh->queuesize = ssh->queuelen + 32;
2413 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2416 ssh->queue[ssh->queuelen++] = pkt;
2420 * Either queue or send a packet, depending on whether queueing is
2423 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2426 ssh2_pkt_queue(ssh, pkt);
2428 ssh2_pkt_send_noqueue(ssh, pkt);
2432 * Either queue or defer a packet, depending on whether queueing is
2435 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2438 ssh2_pkt_queue(ssh, pkt);
2440 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2444 * Send the whole deferred data block constructed by
2445 * ssh2_pkt_defer() or SSH-1's defer_packet().
2447 * The expected use of the defer mechanism is that you call
2448 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2449 * not currently queueing, this simply sets up deferred_send_data
2450 * and then sends it. If we _are_ currently queueing, the calls to
2451 * ssh2_pkt_defer() put the deferred packets on to the queue
2452 * instead, and therefore ssh_pkt_defersend() has no deferred data
2453 * to send. Hence, there's no need to make it conditional on
2456 static void ssh_pkt_defersend(Ssh ssh)
2459 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2460 ssh->deferred_len = ssh->deferred_size = 0;
2461 sfree(ssh->deferred_send_data);
2462 ssh->deferred_send_data = NULL;
2463 if (backlog > SSH_MAX_BACKLOG)
2464 ssh_throttle_all(ssh, 1, backlog);
2466 ssh->outgoing_data_size += ssh->deferred_data_size;
2467 if (!ssh->kex_in_progress &&
2468 !ssh->bare_connection &&
2469 ssh->max_data_size != 0 &&
2470 ssh->outgoing_data_size > ssh->max_data_size)
2471 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2472 ssh->deferred_data_size = 0;
2476 * Send a packet whose length needs to be disguised (typically
2477 * passwords or keyboard-interactive responses).
2479 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2485 * The simplest way to do this is to adjust the
2486 * variable-length padding field in the outgoing packet.
2488 * Currently compiled out, because some Cisco SSH servers
2489 * don't like excessively padded packets (bah, why's it
2492 pkt->forcepad = padsize;
2493 ssh2_pkt_send(ssh, pkt);
2498 * If we can't do that, however, an alternative approach is
2499 * to use the pkt_defer mechanism to bundle the packet
2500 * tightly together with an SSH_MSG_IGNORE such that their
2501 * combined length is a constant. So first we construct the
2502 * final form of this packet and defer its sending.
2504 ssh2_pkt_defer(ssh, pkt);
2507 * Now construct an SSH_MSG_IGNORE which includes a string
2508 * that's an exact multiple of the cipher block size. (If
2509 * the cipher is NULL so that the block size is
2510 * unavailable, we don't do this trick at all, because we
2511 * gain nothing by it.)
2513 if (ssh->cscipher &&
2514 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2517 stringlen = (256 - ssh->deferred_len);
2518 stringlen += ssh->cscipher->blksize - 1;
2519 stringlen -= (stringlen % ssh->cscipher->blksize);
2522 * Temporarily disable actual compression, so we
2523 * can guarantee to get this string exactly the
2524 * length we want it. The compression-disabling
2525 * routine should return an integer indicating how
2526 * many bytes we should adjust our string length
2530 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2532 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2533 ssh2_pkt_addstring_start(pkt);
2534 for (i = 0; i < stringlen; i++) {
2535 char c = (char) random_byte();
2536 ssh2_pkt_addstring_data(pkt, &c, 1);
2538 ssh2_pkt_defer(ssh, pkt);
2540 ssh_pkt_defersend(ssh);
2545 * Send all queued SSH-2 packets. We send them by means of
2546 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2547 * packets that needed to be lumped together.
2549 static void ssh2_pkt_queuesend(Ssh ssh)
2553 assert(!ssh->queueing);
2555 for (i = 0; i < ssh->queuelen; i++)
2556 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2559 ssh_pkt_defersend(ssh);
2563 void bndebug(char *string, Bignum b)
2567 p = ssh2_mpint_fmt(b, &len);
2568 debug(("%s", string));
2569 for (i = 0; i < len; i++)
2570 debug((" %02x", p[i]));
2576 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2580 p = ssh2_mpint_fmt(b, &len);
2581 hash_string(h, s, p, len);
2586 * Packet decode functions for both SSH-1 and SSH-2.
2588 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2590 unsigned long value;
2591 if (pkt->length - pkt->savedpos < 4)
2592 return 0; /* arrgh, no way to decline (FIXME?) */
2593 value = GET_32BIT(pkt->body + pkt->savedpos);
2597 static int ssh2_pkt_getbool(struct Packet *pkt)
2599 unsigned long value;
2600 if (pkt->length - pkt->savedpos < 1)
2601 return 0; /* arrgh, no way to decline (FIXME?) */
2602 value = pkt->body[pkt->savedpos] != 0;
2606 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2611 if (pkt->length - pkt->savedpos < 4)
2613 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2618 if (pkt->length - pkt->savedpos < *length)
2620 *p = (char *)(pkt->body + pkt->savedpos);
2621 pkt->savedpos += *length;
2623 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2625 if (pkt->length - pkt->savedpos < length)
2627 pkt->savedpos += length;
2628 return pkt->body + (pkt->savedpos - length);
2630 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2631 const unsigned char **keystr)
2635 j = makekey(pkt->body + pkt->savedpos,
2636 pkt->length - pkt->savedpos,
2643 assert(pkt->savedpos < pkt->length);
2647 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2652 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2653 pkt->length - pkt->savedpos, &b);
2661 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2667 ssh_pkt_getstring(pkt, &p, &length);
2672 b = bignum_from_bytes((unsigned char *)p, length);
2677 * Helper function to add an SSH-2 signature blob to a packet.
2678 * Expects to be shown the public key blob as well as the signature
2679 * blob. Normally works just like ssh2_pkt_addstring, but will
2680 * fiddle with the signature packet if necessary for
2681 * BUG_SSH2_RSA_PADDING.
2683 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2684 void *pkblob_v, int pkblob_len,
2685 void *sigblob_v, int sigblob_len)
2687 unsigned char *pkblob = (unsigned char *)pkblob_v;
2688 unsigned char *sigblob = (unsigned char *)sigblob_v;
2690 /* dmemdump(pkblob, pkblob_len); */
2691 /* dmemdump(sigblob, sigblob_len); */
2694 * See if this is in fact an ssh-rsa signature and a buggy
2695 * server; otherwise we can just do this the easy way.
2697 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2698 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2699 int pos, len, siglen;
2702 * Find the byte length of the modulus.
2705 pos = 4+7; /* skip over "ssh-rsa" */
2706 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2707 if (len < 0 || len > pkblob_len - pos - 4)
2709 pos += 4 + len; /* skip over exponent */
2710 if (pkblob_len - pos < 4)
2712 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2713 if (len < 0 || len > pkblob_len - pos - 4)
2715 pos += 4; /* find modulus itself */
2716 while (len > 0 && pkblob[pos] == 0)
2718 /* debug(("modulus length is %d\n", len)); */
2721 * Now find the signature integer.
2723 pos = 4+7; /* skip over "ssh-rsa" */
2724 if (sigblob_len < pos+4)
2726 siglen = toint(GET_32BIT(sigblob+pos));
2727 if (siglen != sigblob_len - pos - 4)
2729 /* debug(("signature length is %d\n", siglen)); */
2731 if (len != siglen) {
2732 unsigned char newlen[4];
2733 ssh2_pkt_addstring_start(pkt);
2734 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2735 /* dmemdump(sigblob, pos); */
2736 pos += 4; /* point to start of actual sig */
2737 PUT_32BIT(newlen, len);
2738 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2739 /* dmemdump(newlen, 4); */
2741 while (len-- > siglen) {
2742 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2743 /* dmemdump(newlen, 1); */
2745 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2746 /* dmemdump(sigblob+pos, siglen); */
2750 /* Otherwise fall through and do it the easy way. We also come
2751 * here as a fallback if we discover above that the key blob
2752 * is misformatted in some way. */
2756 ssh2_pkt_addstring_start(pkt);
2757 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2761 * Examine the remote side's version string and compare it against
2762 * a list of known buggy implementations.
2764 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2766 char *imp; /* pointer to implementation part */
2768 imp += strcspn(imp, "-");
2770 imp += strcspn(imp, "-");
2773 ssh->remote_bugs = 0;
2776 * General notes on server version strings:
2777 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2778 * here -- in particular, we've heard of one that's perfectly happy
2779 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2780 * so we can't distinguish them.
2782 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2783 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2784 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2785 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2786 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2787 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2789 * These versions don't support SSH1_MSG_IGNORE, so we have
2790 * to use a different defence against password length
2793 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2794 logevent("We believe remote version has SSH-1 ignore bug");
2797 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2798 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2799 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2801 * These versions need a plain password sent; they can't
2802 * handle having a null and a random length of data after
2805 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2806 logevent("We believe remote version needs a plain SSH-1 password");
2809 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2810 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2811 (!strcmp(imp, "Cisco-1.25")))) {
2813 * These versions apparently have no clue whatever about
2814 * RSA authentication and will panic and die if they see
2815 * an AUTH_RSA message.
2817 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2818 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2821 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2822 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2823 !wc_match("* VShell", imp) &&
2824 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2825 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2826 wc_match("2.1 *", imp)))) {
2828 * These versions have the HMAC bug.
2830 ssh->remote_bugs |= BUG_SSH2_HMAC;
2831 logevent("We believe remote version has SSH-2 HMAC bug");
2834 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2835 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2836 !wc_match("* VShell", imp) &&
2837 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2839 * These versions have the key-derivation bug (failing to
2840 * include the literal shared secret in the hashes that
2841 * generate the keys).
2843 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2844 logevent("We believe remote version has SSH-2 key-derivation bug");
2847 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2848 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2849 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2850 wc_match("OpenSSH_3.[0-2]*", imp) ||
2851 wc_match("mod_sftp/0.[0-8]*", imp) ||
2852 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2854 * These versions have the SSH-2 RSA padding bug.
2856 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2857 logevent("We believe remote version has SSH-2 RSA padding bug");
2860 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2861 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2862 wc_match("OpenSSH_2.[0-2]*", imp))) {
2864 * These versions have the SSH-2 session-ID bug in
2865 * public-key authentication.
2867 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2868 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2871 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2872 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2873 (wc_match("DigiSSH_2.0", imp) ||
2874 wc_match("OpenSSH_2.[0-4]*", imp) ||
2875 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2876 wc_match("Sun_SSH_1.0", imp) ||
2877 wc_match("Sun_SSH_1.0.1", imp) ||
2878 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2879 wc_match("WeOnlyDo-*", imp)))) {
2881 * These versions have the SSH-2 rekey bug.
2883 ssh->remote_bugs |= BUG_SSH2_REKEY;
2884 logevent("We believe remote version has SSH-2 rekey bug");
2887 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2888 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2889 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2890 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2892 * This version ignores our makpkt and needs to be throttled.
2894 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2895 logevent("We believe remote version ignores SSH-2 maximum packet size");
2898 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2900 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2901 * none detected automatically.
2903 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2904 logevent("We believe remote version has SSH-2 ignore bug");
2907 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2908 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2909 (wc_match("OpenSSH_2.[235]*", imp)))) {
2911 * These versions only support the original (pre-RFC4419)
2912 * SSH-2 GEX request.
2914 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2915 logevent("We believe remote version has outdated SSH-2 GEX");
2918 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2920 * Servers that don't support our winadj request for one
2921 * reason or another. Currently, none detected automatically.
2923 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2924 logevent("We believe remote version has winadj bug");
2927 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
2928 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
2929 (wc_match("OpenSSH_[2-5].*", imp) ||
2930 wc_match("OpenSSH_6.[0-6]*", imp) ||
2931 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
2932 wc_match("dropbear_0.5[01]*", imp)))) {
2934 * These versions have the SSH-2 channel request bug.
2935 * OpenSSH 6.7 and above do not:
2936 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
2937 * dropbear_0.52 and above do not:
2938 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
2940 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
2941 logevent("We believe remote version has SSH-2 channel request bug");
2946 * The `software version' part of an SSH version string is required
2947 * to contain no spaces or minus signs.
2949 static void ssh_fix_verstring(char *str)
2951 /* Eat "<protoversion>-". */
2952 while (*str && *str != '-') str++;
2953 assert(*str == '-'); str++;
2955 /* Convert minus signs and spaces in the remaining string into
2958 if (*str == '-' || *str == ' ')
2965 * Send an appropriate SSH version string.
2967 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
2971 if (ssh->version == 2) {
2973 * Construct a v2 version string.
2975 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
2978 * Construct a v1 version string.
2980 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
2981 verstring = dupprintf("SSH-%s-%s\012",
2982 (ssh_versioncmp(svers, "1.5") <= 0 ?
2987 ssh_fix_verstring(verstring + strlen(protoname));
2989 if (ssh->version == 2) {
2992 * Record our version string.
2994 len = strcspn(verstring, "\015\012");
2995 ssh->v_c = snewn(len + 1, char);
2996 memcpy(ssh->v_c, verstring, len);
3000 logeventf(ssh, "We claim version: %.*s",
3001 strcspn(verstring, "\015\012"), verstring);
3002 s_write(ssh, verstring, strlen(verstring));
3006 static int do_ssh_init(Ssh ssh, unsigned char c)
3008 static const char protoname[] = "SSH-";
3010 struct do_ssh_init_state {
3019 crState(do_ssh_init_state);
3023 /* Search for a line beginning with the protocol name prefix in
3026 for (s->i = 0; protoname[s->i]; s->i++) {
3027 if ((char)c != protoname[s->i]) goto no;
3037 s->vstrsize = sizeof(protoname) + 16;
3038 s->vstring = snewn(s->vstrsize, char);
3039 strcpy(s->vstring, protoname);
3040 s->vslen = strlen(protoname);
3043 if (s->vslen >= s->vstrsize - 1) {
3045 s->vstring = sresize(s->vstring, s->vstrsize, char);
3047 s->vstring[s->vslen++] = c;
3050 s->version[s->i] = '\0';
3052 } else if (s->i < sizeof(s->version) - 1)
3053 s->version[s->i++] = c;
3054 } else if (c == '\012')
3056 crReturn(1); /* get another char */
3059 ssh->agentfwd_enabled = FALSE;
3060 ssh->rdpkt2_state.incoming_sequence = 0;
3062 s->vstring[s->vslen] = 0;
3063 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3064 logeventf(ssh, "Server version: %s", s->vstring);
3065 ssh_detect_bugs(ssh, s->vstring);
3068 * Decide which SSH protocol version to support.
3071 /* Anything strictly below "2.0" means protocol 1 is supported. */
3072 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3073 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3074 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3076 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
3077 bombout(("SSH protocol version 1 required by configuration but "
3078 "not provided by server"));
3081 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
3082 bombout(("SSH protocol version 2 required by configuration but "
3083 "not provided by server"));
3087 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3092 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3094 /* Send the version string, if we haven't already */
3095 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3096 ssh_send_verstring(ssh, protoname, s->version);
3098 if (ssh->version == 2) {
3101 * Record their version string.
3103 len = strcspn(s->vstring, "\015\012");
3104 ssh->v_s = snewn(len + 1, char);
3105 memcpy(ssh->v_s, s->vstring, len);
3109 * Initialise SSH-2 protocol.
3111 ssh->protocol = ssh2_protocol;
3112 ssh2_protocol_setup(ssh);
3113 ssh->s_rdpkt = ssh2_rdpkt;
3116 * Initialise SSH-1 protocol.
3118 ssh->protocol = ssh1_protocol;
3119 ssh1_protocol_setup(ssh);
3120 ssh->s_rdpkt = ssh1_rdpkt;
3122 if (ssh->version == 2)
3123 do_ssh2_transport(ssh, NULL, -1, NULL);
3125 update_specials_menu(ssh->frontend);
3126 ssh->state = SSH_STATE_BEFORE_SIZE;
3127 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3134 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3137 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3138 * the ssh-connection part, extracted and given a trivial binary
3139 * packet protocol, so we replace 'SSH-' at the start with a new
3140 * name. In proper SSH style (though of course this part of the
3141 * proper SSH protocol _isn't_ subject to this kind of
3142 * DNS-domain-based extension), we define the new name in our
3145 static const char protoname[] =
3146 "SSHCONNECTION@putty.projects.tartarus.org-";
3148 struct do_ssh_connection_init_state {
3156 crState(do_ssh_connection_init_state);
3160 /* Search for a line beginning with the protocol name prefix in
3163 for (s->i = 0; protoname[s->i]; s->i++) {
3164 if ((char)c != protoname[s->i]) goto no;
3174 s->vstrsize = sizeof(protoname) + 16;
3175 s->vstring = snewn(s->vstrsize, char);
3176 strcpy(s->vstring, protoname);
3177 s->vslen = strlen(protoname);
3180 if (s->vslen >= s->vstrsize - 1) {
3182 s->vstring = sresize(s->vstring, s->vstrsize, char);
3184 s->vstring[s->vslen++] = c;
3187 s->version[s->i] = '\0';
3189 } else if (s->i < sizeof(s->version) - 1)
3190 s->version[s->i++] = c;
3191 } else if (c == '\012')
3193 crReturn(1); /* get another char */
3196 ssh->agentfwd_enabled = FALSE;
3197 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3199 s->vstring[s->vslen] = 0;
3200 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3201 logeventf(ssh, "Server version: %s", s->vstring);
3202 ssh_detect_bugs(ssh, s->vstring);
3205 * Decide which SSH protocol version to support. This is easy in
3206 * bare ssh-connection mode: only 2.0 is legal.
3208 if (ssh_versioncmp(s->version, "2.0") < 0) {
3209 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3212 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3213 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3219 logeventf(ssh, "Using bare ssh-connection protocol");
3221 /* Send the version string, if we haven't already */
3222 ssh_send_verstring(ssh, protoname, s->version);
3225 * Initialise bare connection protocol.
3227 ssh->protocol = ssh2_bare_connection_protocol;
3228 ssh2_bare_connection_protocol_setup(ssh);
3229 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3231 update_specials_menu(ssh->frontend);
3232 ssh->state = SSH_STATE_BEFORE_SIZE;
3233 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3236 * Get authconn (really just conn) under way.
3238 do_ssh2_authconn(ssh, NULL, 0, NULL);
3245 static void ssh_process_incoming_data(Ssh ssh,
3246 unsigned char **data, int *datalen)
3248 struct Packet *pktin;
3250 pktin = ssh->s_rdpkt(ssh, data, datalen);
3252 ssh->protocol(ssh, NULL, 0, pktin);
3253 ssh_free_packet(pktin);
3257 static void ssh_queue_incoming_data(Ssh ssh,
3258 unsigned char **data, int *datalen)
3260 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3265 static void ssh_process_queued_incoming_data(Ssh ssh)
3268 unsigned char *data;
3271 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3272 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3276 while (!ssh->frozen && len > 0)
3277 ssh_process_incoming_data(ssh, &data, &len);
3280 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3284 static void ssh_set_frozen(Ssh ssh, int frozen)
3287 sk_set_frozen(ssh->s, frozen);
3288 ssh->frozen = frozen;
3291 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
3293 /* Log raw data, if we're in that mode. */
3295 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3296 0, NULL, NULL, 0, NULL);
3298 crBegin(ssh->ssh_gotdata_crstate);
3301 * To begin with, feed the characters one by one to the
3302 * protocol initialisation / selection function do_ssh_init().
3303 * When that returns 0, we're done with the initial greeting
3304 * exchange and can move on to packet discipline.
3307 int ret; /* need not be kept across crReturn */
3309 crReturnV; /* more data please */
3310 ret = ssh->do_ssh_init(ssh, *data);
3318 * We emerge from that loop when the initial negotiation is
3319 * over and we have selected an s_rdpkt function. Now pass
3320 * everything to s_rdpkt, and then pass the resulting packets
3321 * to the proper protocol handler.
3325 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3327 ssh_queue_incoming_data(ssh, &data, &datalen);
3328 /* This uses up all data and cannot cause anything interesting
3329 * to happen; indeed, for anything to happen at all, we must
3330 * return, so break out. */
3332 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3333 /* This uses up some or all data, and may freeze the
3335 ssh_process_queued_incoming_data(ssh);
3337 /* This uses up some or all data, and may freeze the
3339 ssh_process_incoming_data(ssh, &data, &datalen);
3341 /* FIXME this is probably EBW. */
3342 if (ssh->state == SSH_STATE_CLOSED)
3345 /* We're out of data. Go and get some more. */
3351 static int ssh_do_close(Ssh ssh, int notify_exit)
3354 struct ssh_channel *c;
3356 ssh->state = SSH_STATE_CLOSED;
3357 expire_timer_context(ssh);
3362 notify_remote_exit(ssh->frontend);
3367 * Now we must shut down any port- and X-forwarded channels going
3368 * through this connection.
3370 if (ssh->channels) {
3371 while (NULL != (c = index234(ssh->channels, 0))) {
3374 x11_close(c->u.x11.xconn);
3377 case CHAN_SOCKDATA_DORMANT:
3378 pfd_close(c->u.pfd.pf);
3381 del234(ssh->channels, c); /* moving next one to index 0 */
3382 if (ssh->version == 2)
3383 bufchain_clear(&c->v.v2.outbuffer);
3388 * Go through port-forwardings, and close any associated
3389 * listening sockets.
3391 if (ssh->portfwds) {
3392 struct ssh_portfwd *pf;
3393 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3394 /* Dispose of any listening socket. */
3396 pfl_terminate(pf->local);
3397 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3400 freetree234(ssh->portfwds);
3401 ssh->portfwds = NULL;
3405 * Also stop attempting to connection-share.
3407 if (ssh->connshare) {
3408 sharestate_free(ssh->connshare);
3409 ssh->connshare = NULL;
3415 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3416 const char *error_msg, int error_code)
3418 Ssh ssh = (Ssh) plug;
3419 char addrbuf[256], *msg;
3421 if (ssh->attempting_connshare) {
3423 * While we're attempting connection sharing, don't loudly log
3424 * everything that happens. Real TCP connections need to be
3425 * logged when we _start_ trying to connect, because it might
3426 * be ages before they respond if something goes wrong; but
3427 * connection sharing is local and quick to respond, and it's
3428 * sufficient to simply wait and see whether it worked
3432 sk_getaddr(addr, addrbuf, lenof(addrbuf));
3435 if (sk_addr_needs_port(addr)) {
3436 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
3438 msg = dupprintf("Connecting to %s", addrbuf);
3441 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
3449 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3450 const char *ds_err, const char *us_err)
3452 if (event == SHARE_NONE) {
3453 /* In this case, 'logtext' is an error message indicating a
3454 * reason why connection sharing couldn't be set up _at all_.
3455 * Failing that, ds_err and us_err indicate why we couldn't be
3456 * a downstream and an upstream respectively. */
3458 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3461 logeventf(ssh, "Could not set up connection sharing"
3462 " as downstream: %s", ds_err);
3464 logeventf(ssh, "Could not set up connection sharing"
3465 " as upstream: %s", us_err);
3467 } else if (event == SHARE_DOWNSTREAM) {
3468 /* In this case, 'logtext' is a local endpoint address */
3469 logeventf(ssh, "Using existing shared connection at %s", logtext);
3470 /* Also we should mention this in the console window to avoid
3471 * confusing users as to why this window doesn't behave the
3473 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3474 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3476 } else if (event == SHARE_UPSTREAM) {
3477 /* In this case, 'logtext' is a local endpoint address too */
3478 logeventf(ssh, "Sharing this connection at %s", logtext);
3482 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3485 Ssh ssh = (Ssh) plug;
3486 int need_notify = ssh_do_close(ssh, FALSE);
3489 if (!ssh->close_expected)
3490 error_msg = "Server unexpectedly closed network connection";
3492 error_msg = "Server closed network connection";
3495 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3499 notify_remote_exit(ssh->frontend);
3502 logevent(error_msg);
3503 if (!ssh->close_expected || !ssh->clean_exit)
3504 connection_fatal(ssh->frontend, "%s", error_msg);
3508 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3510 Ssh ssh = (Ssh) plug;
3511 ssh_gotdata(ssh, (unsigned char *)data, len);
3512 if (ssh->state == SSH_STATE_CLOSED) {
3513 ssh_do_close(ssh, TRUE);
3519 static void ssh_sent(Plug plug, int bufsize)
3521 Ssh ssh = (Ssh) plug;
3523 * If the send backlog on the SSH socket itself clears, we
3524 * should unthrottle the whole world if it was throttled.
3526 if (bufsize < SSH_MAX_BACKLOG)
3527 ssh_throttle_all(ssh, 0, bufsize);
3531 * Connect to specified host and port.
3532 * Returns an error message, or NULL on success.
3533 * Also places the canonical host name into `realhost'. It must be
3534 * freed by the caller.
3536 static const char *connect_to_host(Ssh ssh, char *host, int port,
3537 char **realhost, int nodelay, int keepalive)
3539 static const struct plug_function_table fn_table = {
3550 int addressfamily, sshprot;
3552 loghost = conf_get_str(ssh->conf, CONF_loghost);
3557 tmphost = dupstr(loghost);
3558 ssh->savedport = 22; /* default ssh port */
3561 * A colon suffix on the hostname string also lets us affect
3562 * savedport. (Unless there are multiple colons, in which case
3563 * we assume this is an unbracketed IPv6 literal.)
3565 colon = host_strrchr(tmphost, ':');
3566 if (colon && colon == host_strchr(tmphost, ':')) {
3569 ssh->savedport = atoi(colon);
3572 ssh->savedhost = host_strduptrim(tmphost);
3575 ssh->savedhost = host_strduptrim(host);
3577 port = 22; /* default ssh port */
3578 ssh->savedport = port;
3581 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3584 * Try connection-sharing, in case that means we don't open a
3585 * socket after all. ssh_connection_sharing_init will connect to a
3586 * previously established upstream if it can, and failing that,
3587 * establish a listening socket for _us_ to be the upstream. In
3588 * the latter case it will return NULL just as if it had done
3589 * nothing, because here we only need to care if we're a
3590 * downstream and need to do our connection setup differently.
3592 ssh->connshare = NULL;
3593 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3594 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3595 ssh->conf, ssh, &ssh->connshare);
3596 ssh->attempting_connshare = FALSE;
3597 if (ssh->s != NULL) {
3599 * We are a downstream.
3601 ssh->bare_connection = TRUE;
3602 ssh->do_ssh_init = do_ssh_connection_init;
3603 ssh->fullhostname = NULL;
3604 *realhost = dupstr(host); /* best we can do */
3607 * We're not a downstream, so open a normal socket.
3609 ssh->do_ssh_init = do_ssh_init;
3614 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3615 logeventf(ssh, "Looking up host \"%s\"%s", host,
3616 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3617 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3618 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3619 if ((err = sk_addr_error(addr)) != NULL) {
3623 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3625 ssh->s = new_connection(addr, *realhost, port,
3626 0, 1, nodelay, keepalive,
3627 (Plug) ssh, ssh->conf);
3628 if ((err = sk_socket_error(ssh->s)) != NULL) {
3630 notify_remote_exit(ssh->frontend);
3636 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3637 * send the version string too.
3639 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3642 if (sshprot == 3 && !ssh->bare_connection) {
3644 ssh_send_verstring(ssh, "SSH-", NULL);
3648 * loghost, if configured, overrides realhost.
3652 *realhost = dupstr(loghost);
3659 * Throttle or unthrottle the SSH connection.
3661 static void ssh_throttle_conn(Ssh ssh, int adjust)
3663 int old_count = ssh->conn_throttle_count;
3664 ssh->conn_throttle_count += adjust;
3665 assert(ssh->conn_throttle_count >= 0);
3666 if (ssh->conn_throttle_count && !old_count) {
3667 ssh_set_frozen(ssh, 1);
3668 } else if (!ssh->conn_throttle_count && old_count) {
3669 ssh_set_frozen(ssh, 0);
3674 * Throttle or unthrottle _all_ local data streams (for when sends
3675 * on the SSH connection itself back up).
3677 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3680 struct ssh_channel *c;
3682 if (enable == ssh->throttled_all)
3684 ssh->throttled_all = enable;
3685 ssh->overall_bufsize = bufsize;
3688 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3690 case CHAN_MAINSESSION:
3692 * This is treated separately, outside the switch.
3696 x11_override_throttle(c->u.x11.xconn, enable);
3699 /* Agent channels require no buffer management. */
3702 pfd_override_throttle(c->u.pfd.pf, enable);
3708 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3710 Ssh ssh = (Ssh) sshv;
3712 ssh->agent_response = reply;
3713 ssh->agent_response_len = replylen;
3715 if (ssh->version == 1)
3716 do_ssh1_login(ssh, NULL, -1, NULL);
3718 do_ssh2_authconn(ssh, NULL, -1, NULL);
3721 static void ssh_dialog_callback(void *sshv, int ret)
3723 Ssh ssh = (Ssh) sshv;
3725 ssh->user_response = ret;
3727 if (ssh->version == 1)
3728 do_ssh1_login(ssh, NULL, -1, NULL);
3730 do_ssh2_transport(ssh, NULL, -1, NULL);
3733 * This may have unfrozen the SSH connection, so do a
3736 ssh_process_queued_incoming_data(ssh);
3739 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3741 struct ssh_channel *c = (struct ssh_channel *)cv;
3743 void *sentreply = reply;
3745 c->u.a.outstanding_requests--;
3747 /* Fake SSH_AGENT_FAILURE. */
3748 sentreply = "\0\0\0\1\5";
3751 if (ssh->version == 2) {
3752 ssh2_add_channel_data(c, sentreply, replylen);
3755 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3756 PKT_INT, c->remoteid,
3758 PKT_DATA, sentreply, replylen,
3764 * If we've already seen an incoming EOF but haven't sent an
3765 * outgoing one, this may be the moment to send it.
3767 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3768 sshfwd_write_eof(c);
3772 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3773 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3774 * => log `wire_reason'.
3776 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3777 int code, int clean_exit)
3781 client_reason = wire_reason;
3783 error = dupprintf("Disconnected: %s", client_reason);
3785 error = dupstr("Disconnected");
3787 if (ssh->version == 1) {
3788 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3790 } else if (ssh->version == 2) {
3791 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3792 ssh2_pkt_adduint32(pktout, code);
3793 ssh2_pkt_addstring(pktout, wire_reason);
3794 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3795 ssh2_pkt_send_noqueue(ssh, pktout);
3798 ssh->close_expected = TRUE;
3799 ssh->clean_exit = clean_exit;
3800 ssh_closing((Plug)ssh, error, 0, 0);
3804 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3805 const struct ssh_signkey *ssh2keytype,
3808 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3809 return -1; /* no manual keys configured */
3814 * The fingerprint string we've been given will have things
3815 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3816 * narrow down to just the colon-separated hex block at the
3817 * end of the string.
3819 const char *p = strrchr(fingerprint, ' ');
3820 fingerprint = p ? p+1 : fingerprint;
3821 /* Quick sanity checks, including making sure it's in lowercase */
3822 assert(strlen(fingerprint) == 16*3 - 1);
3823 assert(fingerprint[2] == ':');
3824 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3826 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3828 return 1; /* success */
3833 * Construct the base64-encoded public key blob and see if
3836 unsigned char *binblob;
3838 int binlen, atoms, i;
3839 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3840 atoms = (binlen + 2) / 3;
3841 base64blob = snewn(atoms * 4 + 1, char);
3842 for (i = 0; i < atoms; i++)
3843 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3844 base64blob[atoms * 4] = '\0';
3846 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3849 return 1; /* success */
3858 * Handle the key exchange and user authentication phases.
3860 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3861 struct Packet *pktin)
3864 unsigned char cookie[8], *ptr;
3865 struct MD5Context md5c;
3866 struct do_ssh1_login_state {
3869 unsigned char *rsabuf;
3870 const unsigned char *keystr1, *keystr2;
3871 unsigned long supported_ciphers_mask, supported_auths_mask;
3872 int tried_publickey, tried_agent;
3873 int tis_auth_refused, ccard_auth_refused;
3874 unsigned char session_id[16];
3876 void *publickey_blob;
3877 int publickey_bloblen;
3878 char *publickey_comment;
3879 int publickey_encrypted;
3880 prompts_t *cur_prompt;
3883 unsigned char request[5], *response, *p;
3893 struct RSAKey servkey, hostkey;
3895 crState(do_ssh1_login_state);
3902 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3903 bombout(("Public key packet not received"));
3907 logevent("Received public keys");
3909 ptr = ssh_pkt_getdata(pktin, 8);
3911 bombout(("SSH-1 public key packet stopped before random cookie"));
3914 memcpy(cookie, ptr, 8);
3916 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3917 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3918 bombout(("Failed to read SSH-1 public keys from public key packet"));
3923 * Log the host key fingerprint.
3927 logevent("Host key fingerprint is:");
3928 strcpy(logmsg, " ");
3929 s->hostkey.comment = NULL;
3930 rsa_fingerprint(logmsg + strlen(logmsg),
3931 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3935 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3936 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3937 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3938 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3939 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3941 ssh->v1_local_protoflags =
3942 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3943 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3946 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3947 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3948 MD5Update(&md5c, cookie, 8);
3949 MD5Final(s->session_id, &md5c);
3951 for (i = 0; i < 32; i++)
3952 ssh->session_key[i] = random_byte();
3955 * Verify that the `bits' and `bytes' parameters match.
3957 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3958 s->servkey.bits > s->servkey.bytes * 8) {
3959 bombout(("SSH-1 public keys were badly formatted"));
3963 s->len = (s->hostkey.bytes > s->servkey.bytes ?
3964 s->hostkey.bytes : s->servkey.bytes);
3966 s->rsabuf = snewn(s->len, unsigned char);
3969 * Verify the host key.
3973 * First format the key into a string.
3975 int len = rsastr_len(&s->hostkey);
3976 char fingerprint[100];
3977 char *keystr = snewn(len, char);
3978 rsastr_fmt(keystr, &s->hostkey);
3979 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
3981 /* First check against manually configured host keys. */
3982 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
3983 if (s->dlgret == 0) { /* did not match */
3984 bombout(("Host key did not appear in manually configured list"));
3987 } else if (s->dlgret < 0) { /* none configured; use standard handling */
3988 ssh_set_frozen(ssh, 1);
3989 s->dlgret = verify_ssh_host_key(ssh->frontend,
3990 ssh->savedhost, ssh->savedport,
3991 "rsa", keystr, fingerprint,
3992 ssh_dialog_callback, ssh);
3994 if (s->dlgret < 0) {
3998 bombout(("Unexpected data from server while waiting"
3999 " for user host key response"));
4002 } while (pktin || inlen > 0);
4003 s->dlgret = ssh->user_response;
4005 ssh_set_frozen(ssh, 0);
4007 if (s->dlgret == 0) {
4008 ssh_disconnect(ssh, "User aborted at host key verification",
4017 for (i = 0; i < 32; i++) {
4018 s->rsabuf[i] = ssh->session_key[i];
4020 s->rsabuf[i] ^= s->session_id[i];
4023 if (s->hostkey.bytes > s->servkey.bytes) {
4024 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4026 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4028 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4030 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4033 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4037 logevent("Encrypted session key");
4040 int cipher_chosen = 0, warn = 0;
4041 char *cipher_string = NULL;
4043 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4044 int next_cipher = conf_get_int_int(ssh->conf,
4045 CONF_ssh_cipherlist, i);
4046 if (next_cipher == CIPHER_WARN) {
4047 /* If/when we choose a cipher, warn about it */
4049 } else if (next_cipher == CIPHER_AES) {
4050 /* XXX Probably don't need to mention this. */
4051 logevent("AES not supported in SSH-1, skipping");
4053 switch (next_cipher) {
4054 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4055 cipher_string = "3DES"; break;
4056 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4057 cipher_string = "Blowfish"; break;
4058 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4059 cipher_string = "single-DES"; break;
4061 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4065 if (!cipher_chosen) {
4066 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4067 bombout(("Server violates SSH-1 protocol by not "
4068 "supporting 3DES encryption"));
4070 /* shouldn't happen */
4071 bombout(("No supported ciphers found"));
4075 /* Warn about chosen cipher if necessary. */
4077 ssh_set_frozen(ssh, 1);
4078 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4079 ssh_dialog_callback, ssh);
4080 if (s->dlgret < 0) {
4084 bombout(("Unexpected data from server while waiting"
4085 " for user response"));
4088 } while (pktin || inlen > 0);
4089 s->dlgret = ssh->user_response;
4091 ssh_set_frozen(ssh, 0);
4092 if (s->dlgret == 0) {
4093 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4100 switch (s->cipher_type) {
4101 case SSH_CIPHER_3DES:
4102 logevent("Using 3DES encryption");
4104 case SSH_CIPHER_DES:
4105 logevent("Using single-DES encryption");
4107 case SSH_CIPHER_BLOWFISH:
4108 logevent("Using Blowfish encryption");
4112 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4113 PKT_CHAR, s->cipher_type,
4114 PKT_DATA, cookie, 8,
4115 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4116 PKT_DATA, s->rsabuf, s->len,
4117 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4119 logevent("Trying to enable encryption...");
4123 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4124 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4126 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4127 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4128 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4130 ssh->crcda_ctx = crcda_make_context();
4131 logevent("Installing CRC compensation attack detector");
4133 if (s->servkey.modulus) {
4134 sfree(s->servkey.modulus);
4135 s->servkey.modulus = NULL;
4137 if (s->servkey.exponent) {
4138 sfree(s->servkey.exponent);
4139 s->servkey.exponent = NULL;
4141 if (s->hostkey.modulus) {
4142 sfree(s->hostkey.modulus);
4143 s->hostkey.modulus = NULL;
4145 if (s->hostkey.exponent) {
4146 sfree(s->hostkey.exponent);
4147 s->hostkey.exponent = NULL;
4151 if (pktin->type != SSH1_SMSG_SUCCESS) {
4152 bombout(("Encryption not successfully enabled"));
4156 logevent("Successfully started encryption");
4158 fflush(stdout); /* FIXME eh? */
4160 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4161 int ret; /* need not be kept over crReturn */
4162 s->cur_prompt = new_prompts(ssh->frontend);
4163 s->cur_prompt->to_server = TRUE;
4164 s->cur_prompt->name = dupstr("SSH login name");
4165 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4166 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4169 crWaitUntil(!pktin);
4170 ret = get_userpass_input(s->cur_prompt, in, inlen);
4175 * Failed to get a username. Terminate.
4177 free_prompts(s->cur_prompt);
4178 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4181 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4182 free_prompts(s->cur_prompt);
4185 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4187 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4189 if (flags & FLAG_INTERACTIVE &&
4190 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4191 c_write_str(ssh, userlog);
4192 c_write_str(ssh, "\r\n");
4200 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4201 /* We must not attempt PK auth. Pretend we've already tried it. */
4202 s->tried_publickey = s->tried_agent = 1;
4204 s->tried_publickey = s->tried_agent = 0;
4206 s->tis_auth_refused = s->ccard_auth_refused = 0;
4208 * Load the public half of any configured keyfile for later use.
4210 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4211 if (!filename_is_null(s->keyfile)) {
4213 logeventf(ssh, "Reading private key file \"%.150s\"",
4214 filename_to_str(s->keyfile));
4215 keytype = key_type(s->keyfile);
4216 if (keytype == SSH_KEYTYPE_SSH1) {
4218 if (rsakey_pubblob(s->keyfile,
4219 &s->publickey_blob, &s->publickey_bloblen,
4220 &s->publickey_comment, &error)) {
4221 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
4225 logeventf(ssh, "Unable to load private key (%s)", error);
4226 msgbuf = dupprintf("Unable to load private key file "
4227 "\"%.150s\" (%s)\r\n",
4228 filename_to_str(s->keyfile),
4230 c_write_str(ssh, msgbuf);
4232 s->publickey_blob = NULL;
4236 logeventf(ssh, "Unable to use this key file (%s)",
4237 key_type_to_str(keytype));
4238 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4240 filename_to_str(s->keyfile),
4241 key_type_to_str(keytype));
4242 c_write_str(ssh, msgbuf);
4244 s->publickey_blob = NULL;
4247 s->publickey_blob = NULL;
4249 while (pktin->type == SSH1_SMSG_FAILURE) {
4250 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4252 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4254 * Attempt RSA authentication using Pageant.
4260 logevent("Pageant is running. Requesting keys.");
4262 /* Request the keys held by the agent. */
4263 PUT_32BIT(s->request, 1);
4264 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4265 if (!agent_query(s->request, 5, &r, &s->responselen,
4266 ssh_agent_callback, ssh)) {
4270 bombout(("Unexpected data from server while waiting"
4271 " for agent response"));
4274 } while (pktin || inlen > 0);
4275 r = ssh->agent_response;
4276 s->responselen = ssh->agent_response_len;
4278 s->response = (unsigned char *) r;
4279 if (s->response && s->responselen >= 5 &&
4280 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4281 s->p = s->response + 5;
4282 s->nkeys = toint(GET_32BIT(s->p));
4284 logeventf(ssh, "Pageant reported negative key count %d",
4289 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4290 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4291 unsigned char *pkblob = s->p;
4295 do { /* do while (0) to make breaking easy */
4296 n = ssh1_read_bignum
4297 (s->p, toint(s->responselen-(s->p-s->response)),
4302 n = ssh1_read_bignum
4303 (s->p, toint(s->responselen-(s->p-s->response)),
4308 if (s->responselen - (s->p-s->response) < 4)
4310 s->commentlen = toint(GET_32BIT(s->p));
4312 if (s->commentlen < 0 ||
4313 toint(s->responselen - (s->p-s->response)) <
4316 s->commentp = (char *)s->p;
4317 s->p += s->commentlen;
4321 logevent("Pageant key list packet was truncated");
4325 if (s->publickey_blob) {
4326 if (!memcmp(pkblob, s->publickey_blob,
4327 s->publickey_bloblen)) {
4328 logeventf(ssh, "Pageant key #%d matches "
4329 "configured key file", s->keyi);
4330 s->tried_publickey = 1;
4332 /* Skip non-configured key */
4335 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4336 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4337 PKT_BIGNUM, s->key.modulus, PKT_END);
4339 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4340 logevent("Key refused");
4343 logevent("Received RSA challenge");
4344 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4345 bombout(("Server's RSA challenge was badly formatted"));
4350 char *agentreq, *q, *ret;
4353 len = 1 + 4; /* message type, bit count */
4354 len += ssh1_bignum_length(s->key.exponent);
4355 len += ssh1_bignum_length(s->key.modulus);
4356 len += ssh1_bignum_length(s->challenge);
4357 len += 16; /* session id */
4358 len += 4; /* response format */
4359 agentreq = snewn(4 + len, char);
4360 PUT_32BIT(agentreq, len);
4362 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4363 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4365 q += ssh1_write_bignum(q, s->key.exponent);
4366 q += ssh1_write_bignum(q, s->key.modulus);
4367 q += ssh1_write_bignum(q, s->challenge);
4368 memcpy(q, s->session_id, 16);
4370 PUT_32BIT(q, 1); /* response format */
4371 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4372 ssh_agent_callback, ssh)) {
4377 bombout(("Unexpected data from server"
4378 " while waiting for agent"
4382 } while (pktin || inlen > 0);
4383 vret = ssh->agent_response;
4384 retlen = ssh->agent_response_len;
4389 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4390 logevent("Sending Pageant's response");
4391 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4392 PKT_DATA, ret + 5, 16,
4396 if (pktin->type == SSH1_SMSG_SUCCESS) {
4398 ("Pageant's response accepted");
4399 if (flags & FLAG_VERBOSE) {
4400 c_write_str(ssh, "Authenticated using"
4402 c_write(ssh, s->commentp,
4404 c_write_str(ssh, "\" from agent\r\n");
4409 ("Pageant's response not accepted");
4412 ("Pageant failed to answer challenge");
4416 logevent("No reply received from Pageant");
4419 freebn(s->key.exponent);
4420 freebn(s->key.modulus);
4421 freebn(s->challenge);
4426 if (s->publickey_blob && !s->tried_publickey)
4427 logevent("Configured key file not in Pageant");
4429 logevent("Failed to get reply from Pageant");
4434 if (s->publickey_blob && !s->tried_publickey) {
4436 * Try public key authentication with the specified
4439 int got_passphrase; /* need not be kept over crReturn */
4440 if (flags & FLAG_VERBOSE)
4441 c_write_str(ssh, "Trying public key authentication.\r\n");
4442 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4443 logeventf(ssh, "Trying public key \"%s\"",
4444 filename_to_str(s->keyfile));
4445 s->tried_publickey = 1;
4446 got_passphrase = FALSE;
4447 while (!got_passphrase) {
4449 * Get a passphrase, if necessary.
4451 char *passphrase = NULL; /* only written after crReturn */
4453 if (!s->publickey_encrypted) {
4454 if (flags & FLAG_VERBOSE)
4455 c_write_str(ssh, "No passphrase required.\r\n");
4458 int ret; /* need not be kept over crReturn */
4459 s->cur_prompt = new_prompts(ssh->frontend);
4460 s->cur_prompt->to_server = FALSE;
4461 s->cur_prompt->name = dupstr("SSH key passphrase");
4462 add_prompt(s->cur_prompt,
4463 dupprintf("Passphrase for key \"%.100s\": ",
4464 s->publickey_comment), FALSE);
4465 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4468 crWaitUntil(!pktin);
4469 ret = get_userpass_input(s->cur_prompt, in, inlen);
4473 /* Failed to get a passphrase. Terminate. */
4474 free_prompts(s->cur_prompt);
4475 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4479 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4480 free_prompts(s->cur_prompt);
4483 * Try decrypting key with passphrase.
4485 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4486 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4489 smemclr(passphrase, strlen(passphrase));
4493 /* Correct passphrase. */
4494 got_passphrase = TRUE;
4495 } else if (ret == 0) {
4496 c_write_str(ssh, "Couldn't load private key from ");
4497 c_write_str(ssh, filename_to_str(s->keyfile));
4498 c_write_str(ssh, " (");
4499 c_write_str(ssh, error);
4500 c_write_str(ssh, ").\r\n");
4501 got_passphrase = FALSE;
4502 break; /* go and try something else */
4503 } else if (ret == -1) {
4504 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4505 got_passphrase = FALSE;
4508 assert(0 && "unexpected return from loadrsakey()");
4509 got_passphrase = FALSE; /* placate optimisers */
4513 if (got_passphrase) {
4516 * Send a public key attempt.
4518 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4519 PKT_BIGNUM, s->key.modulus, PKT_END);
4522 if (pktin->type == SSH1_SMSG_FAILURE) {
4523 c_write_str(ssh, "Server refused our public key.\r\n");
4524 continue; /* go and try something else */
4526 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4527 bombout(("Bizarre response to offer of public key"));
4533 unsigned char buffer[32];
4534 Bignum challenge, response;
4536 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4537 bombout(("Server's RSA challenge was badly formatted"));
4540 response = rsadecrypt(challenge, &s->key);
4541 freebn(s->key.private_exponent);/* burn the evidence */
4543 for (i = 0; i < 32; i++) {
4544 buffer[i] = bignum_byte(response, 31 - i);
4548 MD5Update(&md5c, buffer, 32);
4549 MD5Update(&md5c, s->session_id, 16);
4550 MD5Final(buffer, &md5c);
4552 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4553 PKT_DATA, buffer, 16, PKT_END);
4560 if (pktin->type == SSH1_SMSG_FAILURE) {
4561 if (flags & FLAG_VERBOSE)
4562 c_write_str(ssh, "Failed to authenticate with"
4563 " our public key.\r\n");
4564 continue; /* go and try something else */
4565 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4566 bombout(("Bizarre response to RSA authentication response"));
4570 break; /* we're through! */
4576 * Otherwise, try various forms of password-like authentication.
4578 s->cur_prompt = new_prompts(ssh->frontend);
4580 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4581 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4582 !s->tis_auth_refused) {
4583 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4584 logevent("Requested TIS authentication");
4585 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4587 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4588 logevent("TIS authentication declined");
4589 if (flags & FLAG_INTERACTIVE)
4590 c_write_str(ssh, "TIS authentication refused.\r\n");
4591 s->tis_auth_refused = 1;
4596 char *instr_suf, *prompt;
4598 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4600 bombout(("TIS challenge packet was badly formed"));
4603 logevent("Received TIS challenge");
4604 s->cur_prompt->to_server = TRUE;
4605 s->cur_prompt->name = dupstr("SSH TIS authentication");
4606 /* Prompt heuristic comes from OpenSSH */
4607 if (memchr(challenge, '\n', challengelen)) {
4608 instr_suf = dupstr("");
4609 prompt = dupprintf("%.*s", challengelen, challenge);
4611 instr_suf = dupprintf("%.*s", challengelen, challenge);
4612 prompt = dupstr("Response: ");
4614 s->cur_prompt->instruction =
4615 dupprintf("Using TIS authentication.%s%s",
4616 (*instr_suf) ? "\n" : "",
4618 s->cur_prompt->instr_reqd = TRUE;
4619 add_prompt(s->cur_prompt, prompt, FALSE);
4623 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4624 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4625 !s->ccard_auth_refused) {
4626 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4627 logevent("Requested CryptoCard authentication");
4628 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4630 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4631 logevent("CryptoCard authentication declined");
4632 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4633 s->ccard_auth_refused = 1;
4638 char *instr_suf, *prompt;
4640 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4642 bombout(("CryptoCard challenge packet was badly formed"));
4645 logevent("Received CryptoCard challenge");
4646 s->cur_prompt->to_server = TRUE;
4647 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4648 s->cur_prompt->name_reqd = FALSE;
4649 /* Prompt heuristic comes from OpenSSH */
4650 if (memchr(challenge, '\n', challengelen)) {
4651 instr_suf = dupstr("");
4652 prompt = dupprintf("%.*s", challengelen, challenge);
4654 instr_suf = dupprintf("%.*s", challengelen, challenge);
4655 prompt = dupstr("Response: ");
4657 s->cur_prompt->instruction =
4658 dupprintf("Using CryptoCard authentication.%s%s",
4659 (*instr_suf) ? "\n" : "",
4661 s->cur_prompt->instr_reqd = TRUE;
4662 add_prompt(s->cur_prompt, prompt, FALSE);
4666 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4667 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4668 bombout(("No supported authentication methods available"));
4671 s->cur_prompt->to_server = TRUE;
4672 s->cur_prompt->name = dupstr("SSH password");
4673 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4674 ssh->username, ssh->savedhost),
4679 * Show password prompt, having first obtained it via a TIS
4680 * or CryptoCard exchange if we're doing TIS or CryptoCard
4684 int ret; /* need not be kept over crReturn */
4685 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4688 crWaitUntil(!pktin);
4689 ret = get_userpass_input(s->cur_prompt, in, inlen);
4694 * Failed to get a password (for example
4695 * because one was supplied on the command line
4696 * which has already failed to work). Terminate.
4698 free_prompts(s->cur_prompt);
4699 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4704 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4706 * Defence against traffic analysis: we send a
4707 * whole bunch of packets containing strings of
4708 * different lengths. One of these strings is the
4709 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4710 * The others are all random data in
4711 * SSH1_MSG_IGNORE packets. This way a passive
4712 * listener can't tell which is the password, and
4713 * hence can't deduce the password length.
4715 * Anybody with a password length greater than 16
4716 * bytes is going to have enough entropy in their
4717 * password that a listener won't find it _that_
4718 * much help to know how long it is. So what we'll
4721 * - if password length < 16, we send 15 packets
4722 * containing string lengths 1 through 15
4724 * - otherwise, we let N be the nearest multiple
4725 * of 8 below the password length, and send 8
4726 * packets containing string lengths N through
4727 * N+7. This won't obscure the order of
4728 * magnitude of the password length, but it will
4729 * introduce a bit of extra uncertainty.
4731 * A few servers can't deal with SSH1_MSG_IGNORE, at
4732 * least in this context. For these servers, we need
4733 * an alternative defence. We make use of the fact
4734 * that the password is interpreted as a C string:
4735 * so we can append a NUL, then some random data.
4737 * A few servers can deal with neither SSH1_MSG_IGNORE
4738 * here _nor_ a padded password string.
4739 * For these servers we are left with no defences
4740 * against password length sniffing.
4742 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4743 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4745 * The server can deal with SSH1_MSG_IGNORE, so
4746 * we can use the primary defence.
4748 int bottom, top, pwlen, i;
4751 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4753 bottom = 0; /* zero length passwords are OK! :-) */
4756 bottom = pwlen & ~7;
4760 assert(pwlen >= bottom && pwlen <= top);
4762 randomstr = snewn(top + 1, char);
4764 for (i = bottom; i <= top; i++) {
4766 defer_packet(ssh, s->pwpkt_type,
4767 PKT_STR,s->cur_prompt->prompts[0]->result,
4770 for (j = 0; j < i; j++) {
4772 randomstr[j] = random_byte();
4773 } while (randomstr[j] == '\0');
4775 randomstr[i] = '\0';
4776 defer_packet(ssh, SSH1_MSG_IGNORE,
4777 PKT_STR, randomstr, PKT_END);
4780 logevent("Sending password with camouflage packets");
4781 ssh_pkt_defersend(ssh);
4784 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4786 * The server can't deal with SSH1_MSG_IGNORE
4787 * but can deal with padded passwords, so we
4788 * can use the secondary defence.
4794 len = strlen(s->cur_prompt->prompts[0]->result);
4795 if (len < sizeof(string)) {
4797 strcpy(string, s->cur_prompt->prompts[0]->result);
4798 len++; /* cover the zero byte */
4799 while (len < sizeof(string)) {
4800 string[len++] = (char) random_byte();
4803 ss = s->cur_prompt->prompts[0]->result;
4805 logevent("Sending length-padded password");
4806 send_packet(ssh, s->pwpkt_type,
4807 PKT_INT, len, PKT_DATA, ss, len,
4811 * The server is believed unable to cope with
4812 * any of our password camouflage methods.
4815 len = strlen(s->cur_prompt->prompts[0]->result);
4816 logevent("Sending unpadded password");
4817 send_packet(ssh, s->pwpkt_type,
4819 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4823 send_packet(ssh, s->pwpkt_type,
4824 PKT_STR, s->cur_prompt->prompts[0]->result,
4827 logevent("Sent password");
4828 free_prompts(s->cur_prompt);
4830 if (pktin->type == SSH1_SMSG_FAILURE) {
4831 if (flags & FLAG_VERBOSE)
4832 c_write_str(ssh, "Access denied\r\n");
4833 logevent("Authentication refused");
4834 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4835 bombout(("Strange packet received, type %d", pktin->type));
4841 if (s->publickey_blob) {
4842 sfree(s->publickey_blob);
4843 sfree(s->publickey_comment);
4846 logevent("Authentication successful");
4851 static void ssh_channel_try_eof(struct ssh_channel *c)
4854 assert(c->pending_eof); /* precondition for calling us */
4856 return; /* can't close: not even opened yet */
4857 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4858 return; /* can't send EOF: pending outgoing data */
4860 c->pending_eof = FALSE; /* we're about to send it */
4861 if (ssh->version == 1) {
4862 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4864 c->closes |= CLOSES_SENT_EOF;
4866 struct Packet *pktout;
4867 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4868 ssh2_pkt_adduint32(pktout, c->remoteid);
4869 ssh2_pkt_send(ssh, pktout);
4870 c->closes |= CLOSES_SENT_EOF;
4871 ssh2_channel_check_close(c);
4875 Conf *sshfwd_get_conf(struct ssh_channel *c)
4881 void sshfwd_write_eof(struct ssh_channel *c)
4885 if (ssh->state == SSH_STATE_CLOSED)
4888 if (c->closes & CLOSES_SENT_EOF)
4891 c->pending_eof = TRUE;
4892 ssh_channel_try_eof(c);
4895 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4899 if (ssh->state == SSH_STATE_CLOSED)
4904 x11_close(c->u.x11.xconn);
4905 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4909 case CHAN_SOCKDATA_DORMANT:
4910 pfd_close(c->u.pfd.pf);
4911 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4914 c->type = CHAN_ZOMBIE;
4915 c->pending_eof = FALSE; /* this will confuse a zombie channel */
4917 ssh2_channel_check_close(c);
4920 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4924 if (ssh->state == SSH_STATE_CLOSED)
4927 if (ssh->version == 1) {
4928 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4929 PKT_INT, c->remoteid,
4930 PKT_INT, len, PKT_DATA, buf, len,
4933 * In SSH-1 we can return 0 here - implying that forwarded
4934 * connections are never individually throttled - because
4935 * the only circumstance that can cause throttling will be
4936 * the whole SSH connection backing up, in which case
4937 * _everything_ will be throttled as a whole.
4941 ssh2_add_channel_data(c, buf, len);
4942 return ssh2_try_send(c);
4946 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4951 if (ssh->state == SSH_STATE_CLOSED)
4954 if (ssh->version == 1) {
4955 buflimit = SSH1_BUFFER_LIMIT;
4957 buflimit = c->v.v2.locmaxwin;
4958 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4960 if (c->throttling_conn && bufsize <= buflimit) {
4961 c->throttling_conn = 0;
4962 ssh_throttle_conn(ssh, -1);
4966 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4968 struct queued_handler *qh = ssh->qhead;
4972 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4975 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4976 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4979 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4980 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4984 ssh->qhead = qh->next;
4986 if (ssh->qhead->msg1 > 0) {
4987 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4988 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4990 if (ssh->qhead->msg2 > 0) {
4991 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4992 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4995 ssh->qhead = ssh->qtail = NULL;
4998 qh->handler(ssh, pktin, qh->ctx);
5003 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5004 chandler_fn_t handler, void *ctx)
5006 struct queued_handler *qh;
5008 qh = snew(struct queued_handler);
5011 qh->handler = handler;
5015 if (ssh->qtail == NULL) {
5019 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5020 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5023 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5024 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5027 ssh->qtail->next = qh;
5032 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5034 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5036 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5037 SSH2_MSG_REQUEST_SUCCESS)) {
5038 logeventf(ssh, "Remote port forwarding from %s enabled",
5041 logeventf(ssh, "Remote port forwarding from %s refused",
5044 rpf = del234(ssh->rportfwds, pf);
5046 pf->pfrec->remote = NULL;
5051 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5054 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5057 pf->share_ctx = share_ctx;
5058 pf->shost = dupstr(shost);
5060 pf->sportdesc = NULL;
5061 if (!ssh->rportfwds) {
5062 assert(ssh->version == 2);
5063 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5065 if (add234(ssh->rportfwds, pf) != pf) {
5073 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5076 share_got_pkt_from_server(ctx, pktin->type,
5077 pktin->body, pktin->length);
5080 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5082 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5083 ssh_sharing_global_request_response, share_ctx);
5086 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5088 struct ssh_portfwd *epf;
5092 if (!ssh->portfwds) {
5093 ssh->portfwds = newtree234(ssh_portcmp);
5096 * Go through the existing port forwardings and tag them
5097 * with status==DESTROY. Any that we want to keep will be
5098 * re-enabled (status==KEEP) as we go through the
5099 * configuration and find out which bits are the same as
5102 struct ssh_portfwd *epf;
5104 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5105 epf->status = DESTROY;
5108 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5110 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5111 char *kp, *kp2, *vp, *vp2;
5112 char address_family, type;
5113 int sport,dport,sserv,dserv;
5114 char *sports, *dports, *saddr, *host;
5118 address_family = 'A';
5120 if (*kp == 'A' || *kp == '4' || *kp == '6')
5121 address_family = *kp++;
5122 if (*kp == 'L' || *kp == 'R')
5125 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5127 * There's a colon in the middle of the source port
5128 * string, which means that the part before it is
5129 * actually a source address.
5131 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5132 saddr = host_strduptrim(saddr_tmp);
5139 sport = atoi(sports);
5143 sport = net_service_lookup(sports);
5145 logeventf(ssh, "Service lookup failed for source"
5146 " port \"%s\"", sports);
5150 if (type == 'L' && !strcmp(val, "D")) {
5151 /* dynamic forwarding */
5158 /* ordinary forwarding */
5160 vp2 = vp + host_strcspn(vp, ":");
5161 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5165 dport = atoi(dports);
5169 dport = net_service_lookup(dports);
5171 logeventf(ssh, "Service lookup failed for destination"
5172 " port \"%s\"", dports);
5177 if (sport && dport) {
5178 /* Set up a description of the source port. */
5179 struct ssh_portfwd *pfrec, *epfrec;
5181 pfrec = snew(struct ssh_portfwd);
5183 pfrec->saddr = saddr;
5184 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5185 pfrec->sport = sport;
5186 pfrec->daddr = host;
5187 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5188 pfrec->dport = dport;
5189 pfrec->local = NULL;
5190 pfrec->remote = NULL;
5191 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5192 address_family == '6' ? ADDRTYPE_IPV6 :
5195 epfrec = add234(ssh->portfwds, pfrec);
5196 if (epfrec != pfrec) {
5197 if (epfrec->status == DESTROY) {
5199 * We already have a port forwarding up and running
5200 * with precisely these parameters. Hence, no need
5201 * to do anything; simply re-tag the existing one
5204 epfrec->status = KEEP;
5207 * Anything else indicates that there was a duplicate
5208 * in our input, which we'll silently ignore.
5210 free_portfwd(pfrec);
5212 pfrec->status = CREATE;
5221 * Now go through and destroy any port forwardings which were
5224 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5225 if (epf->status == DESTROY) {
5228 message = dupprintf("%s port forwarding from %s%s%d",
5229 epf->type == 'L' ? "local" :
5230 epf->type == 'R' ? "remote" : "dynamic",
5231 epf->saddr ? epf->saddr : "",
5232 epf->saddr ? ":" : "",
5235 if (epf->type != 'D') {
5236 char *msg2 = dupprintf("%s to %s:%d", message,
5237 epf->daddr, epf->dport);
5242 logeventf(ssh, "Cancelling %s", message);
5245 /* epf->remote or epf->local may be NULL if setting up a
5246 * forwarding failed. */
5248 struct ssh_rportfwd *rpf = epf->remote;
5249 struct Packet *pktout;
5252 * Cancel the port forwarding at the server
5255 if (ssh->version == 1) {
5257 * We cannot cancel listening ports on the
5258 * server side in SSH-1! There's no message
5259 * to support it. Instead, we simply remove
5260 * the rportfwd record from the local end
5261 * so that any connections the server tries
5262 * to make on it are rejected.
5265 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5266 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5267 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5269 ssh2_pkt_addstring(pktout, epf->saddr);
5270 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5271 /* XXX: rport_acceptall may not represent
5272 * what was used to open the original connection,
5273 * since it's reconfigurable. */
5274 ssh2_pkt_addstring(pktout, "");
5276 ssh2_pkt_addstring(pktout, "localhost");
5278 ssh2_pkt_adduint32(pktout, epf->sport);
5279 ssh2_pkt_send(ssh, pktout);
5282 del234(ssh->rportfwds, rpf);
5284 } else if (epf->local) {
5285 pfl_terminate(epf->local);
5288 delpos234(ssh->portfwds, i);
5290 i--; /* so we don't skip one in the list */
5294 * And finally, set up any new port forwardings (status==CREATE).
5296 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5297 if (epf->status == CREATE) {
5298 char *sportdesc, *dportdesc;
5299 sportdesc = dupprintf("%s%s%s%s%d%s",
5300 epf->saddr ? epf->saddr : "",
5301 epf->saddr ? ":" : "",
5302 epf->sserv ? epf->sserv : "",
5303 epf->sserv ? "(" : "",
5305 epf->sserv ? ")" : "");
5306 if (epf->type == 'D') {
5309 dportdesc = dupprintf("%s:%s%s%d%s",
5311 epf->dserv ? epf->dserv : "",
5312 epf->dserv ? "(" : "",
5314 epf->dserv ? ")" : "");
5317 if (epf->type == 'L') {
5318 char *err = pfl_listen(epf->daddr, epf->dport,
5319 epf->saddr, epf->sport,
5320 ssh, conf, &epf->local,
5321 epf->addressfamily);
5323 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5324 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5325 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5326 sportdesc, dportdesc,
5327 err ? " failed: " : "", err ? err : "");
5330 } else if (epf->type == 'D') {
5331 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5332 ssh, conf, &epf->local,
5333 epf->addressfamily);
5335 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5336 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5337 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5339 err ? " failed: " : "", err ? err : "");
5344 struct ssh_rportfwd *pf;
5347 * Ensure the remote port forwardings tree exists.
5349 if (!ssh->rportfwds) {
5350 if (ssh->version == 1)
5351 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5353 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5356 pf = snew(struct ssh_rportfwd);
5357 pf->share_ctx = NULL;
5358 pf->dhost = dupstr(epf->daddr);
5359 pf->dport = epf->dport;
5361 pf->shost = dupstr(epf->saddr);
5362 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5363 pf->shost = dupstr("");
5365 pf->shost = dupstr("localhost");
5367 pf->sport = epf->sport;
5368 if (add234(ssh->rportfwds, pf) != pf) {
5369 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5370 epf->daddr, epf->dport);
5373 logeventf(ssh, "Requesting remote port %s"
5374 " forward to %s", sportdesc, dportdesc);
5376 pf->sportdesc = sportdesc;
5381 if (ssh->version == 1) {
5382 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5383 PKT_INT, epf->sport,
5384 PKT_STR, epf->daddr,
5385 PKT_INT, epf->dport,
5387 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5389 ssh_rportfwd_succfail, pf);
5391 struct Packet *pktout;
5392 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5393 ssh2_pkt_addstring(pktout, "tcpip-forward");
5394 ssh2_pkt_addbool(pktout, 1);/* want reply */
5395 ssh2_pkt_addstring(pktout, pf->shost);
5396 ssh2_pkt_adduint32(pktout, pf->sport);
5397 ssh2_pkt_send(ssh, pktout);
5399 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5400 SSH2_MSG_REQUEST_FAILURE,
5401 ssh_rportfwd_succfail, pf);
5410 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5413 int stringlen, bufsize;
5415 ssh_pkt_getstring(pktin, &string, &stringlen);
5416 if (string == NULL) {
5417 bombout(("Incoming terminal data packet was badly formed"));
5421 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5423 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5424 ssh->v1_stdout_throttling = 1;
5425 ssh_throttle_conn(ssh, +1);
5429 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5431 /* Remote side is trying to open a channel to talk to our
5432 * X-Server. Give them back a local channel number. */
5433 struct ssh_channel *c;
5434 int remoteid = ssh_pkt_getuint32(pktin);
5436 logevent("Received X11 connect request");
5437 /* Refuse if X11 forwarding is disabled. */
5438 if (!ssh->X11_fwd_enabled) {
5439 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5440 PKT_INT, remoteid, PKT_END);
5441 logevent("Rejected X11 connect request");
5443 c = snew(struct ssh_channel);
5446 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5447 c->remoteid = remoteid;
5448 c->halfopen = FALSE;
5449 c->localid = alloc_channel_id(ssh);
5451 c->pending_eof = FALSE;
5452 c->throttling_conn = 0;
5453 c->type = CHAN_X11; /* identify channel type */
5454 add234(ssh->channels, c);
5455 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5456 PKT_INT, c->remoteid, PKT_INT,
5457 c->localid, PKT_END);
5458 logevent("Opened X11 forward channel");
5462 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5464 /* Remote side is trying to open a channel to talk to our
5465 * agent. Give them back a local channel number. */
5466 struct ssh_channel *c;
5467 int remoteid = ssh_pkt_getuint32(pktin);
5469 /* Refuse if agent forwarding is disabled. */
5470 if (!ssh->agentfwd_enabled) {
5471 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5472 PKT_INT, remoteid, PKT_END);
5474 c = snew(struct ssh_channel);
5476 c->remoteid = remoteid;
5477 c->halfopen = FALSE;
5478 c->localid = alloc_channel_id(ssh);
5480 c->pending_eof = FALSE;
5481 c->throttling_conn = 0;
5482 c->type = CHAN_AGENT; /* identify channel type */
5483 c->u.a.lensofar = 0;
5484 c->u.a.message = NULL;
5485 c->u.a.outstanding_requests = 0;
5486 add234(ssh->channels, c);
5487 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5488 PKT_INT, c->remoteid, PKT_INT, c->localid,
5493 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5495 /* Remote side is trying to open a channel to talk to a
5496 * forwarded port. Give them back a local channel number. */
5497 struct ssh_rportfwd pf, *pfp;
5503 remoteid = ssh_pkt_getuint32(pktin);
5504 ssh_pkt_getstring(pktin, &host, &hostsize);
5505 port = ssh_pkt_getuint32(pktin);
5507 pf.dhost = dupprintf("%.*s", hostsize, host);
5509 pfp = find234(ssh->rportfwds, &pf, NULL);
5512 logeventf(ssh, "Rejected remote port open request for %s:%d",
5514 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5515 PKT_INT, remoteid, PKT_END);
5517 struct ssh_channel *c = snew(struct ssh_channel);
5520 logeventf(ssh, "Received remote port open request for %s:%d",
5522 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5523 c, ssh->conf, pfp->pfrec->addressfamily);
5525 logeventf(ssh, "Port open failed: %s", err);
5528 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5529 PKT_INT, remoteid, PKT_END);
5531 c->remoteid = remoteid;
5532 c->halfopen = FALSE;
5533 c->localid = alloc_channel_id(ssh);
5535 c->pending_eof = FALSE;
5536 c->throttling_conn = 0;
5537 c->type = CHAN_SOCKDATA; /* identify channel type */
5538 add234(ssh->channels, c);
5539 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5540 PKT_INT, c->remoteid, PKT_INT,
5541 c->localid, PKT_END);
5542 logevent("Forwarded port opened successfully");
5549 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5551 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5552 unsigned int localid = ssh_pkt_getuint32(pktin);
5553 struct ssh_channel *c;
5555 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5556 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5557 c->remoteid = localid;
5558 c->halfopen = FALSE;
5559 c->type = CHAN_SOCKDATA;
5560 c->throttling_conn = 0;
5561 pfd_confirm(c->u.pfd.pf);
5564 if (c && c->pending_eof) {
5566 * We have a pending close on this channel,
5567 * which we decided on before the server acked
5568 * the channel open. So now we know the
5569 * remoteid, we can close it again.
5571 ssh_channel_try_eof(c);
5575 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5577 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5578 struct ssh_channel *c;
5580 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5581 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5582 logevent("Forwarded connection refused by server");
5583 pfd_close(c->u.pfd.pf);
5584 del234(ssh->channels, c);
5589 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5591 /* Remote side closes a channel. */
5592 unsigned i = ssh_pkt_getuint32(pktin);
5593 struct ssh_channel *c;
5594 c = find234(ssh->channels, &i, ssh_channelfind);
5595 if (c && !c->halfopen) {
5597 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5598 !(c->closes & CLOSES_RCVD_EOF)) {
5600 * Received CHANNEL_CLOSE, which we translate into
5603 int send_close = FALSE;
5605 c->closes |= CLOSES_RCVD_EOF;
5610 x11_send_eof(c->u.x11.xconn);
5616 pfd_send_eof(c->u.pfd.pf);
5625 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5626 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5628 c->closes |= CLOSES_SENT_EOF;
5632 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5633 !(c->closes & CLOSES_RCVD_CLOSE)) {
5635 if (!(c->closes & CLOSES_SENT_EOF)) {
5636 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5637 " for which we never sent CHANNEL_CLOSE\n", i));
5640 c->closes |= CLOSES_RCVD_CLOSE;
5643 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5644 !(c->closes & CLOSES_SENT_CLOSE)) {
5645 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5646 PKT_INT, c->remoteid, PKT_END);
5647 c->closes |= CLOSES_SENT_CLOSE;
5650 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5651 ssh_channel_destroy(c);
5653 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5654 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5655 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5660 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5662 /* Data sent down one of our channels. */
5663 int i = ssh_pkt_getuint32(pktin);
5666 struct ssh_channel *c;
5668 ssh_pkt_getstring(pktin, &p, &len);
5670 c = find234(ssh->channels, &i, ssh_channelfind);
5675 bufsize = x11_send(c->u.x11.xconn, p, len);
5678 bufsize = pfd_send(c->u.pfd.pf, p, len);
5681 /* Data for an agent message. Buffer it. */
5683 if (c->u.a.lensofar < 4) {
5684 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5685 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5689 c->u.a.lensofar += l;
5691 if (c->u.a.lensofar == 4) {
5693 4 + GET_32BIT(c->u.a.msglen);
5694 c->u.a.message = snewn(c->u.a.totallen,
5696 memcpy(c->u.a.message, c->u.a.msglen, 4);
5698 if (c->u.a.lensofar >= 4 && len > 0) {
5700 min(c->u.a.totallen - c->u.a.lensofar,
5702 memcpy(c->u.a.message + c->u.a.lensofar, p,
5706 c->u.a.lensofar += l;
5708 if (c->u.a.lensofar == c->u.a.totallen) {
5711 c->u.a.outstanding_requests++;
5712 if (agent_query(c->u.a.message,
5715 ssh_agentf_callback, c))
5716 ssh_agentf_callback(c, reply, replylen);
5717 sfree(c->u.a.message);
5718 c->u.a.lensofar = 0;
5721 bufsize = 0; /* agent channels never back up */
5724 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5725 c->throttling_conn = 1;
5726 ssh_throttle_conn(ssh, +1);
5731 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5733 ssh->exitcode = ssh_pkt_getuint32(pktin);
5734 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5735 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5737 * In case `helpful' firewalls or proxies tack
5738 * extra human-readable text on the end of the
5739 * session which we might mistake for another
5740 * encrypted packet, we close the session once
5741 * we've sent EXIT_CONFIRMATION.
5743 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5746 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5747 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5749 struct Packet *pktout = (struct Packet *)data;
5751 unsigned int arg = 0;
5752 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5753 if (i == lenof(ssh_ttymodes)) return;
5754 switch (ssh_ttymodes[i].type) {
5756 arg = ssh_tty_parse_specchar(val);
5759 arg = ssh_tty_parse_boolean(val);
5762 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5763 ssh2_pkt_addbyte(pktout, arg);
5766 int ssh_agent_forwarding_permitted(Ssh ssh)
5768 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5771 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5772 struct Packet *pktin)
5774 crBegin(ssh->do_ssh1_connection_crstate);
5776 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5777 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5778 ssh1_smsg_stdout_stderr_data;
5780 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5781 ssh1_msg_channel_open_confirmation;
5782 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5783 ssh1_msg_channel_open_failure;
5784 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5785 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5786 ssh1_msg_channel_close;
5787 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5788 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5790 if (ssh_agent_forwarding_permitted(ssh)) {
5791 logevent("Requesting agent forwarding");
5792 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5796 if (pktin->type != SSH1_SMSG_SUCCESS
5797 && pktin->type != SSH1_SMSG_FAILURE) {
5798 bombout(("Protocol confusion"));
5800 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5801 logevent("Agent forwarding refused");
5803 logevent("Agent forwarding enabled");
5804 ssh->agentfwd_enabled = TRUE;
5805 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5809 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5811 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5813 if (!ssh->x11disp) {
5814 /* FIXME: return an error message from x11_setup_display */
5815 logevent("X11 forwarding not enabled: unable to"
5816 " initialise X display");
5818 ssh->x11auth = x11_invent_fake_auth
5819 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5820 ssh->x11auth->disp = ssh->x11disp;
5822 logevent("Requesting X11 forwarding");
5823 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5824 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5825 PKT_STR, ssh->x11auth->protoname,
5826 PKT_STR, ssh->x11auth->datastring,
5827 PKT_INT, ssh->x11disp->screennum,
5830 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5831 PKT_STR, ssh->x11auth->protoname,
5832 PKT_STR, ssh->x11auth->datastring,
5838 if (pktin->type != SSH1_SMSG_SUCCESS
5839 && pktin->type != SSH1_SMSG_FAILURE) {
5840 bombout(("Protocol confusion"));
5842 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5843 logevent("X11 forwarding refused");
5845 logevent("X11 forwarding enabled");
5846 ssh->X11_fwd_enabled = TRUE;
5847 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5852 ssh_setup_portfwd(ssh, ssh->conf);
5853 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5855 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5857 /* Unpick the terminal-speed string. */
5858 /* XXX perhaps we should allow no speeds to be sent. */
5859 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5860 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5861 /* Send the pty request. */
5862 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5863 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5864 ssh_pkt_adduint32(pkt, ssh->term_height);
5865 ssh_pkt_adduint32(pkt, ssh->term_width);
5866 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5867 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5868 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5869 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5870 ssh_pkt_adduint32(pkt, ssh->ispeed);
5871 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5872 ssh_pkt_adduint32(pkt, ssh->ospeed);
5873 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5875 ssh->state = SSH_STATE_INTERMED;
5879 if (pktin->type != SSH1_SMSG_SUCCESS
5880 && pktin->type != SSH1_SMSG_FAILURE) {
5881 bombout(("Protocol confusion"));
5883 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5884 c_write_str(ssh, "Server refused to allocate pty\r\n");
5885 ssh->editing = ssh->echoing = 1;
5887 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5888 ssh->ospeed, ssh->ispeed);
5889 ssh->got_pty = TRUE;
5892 ssh->editing = ssh->echoing = 1;
5895 if (conf_get_int(ssh->conf, CONF_compression)) {
5896 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5900 if (pktin->type != SSH1_SMSG_SUCCESS
5901 && pktin->type != SSH1_SMSG_FAILURE) {
5902 bombout(("Protocol confusion"));
5904 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5905 c_write_str(ssh, "Server refused to compress\r\n");
5907 logevent("Started compression");
5908 ssh->v1_compressing = TRUE;
5909 ssh->cs_comp_ctx = zlib_compress_init();
5910 logevent("Initialised zlib (RFC1950) compression");
5911 ssh->sc_comp_ctx = zlib_decompress_init();
5912 logevent("Initialised zlib (RFC1950) decompression");
5916 * Start the shell or command.
5918 * Special case: if the first-choice command is an SSH-2
5919 * subsystem (hence not usable here) and the second choice
5920 * exists, we fall straight back to that.
5923 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5925 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5926 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5927 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5928 ssh->fallback_cmd = TRUE;
5931 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5933 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5934 logevent("Started session");
5937 ssh->state = SSH_STATE_SESSION;
5938 if (ssh->size_needed)
5939 ssh_size(ssh, ssh->term_width, ssh->term_height);
5940 if (ssh->eof_needed)
5941 ssh_special(ssh, TS_EOF);
5944 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
5946 ssh->channels = newtree234(ssh_channelcmp);
5950 * By this point, most incoming packets are already being
5951 * handled by the dispatch table, and we need only pay
5952 * attention to the unusual ones.
5957 if (pktin->type == SSH1_SMSG_SUCCESS) {
5958 /* may be from EXEC_SHELL on some servers */
5959 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5960 /* may be from EXEC_SHELL on some servers
5961 * if no pty is available or in other odd cases. Ignore */
5963 bombout(("Strange packet received: type %d", pktin->type));
5968 int len = min(inlen, 512);
5969 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5970 PKT_INT, len, PKT_DATA, in, len,
5982 * Handle the top-level SSH-2 protocol.
5984 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5989 ssh_pkt_getstring(pktin, &msg, &msglen);
5990 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5993 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5995 /* log reason code in disconnect message */
5999 ssh_pkt_getstring(pktin, &msg, &msglen);
6000 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
6003 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6005 /* Do nothing, because we're ignoring it! Duhh. */
6008 static void ssh1_protocol_setup(Ssh ssh)
6013 * Most messages are handled by the coroutines.
6015 for (i = 0; i < 256; i++)
6016 ssh->packet_dispatch[i] = NULL;
6019 * These special message types we install handlers for.
6021 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6022 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6023 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6026 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
6027 struct Packet *pktin)
6029 unsigned char *in=(unsigned char*)vin;
6030 if (ssh->state == SSH_STATE_CLOSED)
6033 if (pktin && ssh->packet_dispatch[pktin->type]) {
6034 ssh->packet_dispatch[pktin->type](ssh, pktin);
6038 if (!ssh->protocol_initial_phase_done) {
6039 if (do_ssh1_login(ssh, in, inlen, pktin))
6040 ssh->protocol_initial_phase_done = TRUE;
6045 do_ssh1_connection(ssh, in, inlen, pktin);
6049 * Utility routine for decoding comma-separated strings in KEXINIT.
6051 static int in_commasep_string(char const *needle, char const *haystack,
6055 if (!needle || !haystack) /* protect against null pointers */
6057 needlen = strlen(needle);
6060 * Is it at the start of the string?
6062 if (haylen >= needlen && /* haystack is long enough */
6063 !memcmp(needle, haystack, needlen) && /* initial match */
6064 (haylen == needlen || haystack[needlen] == ',')
6065 /* either , or EOS follows */
6069 * If not, search for the next comma and resume after that.
6070 * If no comma found, terminate.
6072 while (haylen > 0 && *haystack != ',')
6073 haylen--, haystack++;
6076 haylen--, haystack++; /* skip over comma itself */
6081 * Similar routine for checking whether we have the first string in a list.
6083 static int first_in_commasep_string(char const *needle, char const *haystack,
6087 if (!needle || !haystack) /* protect against null pointers */
6089 needlen = strlen(needle);
6091 * Is it at the start of the string?
6093 if (haylen >= needlen && /* haystack is long enough */
6094 !memcmp(needle, haystack, needlen) && /* initial match */
6095 (haylen == needlen || haystack[needlen] == ',')
6096 /* either , or EOS follows */
6103 * Add a value to the comma-separated string at the end of the packet.
6104 * If the value is already in the string, don't bother adding it again.
6106 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6108 if (in_commasep_string(data, (char *)pkt->data + pkt->savedpos,
6109 pkt->length - pkt->savedpos)) return;
6110 if (pkt->length - pkt->savedpos > 0)
6111 ssh_pkt_addstring_str(pkt, ",");
6112 ssh_pkt_addstring_str(pkt, data);
6117 * SSH-2 key creation method.
6118 * (Currently assumes 2 lots of any hash are sufficient to generate
6119 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
6121 #define SSH2_MKKEY_ITERS (2)
6122 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
6123 unsigned char *keyspace)
6125 const struct ssh_hash *h = ssh->kex->hash;
6127 /* First hlen bytes. */
6129 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6130 hash_mpint(h, s, K);
6131 h->bytes(s, H, h->hlen);
6132 h->bytes(s, &chr, 1);
6133 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6134 h->final(s, keyspace);
6135 /* Next hlen bytes. */
6137 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6138 hash_mpint(h, s, K);
6139 h->bytes(s, H, h->hlen);
6140 h->bytes(s, keyspace, h->hlen);
6141 h->final(s, keyspace + h->hlen);
6145 * Handle the SSH-2 transport layer.
6147 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
6148 struct Packet *pktin)
6150 unsigned char *in = (unsigned char *)vin;
6151 struct do_ssh2_transport_state {
6153 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
6154 Bignum p, g, e, f, K;
6157 int kex_init_value, kex_reply_value;
6158 const struct ssh_mac **maclist;
6160 const struct ssh2_cipher *cscipher_tobe;
6161 const struct ssh2_cipher *sccipher_tobe;
6162 const struct ssh_mac *csmac_tobe;
6163 const struct ssh_mac *scmac_tobe;
6164 int csmac_etm_tobe, scmac_etm_tobe;
6165 const struct ssh_compress *cscomp_tobe;
6166 const struct ssh_compress *sccomp_tobe;
6167 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6168 int hostkeylen, siglen, rsakeylen;
6169 void *hkey; /* actual host key */
6170 void *rsakey; /* for RSA kex */
6171 void *eckey; /* for ECDH kex */
6172 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6173 int n_preferred_kex;
6174 const struct ssh_kexes *preferred_kex[KEX_MAX];
6175 int n_preferred_ciphers;
6176 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6177 const struct ssh_compress *preferred_comp;
6178 int userauth_succeeded; /* for delayed compression */
6179 int pending_compression;
6180 int got_session_id, activated_authconn;
6181 struct Packet *pktout;
6186 crState(do_ssh2_transport_state);
6188 assert(!ssh->bare_connection);
6192 s->cscipher_tobe = s->sccipher_tobe = NULL;
6193 s->csmac_tobe = s->scmac_tobe = NULL;
6194 s->cscomp_tobe = s->sccomp_tobe = NULL;
6196 s->got_session_id = s->activated_authconn = FALSE;
6197 s->userauth_succeeded = FALSE;
6198 s->pending_compression = FALSE;
6201 * Be prepared to work around the buggy MAC problem.
6203 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6204 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6206 s->maclist = macs, s->nmacs = lenof(macs);
6209 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6214 * Set up the preferred key exchange. (NULL => warn below here)
6216 s->n_preferred_kex = 0;
6217 for (i = 0; i < KEX_MAX; i++) {
6218 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6220 s->preferred_kex[s->n_preferred_kex++] =
6221 &ssh_diffiehellman_gex;
6224 s->preferred_kex[s->n_preferred_kex++] =
6225 &ssh_diffiehellman_group14;
6228 s->preferred_kex[s->n_preferred_kex++] =
6229 &ssh_diffiehellman_group1;
6232 s->preferred_kex[s->n_preferred_kex++] =
6236 s->preferred_kex[s->n_preferred_kex++] =
6240 /* Flag for later. Don't bother if it's the last in
6242 if (i < KEX_MAX - 1) {
6243 s->preferred_kex[s->n_preferred_kex++] = NULL;
6250 * Set up the preferred ciphers. (NULL => warn below here)
6252 s->n_preferred_ciphers = 0;
6253 for (i = 0; i < CIPHER_MAX; i++) {
6254 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6255 case CIPHER_BLOWFISH:
6256 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6259 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6260 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6264 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6267 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6269 case CIPHER_ARCFOUR:
6270 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6273 /* Flag for later. Don't bother if it's the last in
6275 if (i < CIPHER_MAX - 1) {
6276 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6283 * Set up preferred compression.
6285 if (conf_get_int(ssh->conf, CONF_compression))
6286 s->preferred_comp = &ssh_zlib;
6288 s->preferred_comp = &ssh_comp_none;
6291 * Enable queueing of outgoing auth- or connection-layer
6292 * packets while we are in the middle of a key exchange.
6294 ssh->queueing = TRUE;
6297 * Flag that KEX is in progress.
6299 ssh->kex_in_progress = TRUE;
6302 * Construct and send our key exchange packet.
6304 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6305 for (i = 0; i < 16; i++)
6306 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6307 /* List key exchange algorithms. */
6308 ssh2_pkt_addstring_start(s->pktout);
6309 for (i = 0; i < s->n_preferred_kex; i++) {
6310 const struct ssh_kexes *k = s->preferred_kex[i];
6311 if (!k) continue; /* warning flag */
6312 for (j = 0; j < k->nkexes; j++)
6313 ssh2_pkt_addstring_commasep(s->pktout, k->list[j]->name);
6315 /* List server host key algorithms. */
6316 if (!s->got_session_id) {
6318 * In the first key exchange, we list all the algorithms
6319 * we're prepared to cope with.
6321 ssh2_pkt_addstring_start(s->pktout);
6322 for (i = 0; i < lenof(hostkey_algs); i++)
6323 ssh2_pkt_addstring_commasep(s->pktout, hostkey_algs[i]->name);
6326 * In subsequent key exchanges, we list only the kex
6327 * algorithm that was selected in the first key exchange,
6328 * so that we keep getting the same host key and hence
6329 * don't have to interrupt the user's session to ask for
6333 ssh2_pkt_addstring(s->pktout, ssh->hostkey->name);
6335 /* List encryption algorithms (client->server then server->client). */
6336 for (k = 0; k < 2; k++) {
6337 ssh2_pkt_addstring_start(s->pktout);
6338 for (i = 0; i < s->n_preferred_ciphers; i++) {
6339 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6340 if (!c) continue; /* warning flag */
6341 for (j = 0; j < c->nciphers; j++)
6342 ssh2_pkt_addstring_commasep(s->pktout, c->list[j]->name);
6345 /* List MAC algorithms (client->server then server->client). */
6346 for (j = 0; j < 2; j++) {
6347 ssh2_pkt_addstring_start(s->pktout);
6348 for (i = 0; i < s->nmacs; i++) {
6349 ssh2_pkt_addstring_commasep(s->pktout, s->maclist[i]->name);
6351 for (i = 0; i < s->nmacs; i++) {
6352 /* For each MAC, there may also be an ETM version,
6353 * which we list second. */
6354 if (s->maclist[i]->etm_name)
6355 ssh2_pkt_addstring_commasep(s->pktout, s->maclist[i]->etm_name);
6358 /* List client->server compression algorithms,
6359 * then server->client compression algorithms. (We use the
6360 * same set twice.) */
6361 for (j = 0; j < 2; j++) {
6362 ssh2_pkt_addstring_start(s->pktout);
6363 assert(lenof(compressions) > 1);
6364 /* Prefer non-delayed versions */
6365 ssh2_pkt_addstring_commasep(s->pktout, s->preferred_comp->name);
6366 /* We don't even list delayed versions of algorithms until
6367 * they're allowed to be used, to avoid a race. See the end of
6369 if (s->userauth_succeeded && s->preferred_comp->delayed_name)
6370 ssh2_pkt_addstring_commasep(s->pktout,
6371 s->preferred_comp->delayed_name);
6372 for (i = 0; i < lenof(compressions); i++) {
6373 const struct ssh_compress *c = compressions[i];
6374 ssh2_pkt_addstring_commasep(s->pktout, c->name);
6375 if (s->userauth_succeeded && c->delayed_name)
6376 ssh2_pkt_addstring_commasep(s->pktout, c->delayed_name);
6379 /* List client->server languages. Empty list. */
6380 ssh2_pkt_addstring_start(s->pktout);
6381 /* List server->client languages. Empty list. */
6382 ssh2_pkt_addstring_start(s->pktout);
6383 /* First KEX packet does _not_ follow, because we're not that brave. */
6384 ssh2_pkt_addbool(s->pktout, FALSE);
6386 ssh2_pkt_adduint32(s->pktout, 0);
6389 s->our_kexinitlen = s->pktout->length - 5;
6390 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6391 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6393 ssh2_pkt_send_noqueue(ssh, s->pktout);
6396 crWaitUntilV(pktin);
6399 * Now examine the other side's KEXINIT to see what we're up
6403 char *str, *preferred;
6406 if (pktin->type != SSH2_MSG_KEXINIT) {
6407 bombout(("expected key exchange packet from server"));
6411 ssh->hostkey = NULL;
6412 s->cscipher_tobe = NULL;
6413 s->sccipher_tobe = NULL;
6414 s->csmac_tobe = NULL;
6415 s->scmac_tobe = NULL;
6416 s->cscomp_tobe = NULL;
6417 s->sccomp_tobe = NULL;
6418 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
6420 pktin->savedpos += 16; /* skip garbage cookie */
6421 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
6423 bombout(("KEXINIT packet was incomplete"));
6428 for (i = 0; i < s->n_preferred_kex; i++) {
6429 const struct ssh_kexes *k = s->preferred_kex[i];
6433 for (j = 0; j < k->nkexes; j++) {
6434 if (!preferred) preferred = k->list[j]->name;
6435 if (in_commasep_string(k->list[j]->name, str, len)) {
6436 ssh->kex = k->list[j];
6445 bombout(("Couldn't agree a key exchange algorithm"
6446 " (available: %.*s)", len, str));
6450 * Note that the server's guess is considered wrong if it doesn't match
6451 * the first algorithm in our list, even if it's still the algorithm
6454 s->guessok = first_in_commasep_string(preferred, str, len);
6455 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
6457 bombout(("KEXINIT packet was incomplete"));
6460 for (i = 0; i < lenof(hostkey_algs); i++) {
6461 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
6462 ssh->hostkey = hostkey_algs[i];
6466 if (!ssh->hostkey) {
6467 bombout(("Couldn't agree a host key algorithm"
6468 " (available: %.*s)", len, str));
6472 s->guessok = s->guessok &&
6473 first_in_commasep_string(hostkey_algs[0]->name, str, len);
6474 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
6476 bombout(("KEXINIT packet was incomplete"));
6479 for (i = 0; i < s->n_preferred_ciphers; i++) {
6480 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6482 s->warn_cscipher = TRUE;
6484 for (j = 0; j < c->nciphers; j++) {
6485 if (in_commasep_string(c->list[j]->name, str, len)) {
6486 s->cscipher_tobe = c->list[j];
6491 if (s->cscipher_tobe)
6494 if (!s->cscipher_tobe) {
6495 bombout(("Couldn't agree a client-to-server cipher"
6496 " (available: %.*s)", len, str));
6500 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
6502 bombout(("KEXINIT packet was incomplete"));
6505 for (i = 0; i < s->n_preferred_ciphers; i++) {
6506 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6508 s->warn_sccipher = TRUE;
6510 for (j = 0; j < c->nciphers; j++) {
6511 if (in_commasep_string(c->list[j]->name, str, len)) {
6512 s->sccipher_tobe = c->list[j];
6517 if (s->sccipher_tobe)
6520 if (!s->sccipher_tobe) {
6521 bombout(("Couldn't agree a server-to-client cipher"
6522 " (available: %.*s)", len, str));
6526 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
6528 bombout(("KEXINIT packet was incomplete"));
6531 for (i = 0; i < s->nmacs; i++) {
6532 if (in_commasep_string(s->maclist[i]->name, str, len)) {
6533 s->csmac_tobe = s->maclist[i];
6534 s->csmac_etm_tobe = FALSE;
6538 if (!s->csmac_tobe) {
6539 for (i = 0; i < s->nmacs; i++) {
6540 if (s->maclist[i]->etm_name &&
6541 in_commasep_string(s->maclist[i]->etm_name, str, len)) {
6542 s->csmac_tobe = s->maclist[i];
6543 s->csmac_etm_tobe = TRUE;
6548 if (!s->csmac_tobe) {
6549 bombout(("Couldn't agree a client-to-server MAC"
6550 " (available: %.*s)", len, str));
6553 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
6555 bombout(("KEXINIT packet was incomplete"));
6558 for (i = 0; i < s->nmacs; i++) {
6559 if (in_commasep_string(s->maclist[i]->name, str, len)) {
6560 s->scmac_tobe = s->maclist[i];
6561 s->scmac_etm_tobe = FALSE;
6565 if (!s->scmac_tobe) {
6566 for (i = 0; i < s->nmacs; i++) {
6567 if (s->maclist[i]->etm_name &&
6568 in_commasep_string(s->maclist[i]->etm_name, str, len)) {
6569 s->scmac_tobe = s->maclist[i];
6570 s->scmac_etm_tobe = TRUE;
6575 if (!s->scmac_tobe) {
6576 bombout(("Couldn't agree a server-to-client MAC"
6577 " (available: %.*s)", len, str));
6580 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
6582 bombout(("KEXINIT packet was incomplete"));
6585 for (i = 0; i < lenof(compressions) + 1; i++) {
6586 const struct ssh_compress *c =
6587 i == 0 ? s->preferred_comp : compressions[i - 1];
6588 if (in_commasep_string(c->name, str, len)) {
6591 } else if (in_commasep_string(c->delayed_name, str, len)) {
6592 if (s->userauth_succeeded) {
6596 s->pending_compression = TRUE; /* try this later */
6600 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
6602 bombout(("KEXINIT packet was incomplete"));
6605 for (i = 0; i < lenof(compressions) + 1; i++) {
6606 const struct ssh_compress *c =
6607 i == 0 ? s->preferred_comp : compressions[i - 1];
6608 if (in_commasep_string(c->name, str, len)) {
6611 } else if (in_commasep_string(c->delayed_name, str, len)) {
6612 if (s->userauth_succeeded) {
6616 s->pending_compression = TRUE; /* try this later */
6620 if (s->pending_compression) {
6621 logevent("Server supports delayed compression; "
6622 "will try this later");
6624 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6625 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6626 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6628 ssh->exhash = ssh->kex->hash->init();
6629 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6630 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6631 hash_string(ssh->kex->hash, ssh->exhash,
6632 s->our_kexinit, s->our_kexinitlen);
6633 sfree(s->our_kexinit);
6634 /* Include the type byte in the hash of server's KEXINIT */
6635 hash_string(ssh->kex->hash, ssh->exhash,
6636 pktin->body - 1, pktin->length + 1);
6639 ssh_set_frozen(ssh, 1);
6640 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6642 ssh_dialog_callback, ssh);
6643 if (s->dlgret < 0) {
6647 bombout(("Unexpected data from server while"
6648 " waiting for user response"));
6651 } while (pktin || inlen > 0);
6652 s->dlgret = ssh->user_response;
6654 ssh_set_frozen(ssh, 0);
6655 if (s->dlgret == 0) {
6656 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6662 if (s->warn_cscipher) {
6663 ssh_set_frozen(ssh, 1);
6664 s->dlgret = askalg(ssh->frontend,
6665 "client-to-server cipher",
6666 s->cscipher_tobe->name,
6667 ssh_dialog_callback, ssh);
6668 if (s->dlgret < 0) {
6672 bombout(("Unexpected data from server while"
6673 " waiting for user response"));
6676 } while (pktin || inlen > 0);
6677 s->dlgret = ssh->user_response;
6679 ssh_set_frozen(ssh, 0);
6680 if (s->dlgret == 0) {
6681 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6687 if (s->warn_sccipher) {
6688 ssh_set_frozen(ssh, 1);
6689 s->dlgret = askalg(ssh->frontend,
6690 "server-to-client cipher",
6691 s->sccipher_tobe->name,
6692 ssh_dialog_callback, ssh);
6693 if (s->dlgret < 0) {
6697 bombout(("Unexpected data from server while"
6698 " waiting for user response"));
6701 } while (pktin || inlen > 0);
6702 s->dlgret = ssh->user_response;
6704 ssh_set_frozen(ssh, 0);
6705 if (s->dlgret == 0) {
6706 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6712 if (s->ignorepkt) /* first_kex_packet_follows */
6713 crWaitUntilV(pktin); /* Ignore packet */
6716 if (ssh->kex->main_type == KEXTYPE_DH) {
6718 * Work out the number of bits of key we will need from the
6719 * key exchange. We start with the maximum key length of
6725 csbits = s->cscipher_tobe->keylen;
6726 scbits = s->sccipher_tobe->keylen;
6727 s->nbits = (csbits > scbits ? csbits : scbits);
6729 /* The keys only have hlen-bit entropy, since they're based on
6730 * a hash. So cap the key size at hlen bits. */
6731 if (s->nbits > ssh->kex->hash->hlen * 8)
6732 s->nbits = ssh->kex->hash->hlen * 8;
6735 * If we're doing Diffie-Hellman group exchange, start by
6736 * requesting a group.
6738 if (!ssh->kex->pdata) {
6739 logevent("Doing Diffie-Hellman group exchange");
6740 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6742 * Work out how big a DH group we will need to allow that
6745 s->pbits = 512 << ((s->nbits - 1) / 64);
6746 if (s->pbits < DH_MIN_SIZE)
6747 s->pbits = DH_MIN_SIZE;
6748 if (s->pbits > DH_MAX_SIZE)
6749 s->pbits = DH_MAX_SIZE;
6750 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6751 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6752 ssh2_pkt_adduint32(s->pktout, s->pbits);
6754 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6755 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6756 ssh2_pkt_adduint32(s->pktout, s->pbits);
6757 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6759 ssh2_pkt_send_noqueue(ssh, s->pktout);
6761 crWaitUntilV(pktin);
6762 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6763 bombout(("expected key exchange group packet from server"));
6766 s->p = ssh2_pkt_getmp(pktin);
6767 s->g = ssh2_pkt_getmp(pktin);
6768 if (!s->p || !s->g) {
6769 bombout(("unable to read mp-ints from incoming group packet"));
6772 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6773 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6774 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6776 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6777 ssh->kex_ctx = dh_setup_group(ssh->kex);
6778 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6779 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6780 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6781 ssh->kex->groupname);
6784 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6785 ssh->kex->hash->text_name);
6787 * Now generate and send e for Diffie-Hellman.
6789 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6790 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6791 s->pktout = ssh2_pkt_init(s->kex_init_value);
6792 ssh2_pkt_addmp(s->pktout, s->e);
6793 ssh2_pkt_send_noqueue(ssh, s->pktout);
6795 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6796 crWaitUntilV(pktin);
6797 if (pktin->type != s->kex_reply_value) {
6798 bombout(("expected key exchange reply packet from server"));
6801 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6802 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6803 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6804 s->f = ssh2_pkt_getmp(pktin);
6806 bombout(("unable to parse key exchange reply packet"));
6809 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6812 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
6814 bombout(("key exchange reply failed validation: %s", err));
6818 s->K = dh_find_K(ssh->kex_ctx, s->f);
6820 /* We assume everything from now on will be quick, and it might
6821 * involve user interaction. */
6822 set_busy_status(ssh->frontend, BUSY_NOT);
6824 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6825 if (!ssh->kex->pdata) {
6826 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6827 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
6828 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6829 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6830 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
6831 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6832 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6834 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6835 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6837 dh_cleanup(ssh->kex_ctx);
6839 if (!ssh->kex->pdata) {
6843 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
6845 logeventf(ssh, "Doing ECDH key exchange with hash %s",
6846 ssh->kex->hash->text_name);
6847 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
6849 s->eckey = ssh_ecdhkex_newkey(ssh->kex->name);
6851 bombout(("Unable to generate key for ECDH"));
6857 int publicPointLength;
6858 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6860 ssh_ecdhkex_freekey(s->eckey);
6861 bombout(("Unable to encode public key for ECDH"));
6864 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
6865 ssh2_pkt_addstring_start(s->pktout);
6866 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
6870 ssh2_pkt_send_noqueue(ssh, s->pktout);
6872 crWaitUntilV(pktin);
6873 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
6874 ssh_ecdhkex_freekey(s->eckey);
6875 bombout(("expected ECDH reply packet from server"));
6879 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6880 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6881 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6885 int publicPointLength;
6886 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6888 ssh_ecdhkex_freekey(s->eckey);
6889 bombout(("Unable to encode public key for ECDH hash"));
6892 hash_string(ssh->kex->hash, ssh->exhash,
6893 publicPoint, publicPointLength);
6900 ssh_pkt_getstring(pktin, &keydata, &keylen);
6901 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
6902 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
6904 ssh_ecdhkex_freekey(s->eckey);
6905 bombout(("point received in ECDH was not valid"));
6910 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6912 ssh_ecdhkex_freekey(s->eckey);
6914 logeventf(ssh, "Doing RSA key exchange with hash %s",
6915 ssh->kex->hash->text_name);
6916 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6918 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6921 crWaitUntilV(pktin);
6922 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6923 bombout(("expected RSA public key packet from server"));
6927 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6928 hash_string(ssh->kex->hash, ssh->exhash,
6929 s->hostkeydata, s->hostkeylen);
6930 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6934 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6935 s->rsakeydata = snewn(s->rsakeylen, char);
6936 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6939 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6941 sfree(s->rsakeydata);
6942 bombout(("unable to parse RSA public key from server"));
6946 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6949 * Next, set up a shared secret K, of precisely KLEN -
6950 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6951 * RSA key modulus and HLEN is the bit length of the hash
6955 int klen = ssh_rsakex_klen(s->rsakey);
6956 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6958 unsigned char *kstr1, *kstr2, *outstr;
6959 int kstr1len, kstr2len, outstrlen;
6961 s->K = bn_power_2(nbits - 1);
6963 for (i = 0; i < nbits; i++) {
6965 byte = random_byte();
6967 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6971 * Encode this as an mpint.
6973 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6974 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6975 PUT_32BIT(kstr2, kstr1len);
6976 memcpy(kstr2 + 4, kstr1, kstr1len);
6979 * Encrypt it with the given RSA key.
6981 outstrlen = (klen + 7) / 8;
6982 outstr = snewn(outstrlen, unsigned char);
6983 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6984 outstr, outstrlen, s->rsakey);
6987 * And send it off in a return packet.
6989 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6990 ssh2_pkt_addstring_start(s->pktout);
6991 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6992 ssh2_pkt_send_noqueue(ssh, s->pktout);
6994 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7001 ssh_rsakex_freekey(s->rsakey);
7003 crWaitUntilV(pktin);
7004 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7005 sfree(s->rsakeydata);
7006 bombout(("expected signature packet from server"));
7010 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7012 sfree(s->rsakeydata);
7015 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7016 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7017 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7019 ssh->kex_ctx = NULL;
7022 debug(("Exchange hash is:\n"));
7023 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7027 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7028 (char *)s->exchange_hash,
7029 ssh->kex->hash->hlen)) {
7030 bombout(("Server's host key did not match the signature supplied"));
7034 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7035 if (!s->got_session_id) {
7037 * Authenticate remote host: verify host key. (We've already
7038 * checked the signature of the exchange hash.)
7040 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
7041 logevent("Host key fingerprint is:");
7042 logevent(s->fingerprint);
7043 /* First check against manually configured host keys. */
7044 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7045 ssh->hostkey, s->hkey);
7046 if (s->dlgret == 0) { /* did not match */
7047 bombout(("Host key did not appear in manually configured list"));
7049 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7050 ssh_set_frozen(ssh, 1);
7051 s->dlgret = verify_ssh_host_key(ssh->frontend,
7052 ssh->savedhost, ssh->savedport,
7053 ssh->hostkey->keytype, s->keystr,
7055 ssh_dialog_callback, ssh);
7056 if (s->dlgret < 0) {
7060 bombout(("Unexpected data from server while waiting"
7061 " for user host key response"));
7064 } while (pktin || inlen > 0);
7065 s->dlgret = ssh->user_response;
7067 ssh_set_frozen(ssh, 0);
7068 if (s->dlgret == 0) {
7069 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7074 sfree(s->fingerprint);
7076 * Save this host key, to check against the one presented in
7077 * subsequent rekeys.
7079 ssh->hostkey_str = s->keystr;
7082 * In a rekey, we never present an interactive host key
7083 * verification request to the user. Instead, we simply
7084 * enforce that the key we're seeing this time is identical to
7085 * the one we saw before.
7087 if (strcmp(ssh->hostkey_str, s->keystr)) {
7088 bombout(("Host key was different in repeat key exchange"));
7093 ssh->hostkey->freekey(s->hkey);
7096 * The exchange hash from the very first key exchange is also
7097 * the session id, used in session key construction and
7100 if (!s->got_session_id) {
7101 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7102 memcpy(ssh->v2_session_id, s->exchange_hash,
7103 sizeof(s->exchange_hash));
7104 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7105 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7106 s->got_session_id = TRUE;
7110 * Send SSH2_MSG_NEWKEYS.
7112 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7113 ssh2_pkt_send_noqueue(ssh, s->pktout);
7114 ssh->outgoing_data_size = 0; /* start counting from here */
7117 * We've sent client NEWKEYS, so create and initialise
7118 * client-to-server session keys.
7120 if (ssh->cs_cipher_ctx)
7121 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7122 ssh->cscipher = s->cscipher_tobe;
7123 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7125 if (ssh->cs_mac_ctx)
7126 ssh->csmac->free_context(ssh->cs_mac_ctx);
7127 ssh->csmac = s->csmac_tobe;
7128 ssh->csmac_etm = s->csmac_etm_tobe;
7129 ssh->cs_mac_ctx = ssh->csmac->make_context();
7131 if (ssh->cs_comp_ctx)
7132 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7133 ssh->cscomp = s->cscomp_tobe;
7134 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7137 * Set IVs on client-to-server keys. Here we use the exchange
7138 * hash from the _first_ key exchange.
7141 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
7142 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7143 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
7144 assert((ssh->cscipher->keylen+7) / 8 <=
7145 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7146 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
7147 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
7148 assert(ssh->cscipher->blksize <=
7149 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7150 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
7151 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
7152 assert(ssh->csmac->len <=
7153 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7154 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
7155 smemclr(keyspace, sizeof(keyspace));
7158 logeventf(ssh, "Initialised %.200s client->server encryption",
7159 ssh->cscipher->text_name);
7160 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s",
7161 ssh->csmac->text_name,
7162 ssh->csmac_etm ? " (in ETM mode)" : "");
7163 if (ssh->cscomp->text_name)
7164 logeventf(ssh, "Initialised %s compression",
7165 ssh->cscomp->text_name);
7168 * Now our end of the key exchange is complete, we can send all
7169 * our queued higher-layer packets.
7171 ssh->queueing = FALSE;
7172 ssh2_pkt_queuesend(ssh);
7175 * Expect SSH2_MSG_NEWKEYS from server.
7177 crWaitUntilV(pktin);
7178 if (pktin->type != SSH2_MSG_NEWKEYS) {
7179 bombout(("expected new-keys packet from server"));
7182 ssh->incoming_data_size = 0; /* start counting from here */
7185 * We've seen server NEWKEYS, so create and initialise
7186 * server-to-client session keys.
7188 if (ssh->sc_cipher_ctx)
7189 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7190 ssh->sccipher = s->sccipher_tobe;
7191 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7193 if (ssh->sc_mac_ctx)
7194 ssh->scmac->free_context(ssh->sc_mac_ctx);
7195 ssh->scmac = s->scmac_tobe;
7196 ssh->scmac_etm = s->scmac_etm_tobe;
7197 ssh->sc_mac_ctx = ssh->scmac->make_context();
7199 if (ssh->sc_comp_ctx)
7200 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7201 ssh->sccomp = s->sccomp_tobe;
7202 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7205 * Set IVs on server-to-client keys. Here we use the exchange
7206 * hash from the _first_ key exchange.
7209 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
7210 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7211 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
7212 assert((ssh->sccipher->keylen+7) / 8 <=
7213 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7214 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
7215 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
7216 assert(ssh->sccipher->blksize <=
7217 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7218 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
7219 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
7220 assert(ssh->scmac->len <=
7221 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7222 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
7223 smemclr(keyspace, sizeof(keyspace));
7225 logeventf(ssh, "Initialised %.200s server->client encryption",
7226 ssh->sccipher->text_name);
7227 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s",
7228 ssh->scmac->text_name,
7229 ssh->scmac_etm ? " (in ETM mode)" : "");
7230 if (ssh->sccomp->text_name)
7231 logeventf(ssh, "Initialised %s decompression",
7232 ssh->sccomp->text_name);
7235 * Free shared secret.
7240 * Key exchange is over. Loop straight back round if we have a
7241 * deferred rekey reason.
7243 if (ssh->deferred_rekey_reason) {
7244 logevent(ssh->deferred_rekey_reason);
7246 ssh->deferred_rekey_reason = NULL;
7247 goto begin_key_exchange;
7251 * Otherwise, schedule a timer for our next rekey.
7253 ssh->kex_in_progress = FALSE;
7254 ssh->last_rekey = GETTICKCOUNT();
7255 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7256 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7260 * Now we're encrypting. Begin returning 1 to the protocol main
7261 * function so that other things can run on top of the
7262 * transport. If we ever see a KEXINIT, we must go back to the
7265 * We _also_ go back to the start if we see pktin==NULL and
7266 * inlen negative, because this is a special signal meaning
7267 * `initiate client-driven rekey', and `in' contains a message
7268 * giving the reason for the rekey.
7270 * inlen==-1 means always initiate a rekey;
7271 * inlen==-2 means that userauth has completed successfully and
7272 * we should consider rekeying (for delayed compression).
7274 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7275 (!pktin && inlen < 0))) {
7277 if (!ssh->protocol_initial_phase_done) {
7278 ssh->protocol_initial_phase_done = TRUE;
7280 * Allow authconn to initialise itself.
7282 do_ssh2_authconn(ssh, NULL, 0, NULL);
7287 logevent("Server initiated key re-exchange");
7291 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7292 * delayed compression, if it's available.
7294 * draft-miller-secsh-compression-delayed-00 says that you
7295 * negotiate delayed compression in the first key exchange, and
7296 * both sides start compressing when the server has sent
7297 * USERAUTH_SUCCESS. This has a race condition -- the server
7298 * can't know when the client has seen it, and thus which incoming
7299 * packets it should treat as compressed.
7301 * Instead, we do the initial key exchange without offering the
7302 * delayed methods, but note if the server offers them; when we
7303 * get here, if a delayed method was available that was higher
7304 * on our list than what we got, we initiate a rekey in which we
7305 * _do_ list the delayed methods (and hopefully get it as a
7306 * result). Subsequent rekeys will do the same.
7308 assert(!s->userauth_succeeded); /* should only happen once */
7309 s->userauth_succeeded = TRUE;
7310 if (!s->pending_compression)
7311 /* Can't see any point rekeying. */
7312 goto wait_for_rekey; /* this is utterly horrid */
7313 /* else fall through to rekey... */
7314 s->pending_compression = FALSE;
7317 * Now we've decided to rekey.
7319 * Special case: if the server bug is set that doesn't
7320 * allow rekeying, we give a different log message and
7321 * continue waiting. (If such a server _initiates_ a rekey,
7322 * we process it anyway!)
7324 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7325 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7327 /* Reset the counters, so that at least this message doesn't
7328 * hit the event log _too_ often. */
7329 ssh->outgoing_data_size = 0;
7330 ssh->incoming_data_size = 0;
7331 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7333 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7336 goto wait_for_rekey; /* this is still utterly horrid */
7338 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7341 goto begin_key_exchange;
7347 * Add data to an SSH-2 channel output buffer.
7349 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
7352 bufchain_add(&c->v.v2.outbuffer, buf, len);
7356 * Attempt to send data on an SSH-2 channel.
7358 static int ssh2_try_send(struct ssh_channel *c)
7361 struct Packet *pktout;
7364 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7367 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7368 if ((unsigned)len > c->v.v2.remwindow)
7369 len = c->v.v2.remwindow;
7370 if ((unsigned)len > c->v.v2.remmaxpkt)
7371 len = c->v.v2.remmaxpkt;
7372 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7373 ssh2_pkt_adduint32(pktout, c->remoteid);
7374 ssh2_pkt_addstring_start(pktout);
7375 ssh2_pkt_addstring_data(pktout, data, len);
7376 ssh2_pkt_send(ssh, pktout);
7377 bufchain_consume(&c->v.v2.outbuffer, len);
7378 c->v.v2.remwindow -= len;
7382 * After having sent as much data as we can, return the amount
7385 ret = bufchain_size(&c->v.v2.outbuffer);
7388 * And if there's no data pending but we need to send an EOF, send
7391 if (!ret && c->pending_eof)
7392 ssh_channel_try_eof(c);
7397 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7400 if (c->closes & CLOSES_SENT_EOF)
7401 return; /* don't send on channels we've EOFed */
7402 bufsize = ssh2_try_send(c);
7405 case CHAN_MAINSESSION:
7406 /* stdin need not receive an unthrottle
7407 * notification since it will be polled */
7410 x11_unthrottle(c->u.x11.xconn);
7413 /* agent sockets are request/response and need no
7414 * buffer management */
7417 pfd_unthrottle(c->u.pfd.pf);
7423 static int ssh_is_simple(Ssh ssh)
7426 * We use the 'simple' variant of the SSH protocol if we're asked
7427 * to, except not if we're also doing connection-sharing (either
7428 * tunnelling our packets over an upstream or expecting to be
7429 * tunnelled over ourselves), since then the assumption that we
7430 * have only one channel to worry about is not true after all.
7432 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7433 !ssh->bare_connection && !ssh->connshare);
7437 * Set up most of a new ssh_channel for SSH-2.
7439 static void ssh2_channel_init(struct ssh_channel *c)
7442 c->localid = alloc_channel_id(ssh);
7444 c->pending_eof = FALSE;
7445 c->throttling_conn = FALSE;
7446 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7447 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7448 c->v.v2.chanreq_head = NULL;
7449 c->v.v2.throttle_state = UNTHROTTLED;
7450 bufchain_init(&c->v.v2.outbuffer);
7454 * Construct the common parts of a CHANNEL_OPEN.
7456 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c, char *type)
7458 struct Packet *pktout;
7460 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7461 ssh2_pkt_addstring(pktout, type);
7462 ssh2_pkt_adduint32(pktout, c->localid);
7463 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7464 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7469 * CHANNEL_FAILURE doesn't come with any indication of what message
7470 * caused it, so we have to keep track of the outstanding
7471 * CHANNEL_REQUESTs ourselves.
7473 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7474 cchandler_fn_t handler, void *ctx)
7476 struct outstanding_channel_request *ocr =
7477 snew(struct outstanding_channel_request);
7479 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7480 ocr->handler = handler;
7483 if (!c->v.v2.chanreq_head)
7484 c->v.v2.chanreq_head = ocr;
7486 c->v.v2.chanreq_tail->next = ocr;
7487 c->v.v2.chanreq_tail = ocr;
7491 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7492 * NULL then a reply will be requested and the handler will be called
7493 * when it arrives. The returned packet is ready to have any
7494 * request-specific data added and be sent. Note that if a handler is
7495 * provided, it's essential that the request actually be sent.
7497 * The handler will usually be passed the response packet in pktin. If
7498 * pktin is NULL, this means that no reply will ever be forthcoming
7499 * (e.g. because the entire connection is being destroyed, or because
7500 * the server initiated channel closure before we saw the response)
7501 * and the handler should free any storage it's holding.
7503 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c, char *type,
7504 cchandler_fn_t handler, void *ctx)
7506 struct Packet *pktout;
7508 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7509 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7510 ssh2_pkt_adduint32(pktout, c->remoteid);
7511 ssh2_pkt_addstring(pktout, type);
7512 ssh2_pkt_addbool(pktout, handler != NULL);
7513 if (handler != NULL)
7514 ssh2_queue_chanreq_handler(c, handler, ctx);
7519 * Potentially enlarge the window on an SSH-2 channel.
7521 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7523 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7528 * Never send WINDOW_ADJUST for a channel that the remote side has
7529 * already sent EOF on; there's no point, since it won't be
7530 * sending any more data anyway. Ditto if _we've_ already sent
7533 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7537 * Also, never widen the window for an X11 channel when we're
7538 * still waiting to see its initial auth and may yet hand it off
7541 if (c->type == CHAN_X11 && c->u.x11.initial)
7545 * If the remote end has a habit of ignoring maxpkt, limit the
7546 * window so that it has no choice (assuming it doesn't ignore the
7549 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7550 newwin = OUR_V2_MAXPKT;
7553 * Only send a WINDOW_ADJUST if there's significantly more window
7554 * available than the other end thinks there is. This saves us
7555 * sending a WINDOW_ADJUST for every character in a shell session.
7557 * "Significant" is arbitrarily defined as half the window size.
7559 if (newwin / 2 >= c->v.v2.locwindow) {
7560 struct Packet *pktout;
7564 * In order to keep track of how much window the client
7565 * actually has available, we'd like it to acknowledge each
7566 * WINDOW_ADJUST. We can't do that directly, so we accompany
7567 * it with a CHANNEL_REQUEST that has to be acknowledged.
7569 * This is only necessary if we're opening the window wide.
7570 * If we're not, then throughput is being constrained by
7571 * something other than the maximum window size anyway.
7573 if (newwin == c->v.v2.locmaxwin &&
7574 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7575 up = snew(unsigned);
7576 *up = newwin - c->v.v2.locwindow;
7577 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7578 ssh2_handle_winadj_response, up);
7579 ssh2_pkt_send(ssh, pktout);
7581 if (c->v.v2.throttle_state != UNTHROTTLED)
7582 c->v.v2.throttle_state = UNTHROTTLING;
7584 /* Pretend the WINDOW_ADJUST was acked immediately. */
7585 c->v.v2.remlocwin = newwin;
7586 c->v.v2.throttle_state = THROTTLED;
7588 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7589 ssh2_pkt_adduint32(pktout, c->remoteid);
7590 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7591 ssh2_pkt_send(ssh, pktout);
7592 c->v.v2.locwindow = newwin;
7597 * Find the channel associated with a message. If there's no channel,
7598 * or it's not properly open, make a noise about it and return NULL.
7600 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7602 unsigned localid = ssh_pkt_getuint32(pktin);
7603 struct ssh_channel *c;
7605 c = find234(ssh->channels, &localid, ssh_channelfind);
7607 (c->type != CHAN_SHARING && c->halfopen &&
7608 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7609 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7610 char *buf = dupprintf("Received %s for %s channel %u",
7611 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7613 c ? "half-open" : "nonexistent", localid);
7614 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7621 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7622 struct Packet *pktin, void *ctx)
7624 unsigned *sizep = ctx;
7627 * Winadj responses should always be failures. However, at least
7628 * one server ("boks_sshd") is known to return SUCCESS for channel
7629 * requests it's never heard of, such as "winadj@putty". Raised
7630 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7631 * life, we don't worry about what kind of response we got.
7634 c->v.v2.remlocwin += *sizep;
7637 * winadj messages are only sent when the window is fully open, so
7638 * if we get an ack of one, we know any pending unthrottle is
7641 if (c->v.v2.throttle_state == UNTHROTTLING)
7642 c->v.v2.throttle_state = UNTHROTTLED;
7645 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
7647 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
7648 struct outstanding_channel_request *ocr;
7651 if (c->type == CHAN_SHARING) {
7652 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7653 pktin->body, pktin->length);
7656 ocr = c->v.v2.chanreq_head;
7658 ssh2_msg_unexpected(ssh, pktin);
7661 ocr->handler(c, pktin, ocr->ctx);
7662 c->v.v2.chanreq_head = ocr->next;
7665 * We may now initiate channel-closing procedures, if that
7666 * CHANNEL_REQUEST was the last thing outstanding before we send
7669 ssh2_channel_check_close(c);
7672 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
7674 struct ssh_channel *c;
7675 c = ssh2_channel_msg(ssh, pktin);
7678 if (c->type == CHAN_SHARING) {
7679 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7680 pktin->body, pktin->length);
7683 if (!(c->closes & CLOSES_SENT_EOF)) {
7684 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
7685 ssh2_try_send_and_unthrottle(ssh, c);
7689 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
7693 struct ssh_channel *c;
7694 c = ssh2_channel_msg(ssh, pktin);
7697 if (c->type == CHAN_SHARING) {
7698 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7699 pktin->body, pktin->length);
7702 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
7703 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
7704 return; /* extended but not stderr */
7705 ssh_pkt_getstring(pktin, &data, &length);
7708 c->v.v2.locwindow -= length;
7709 c->v.v2.remlocwin -= length;
7711 case CHAN_MAINSESSION:
7713 from_backend(ssh->frontend, pktin->type ==
7714 SSH2_MSG_CHANNEL_EXTENDED_DATA,
7718 bufsize = x11_send(c->u.x11.xconn, data, length);
7721 bufsize = pfd_send(c->u.pfd.pf, data, length);
7724 while (length > 0) {
7725 if (c->u.a.lensofar < 4) {
7726 unsigned int l = min(4 - c->u.a.lensofar,
7728 memcpy(c->u.a.msglen + c->u.a.lensofar,
7732 c->u.a.lensofar += l;
7734 if (c->u.a.lensofar == 4) {
7736 4 + GET_32BIT(c->u.a.msglen);
7737 c->u.a.message = snewn(c->u.a.totallen,
7739 memcpy(c->u.a.message, c->u.a.msglen, 4);
7741 if (c->u.a.lensofar >= 4 && length > 0) {
7743 min(c->u.a.totallen - c->u.a.lensofar,
7745 memcpy(c->u.a.message + c->u.a.lensofar,
7749 c->u.a.lensofar += l;
7751 if (c->u.a.lensofar == c->u.a.totallen) {
7754 c->u.a.outstanding_requests++;
7755 if (agent_query(c->u.a.message,
7758 ssh_agentf_callback, c))
7759 ssh_agentf_callback(c, reply, replylen);
7760 sfree(c->u.a.message);
7761 c->u.a.message = NULL;
7762 c->u.a.lensofar = 0;
7769 * If it looks like the remote end hit the end of its window,
7770 * and we didn't want it to do that, think about using a
7773 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
7774 c->v.v2.locmaxwin < 0x40000000)
7775 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
7777 * If we are not buffering too much data,
7778 * enlarge the window again at the remote side.
7779 * If we are buffering too much, we may still
7780 * need to adjust the window if the server's
7783 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7784 c->v.v2.locmaxwin - bufsize : 0);
7786 * If we're either buffering way too much data, or if we're
7787 * buffering anything at all and we're in "simple" mode,
7788 * throttle the whole channel.
7790 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
7791 && !c->throttling_conn) {
7792 c->throttling_conn = 1;
7793 ssh_throttle_conn(ssh, +1);
7798 static void ssh_check_termination(Ssh ssh)
7800 if (ssh->version == 2 &&
7801 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7802 count234(ssh->channels) == 0 &&
7803 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
7805 * We used to send SSH_MSG_DISCONNECT here, because I'd
7806 * believed that _every_ conforming SSH-2 connection had to
7807 * end with a disconnect being sent by at least one side;
7808 * apparently I was wrong and it's perfectly OK to
7809 * unceremoniously slam the connection shut when you're done,
7810 * and indeed OpenSSH feels this is more polite than sending a
7811 * DISCONNECT. So now we don't.
7813 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7817 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id)
7819 logeventf(ssh, "Connection sharing downstream #%u connected", id);
7822 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
7824 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
7825 ssh_check_termination(ssh);
7828 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
7833 va_start(ap, logfmt);
7834 buf = dupvprintf(logfmt, ap);
7837 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
7839 logeventf(ssh, "Connection sharing: %s", buf);
7843 static void ssh_channel_destroy(struct ssh_channel *c)
7848 case CHAN_MAINSESSION:
7849 ssh->mainchan = NULL;
7850 update_specials_menu(ssh->frontend);
7853 if (c->u.x11.xconn != NULL)
7854 x11_close(c->u.x11.xconn);
7855 logevent("Forwarded X11 connection terminated");
7858 sfree(c->u.a.message);
7861 if (c->u.pfd.pf != NULL)
7862 pfd_close(c->u.pfd.pf);
7863 logevent("Forwarded port closed");
7867 del234(ssh->channels, c);
7868 if (ssh->version == 2) {
7869 bufchain_clear(&c->v.v2.outbuffer);
7870 assert(c->v.v2.chanreq_head == NULL);
7875 * If that was the last channel left open, we might need to
7878 ssh_check_termination(ssh);
7881 static void ssh2_channel_check_close(struct ssh_channel *c)
7884 struct Packet *pktout;
7888 * If we've sent out our own CHANNEL_OPEN but not yet seen
7889 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
7890 * it's too early to be sending close messages of any kind.
7895 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
7896 c->type == CHAN_ZOMBIE) &&
7897 !c->v.v2.chanreq_head &&
7898 !(c->closes & CLOSES_SENT_CLOSE)) {
7900 * We have both sent and received EOF (or the channel is a
7901 * zombie), and we have no outstanding channel requests, which
7902 * means the channel is in final wind-up. But we haven't sent
7903 * CLOSE, so let's do so now.
7905 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
7906 ssh2_pkt_adduint32(pktout, c->remoteid);
7907 ssh2_pkt_send(ssh, pktout);
7908 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
7911 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
7912 assert(c->v.v2.chanreq_head == NULL);
7914 * We have both sent and received CLOSE, which means we're
7915 * completely done with the channel.
7917 ssh_channel_destroy(c);
7921 static void ssh2_channel_got_eof(struct ssh_channel *c)
7923 if (c->closes & CLOSES_RCVD_EOF)
7924 return; /* already seen EOF */
7925 c->closes |= CLOSES_RCVD_EOF;
7927 if (c->type == CHAN_X11) {
7928 x11_send_eof(c->u.x11.xconn);
7929 } else if (c->type == CHAN_AGENT) {
7930 if (c->u.a.outstanding_requests == 0) {
7931 /* Manufacture an outgoing EOF in response to the incoming one. */
7932 sshfwd_write_eof(c);
7934 } else if (c->type == CHAN_SOCKDATA) {
7935 pfd_send_eof(c->u.pfd.pf);
7936 } else if (c->type == CHAN_MAINSESSION) {
7939 if (!ssh->sent_console_eof &&
7940 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
7942 * Either from_backend_eof told us that the front end
7943 * wants us to close the outgoing side of the connection
7944 * as soon as we see EOF from the far end, or else we've
7945 * unilaterally decided to do that because we've allocated
7946 * a remote pty and hence EOF isn't a particularly
7947 * meaningful concept.
7949 sshfwd_write_eof(c);
7951 ssh->sent_console_eof = TRUE;
7954 ssh2_channel_check_close(c);
7957 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
7959 struct ssh_channel *c;
7961 c = ssh2_channel_msg(ssh, pktin);
7964 if (c->type == CHAN_SHARING) {
7965 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7966 pktin->body, pktin->length);
7969 ssh2_channel_got_eof(c);
7972 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7974 struct ssh_channel *c;
7976 c = ssh2_channel_msg(ssh, pktin);
7979 if (c->type == CHAN_SHARING) {
7980 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7981 pktin->body, pktin->length);
7986 * When we receive CLOSE on a channel, we assume it comes with an
7987 * implied EOF if we haven't seen EOF yet.
7989 ssh2_channel_got_eof(c);
7991 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
7993 * It also means we stop expecting to see replies to any
7994 * outstanding channel requests, so clean those up too.
7995 * (ssh_chanreq_init will enforce by assertion that we don't
7996 * subsequently put anything back on this list.)
7998 while (c->v.v2.chanreq_head) {
7999 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8000 ocr->handler(c, NULL, ocr->ctx);
8001 c->v.v2.chanreq_head = ocr->next;
8007 * And we also send an outgoing EOF, if we haven't already, on the
8008 * assumption that CLOSE is a pretty forceful announcement that
8009 * the remote side is doing away with the entire channel. (If it
8010 * had wanted to send us EOF and continue receiving data from us,
8011 * it would have just sent CHANNEL_EOF.)
8013 if (!(c->closes & CLOSES_SENT_EOF)) {
8015 * Make sure we don't read any more from whatever our local
8016 * data source is for this channel.
8019 case CHAN_MAINSESSION:
8020 ssh->send_ok = 0; /* stop trying to read from stdin */
8023 x11_override_throttle(c->u.x11.xconn, 1);
8026 pfd_override_throttle(c->u.pfd.pf, 1);
8031 * Abandon any buffered data we still wanted to send to this
8032 * channel. Receiving a CHANNEL_CLOSE is an indication that
8033 * the server really wants to get on and _destroy_ this
8034 * channel, and it isn't going to send us any further
8035 * WINDOW_ADJUSTs to permit us to send pending stuff.
8037 bufchain_clear(&c->v.v2.outbuffer);
8040 * Send outgoing EOF.
8042 sshfwd_write_eof(c);
8046 * Now process the actual close.
8048 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8049 c->closes |= CLOSES_RCVD_CLOSE;
8050 ssh2_channel_check_close(c);
8054 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8056 struct ssh_channel *c;
8058 c = ssh2_channel_msg(ssh, pktin);
8061 if (c->type == CHAN_SHARING) {
8062 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8063 pktin->body, pktin->length);
8066 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8067 c->remoteid = ssh_pkt_getuint32(pktin);
8068 c->halfopen = FALSE;
8069 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8070 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8072 if (c->type == CHAN_SOCKDATA_DORMANT) {
8073 c->type = CHAN_SOCKDATA;
8075 pfd_confirm(c->u.pfd.pf);
8076 } else if (c->type == CHAN_ZOMBIE) {
8078 * This case can occur if a local socket error occurred
8079 * between us sending out CHANNEL_OPEN and receiving
8080 * OPEN_CONFIRMATION. In this case, all we can do is
8081 * immediately initiate close proceedings now that we know the
8082 * server's id to put in the close message.
8084 ssh2_channel_check_close(c);
8087 * We never expect to receive OPEN_CONFIRMATION for any
8088 * *other* channel type (since only local-to-remote port
8089 * forwardings cause us to send CHANNEL_OPEN after the main
8090 * channel is live - all other auxiliary channel types are
8091 * initiated from the server end). It's safe to enforce this
8092 * by assertion rather than by ssh_disconnect, because the
8093 * real point is that we never constructed a half-open channel
8094 * structure in the first place with any type other than the
8097 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8101 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8104 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8106 static const char *const reasons[] = {
8107 "<unknown reason code>",
8108 "Administratively prohibited",
8110 "Unknown channel type",
8111 "Resource shortage",
8113 unsigned reason_code;
8114 char *reason_string;
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);
8126 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8128 if (c->type == CHAN_SOCKDATA_DORMANT) {
8129 reason_code = ssh_pkt_getuint32(pktin);
8130 if (reason_code >= lenof(reasons))
8131 reason_code = 0; /* ensure reasons[reason_code] in range */
8132 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8133 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8134 reasons[reason_code], reason_length, reason_string);
8136 pfd_close(c->u.pfd.pf);
8137 } else if (c->type == CHAN_ZOMBIE) {
8139 * This case can occur if a local socket error occurred
8140 * between us sending out CHANNEL_OPEN and receiving
8141 * OPEN_FAILURE. In this case, we need do nothing except allow
8142 * the code below to throw the half-open channel away.
8146 * We never expect to receive OPEN_FAILURE for any *other*
8147 * channel type (since only local-to-remote port forwardings
8148 * cause us to send CHANNEL_OPEN after the main channel is
8149 * live - all other auxiliary channel types are initiated from
8150 * the server end). It's safe to enforce this by assertion
8151 * rather than by ssh_disconnect, because the real point is
8152 * that we never constructed a half-open channel structure in
8153 * the first place with any type other than the above.
8155 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8158 del234(ssh->channels, c);
8162 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8165 int typelen, want_reply;
8166 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8167 struct ssh_channel *c;
8168 struct Packet *pktout;
8170 c = ssh2_channel_msg(ssh, pktin);
8173 if (c->type == CHAN_SHARING) {
8174 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8175 pktin->body, pktin->length);
8178 ssh_pkt_getstring(pktin, &type, &typelen);
8179 want_reply = ssh2_pkt_getbool(pktin);
8181 if (c->closes & CLOSES_SENT_CLOSE) {
8183 * We don't reply to channel requests after we've sent
8184 * CHANNEL_CLOSE for the channel, because our reply might
8185 * cross in the network with the other side's CHANNEL_CLOSE
8186 * and arrive after they have wound the channel up completely.
8192 * Having got the channel number, we now look at
8193 * the request type string to see if it's something
8196 if (c == ssh->mainchan) {
8198 * We recognise "exit-status" and "exit-signal" on
8199 * the primary channel.
8201 if (typelen == 11 &&
8202 !memcmp(type, "exit-status", 11)) {
8204 ssh->exitcode = ssh_pkt_getuint32(pktin);
8205 logeventf(ssh, "Server sent command exit status %d",
8207 reply = SSH2_MSG_CHANNEL_SUCCESS;
8209 } else if (typelen == 11 &&
8210 !memcmp(type, "exit-signal", 11)) {
8212 int is_plausible = TRUE, is_int = FALSE;
8213 char *fmt_sig = "", *fmt_msg = "";
8215 int msglen = 0, core = FALSE;
8216 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8217 * provide an `int' for the signal, despite its
8218 * having been a `string' in the drafts of RFC 4254 since at
8219 * least 2001. (Fixed in session.c 1.147.) Try to
8220 * infer which we can safely parse it as. */
8222 unsigned char *p = pktin->body +
8224 long len = pktin->length - pktin->savedpos;
8225 unsigned long num = GET_32BIT(p); /* what is it? */
8226 /* If it's 0, it hardly matters; assume string */
8230 int maybe_int = FALSE, maybe_str = FALSE;
8231 #define CHECK_HYPOTHESIS(offset, result) \
8234 int q = toint(offset); \
8235 if (q >= 0 && q+4 <= len) { \
8236 q = toint(q + 4 + GET_32BIT(p+q)); \
8237 if (q >= 0 && q+4 <= len && \
8238 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8243 CHECK_HYPOTHESIS(4+1, maybe_int);
8244 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8245 #undef CHECK_HYPOTHESIS
8246 if (maybe_int && !maybe_str)
8248 else if (!maybe_int && maybe_str)
8251 /* Crikey. Either or neither. Panic. */
8252 is_plausible = FALSE;
8255 ssh->exitcode = 128; /* means `unknown signal' */
8258 /* Old non-standard OpenSSH. */
8259 int signum = ssh_pkt_getuint32(pktin);
8260 fmt_sig = dupprintf(" %d", signum);
8261 ssh->exitcode = 128 + signum;
8263 /* As per RFC 4254. */
8266 ssh_pkt_getstring(pktin, &sig, &siglen);
8267 /* Signal name isn't supposed to be blank, but
8268 * let's cope gracefully if it is. */
8270 fmt_sig = dupprintf(" \"%.*s\"",
8275 * Really hideous method of translating the
8276 * signal description back into a locally
8277 * meaningful number.
8282 #define TRANSLATE_SIGNAL(s) \
8283 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8284 ssh->exitcode = 128 + SIG ## s
8286 TRANSLATE_SIGNAL(ABRT);
8289 TRANSLATE_SIGNAL(ALRM);
8292 TRANSLATE_SIGNAL(FPE);
8295 TRANSLATE_SIGNAL(HUP);
8298 TRANSLATE_SIGNAL(ILL);
8301 TRANSLATE_SIGNAL(INT);
8304 TRANSLATE_SIGNAL(KILL);
8307 TRANSLATE_SIGNAL(PIPE);
8310 TRANSLATE_SIGNAL(QUIT);
8313 TRANSLATE_SIGNAL(SEGV);
8316 TRANSLATE_SIGNAL(TERM);
8319 TRANSLATE_SIGNAL(USR1);
8322 TRANSLATE_SIGNAL(USR2);
8324 #undef TRANSLATE_SIGNAL
8326 ssh->exitcode = 128;
8328 core = ssh2_pkt_getbool(pktin);
8329 ssh_pkt_getstring(pktin, &msg, &msglen);
8331 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8333 /* ignore lang tag */
8334 } /* else don't attempt to parse */
8335 logeventf(ssh, "Server exited on signal%s%s%s",
8336 fmt_sig, core ? " (core dumped)" : "",
8338 if (*fmt_sig) sfree(fmt_sig);
8339 if (*fmt_msg) sfree(fmt_msg);
8340 reply = SSH2_MSG_CHANNEL_SUCCESS;
8345 * This is a channel request we don't know
8346 * about, so we now either ignore the request
8347 * or respond with CHANNEL_FAILURE, depending
8350 reply = SSH2_MSG_CHANNEL_FAILURE;
8353 pktout = ssh2_pkt_init(reply);
8354 ssh2_pkt_adduint32(pktout, c->remoteid);
8355 ssh2_pkt_send(ssh, pktout);
8359 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8362 int typelen, want_reply;
8363 struct Packet *pktout;
8365 ssh_pkt_getstring(pktin, &type, &typelen);
8366 want_reply = ssh2_pkt_getbool(pktin);
8369 * We currently don't support any global requests
8370 * at all, so we either ignore the request or
8371 * respond with REQUEST_FAILURE, depending on
8375 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8376 ssh2_pkt_send(ssh, pktout);
8380 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8384 struct X11FakeAuth *auth;
8387 * Make up a new set of fake X11 auth data, and add it to the tree
8388 * of currently valid ones with an indication of the sharing
8389 * context that it's relevant to.
8391 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8392 auth->share_cs = share_cs;
8393 auth->share_chan = share_chan;
8398 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8400 del234(ssh->x11authtree, auth);
8401 x11_free_fake_auth(auth);
8404 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8412 struct ssh_channel *c;
8413 unsigned remid, winsize, pktsize;
8414 unsigned our_winsize_override = 0;
8415 struct Packet *pktout;
8417 ssh_pkt_getstring(pktin, &type, &typelen);
8418 c = snew(struct ssh_channel);
8421 remid = ssh_pkt_getuint32(pktin);
8422 winsize = ssh_pkt_getuint32(pktin);
8423 pktsize = ssh_pkt_getuint32(pktin);
8425 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8428 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8429 addrstr = snewn(peeraddrlen+1, char);
8430 memcpy(addrstr, peeraddr, peeraddrlen);
8431 addrstr[peeraddrlen] = '\0';
8432 peerport = ssh_pkt_getuint32(pktin);
8434 logeventf(ssh, "Received X11 connect request from %s:%d",
8437 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8438 error = "X11 forwarding is not enabled";
8440 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8443 c->u.x11.initial = TRUE;
8446 * If we are a connection-sharing upstream, then we should
8447 * initially present a very small window, adequate to take
8448 * the X11 initial authorisation packet but not much more.
8449 * Downstream will then present us a larger window (by
8450 * fiat of the connection-sharing protocol) and we can
8451 * guarantee to send a positive-valued WINDOW_ADJUST.
8454 our_winsize_override = 128;
8456 logevent("Opened X11 forward channel");
8460 } else if (typelen == 15 &&
8461 !memcmp(type, "forwarded-tcpip", 15)) {
8462 struct ssh_rportfwd pf, *realpf;
8465 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8466 pf.shost = dupprintf("%.*s", shostlen, shost);
8467 pf.sport = ssh_pkt_getuint32(pktin);
8468 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8469 peerport = ssh_pkt_getuint32(pktin);
8470 realpf = find234(ssh->rportfwds, &pf, NULL);
8471 logeventf(ssh, "Received remote port %s:%d open request "
8472 "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
8475 if (realpf == NULL) {
8476 error = "Remote port is not recognised";
8480 if (realpf->share_ctx) {
8482 * This port forwarding is on behalf of a
8483 * connection-sharing downstream, so abandon our own
8484 * channel-open procedure and just pass the message on
8487 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8488 pktin->body, pktin->length);
8493 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8494 c, ssh->conf, realpf->pfrec->addressfamily);
8495 logeventf(ssh, "Attempting to forward remote port to "
8496 "%s:%d", realpf->dhost, realpf->dport);
8498 logeventf(ssh, "Port open failed: %s", err);
8500 error = "Port open failed";
8502 logevent("Forwarded port opened successfully");
8503 c->type = CHAN_SOCKDATA;
8506 } else if (typelen == 22 &&
8507 !memcmp(type, "auth-agent@openssh.com", 22)) {
8508 if (!ssh->agentfwd_enabled)
8509 error = "Agent forwarding is not enabled";
8511 c->type = CHAN_AGENT; /* identify channel type */
8512 c->u.a.lensofar = 0;
8513 c->u.a.message = NULL;
8514 c->u.a.outstanding_requests = 0;
8517 error = "Unsupported channel type requested";
8520 c->remoteid = remid;
8521 c->halfopen = FALSE;
8523 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8524 ssh2_pkt_adduint32(pktout, c->remoteid);
8525 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8526 ssh2_pkt_addstring(pktout, error);
8527 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8528 ssh2_pkt_send(ssh, pktout);
8529 logeventf(ssh, "Rejected channel open: %s", error);
8532 ssh2_channel_init(c);
8533 c->v.v2.remwindow = winsize;
8534 c->v.v2.remmaxpkt = pktsize;
8535 if (our_winsize_override) {
8536 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8537 our_winsize_override;
8539 add234(ssh->channels, c);
8540 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8541 ssh2_pkt_adduint32(pktout, c->remoteid);
8542 ssh2_pkt_adduint32(pktout, c->localid);
8543 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8544 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8545 ssh2_pkt_send(ssh, pktout);
8549 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8550 void *share_cs, void *share_chan,
8551 const char *peer_addr, int peer_port,
8552 int endian, int protomajor, int protominor,
8553 const void *initial_data, int initial_len)
8556 * This function is called when we've just discovered that an X
8557 * forwarding channel on which we'd been handling the initial auth
8558 * ourselves turns out to be destined for a connection-sharing
8559 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8560 * that we completely stop tracking windows and buffering data and
8561 * just pass more or less unmodified SSH messages back and forth.
8563 c->type = CHAN_SHARING;
8564 c->u.sharing.ctx = share_cs;
8565 share_setup_x11_channel(share_cs, share_chan,
8566 c->localid, c->remoteid, c->v.v2.remwindow,
8567 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8568 peer_addr, peer_port, endian,
8569 protomajor, protominor,
8570 initial_data, initial_len);
8573 void sshfwd_x11_is_local(struct ssh_channel *c)
8576 * This function is called when we've just discovered that an X
8577 * forwarding channel is _not_ destined for a connection-sharing
8578 * downstream but we're going to handle it ourselves. We stop
8579 * presenting a cautiously small window and go into ordinary data
8582 c->u.x11.initial = FALSE;
8583 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8587 * Buffer banner messages for later display at some convenient point,
8588 * if we're going to display them.
8590 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8592 /* Arbitrary limit to prevent unbounded inflation of buffer */
8593 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8594 bufchain_size(&ssh->banner) <= 131072) {
8595 char *banner = NULL;
8597 ssh_pkt_getstring(pktin, &banner, &size);
8599 bufchain_add(&ssh->banner, banner, size);
8603 /* Helper function to deal with sending tty modes for "pty-req" */
8604 static void ssh2_send_ttymode(void *data, char *mode, char *val)
8606 struct Packet *pktout = (struct Packet *)data;
8608 unsigned int arg = 0;
8609 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
8610 if (i == lenof(ssh_ttymodes)) return;
8611 switch (ssh_ttymodes[i].type) {
8613 arg = ssh_tty_parse_specchar(val);
8616 arg = ssh_tty_parse_boolean(val);
8619 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
8620 ssh2_pkt_adduint32(pktout, arg);
8623 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8626 struct ssh2_setup_x11_state {
8630 struct Packet *pktout;
8631 crStateP(ssh2_setup_x11_state, ctx);
8635 logevent("Requesting X11 forwarding");
8636 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8638 ssh2_pkt_addbool(pktout, 0); /* many connections */
8639 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8640 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8641 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8642 ssh2_pkt_send(ssh, pktout);
8644 /* Wait to be called back with either a response packet, or NULL
8645 * meaning clean up and free our data */
8649 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8650 logevent("X11 forwarding enabled");
8651 ssh->X11_fwd_enabled = TRUE;
8653 logevent("X11 forwarding refused");
8659 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8662 struct ssh2_setup_agent_state {
8666 struct Packet *pktout;
8667 crStateP(ssh2_setup_agent_state, ctx);
8671 logevent("Requesting OpenSSH-style agent forwarding");
8672 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8673 ssh2_setup_agent, s);
8674 ssh2_pkt_send(ssh, pktout);
8676 /* Wait to be called back with either a response packet, or NULL
8677 * meaning clean up and free our data */
8681 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8682 logevent("Agent forwarding enabled");
8683 ssh->agentfwd_enabled = TRUE;
8685 logevent("Agent forwarding refused");
8691 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8694 struct ssh2_setup_pty_state {
8698 struct Packet *pktout;
8699 crStateP(ssh2_setup_pty_state, ctx);
8703 /* Unpick the terminal-speed string. */
8704 /* XXX perhaps we should allow no speeds to be sent. */
8705 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8706 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8707 /* Build the pty request. */
8708 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
8710 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
8711 ssh2_pkt_adduint32(pktout, ssh->term_width);
8712 ssh2_pkt_adduint32(pktout, ssh->term_height);
8713 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
8714 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
8715 ssh2_pkt_addstring_start(pktout);
8716 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
8717 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
8718 ssh2_pkt_adduint32(pktout, ssh->ispeed);
8719 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
8720 ssh2_pkt_adduint32(pktout, ssh->ospeed);
8721 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
8722 ssh2_pkt_send(ssh, pktout);
8723 ssh->state = SSH_STATE_INTERMED;
8725 /* Wait to be called back with either a response packet, or NULL
8726 * meaning clean up and free our data */
8730 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8731 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8732 ssh->ospeed, ssh->ispeed);
8733 ssh->got_pty = TRUE;
8735 c_write_str(ssh, "Server refused to allocate pty\r\n");
8736 ssh->editing = ssh->echoing = 1;
8743 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
8746 struct ssh2_setup_env_state {
8748 int num_env, env_left, env_ok;
8751 struct Packet *pktout;
8752 crStateP(ssh2_setup_env_state, ctx);
8757 * Send environment variables.
8759 * Simplest thing here is to send all the requests at once, and
8760 * then wait for a whole bunch of successes or failures.
8766 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
8768 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
8769 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
8770 ssh2_pkt_addstring(pktout, key);
8771 ssh2_pkt_addstring(pktout, val);
8772 ssh2_pkt_send(ssh, pktout);
8777 logeventf(ssh, "Sent %d environment variables", s->num_env);
8782 s->env_left = s->num_env;
8784 while (s->env_left > 0) {
8785 /* Wait to be called back with either a response packet,
8786 * or NULL meaning clean up and free our data */
8788 if (!pktin) goto out;
8789 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
8794 if (s->env_ok == s->num_env) {
8795 logevent("All environment variables successfully set");
8796 } else if (s->env_ok == 0) {
8797 logevent("All environment variables refused");
8798 c_write_str(ssh, "Server refused to set environment variables\r\n");
8800 logeventf(ssh, "%d environment variables refused",
8801 s->num_env - s->env_ok);
8802 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8810 * Handle the SSH-2 userauth and connection layers.
8812 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
8814 do_ssh2_authconn(ssh, NULL, 0, pktin);
8817 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
8821 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
8824 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
8825 struct Packet *pktin)
8827 struct do_ssh2_authconn_state {
8831 AUTH_TYPE_PUBLICKEY,
8832 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
8833 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
8835 AUTH_TYPE_GSSAPI, /* always QUIET */
8836 AUTH_TYPE_KEYBOARD_INTERACTIVE,
8837 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
8839 int done_service_req;
8840 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
8841 int tried_pubkey_config, done_agent;
8846 int kbd_inter_refused;
8847 int we_are_in, userauth_success;
8848 prompts_t *cur_prompt;
8853 void *publickey_blob;
8854 int publickey_bloblen;
8855 int publickey_encrypted;
8856 char *publickey_algorithm;
8857 char *publickey_comment;
8858 unsigned char agent_request[5], *agent_response, *agentp;
8859 int agent_responselen;
8860 unsigned char *pkblob_in_agent;
8862 char *pkblob, *alg, *commentp;
8863 int pklen, alglen, commentlen;
8864 int siglen, retlen, len;
8865 char *q, *agentreq, *ret;
8867 struct Packet *pktout;
8870 struct ssh_gss_library *gsslib;
8871 Ssh_gss_ctx gss_ctx;
8872 Ssh_gss_buf gss_buf;
8873 Ssh_gss_buf gss_rcvtok, gss_sndtok;
8874 Ssh_gss_name gss_srv_name;
8875 Ssh_gss_stat gss_stat;
8878 crState(do_ssh2_authconn_state);
8882 /* Register as a handler for all the messages this coroutine handles. */
8883 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
8884 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
8885 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
8886 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
8887 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
8888 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
8889 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
8890 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
8891 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
8892 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
8893 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
8894 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
8895 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
8896 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
8897 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
8898 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
8899 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
8900 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
8901 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
8902 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
8904 s->done_service_req = FALSE;
8905 s->we_are_in = s->userauth_success = FALSE;
8906 s->agent_response = NULL;
8908 s->tried_gssapi = FALSE;
8911 if (!ssh->bare_connection) {
8912 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
8914 * Request userauth protocol, and await a response to it.
8916 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8917 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
8918 ssh2_pkt_send(ssh, s->pktout);
8919 crWaitUntilV(pktin);
8920 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
8921 s->done_service_req = TRUE;
8923 if (!s->done_service_req) {
8925 * Request connection protocol directly, without authentication.
8927 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8928 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8929 ssh2_pkt_send(ssh, s->pktout);
8930 crWaitUntilV(pktin);
8931 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
8932 s->we_are_in = TRUE; /* no auth required */
8934 bombout(("Server refused service request"));
8939 s->we_are_in = TRUE;
8942 /* Arrange to be able to deal with any BANNERs that come in.
8943 * (We do this now as packets may come in during the next bit.) */
8944 bufchain_init(&ssh->banner);
8945 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
8946 ssh2_msg_userauth_banner;
8949 * Misc one-time setup for authentication.
8951 s->publickey_blob = NULL;
8952 if (!s->we_are_in) {
8955 * Load the public half of any configured public key file
8958 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8959 if (!filename_is_null(s->keyfile)) {
8961 logeventf(ssh, "Reading private key file \"%.150s\"",
8962 filename_to_str(s->keyfile));
8963 keytype = key_type(s->keyfile);
8964 if (keytype == SSH_KEYTYPE_SSH2) {
8967 ssh2_userkey_loadpub(s->keyfile,
8968 &s->publickey_algorithm,
8969 &s->publickey_bloblen,
8970 &s->publickey_comment, &error);
8971 if (s->publickey_blob) {
8972 s->publickey_encrypted =
8973 ssh2_userkey_encrypted(s->keyfile, NULL);
8976 logeventf(ssh, "Unable to load private key (%s)",
8978 msgbuf = dupprintf("Unable to load private key file "
8979 "\"%.150s\" (%s)\r\n",
8980 filename_to_str(s->keyfile),
8982 c_write_str(ssh, msgbuf);
8987 logeventf(ssh, "Unable to use this key file (%s)",
8988 key_type_to_str(keytype));
8989 msgbuf = dupprintf("Unable to use key file \"%.150s\""
8991 filename_to_str(s->keyfile),
8992 key_type_to_str(keytype));
8993 c_write_str(ssh, msgbuf);
8995 s->publickey_blob = NULL;
9000 * Find out about any keys Pageant has (but if there's a
9001 * public key configured, filter out all others).
9004 s->agent_response = NULL;
9005 s->pkblob_in_agent = NULL;
9006 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9010 logevent("Pageant is running. Requesting keys.");
9012 /* Request the keys held by the agent. */
9013 PUT_32BIT(s->agent_request, 1);
9014 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9015 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9016 ssh_agent_callback, ssh)) {
9020 bombout(("Unexpected data from server while"
9021 " waiting for agent response"));
9024 } while (pktin || inlen > 0);
9025 r = ssh->agent_response;
9026 s->agent_responselen = ssh->agent_response_len;
9028 s->agent_response = (unsigned char *) r;
9029 if (s->agent_response && s->agent_responselen >= 5 &&
9030 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9033 p = s->agent_response + 5;
9034 s->nkeys = toint(GET_32BIT(p));
9037 * Vet the Pageant response to ensure that the key
9038 * count and blob lengths make sense.
9041 logeventf(ssh, "Pageant response contained a negative"
9042 " key count %d", s->nkeys);
9044 goto done_agent_query;
9046 unsigned char *q = p + 4;
9047 int lenleft = s->agent_responselen - 5 - 4;
9049 for (keyi = 0; keyi < s->nkeys; keyi++) {
9050 int bloblen, commentlen;
9052 logeventf(ssh, "Pageant response was truncated");
9054 goto done_agent_query;
9056 bloblen = toint(GET_32BIT(q));
9057 if (bloblen < 0 || bloblen > lenleft) {
9058 logeventf(ssh, "Pageant response was truncated");
9060 goto done_agent_query;
9062 lenleft -= 4 + bloblen;
9064 commentlen = toint(GET_32BIT(q));
9065 if (commentlen < 0 || commentlen > lenleft) {
9066 logeventf(ssh, "Pageant response was truncated");
9068 goto done_agent_query;
9070 lenleft -= 4 + commentlen;
9071 q += 4 + commentlen;
9076 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9077 if (s->publickey_blob) {
9078 /* See if configured key is in agent. */
9079 for (keyi = 0; keyi < s->nkeys; keyi++) {
9080 s->pklen = toint(GET_32BIT(p));
9081 if (s->pklen == s->publickey_bloblen &&
9082 !memcmp(p+4, s->publickey_blob,
9083 s->publickey_bloblen)) {
9084 logeventf(ssh, "Pageant key #%d matches "
9085 "configured key file", keyi);
9087 s->pkblob_in_agent = p;
9091 p += toint(GET_32BIT(p)) + 4; /* comment */
9093 if (!s->pkblob_in_agent) {
9094 logevent("Configured key file not in Pageant");
9099 logevent("Failed to get reply from Pageant");
9107 * We repeat this whole loop, including the username prompt,
9108 * until we manage a successful authentication. If the user
9109 * types the wrong _password_, they can be sent back to the
9110 * beginning to try another username, if this is configured on.
9111 * (If they specify a username in the config, they are never
9112 * asked, even if they do give a wrong password.)
9114 * I think this best serves the needs of
9116 * - the people who have no configuration, no keys, and just
9117 * want to try repeated (username,password) pairs until they
9118 * type both correctly
9120 * - people who have keys and configuration but occasionally
9121 * need to fall back to passwords
9123 * - people with a key held in Pageant, who might not have
9124 * logged in to a particular machine before; so they want to
9125 * type a username, and then _either_ their key will be
9126 * accepted, _or_ they will type a password. If they mistype
9127 * the username they will want to be able to get back and
9130 s->got_username = FALSE;
9131 while (!s->we_are_in) {
9135 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9137 * We got a username last time round this loop, and
9138 * with change_username turned off we don't try to get
9141 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9142 int ret; /* need not be kept over crReturn */
9143 s->cur_prompt = new_prompts(ssh->frontend);
9144 s->cur_prompt->to_server = TRUE;
9145 s->cur_prompt->name = dupstr("SSH login name");
9146 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9147 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9150 crWaitUntilV(!pktin);
9151 ret = get_userpass_input(s->cur_prompt, in, inlen);
9156 * get_userpass_input() failed to get a username.
9159 free_prompts(s->cur_prompt);
9160 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9163 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9164 free_prompts(s->cur_prompt);
9167 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9168 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9169 c_write_str(ssh, stuff);
9173 s->got_username = TRUE;
9176 * Send an authentication request using method "none": (a)
9177 * just in case it succeeds, and (b) so that we know what
9178 * authentication methods we can usefully try next.
9180 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9182 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9183 ssh2_pkt_addstring(s->pktout, ssh->username);
9184 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9185 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9186 ssh2_pkt_send(ssh, s->pktout);
9187 s->type = AUTH_TYPE_NONE;
9189 s->we_are_in = FALSE;
9191 s->tried_pubkey_config = FALSE;
9192 s->kbd_inter_refused = FALSE;
9194 /* Reset agent request state. */
9195 s->done_agent = FALSE;
9196 if (s->agent_response) {
9197 if (s->pkblob_in_agent) {
9198 s->agentp = s->pkblob_in_agent;
9200 s->agentp = s->agent_response + 5 + 4;
9206 char *methods = NULL;
9210 * Wait for the result of the last authentication request.
9213 crWaitUntilV(pktin);
9215 * Now is a convenient point to spew any banner material
9216 * that we've accumulated. (This should ensure that when
9217 * we exit the auth loop, we haven't any left to deal
9221 int size = bufchain_size(&ssh->banner);
9223 * Don't show the banner if we're operating in
9224 * non-verbose non-interactive mode. (It's probably
9225 * a script, which means nobody will read the
9226 * banner _anyway_, and moreover the printing of
9227 * the banner will screw up processing on the
9228 * output of (say) plink.)
9230 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9231 char *banner = snewn(size, char);
9232 bufchain_fetch(&ssh->banner, banner, size);
9233 c_write_untrusted(ssh, banner, size);
9236 bufchain_clear(&ssh->banner);
9238 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9239 logevent("Access granted");
9240 s->we_are_in = s->userauth_success = TRUE;
9244 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9245 bombout(("Strange packet received during authentication: "
9246 "type %d", pktin->type));
9253 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9254 * we can look at the string in it and know what we can
9255 * helpfully try next.
9257 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9258 ssh_pkt_getstring(pktin, &methods, &methlen);
9259 if (!ssh2_pkt_getbool(pktin)) {
9261 * We have received an unequivocal Access
9262 * Denied. This can translate to a variety of
9263 * messages, or no message at all.
9265 * For forms of authentication which are attempted
9266 * implicitly, by which I mean without printing
9267 * anything in the window indicating that we're
9268 * trying them, we should never print 'Access
9271 * If we do print a message saying that we're
9272 * attempting some kind of authentication, it's OK
9273 * to print a followup message saying it failed -
9274 * but the message may sometimes be more specific
9275 * than simply 'Access denied'.
9277 * Additionally, if we'd just tried password
9278 * authentication, we should break out of this
9279 * whole loop so as to go back to the username
9280 * prompt (iff we're configured to allow
9281 * username change attempts).
9283 if (s->type == AUTH_TYPE_NONE) {
9285 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9286 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9287 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9288 c_write_str(ssh, "Server refused our key\r\n");
9289 logevent("Server refused our key");
9290 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9291 /* This _shouldn't_ happen except by a
9292 * protocol bug causing client and server to
9293 * disagree on what is a correct signature. */
9294 c_write_str(ssh, "Server refused public-key signature"
9295 " despite accepting key!\r\n");
9296 logevent("Server refused public-key signature"
9297 " despite accepting key!");
9298 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9299 /* quiet, so no c_write */
9300 logevent("Server refused keyboard-interactive authentication");
9301 } else if (s->type==AUTH_TYPE_GSSAPI) {
9302 /* always quiet, so no c_write */
9303 /* also, the code down in the GSSAPI block has
9304 * already logged this in the Event Log */
9305 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9306 logevent("Keyboard-interactive authentication failed");
9307 c_write_str(ssh, "Access denied\r\n");
9309 assert(s->type == AUTH_TYPE_PASSWORD);
9310 logevent("Password authentication failed");
9311 c_write_str(ssh, "Access denied\r\n");
9313 if (conf_get_int(ssh->conf, CONF_change_username)) {
9314 /* XXX perhaps we should allow
9315 * keyboard-interactive to do this too? */
9316 s->we_are_in = FALSE;
9321 c_write_str(ssh, "Further authentication required\r\n");
9322 logevent("Further authentication required");
9326 in_commasep_string("publickey", methods, methlen);
9328 in_commasep_string("password", methods, methlen);
9329 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9330 in_commasep_string("keyboard-interactive", methods, methlen);
9333 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9334 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9335 in_commasep_string("gssapi-with-mic", methods, methlen) &&
9336 ssh->gsslibs->nlibraries > 0;
9340 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9342 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9345 * Attempt public-key authentication using a key from Pageant.
9348 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9350 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9352 /* Unpack key from agent response */
9353 s->pklen = toint(GET_32BIT(s->agentp));
9355 s->pkblob = (char *)s->agentp;
9356 s->agentp += s->pklen;
9357 s->alglen = toint(GET_32BIT(s->pkblob));
9358 s->alg = s->pkblob + 4;
9359 s->commentlen = toint(GET_32BIT(s->agentp));
9361 s->commentp = (char *)s->agentp;
9362 s->agentp += s->commentlen;
9363 /* s->agentp now points at next key, if any */
9365 /* See if server will accept it */
9366 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9367 ssh2_pkt_addstring(s->pktout, ssh->username);
9368 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9369 /* service requested */
9370 ssh2_pkt_addstring(s->pktout, "publickey");
9372 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9373 ssh2_pkt_addstring_start(s->pktout);
9374 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9375 ssh2_pkt_addstring_start(s->pktout);
9376 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9377 ssh2_pkt_send(ssh, s->pktout);
9378 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9380 crWaitUntilV(pktin);
9381 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9383 /* Offer of key refused. */
9390 if (flags & FLAG_VERBOSE) {
9391 c_write_str(ssh, "Authenticating with "
9393 c_write(ssh, s->commentp, s->commentlen);
9394 c_write_str(ssh, "\" from agent\r\n");
9398 * Server is willing to accept the key.
9399 * Construct a SIGN_REQUEST.
9401 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9402 ssh2_pkt_addstring(s->pktout, ssh->username);
9403 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9404 /* service requested */
9405 ssh2_pkt_addstring(s->pktout, "publickey");
9407 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9408 ssh2_pkt_addstring_start(s->pktout);
9409 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9410 ssh2_pkt_addstring_start(s->pktout);
9411 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9413 /* Ask agent for signature. */
9414 s->siglen = s->pktout->length - 5 + 4 +
9415 ssh->v2_session_id_len;
9416 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9418 s->len = 1; /* message type */
9419 s->len += 4 + s->pklen; /* key blob */
9420 s->len += 4 + s->siglen; /* data to sign */
9421 s->len += 4; /* flags */
9422 s->agentreq = snewn(4 + s->len, char);
9423 PUT_32BIT(s->agentreq, s->len);
9424 s->q = s->agentreq + 4;
9425 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9426 PUT_32BIT(s->q, s->pklen);
9428 memcpy(s->q, s->pkblob, s->pklen);
9430 PUT_32BIT(s->q, s->siglen);
9432 /* Now the data to be signed... */
9433 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9434 PUT_32BIT(s->q, ssh->v2_session_id_len);
9437 memcpy(s->q, ssh->v2_session_id,
9438 ssh->v2_session_id_len);
9439 s->q += ssh->v2_session_id_len;
9440 memcpy(s->q, s->pktout->data + 5,
9441 s->pktout->length - 5);
9442 s->q += s->pktout->length - 5;
9443 /* And finally the (zero) flags word. */
9445 if (!agent_query(s->agentreq, s->len + 4,
9447 ssh_agent_callback, ssh)) {
9451 bombout(("Unexpected data from server"
9452 " while waiting for agent"
9456 } while (pktin || inlen > 0);
9457 vret = ssh->agent_response;
9458 s->retlen = ssh->agent_response_len;
9463 if (s->retlen >= 9 &&
9464 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9465 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9466 logevent("Sending Pageant's response");
9467 ssh2_add_sigblob(ssh, s->pktout,
9468 s->pkblob, s->pklen,
9470 GET_32BIT(s->ret + 5));
9471 ssh2_pkt_send(ssh, s->pktout);
9472 s->type = AUTH_TYPE_PUBLICKEY;
9474 /* FIXME: less drastic response */
9475 bombout(("Pageant failed to answer challenge"));
9481 /* Do we have any keys left to try? */
9482 if (s->pkblob_in_agent) {
9483 s->done_agent = TRUE;
9484 s->tried_pubkey_config = TRUE;
9487 if (s->keyi >= s->nkeys)
9488 s->done_agent = TRUE;
9491 } else if (s->can_pubkey && s->publickey_blob &&
9492 !s->tried_pubkey_config) {
9494 struct ssh2_userkey *key; /* not live over crReturn */
9495 char *passphrase; /* not live over crReturn */
9497 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9499 s->tried_pubkey_config = TRUE;
9502 * Try the public key supplied in the configuration.
9504 * First, offer the public blob to see if the server is
9505 * willing to accept it.
9507 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9508 ssh2_pkt_addstring(s->pktout, ssh->username);
9509 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9510 /* service requested */
9511 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9512 ssh2_pkt_addbool(s->pktout, FALSE);
9513 /* no signature included */
9514 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9515 ssh2_pkt_addstring_start(s->pktout);
9516 ssh2_pkt_addstring_data(s->pktout,
9517 (char *)s->publickey_blob,
9518 s->publickey_bloblen);
9519 ssh2_pkt_send(ssh, s->pktout);
9520 logevent("Offered public key");
9522 crWaitUntilV(pktin);
9523 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9524 /* Key refused. Give up. */
9525 s->gotit = TRUE; /* reconsider message next loop */
9526 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9527 continue; /* process this new message */
9529 logevent("Offer of public key accepted");
9532 * Actually attempt a serious authentication using
9535 if (flags & FLAG_VERBOSE) {
9536 c_write_str(ssh, "Authenticating with public key \"");
9537 c_write_str(ssh, s->publickey_comment);
9538 c_write_str(ssh, "\"\r\n");
9542 const char *error; /* not live over crReturn */
9543 if (s->publickey_encrypted) {
9545 * Get a passphrase from the user.
9547 int ret; /* need not be kept over crReturn */
9548 s->cur_prompt = new_prompts(ssh->frontend);
9549 s->cur_prompt->to_server = FALSE;
9550 s->cur_prompt->name = dupstr("SSH key passphrase");
9551 add_prompt(s->cur_prompt,
9552 dupprintf("Passphrase for key \"%.100s\": ",
9553 s->publickey_comment),
9555 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9558 crWaitUntilV(!pktin);
9559 ret = get_userpass_input(s->cur_prompt,
9564 /* Failed to get a passphrase. Terminate. */
9565 free_prompts(s->cur_prompt);
9566 ssh_disconnect(ssh, NULL,
9567 "Unable to authenticate",
9568 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9573 dupstr(s->cur_prompt->prompts[0]->result);
9574 free_prompts(s->cur_prompt);
9576 passphrase = NULL; /* no passphrase needed */
9580 * Try decrypting the key.
9582 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9583 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9585 /* burn the evidence */
9586 smemclr(passphrase, strlen(passphrase));
9589 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9591 (key == SSH2_WRONG_PASSPHRASE)) {
9592 c_write_str(ssh, "Wrong passphrase\r\n");
9594 /* and loop again */
9596 c_write_str(ssh, "Unable to load private key (");
9597 c_write_str(ssh, error);
9598 c_write_str(ssh, ")\r\n");
9600 break; /* try something else */
9606 unsigned char *pkblob, *sigblob, *sigdata;
9607 int pkblob_len, sigblob_len, sigdata_len;
9611 * We have loaded the private key and the server
9612 * has announced that it's willing to accept it.
9613 * Hallelujah. Generate a signature and send it.
9615 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9616 ssh2_pkt_addstring(s->pktout, ssh->username);
9617 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9618 /* service requested */
9619 ssh2_pkt_addstring(s->pktout, "publickey");
9621 ssh2_pkt_addbool(s->pktout, TRUE);
9622 /* signature follows */
9623 ssh2_pkt_addstring(s->pktout, key->alg->name);
9624 pkblob = key->alg->public_blob(key->data,
9626 ssh2_pkt_addstring_start(s->pktout);
9627 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9631 * The data to be signed is:
9635 * followed by everything so far placed in the
9638 sigdata_len = s->pktout->length - 5 + 4 +
9639 ssh->v2_session_id_len;
9640 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9642 sigdata = snewn(sigdata_len, unsigned char);
9644 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9645 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9648 memcpy(sigdata+p, ssh->v2_session_id,
9649 ssh->v2_session_id_len);
9650 p += ssh->v2_session_id_len;
9651 memcpy(sigdata+p, s->pktout->data + 5,
9652 s->pktout->length - 5);
9653 p += s->pktout->length - 5;
9654 assert(p == sigdata_len);
9655 sigblob = key->alg->sign(key->data, (char *)sigdata,
9656 sigdata_len, &sigblob_len);
9657 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9658 sigblob, sigblob_len);
9663 ssh2_pkt_send(ssh, s->pktout);
9664 logevent("Sent public key signature");
9665 s->type = AUTH_TYPE_PUBLICKEY;
9666 key->alg->freekey(key->data);
9667 sfree(key->comment);
9672 } else if (s->can_gssapi && !s->tried_gssapi) {
9674 /* GSSAPI Authentication */
9679 s->type = AUTH_TYPE_GSSAPI;
9680 s->tried_gssapi = TRUE;
9682 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9685 * Pick the highest GSS library on the preference
9691 for (i = 0; i < ngsslibs; i++) {
9692 int want_id = conf_get_int_int(ssh->conf,
9693 CONF_ssh_gsslist, i);
9694 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
9695 if (ssh->gsslibs->libraries[j].id == want_id) {
9696 s->gsslib = &ssh->gsslibs->libraries[j];
9697 goto got_gsslib; /* double break */
9702 * We always expect to have found something in
9703 * the above loop: we only came here if there
9704 * was at least one viable GSS library, and the
9705 * preference list should always mention
9706 * everything and only change the order.
9711 if (s->gsslib->gsslogmsg)
9712 logevent(s->gsslib->gsslogmsg);
9714 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
9715 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9716 ssh2_pkt_addstring(s->pktout, ssh->username);
9717 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9718 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
9719 logevent("Attempting GSSAPI authentication");
9721 /* add mechanism info */
9722 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
9724 /* number of GSSAPI mechanisms */
9725 ssh2_pkt_adduint32(s->pktout,1);
9727 /* length of OID + 2 */
9728 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
9729 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
9732 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
9734 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
9736 ssh2_pkt_send(ssh, s->pktout);
9737 crWaitUntilV(pktin);
9738 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
9739 logevent("GSSAPI authentication request refused");
9743 /* check returned packet ... */
9745 ssh_pkt_getstring(pktin, &data, &len);
9746 s->gss_rcvtok.value = data;
9747 s->gss_rcvtok.length = len;
9748 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
9749 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
9750 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
9751 memcmp((char *)s->gss_rcvtok.value + 2,
9752 s->gss_buf.value,s->gss_buf.length) ) {
9753 logevent("GSSAPI authentication - wrong response from server");
9757 /* now start running */
9758 s->gss_stat = s->gsslib->import_name(s->gsslib,
9761 if (s->gss_stat != SSH_GSS_OK) {
9762 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
9763 logevent("GSSAPI import name failed - Bad service name");
9765 logevent("GSSAPI import name failed");
9769 /* fetch TGT into GSS engine */
9770 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
9772 if (s->gss_stat != SSH_GSS_OK) {
9773 logevent("GSSAPI authentication failed to get credentials");
9774 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9778 /* initial tokens are empty */
9779 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
9780 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
9782 /* now enter the loop */
9784 s->gss_stat = s->gsslib->init_sec_context
9788 conf_get_int(ssh->conf, CONF_gssapifwd),
9792 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
9793 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
9794 logevent("GSSAPI authentication initialisation failed");
9796 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
9797 &s->gss_buf) == SSH_GSS_OK) {
9798 logevent(s->gss_buf.value);
9799 sfree(s->gss_buf.value);
9804 logevent("GSSAPI authentication initialised");
9806 /* Client and server now exchange tokens until GSSAPI
9807 * no longer says CONTINUE_NEEDED */
9809 if (s->gss_sndtok.length != 0) {
9810 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
9811 ssh_pkt_addstring_start(s->pktout);
9812 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
9813 ssh2_pkt_send(ssh, s->pktout);
9814 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
9817 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
9818 crWaitUntilV(pktin);
9819 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
9820 logevent("GSSAPI authentication - bad server response");
9821 s->gss_stat = SSH_GSS_FAILURE;
9824 ssh_pkt_getstring(pktin, &data, &len);
9825 s->gss_rcvtok.value = data;
9826 s->gss_rcvtok.length = len;
9828 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
9830 if (s->gss_stat != SSH_GSS_OK) {
9831 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9832 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9835 logevent("GSSAPI authentication loop finished OK");
9837 /* Now send the MIC */
9839 s->pktout = ssh2_pkt_init(0);
9840 micoffset = s->pktout->length;
9841 ssh_pkt_addstring_start(s->pktout);
9842 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
9843 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
9844 ssh_pkt_addstring(s->pktout, ssh->username);
9845 ssh_pkt_addstring(s->pktout, "ssh-connection");
9846 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
9848 s->gss_buf.value = (char *)s->pktout->data + micoffset;
9849 s->gss_buf.length = s->pktout->length - micoffset;
9851 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
9852 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
9853 ssh_pkt_addstring_start(s->pktout);
9854 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
9855 ssh2_pkt_send(ssh, s->pktout);
9856 s->gsslib->free_mic(s->gsslib, &mic);
9860 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9861 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9864 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
9867 * Keyboard-interactive authentication.
9870 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
9872 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
9874 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9875 ssh2_pkt_addstring(s->pktout, ssh->username);
9876 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9877 /* service requested */
9878 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
9880 ssh2_pkt_addstring(s->pktout, ""); /* lang */
9881 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
9882 ssh2_pkt_send(ssh, s->pktout);
9884 logevent("Attempting keyboard-interactive authentication");
9886 crWaitUntilV(pktin);
9887 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
9888 /* Server is not willing to do keyboard-interactive
9889 * at all (or, bizarrely but legally, accepts the
9890 * user without actually issuing any prompts).
9891 * Give up on it entirely. */
9893 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
9894 s->kbd_inter_refused = TRUE; /* don't try it again */
9899 * Loop while the server continues to send INFO_REQUESTs.
9901 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
9903 char *name, *inst, *lang;
9904 int name_len, inst_len, lang_len;
9908 * We've got a fresh USERAUTH_INFO_REQUEST.
9909 * Get the preamble and start building a prompt.
9911 ssh_pkt_getstring(pktin, &name, &name_len);
9912 ssh_pkt_getstring(pktin, &inst, &inst_len);
9913 ssh_pkt_getstring(pktin, &lang, &lang_len);
9914 s->cur_prompt = new_prompts(ssh->frontend);
9915 s->cur_prompt->to_server = TRUE;
9918 * Get any prompt(s) from the packet.
9920 s->num_prompts = ssh_pkt_getuint32(pktin);
9921 for (i = 0; i < s->num_prompts; i++) {
9925 static char noprompt[] =
9926 "<server failed to send prompt>: ";
9928 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9929 echo = ssh2_pkt_getbool(pktin);
9932 prompt_len = lenof(noprompt)-1;
9934 add_prompt(s->cur_prompt,
9935 dupprintf("%.*s", prompt_len, prompt),
9940 /* FIXME: better prefix to distinguish from
9942 s->cur_prompt->name =
9943 dupprintf("SSH server: %.*s", name_len, name);
9944 s->cur_prompt->name_reqd = TRUE;
9946 s->cur_prompt->name =
9947 dupstr("SSH server authentication");
9948 s->cur_prompt->name_reqd = FALSE;
9950 /* We add a prefix to try to make it clear that a prompt
9951 * has come from the server.
9952 * FIXME: ugly to print "Using..." in prompt _every_
9953 * time round. Can this be done more subtly? */
9954 /* Special case: for reasons best known to themselves,
9955 * some servers send k-i requests with no prompts and
9956 * nothing to display. Keep quiet in this case. */
9957 if (s->num_prompts || name_len || inst_len) {
9958 s->cur_prompt->instruction =
9959 dupprintf("Using keyboard-interactive authentication.%s%.*s",
9960 inst_len ? "\n" : "", inst_len, inst);
9961 s->cur_prompt->instr_reqd = TRUE;
9963 s->cur_prompt->instr_reqd = FALSE;
9967 * Display any instructions, and get the user's
9971 int ret; /* not live over crReturn */
9972 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9975 crWaitUntilV(!pktin);
9976 ret = get_userpass_input(s->cur_prompt, in, inlen);
9981 * Failed to get responses. Terminate.
9983 free_prompts(s->cur_prompt);
9984 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9985 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9992 * Send the response(s) to the server.
9994 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
9995 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
9996 for (i=0; i < s->num_prompts; i++) {
9997 ssh2_pkt_addstring(s->pktout,
9998 s->cur_prompt->prompts[i]->result);
10000 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10003 * Free the prompts structure from this iteration.
10004 * If there's another, a new one will be allocated
10005 * when we return to the top of this while loop.
10007 free_prompts(s->cur_prompt);
10010 * Get the next packet in case it's another
10013 crWaitUntilV(pktin);
10018 * We should have SUCCESS or FAILURE now.
10022 } else if (s->can_passwd) {
10025 * Plain old password authentication.
10027 int ret; /* not live over crReturn */
10028 int changereq_first_time; /* not live over crReturn */
10030 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10032 s->cur_prompt = new_prompts(ssh->frontend);
10033 s->cur_prompt->to_server = TRUE;
10034 s->cur_prompt->name = dupstr("SSH password");
10035 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10040 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10043 crWaitUntilV(!pktin);
10044 ret = get_userpass_input(s->cur_prompt, in, inlen);
10049 * Failed to get responses. Terminate.
10051 free_prompts(s->cur_prompt);
10052 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10053 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10058 * Squirrel away the password. (We may need it later if
10059 * asked to change it.)
10061 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10062 free_prompts(s->cur_prompt);
10065 * Send the password packet.
10067 * We pad out the password packet to 256 bytes to make
10068 * it harder for an attacker to find the length of the
10071 * Anyone using a password longer than 256 bytes
10072 * probably doesn't have much to worry about from
10073 * people who find out how long their password is!
10075 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10076 ssh2_pkt_addstring(s->pktout, ssh->username);
10077 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10078 /* service requested */
10079 ssh2_pkt_addstring(s->pktout, "password");
10080 ssh2_pkt_addbool(s->pktout, FALSE);
10081 ssh2_pkt_addstring(s->pktout, s->password);
10082 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10083 logevent("Sent password");
10084 s->type = AUTH_TYPE_PASSWORD;
10087 * Wait for next packet, in case it's a password change
10090 crWaitUntilV(pktin);
10091 changereq_first_time = TRUE;
10093 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10096 * We're being asked for a new password
10097 * (perhaps not for the first time).
10098 * Loop until the server accepts it.
10101 int got_new = FALSE; /* not live over crReturn */
10102 char *prompt; /* not live over crReturn */
10103 int prompt_len; /* not live over crReturn */
10107 if (changereq_first_time)
10108 msg = "Server requested password change";
10110 msg = "Server rejected new password";
10112 c_write_str(ssh, msg);
10113 c_write_str(ssh, "\r\n");
10116 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10118 s->cur_prompt = new_prompts(ssh->frontend);
10119 s->cur_prompt->to_server = TRUE;
10120 s->cur_prompt->name = dupstr("New SSH password");
10121 s->cur_prompt->instruction =
10122 dupprintf("%.*s", prompt_len, prompt);
10123 s->cur_prompt->instr_reqd = TRUE;
10125 * There's no explicit requirement in the protocol
10126 * for the "old" passwords in the original and
10127 * password-change messages to be the same, and
10128 * apparently some Cisco kit supports password change
10129 * by the user entering a blank password originally
10130 * and the real password subsequently, so,
10131 * reluctantly, we prompt for the old password again.
10133 * (On the other hand, some servers don't even bother
10134 * to check this field.)
10136 add_prompt(s->cur_prompt,
10137 dupstr("Current password (blank for previously entered password): "),
10139 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10141 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10145 * Loop until the user manages to enter the same
10150 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10153 crWaitUntilV(!pktin);
10154 ret = get_userpass_input(s->cur_prompt, in, inlen);
10159 * Failed to get responses. Terminate.
10161 /* burn the evidence */
10162 free_prompts(s->cur_prompt);
10163 smemclr(s->password, strlen(s->password));
10164 sfree(s->password);
10165 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10166 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10172 * If the user specified a new original password
10173 * (IYSWIM), overwrite any previously specified
10175 * (A side effect is that the user doesn't have to
10176 * re-enter it if they louse up the new password.)
10178 if (s->cur_prompt->prompts[0]->result[0]) {
10179 smemclr(s->password, strlen(s->password));
10180 /* burn the evidence */
10181 sfree(s->password);
10183 dupstr(s->cur_prompt->prompts[0]->result);
10187 * Check the two new passwords match.
10189 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10190 s->cur_prompt->prompts[2]->result)
10193 /* They don't. Silly user. */
10194 c_write_str(ssh, "Passwords do not match\r\n");
10199 * Send the new password (along with the old one).
10200 * (see above for padding rationale)
10202 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10203 ssh2_pkt_addstring(s->pktout, ssh->username);
10204 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10205 /* service requested */
10206 ssh2_pkt_addstring(s->pktout, "password");
10207 ssh2_pkt_addbool(s->pktout, TRUE);
10208 ssh2_pkt_addstring(s->pktout, s->password);
10209 ssh2_pkt_addstring(s->pktout,
10210 s->cur_prompt->prompts[1]->result);
10211 free_prompts(s->cur_prompt);
10212 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10213 logevent("Sent new password");
10216 * Now see what the server has to say about it.
10217 * (If it's CHANGEREQ again, it's not happy with the
10220 crWaitUntilV(pktin);
10221 changereq_first_time = FALSE;
10226 * We need to reexamine the current pktin at the top
10227 * of the loop. Either:
10228 * - we weren't asked to change password at all, in
10229 * which case it's a SUCCESS or FAILURE with the
10231 * - we sent a new password, and the server was
10232 * either OK with it (SUCCESS or FAILURE w/partial
10233 * success) or unhappy with the _old_ password
10234 * (FAILURE w/o partial success)
10235 * In any of these cases, we go back to the top of
10236 * the loop and start again.
10241 * We don't need the old password any more, in any
10242 * case. Burn the evidence.
10244 smemclr(s->password, strlen(s->password));
10245 sfree(s->password);
10248 char *str = dupprintf("No supported authentication methods available"
10249 " (server sent: %.*s)",
10252 ssh_disconnect(ssh, str,
10253 "No supported authentication methods available",
10254 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10264 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10266 /* Clear up various bits and pieces from authentication. */
10267 if (s->publickey_blob) {
10268 sfree(s->publickey_blob);
10269 sfree(s->publickey_comment);
10271 if (s->agent_response)
10272 sfree(s->agent_response);
10274 if (s->userauth_success && !ssh->bare_connection) {
10276 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10277 * packets since. Signal the transport layer to consider enacting
10278 * delayed compression.
10280 * (Relying on we_are_in is not sufficient, as
10281 * draft-miller-secsh-compression-delayed is quite clear that it
10282 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10283 * become set for other reasons.)
10285 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10288 ssh->channels = newtree234(ssh_channelcmp);
10291 * Set up handlers for some connection protocol messages, so we
10292 * don't have to handle them repeatedly in this coroutine.
10294 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10295 ssh2_msg_channel_window_adjust;
10296 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10297 ssh2_msg_global_request;
10300 * Create the main session channel.
10302 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10303 ssh->mainchan = NULL;
10305 ssh->mainchan = snew(struct ssh_channel);
10306 ssh->mainchan->ssh = ssh;
10307 ssh2_channel_init(ssh->mainchan);
10309 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10311 * Just start a direct-tcpip channel and use it as the main
10314 ssh_send_port_open(ssh->mainchan,
10315 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10316 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10318 ssh->ncmode = TRUE;
10320 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10321 logevent("Opening session as main channel");
10322 ssh2_pkt_send(ssh, s->pktout);
10323 ssh->ncmode = FALSE;
10325 crWaitUntilV(pktin);
10326 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10327 bombout(("Server refused to open channel"));
10329 /* FIXME: error data comes back in FAILURE packet */
10331 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10332 bombout(("Server's channel confirmation cited wrong channel"));
10335 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10336 ssh->mainchan->halfopen = FALSE;
10337 ssh->mainchan->type = CHAN_MAINSESSION;
10338 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10339 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10340 add234(ssh->channels, ssh->mainchan);
10341 update_specials_menu(ssh->frontend);
10342 logevent("Opened main channel");
10346 * Now we have a channel, make dispatch table entries for
10347 * general channel-based messages.
10349 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10350 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10351 ssh2_msg_channel_data;
10352 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10353 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10354 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10355 ssh2_msg_channel_open_confirmation;
10356 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10357 ssh2_msg_channel_open_failure;
10358 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10359 ssh2_msg_channel_request;
10360 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10361 ssh2_msg_channel_open;
10362 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10363 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10366 * Now the connection protocol is properly up and running, with
10367 * all those dispatch table entries, so it's safe to let
10368 * downstreams start trying to open extra channels through us.
10370 if (ssh->connshare)
10371 share_activate(ssh->connshare, ssh->v_s);
10373 if (ssh->mainchan && ssh_is_simple(ssh)) {
10375 * This message indicates to the server that we promise
10376 * not to try to run any other channel in parallel with
10377 * this one, so it's safe for it to advertise a very large
10378 * window and leave the flow control to TCP.
10380 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10381 "simple@putty.projects.tartarus.org",
10383 ssh2_pkt_send(ssh, s->pktout);
10387 * Enable port forwardings.
10389 ssh_setup_portfwd(ssh, ssh->conf);
10391 if (ssh->mainchan && !ssh->ncmode) {
10393 * Send the CHANNEL_REQUESTS for the main session channel.
10394 * Each one is handled by its own little asynchronous
10398 /* Potentially enable X11 forwarding. */
10399 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10401 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10403 if (!ssh->x11disp) {
10404 /* FIXME: return an error message from x11_setup_display */
10405 logevent("X11 forwarding not enabled: unable to"
10406 " initialise X display");
10408 ssh->x11auth = x11_invent_fake_auth
10409 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10410 ssh->x11auth->disp = ssh->x11disp;
10412 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10416 /* Potentially enable agent forwarding. */
10417 if (ssh_agent_forwarding_permitted(ssh))
10418 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10420 /* Now allocate a pty for the session. */
10421 if (!conf_get_int(ssh->conf, CONF_nopty))
10422 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10424 /* Send environment variables. */
10425 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10428 * Start a shell or a remote command. We may have to attempt
10429 * this twice if the config data has provided a second choice
10436 if (ssh->fallback_cmd) {
10437 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10438 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10440 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10441 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10445 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10446 ssh2_response_authconn, NULL);
10447 ssh2_pkt_addstring(s->pktout, cmd);
10449 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10450 ssh2_response_authconn, NULL);
10451 ssh2_pkt_addstring(s->pktout, cmd);
10453 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10454 ssh2_response_authconn, NULL);
10456 ssh2_pkt_send(ssh, s->pktout);
10458 crWaitUntilV(pktin);
10460 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10461 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10462 bombout(("Unexpected response to shell/command request:"
10463 " packet type %d", pktin->type));
10467 * We failed to start the command. If this is the
10468 * fallback command, we really are finished; if it's
10469 * not, and if the fallback command exists, try falling
10470 * back to it before complaining.
10472 if (!ssh->fallback_cmd &&
10473 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10474 logevent("Primary command failed; attempting fallback");
10475 ssh->fallback_cmd = TRUE;
10478 bombout(("Server refused to start a shell/command"));
10481 logevent("Started a shell/command");
10486 ssh->editing = ssh->echoing = TRUE;
10489 ssh->state = SSH_STATE_SESSION;
10490 if (ssh->size_needed)
10491 ssh_size(ssh, ssh->term_width, ssh->term_height);
10492 if (ssh->eof_needed)
10493 ssh_special(ssh, TS_EOF);
10499 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10504 s->try_send = FALSE;
10508 * _All_ the connection-layer packets we expect to
10509 * receive are now handled by the dispatch table.
10510 * Anything that reaches here must be bogus.
10513 bombout(("Strange packet received: type %d", pktin->type));
10515 } else if (ssh->mainchan) {
10517 * We have spare data. Add it to the channel buffer.
10519 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
10520 s->try_send = TRUE;
10524 struct ssh_channel *c;
10526 * Try to send data on all channels if we can.
10528 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
10529 ssh2_try_send_and_unthrottle(ssh, c);
10537 * Handlers for SSH-2 messages that might arrive at any moment.
10539 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10541 /* log reason code in disconnect message */
10543 int reason, msglen;
10545 reason = ssh_pkt_getuint32(pktin);
10546 ssh_pkt_getstring(pktin, &msg, &msglen);
10548 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10549 buf = dupprintf("Received disconnect message (%s)",
10550 ssh2_disconnect_reasons[reason]);
10552 buf = dupprintf("Received disconnect message (unknown"
10553 " type %d)", reason);
10557 buf = dupprintf("Disconnection message text: %.*s",
10560 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10562 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10563 ssh2_disconnect_reasons[reason] : "unknown",
10568 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10570 /* log the debug message */
10574 /* XXX maybe we should actually take notice of the return value */
10575 ssh2_pkt_getbool(pktin);
10576 ssh_pkt_getstring(pktin, &msg, &msglen);
10578 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
10581 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10583 do_ssh2_transport(ssh, NULL, 0, pktin);
10587 * Called if we receive a packet that isn't allowed by the protocol.
10588 * This only applies to packets whose meaning PuTTY understands.
10589 * Entirely unknown packets are handled below.
10591 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10593 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10594 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10596 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10600 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10602 struct Packet *pktout;
10603 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10604 ssh2_pkt_adduint32(pktout, pktin->sequence);
10606 * UNIMPLEMENTED messages MUST appear in the same order as the
10607 * messages they respond to. Hence, never queue them.
10609 ssh2_pkt_send_noqueue(ssh, pktout);
10613 * Handle the top-level SSH-2 protocol.
10615 static void ssh2_protocol_setup(Ssh ssh)
10620 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10622 for (i = 0; i < 256; i++)
10623 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10626 * Initially, we only accept transport messages (and a few generic
10627 * ones). do_ssh2_authconn will add more when it starts.
10628 * Messages that are understood but not currently acceptable go to
10629 * ssh2_msg_unexpected.
10631 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10632 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10633 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10634 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10635 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10636 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10637 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10638 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10639 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10640 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10641 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10642 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10643 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10644 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10645 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10646 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10647 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10648 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10649 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10650 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10651 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10652 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10653 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10654 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10655 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10656 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10657 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10658 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10659 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10660 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10661 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10662 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10663 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10666 * These messages have a special handler from the start.
10668 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10669 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10670 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10673 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10678 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10680 for (i = 0; i < 256; i++)
10681 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10684 * Initially, we set all ssh-connection messages to 'unexpected';
10685 * do_ssh2_authconn will fill things in properly. We also handle a
10686 * couple of messages from the transport protocol which aren't
10687 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10690 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10691 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10692 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10693 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10694 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10695 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10696 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10697 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10698 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10699 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10700 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10701 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10702 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10703 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10705 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10708 * These messages have a special handler from the start.
10710 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10711 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
10712 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10715 static void ssh2_timer(void *ctx, unsigned long now)
10717 Ssh ssh = (Ssh)ctx;
10719 if (ssh->state == SSH_STATE_CLOSED)
10722 if (!ssh->kex_in_progress && !ssh->bare_connection &&
10723 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
10724 now == ssh->next_rekey) {
10725 do_ssh2_transport(ssh, "timeout", -1, NULL);
10729 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
10730 struct Packet *pktin)
10732 unsigned char *in = (unsigned char *)vin;
10733 if (ssh->state == SSH_STATE_CLOSED)
10737 ssh->incoming_data_size += pktin->encrypted_len;
10738 if (!ssh->kex_in_progress &&
10739 ssh->max_data_size != 0 &&
10740 ssh->incoming_data_size > ssh->max_data_size)
10741 do_ssh2_transport(ssh, "too much data received", -1, NULL);
10745 ssh->packet_dispatch[pktin->type](ssh, pktin);
10746 else if (!ssh->protocol_initial_phase_done)
10747 do_ssh2_transport(ssh, in, inlen, pktin);
10749 do_ssh2_authconn(ssh, in, inlen, pktin);
10752 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
10753 struct Packet *pktin)
10755 unsigned char *in = (unsigned char *)vin;
10756 if (ssh->state == SSH_STATE_CLOSED)
10760 ssh->packet_dispatch[pktin->type](ssh, pktin);
10762 do_ssh2_authconn(ssh, in, inlen, pktin);
10765 static void ssh_cache_conf_values(Ssh ssh)
10767 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
10771 * Called to set up the connection.
10773 * Returns an error message, or NULL on success.
10775 static const char *ssh_init(void *frontend_handle, void **backend_handle,
10776 Conf *conf, char *host, int port, char **realhost,
10777 int nodelay, int keepalive)
10782 ssh = snew(struct ssh_tag);
10783 ssh->conf = conf_copy(conf);
10784 ssh_cache_conf_values(ssh);
10785 ssh->version = 0; /* when not ready yet */
10787 ssh->cipher = NULL;
10788 ssh->v1_cipher_ctx = NULL;
10789 ssh->crcda_ctx = NULL;
10790 ssh->cscipher = NULL;
10791 ssh->cs_cipher_ctx = NULL;
10792 ssh->sccipher = NULL;
10793 ssh->sc_cipher_ctx = NULL;
10795 ssh->cs_mac_ctx = NULL;
10797 ssh->sc_mac_ctx = NULL;
10798 ssh->cscomp = NULL;
10799 ssh->cs_comp_ctx = NULL;
10800 ssh->sccomp = NULL;
10801 ssh->sc_comp_ctx = NULL;
10803 ssh->kex_ctx = NULL;
10804 ssh->hostkey = NULL;
10805 ssh->hostkey_str = NULL;
10806 ssh->exitcode = -1;
10807 ssh->close_expected = FALSE;
10808 ssh->clean_exit = FALSE;
10809 ssh->state = SSH_STATE_PREPACKET;
10810 ssh->size_needed = FALSE;
10811 ssh->eof_needed = FALSE;
10813 ssh->logctx = NULL;
10814 ssh->deferred_send_data = NULL;
10815 ssh->deferred_len = 0;
10816 ssh->deferred_size = 0;
10817 ssh->fallback_cmd = 0;
10818 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
10819 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
10820 ssh->x11disp = NULL;
10821 ssh->x11auth = NULL;
10822 ssh->x11authtree = newtree234(x11_authcmp);
10823 ssh->v1_compressing = FALSE;
10824 ssh->v2_outgoing_sequence = 0;
10825 ssh->ssh1_rdpkt_crstate = 0;
10826 ssh->ssh2_rdpkt_crstate = 0;
10827 ssh->ssh2_bare_rdpkt_crstate = 0;
10828 ssh->ssh_gotdata_crstate = 0;
10829 ssh->do_ssh1_connection_crstate = 0;
10830 ssh->do_ssh_init_state = NULL;
10831 ssh->do_ssh_connection_init_state = NULL;
10832 ssh->do_ssh1_login_state = NULL;
10833 ssh->do_ssh2_transport_state = NULL;
10834 ssh->do_ssh2_authconn_state = NULL;
10837 ssh->mainchan = NULL;
10838 ssh->throttled_all = 0;
10839 ssh->v1_stdout_throttling = 0;
10841 ssh->queuelen = ssh->queuesize = 0;
10842 ssh->queueing = FALSE;
10843 ssh->qhead = ssh->qtail = NULL;
10844 ssh->deferred_rekey_reason = NULL;
10845 bufchain_init(&ssh->queued_incoming_data);
10846 ssh->frozen = FALSE;
10847 ssh->username = NULL;
10848 ssh->sent_console_eof = FALSE;
10849 ssh->got_pty = FALSE;
10850 ssh->bare_connection = FALSE;
10851 ssh->X11_fwd_enabled = FALSE;
10852 ssh->connshare = NULL;
10853 ssh->attempting_connshare = FALSE;
10855 *backend_handle = ssh;
10858 if (crypto_startup() == 0)
10859 return "Microsoft high encryption pack not installed!";
10862 ssh->frontend = frontend_handle;
10863 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
10864 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
10866 ssh->channels = NULL;
10867 ssh->rportfwds = NULL;
10868 ssh->portfwds = NULL;
10873 ssh->conn_throttle_count = 0;
10874 ssh->overall_bufsize = 0;
10875 ssh->fallback_cmd = 0;
10877 ssh->protocol = NULL;
10879 ssh->protocol_initial_phase_done = FALSE;
10881 ssh->pinger = NULL;
10883 ssh->incoming_data_size = ssh->outgoing_data_size =
10884 ssh->deferred_data_size = 0L;
10885 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10886 CONF_ssh_rekey_data));
10887 ssh->kex_in_progress = FALSE;
10890 ssh->gsslibs = NULL;
10893 random_ref(); /* do this now - may be needed by sharing setup code */
10895 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
10904 static void ssh_free(void *handle)
10906 Ssh ssh = (Ssh) handle;
10907 struct ssh_channel *c;
10908 struct ssh_rportfwd *pf;
10909 struct X11FakeAuth *auth;
10911 if (ssh->v1_cipher_ctx)
10912 ssh->cipher->free_context(ssh->v1_cipher_ctx);
10913 if (ssh->cs_cipher_ctx)
10914 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
10915 if (ssh->sc_cipher_ctx)
10916 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
10917 if (ssh->cs_mac_ctx)
10918 ssh->csmac->free_context(ssh->cs_mac_ctx);
10919 if (ssh->sc_mac_ctx)
10920 ssh->scmac->free_context(ssh->sc_mac_ctx);
10921 if (ssh->cs_comp_ctx) {
10923 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
10925 zlib_compress_cleanup(ssh->cs_comp_ctx);
10927 if (ssh->sc_comp_ctx) {
10929 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
10931 zlib_decompress_cleanup(ssh->sc_comp_ctx);
10934 dh_cleanup(ssh->kex_ctx);
10935 sfree(ssh->savedhost);
10937 while (ssh->queuelen-- > 0)
10938 ssh_free_packet(ssh->queue[ssh->queuelen]);
10941 while (ssh->qhead) {
10942 struct queued_handler *qh = ssh->qhead;
10943 ssh->qhead = qh->next;
10946 ssh->qhead = ssh->qtail = NULL;
10948 if (ssh->channels) {
10949 while ((c = delpos234(ssh->channels, 0)) != NULL) {
10952 if (c->u.x11.xconn != NULL)
10953 x11_close(c->u.x11.xconn);
10955 case CHAN_SOCKDATA:
10956 case CHAN_SOCKDATA_DORMANT:
10957 if (c->u.pfd.pf != NULL)
10958 pfd_close(c->u.pfd.pf);
10961 if (ssh->version == 2) {
10962 struct outstanding_channel_request *ocr, *nocr;
10963 ocr = c->v.v2.chanreq_head;
10965 ocr->handler(c, NULL, ocr->ctx);
10970 bufchain_clear(&c->v.v2.outbuffer);
10974 freetree234(ssh->channels);
10975 ssh->channels = NULL;
10978 if (ssh->connshare)
10979 sharestate_free(ssh->connshare);
10981 if (ssh->rportfwds) {
10982 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
10984 freetree234(ssh->rportfwds);
10985 ssh->rportfwds = NULL;
10987 sfree(ssh->deferred_send_data);
10989 x11_free_display(ssh->x11disp);
10990 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
10991 x11_free_fake_auth(auth);
10992 freetree234(ssh->x11authtree);
10993 sfree(ssh->do_ssh_init_state);
10994 sfree(ssh->do_ssh1_login_state);
10995 sfree(ssh->do_ssh2_transport_state);
10996 sfree(ssh->do_ssh2_authconn_state);
10999 sfree(ssh->fullhostname);
11000 sfree(ssh->hostkey_str);
11001 if (ssh->crcda_ctx) {
11002 crcda_free_context(ssh->crcda_ctx);
11003 ssh->crcda_ctx = NULL;
11006 ssh_do_close(ssh, TRUE);
11007 expire_timer_context(ssh);
11009 pinger_free(ssh->pinger);
11010 bufchain_clear(&ssh->queued_incoming_data);
11011 sfree(ssh->username);
11012 conf_free(ssh->conf);
11015 ssh_gss_cleanup(ssh->gsslibs);
11023 * Reconfigure the SSH backend.
11025 static void ssh_reconfig(void *handle, Conf *conf)
11027 Ssh ssh = (Ssh) handle;
11028 char *rekeying = NULL, rekey_mandatory = FALSE;
11029 unsigned long old_max_data_size;
11032 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11034 ssh_setup_portfwd(ssh, conf);
11036 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11037 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11039 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11040 unsigned long now = GETTICKCOUNT();
11042 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11043 rekeying = "timeout shortened";
11045 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11049 old_max_data_size = ssh->max_data_size;
11050 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11051 CONF_ssh_rekey_data));
11052 if (old_max_data_size != ssh->max_data_size &&
11053 ssh->max_data_size != 0) {
11054 if (ssh->outgoing_data_size > ssh->max_data_size ||
11055 ssh->incoming_data_size > ssh->max_data_size)
11056 rekeying = "data limit lowered";
11059 if (conf_get_int(ssh->conf, CONF_compression) !=
11060 conf_get_int(conf, CONF_compression)) {
11061 rekeying = "compression setting changed";
11062 rekey_mandatory = TRUE;
11065 for (i = 0; i < CIPHER_MAX; i++)
11066 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11067 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11068 rekeying = "cipher settings changed";
11069 rekey_mandatory = TRUE;
11071 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11072 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11073 rekeying = "cipher settings changed";
11074 rekey_mandatory = TRUE;
11077 conf_free(ssh->conf);
11078 ssh->conf = conf_copy(conf);
11079 ssh_cache_conf_values(ssh);
11081 if (!ssh->bare_connection && rekeying) {
11082 if (!ssh->kex_in_progress) {
11083 do_ssh2_transport(ssh, rekeying, -1, NULL);
11084 } else if (rekey_mandatory) {
11085 ssh->deferred_rekey_reason = rekeying;
11091 * Called to send data down the SSH connection.
11093 static int ssh_send(void *handle, char *buf, int len)
11095 Ssh ssh = (Ssh) handle;
11097 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11100 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
11102 return ssh_sendbuffer(ssh);
11106 * Called to query the current amount of buffered stdin data.
11108 static int ssh_sendbuffer(void *handle)
11110 Ssh ssh = (Ssh) handle;
11111 int override_value;
11113 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11117 * If the SSH socket itself has backed up, add the total backup
11118 * size on that to any individual buffer on the stdin channel.
11120 override_value = 0;
11121 if (ssh->throttled_all)
11122 override_value = ssh->overall_bufsize;
11124 if (ssh->version == 1) {
11125 return override_value;
11126 } else if (ssh->version == 2) {
11127 if (!ssh->mainchan)
11128 return override_value;
11130 return (override_value +
11131 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11138 * Called to set the size of the window from SSH's POV.
11140 static void ssh_size(void *handle, int width, int height)
11142 Ssh ssh = (Ssh) handle;
11143 struct Packet *pktout;
11145 ssh->term_width = width;
11146 ssh->term_height = height;
11148 switch (ssh->state) {
11149 case SSH_STATE_BEFORE_SIZE:
11150 case SSH_STATE_PREPACKET:
11151 case SSH_STATE_CLOSED:
11152 break; /* do nothing */
11153 case SSH_STATE_INTERMED:
11154 ssh->size_needed = TRUE; /* buffer for later */
11156 case SSH_STATE_SESSION:
11157 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11158 if (ssh->version == 1) {
11159 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11160 PKT_INT, ssh->term_height,
11161 PKT_INT, ssh->term_width,
11162 PKT_INT, 0, PKT_INT, 0, PKT_END);
11163 } else if (ssh->mainchan) {
11164 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11166 ssh2_pkt_adduint32(pktout, ssh->term_width);
11167 ssh2_pkt_adduint32(pktout, ssh->term_height);
11168 ssh2_pkt_adduint32(pktout, 0);
11169 ssh2_pkt_adduint32(pktout, 0);
11170 ssh2_pkt_send(ssh, pktout);
11178 * Return a list of the special codes that make sense in this
11181 static const struct telnet_special *ssh_get_specials(void *handle)
11183 static const struct telnet_special ssh1_ignore_special[] = {
11184 {"IGNORE message", TS_NOP}
11186 static const struct telnet_special ssh2_ignore_special[] = {
11187 {"IGNORE message", TS_NOP},
11189 static const struct telnet_special ssh2_rekey_special[] = {
11190 {"Repeat key exchange", TS_REKEY},
11192 static const struct telnet_special ssh2_session_specials[] = {
11195 /* These are the signal names defined by RFC 4254.
11196 * They include all the ISO C signals, but are a subset of the POSIX
11197 * required signals. */
11198 {"SIGINT (Interrupt)", TS_SIGINT},
11199 {"SIGTERM (Terminate)", TS_SIGTERM},
11200 {"SIGKILL (Kill)", TS_SIGKILL},
11201 {"SIGQUIT (Quit)", TS_SIGQUIT},
11202 {"SIGHUP (Hangup)", TS_SIGHUP},
11203 {"More signals", TS_SUBMENU},
11204 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11205 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11206 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11207 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11208 {NULL, TS_EXITMENU}
11210 static const struct telnet_special specials_end[] = {
11211 {NULL, TS_EXITMENU}
11213 /* XXX review this length for any changes: */
11214 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
11215 lenof(ssh2_rekey_special) +
11216 lenof(ssh2_session_specials) +
11217 lenof(specials_end)];
11218 Ssh ssh = (Ssh) handle;
11220 #define ADD_SPECIALS(name) \
11222 assert((i + lenof(name)) <= lenof(ssh_specials)); \
11223 memcpy(&ssh_specials[i], name, sizeof name); \
11224 i += lenof(name); \
11227 if (ssh->version == 1) {
11228 /* Don't bother offering IGNORE if we've decided the remote
11229 * won't cope with it, since we wouldn't bother sending it if
11231 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11232 ADD_SPECIALS(ssh1_ignore_special);
11233 } else if (ssh->version == 2) {
11234 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11235 ADD_SPECIALS(ssh2_ignore_special);
11236 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11237 ADD_SPECIALS(ssh2_rekey_special);
11239 ADD_SPECIALS(ssh2_session_specials);
11240 } /* else we're not ready yet */
11243 ADD_SPECIALS(specials_end);
11244 return ssh_specials;
11248 #undef ADD_SPECIALS
11252 * Send special codes. TS_EOF is useful for `plink', so you
11253 * can send an EOF and collect resulting output (e.g. `plink
11256 static void ssh_special(void *handle, Telnet_Special code)
11258 Ssh ssh = (Ssh) handle;
11259 struct Packet *pktout;
11261 if (code == TS_EOF) {
11262 if (ssh->state != SSH_STATE_SESSION) {
11264 * Buffer the EOF in case we are pre-SESSION, so we can
11265 * send it as soon as we reach SESSION.
11267 if (code == TS_EOF)
11268 ssh->eof_needed = TRUE;
11271 if (ssh->version == 1) {
11272 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11273 } else if (ssh->mainchan) {
11274 sshfwd_write_eof(ssh->mainchan);
11275 ssh->send_ok = 0; /* now stop trying to read from stdin */
11277 logevent("Sent EOF message");
11278 } else if (code == TS_PING || code == TS_NOP) {
11279 if (ssh->state == SSH_STATE_CLOSED
11280 || ssh->state == SSH_STATE_PREPACKET) return;
11281 if (ssh->version == 1) {
11282 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11283 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11285 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11286 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11287 ssh2_pkt_addstring_start(pktout);
11288 ssh2_pkt_send_noqueue(ssh, pktout);
11291 } else if (code == TS_REKEY) {
11292 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11293 ssh->version == 2) {
11294 do_ssh2_transport(ssh, "at user request", -1, NULL);
11296 } else if (code == TS_BRK) {
11297 if (ssh->state == SSH_STATE_CLOSED
11298 || ssh->state == SSH_STATE_PREPACKET) return;
11299 if (ssh->version == 1) {
11300 logevent("Unable to send BREAK signal in SSH-1");
11301 } else if (ssh->mainchan) {
11302 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11303 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11304 ssh2_pkt_send(ssh, pktout);
11307 /* Is is a POSIX signal? */
11308 char *signame = NULL;
11309 if (code == TS_SIGABRT) signame = "ABRT";
11310 if (code == TS_SIGALRM) signame = "ALRM";
11311 if (code == TS_SIGFPE) signame = "FPE";
11312 if (code == TS_SIGHUP) signame = "HUP";
11313 if (code == TS_SIGILL) signame = "ILL";
11314 if (code == TS_SIGINT) signame = "INT";
11315 if (code == TS_SIGKILL) signame = "KILL";
11316 if (code == TS_SIGPIPE) signame = "PIPE";
11317 if (code == TS_SIGQUIT) signame = "QUIT";
11318 if (code == TS_SIGSEGV) signame = "SEGV";
11319 if (code == TS_SIGTERM) signame = "TERM";
11320 if (code == TS_SIGUSR1) signame = "USR1";
11321 if (code == TS_SIGUSR2) signame = "USR2";
11322 /* The SSH-2 protocol does in principle support arbitrary named
11323 * signals, including signame@domain, but we don't support those. */
11325 /* It's a signal. */
11326 if (ssh->version == 2 && ssh->mainchan) {
11327 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11328 ssh2_pkt_addstring(pktout, signame);
11329 ssh2_pkt_send(ssh, pktout);
11330 logeventf(ssh, "Sent signal SIG%s", signame);
11333 /* Never heard of it. Do nothing */
11338 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11340 Ssh ssh = (Ssh) handle;
11341 struct ssh_channel *c;
11342 c = snew(struct ssh_channel);
11345 ssh2_channel_init(c);
11346 c->halfopen = TRUE;
11347 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11349 add234(ssh->channels, c);
11353 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11355 struct ssh_channel *c;
11356 c = snew(struct ssh_channel);
11359 ssh2_channel_init(c);
11360 c->type = CHAN_SHARING;
11361 c->u.sharing.ctx = sharing_ctx;
11362 add234(ssh->channels, c);
11366 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11368 struct ssh_channel *c;
11370 c = find234(ssh->channels, &localid, ssh_channelfind);
11372 ssh_channel_destroy(c);
11375 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11376 const void *data, int datalen,
11377 const char *additional_log_text)
11379 struct Packet *pkt;
11381 pkt = ssh2_pkt_init(type);
11382 pkt->downstream_id = id;
11383 pkt->additional_log_text = additional_log_text;
11384 ssh2_pkt_adddata(pkt, data, datalen);
11385 ssh2_pkt_send(ssh, pkt);
11389 * This is called when stdout/stderr (the entity to which
11390 * from_backend sends data) manages to clear some backlog.
11392 static void ssh_unthrottle(void *handle, int bufsize)
11394 Ssh ssh = (Ssh) handle;
11397 if (ssh->version == 1) {
11398 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11399 ssh->v1_stdout_throttling = 0;
11400 ssh_throttle_conn(ssh, -1);
11403 if (ssh->mainchan) {
11404 ssh2_set_window(ssh->mainchan,
11405 bufsize < ssh->mainchan->v.v2.locmaxwin ?
11406 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11407 if (ssh_is_simple(ssh))
11410 buflimit = ssh->mainchan->v.v2.locmaxwin;
11411 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11412 ssh->mainchan->throttling_conn = 0;
11413 ssh_throttle_conn(ssh, -1);
11419 * Now process any SSH connection data that was stashed in our
11420 * queue while we were frozen.
11422 ssh_process_queued_incoming_data(ssh);
11425 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
11427 struct ssh_channel *c = (struct ssh_channel *)channel;
11429 struct Packet *pktout;
11431 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11433 if (ssh->version == 1) {
11434 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11435 PKT_INT, c->localid,
11438 /* PKT_STR, <org:orgport>, */
11441 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11443 char *trimmed_host = host_strduptrim(hostname);
11444 ssh2_pkt_addstring(pktout, trimmed_host);
11445 sfree(trimmed_host);
11447 ssh2_pkt_adduint32(pktout, port);
11449 * We make up values for the originator data; partly it's
11450 * too much hassle to keep track, and partly I'm not
11451 * convinced the server should be told details like that
11452 * about my local network configuration.
11453 * The "originator IP address" is syntactically a numeric
11454 * IP address, and some servers (e.g., Tectia) get upset
11455 * if it doesn't match this syntax.
11457 ssh2_pkt_addstring(pktout, "0.0.0.0");
11458 ssh2_pkt_adduint32(pktout, 0);
11459 ssh2_pkt_send(ssh, pktout);
11463 static int ssh_connected(void *handle)
11465 Ssh ssh = (Ssh) handle;
11466 return ssh->s != NULL;
11469 static int ssh_sendok(void *handle)
11471 Ssh ssh = (Ssh) handle;
11472 return ssh->send_ok;
11475 static int ssh_ldisc(void *handle, int option)
11477 Ssh ssh = (Ssh) handle;
11478 if (option == LD_ECHO)
11479 return ssh->echoing;
11480 if (option == LD_EDIT)
11481 return ssh->editing;
11485 static void ssh_provide_ldisc(void *handle, void *ldisc)
11487 Ssh ssh = (Ssh) handle;
11488 ssh->ldisc = ldisc;
11491 static void ssh_provide_logctx(void *handle, void *logctx)
11493 Ssh ssh = (Ssh) handle;
11494 ssh->logctx = logctx;
11497 static int ssh_return_exitcode(void *handle)
11499 Ssh ssh = (Ssh) handle;
11500 if (ssh->s != NULL)
11503 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11507 * cfg_info for SSH is the protocol running in this session.
11508 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11509 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11511 static int ssh_cfg_info(void *handle)
11513 Ssh ssh = (Ssh) handle;
11514 if (ssh->version == 0)
11515 return 0; /* don't know yet */
11516 else if (ssh->bare_connection)
11519 return ssh->version;
11523 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11524 * that fails. This variable is the means by which scp.c can reach
11525 * into the SSH code and find out which one it got.
11527 extern int ssh_fallback_cmd(void *handle)
11529 Ssh ssh = (Ssh) handle;
11530 return ssh->fallback_cmd;
11533 Backend ssh_backend = {
11543 ssh_return_exitcode,
11547 ssh_provide_logctx,