28 * Packet type contexts, so that ssh2_pkt_type can correctly decode
29 * the ambiguous type numbers back into the correct type strings.
39 SSH2_PKTCTX_PUBLICKEY,
45 static const char *const ssh2_disconnect_reasons[] = {
47 "host not allowed to connect",
49 "key exchange failed",
50 "host authentication failed",
53 "service not available",
54 "protocol version not supported",
55 "host key not verifiable",
58 "too many connections",
59 "auth cancelled by user",
60 "no more auth methods available",
65 * Various remote-bug flags.
67 #define BUG_CHOKES_ON_SSH1_IGNORE 1
68 #define BUG_SSH2_HMAC 2
69 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
70 #define BUG_CHOKES_ON_RSA 8
71 #define BUG_SSH2_RSA_PADDING 16
72 #define BUG_SSH2_DERIVEKEY 32
73 #define BUG_SSH2_REKEY 64
74 #define BUG_SSH2_PK_SESSIONID 128
75 #define BUG_SSH2_MAXPKT 256
76 #define BUG_CHOKES_ON_SSH2_IGNORE 512
77 #define BUG_CHOKES_ON_WINADJ 1024
78 #define BUG_SENDS_LATE_REQUEST_REPLY 2048
79 #define BUG_SSH2_OLDGEX 4096
81 #define DH_MIN_SIZE 1024
82 #define DH_MAX_SIZE 8192
85 * Codes for terminal modes.
86 * Most of these are the same in SSH-1 and SSH-2.
87 * This list is derived from RFC 4254 and
91 const char* const mode;
93 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
95 /* "V" prefix discarded for special characters relative to SSH specs */
96 { "INTR", 1, TTY_OP_CHAR },
97 { "QUIT", 2, TTY_OP_CHAR },
98 { "ERASE", 3, TTY_OP_CHAR },
99 { "KILL", 4, TTY_OP_CHAR },
100 { "EOF", 5, TTY_OP_CHAR },
101 { "EOL", 6, TTY_OP_CHAR },
102 { "EOL2", 7, TTY_OP_CHAR },
103 { "START", 8, TTY_OP_CHAR },
104 { "STOP", 9, TTY_OP_CHAR },
105 { "SUSP", 10, TTY_OP_CHAR },
106 { "DSUSP", 11, TTY_OP_CHAR },
107 { "REPRINT", 12, TTY_OP_CHAR },
108 { "WERASE", 13, TTY_OP_CHAR },
109 { "LNEXT", 14, TTY_OP_CHAR },
110 { "FLUSH", 15, TTY_OP_CHAR },
111 { "SWTCH", 16, TTY_OP_CHAR },
112 { "STATUS", 17, TTY_OP_CHAR },
113 { "DISCARD", 18, TTY_OP_CHAR },
114 { "IGNPAR", 30, TTY_OP_BOOL },
115 { "PARMRK", 31, TTY_OP_BOOL },
116 { "INPCK", 32, TTY_OP_BOOL },
117 { "ISTRIP", 33, TTY_OP_BOOL },
118 { "INLCR", 34, TTY_OP_BOOL },
119 { "IGNCR", 35, TTY_OP_BOOL },
120 { "ICRNL", 36, TTY_OP_BOOL },
121 { "IUCLC", 37, TTY_OP_BOOL },
122 { "IXON", 38, TTY_OP_BOOL },
123 { "IXANY", 39, TTY_OP_BOOL },
124 { "IXOFF", 40, TTY_OP_BOOL },
125 { "IMAXBEL", 41, TTY_OP_BOOL },
126 { "ISIG", 50, TTY_OP_BOOL },
127 { "ICANON", 51, TTY_OP_BOOL },
128 { "XCASE", 52, TTY_OP_BOOL },
129 { "ECHO", 53, TTY_OP_BOOL },
130 { "ECHOE", 54, TTY_OP_BOOL },
131 { "ECHOK", 55, TTY_OP_BOOL },
132 { "ECHONL", 56, TTY_OP_BOOL },
133 { "NOFLSH", 57, TTY_OP_BOOL },
134 { "TOSTOP", 58, TTY_OP_BOOL },
135 { "IEXTEN", 59, TTY_OP_BOOL },
136 { "ECHOCTL", 60, TTY_OP_BOOL },
137 { "ECHOKE", 61, TTY_OP_BOOL },
138 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
139 { "OPOST", 70, TTY_OP_BOOL },
140 { "OLCUC", 71, TTY_OP_BOOL },
141 { "ONLCR", 72, TTY_OP_BOOL },
142 { "OCRNL", 73, TTY_OP_BOOL },
143 { "ONOCR", 74, TTY_OP_BOOL },
144 { "ONLRET", 75, TTY_OP_BOOL },
145 { "CS7", 90, TTY_OP_BOOL },
146 { "CS8", 91, TTY_OP_BOOL },
147 { "PARENB", 92, TTY_OP_BOOL },
148 { "PARODD", 93, TTY_OP_BOOL }
151 /* Miscellaneous other tty-related constants. */
152 #define SSH_TTY_OP_END 0
153 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
154 #define SSH1_TTY_OP_ISPEED 192
155 #define SSH1_TTY_OP_OSPEED 193
156 #define SSH2_TTY_OP_ISPEED 128
157 #define SSH2_TTY_OP_OSPEED 129
159 /* Helper functions for parsing tty-related config. */
160 static unsigned int ssh_tty_parse_specchar(char *s)
165 ret = ctrlparse(s, &next);
166 if (!next) ret = s[0];
168 ret = 255; /* special value meaning "don't set" */
172 static unsigned int ssh_tty_parse_boolean(char *s)
174 if (stricmp(s, "yes") == 0 ||
175 stricmp(s, "on") == 0 ||
176 stricmp(s, "true") == 0 ||
177 stricmp(s, "+") == 0)
179 else if (stricmp(s, "no") == 0 ||
180 stricmp(s, "off") == 0 ||
181 stricmp(s, "false") == 0 ||
182 stricmp(s, "-") == 0)
183 return 0; /* false */
185 return (atoi(s) != 0);
188 #define translate(x) if (type == x) return #x
189 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
190 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
191 static char *ssh1_pkt_type(int type)
193 translate(SSH1_MSG_DISCONNECT);
194 translate(SSH1_SMSG_PUBLIC_KEY);
195 translate(SSH1_CMSG_SESSION_KEY);
196 translate(SSH1_CMSG_USER);
197 translate(SSH1_CMSG_AUTH_RSA);
198 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
199 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
200 translate(SSH1_CMSG_AUTH_PASSWORD);
201 translate(SSH1_CMSG_REQUEST_PTY);
202 translate(SSH1_CMSG_WINDOW_SIZE);
203 translate(SSH1_CMSG_EXEC_SHELL);
204 translate(SSH1_CMSG_EXEC_CMD);
205 translate(SSH1_SMSG_SUCCESS);
206 translate(SSH1_SMSG_FAILURE);
207 translate(SSH1_CMSG_STDIN_DATA);
208 translate(SSH1_SMSG_STDOUT_DATA);
209 translate(SSH1_SMSG_STDERR_DATA);
210 translate(SSH1_CMSG_EOF);
211 translate(SSH1_SMSG_EXIT_STATUS);
212 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
213 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
214 translate(SSH1_MSG_CHANNEL_DATA);
215 translate(SSH1_MSG_CHANNEL_CLOSE);
216 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
217 translate(SSH1_SMSG_X11_OPEN);
218 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
219 translate(SSH1_MSG_PORT_OPEN);
220 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
221 translate(SSH1_SMSG_AGENT_OPEN);
222 translate(SSH1_MSG_IGNORE);
223 translate(SSH1_CMSG_EXIT_CONFIRMATION);
224 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
225 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
226 translate(SSH1_MSG_DEBUG);
227 translate(SSH1_CMSG_REQUEST_COMPRESSION);
228 translate(SSH1_CMSG_AUTH_TIS);
229 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
230 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
231 translate(SSH1_CMSG_AUTH_CCARD);
232 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
233 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
236 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
238 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
239 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
240 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
241 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
242 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
243 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
244 translate(SSH2_MSG_DISCONNECT);
245 translate(SSH2_MSG_IGNORE);
246 translate(SSH2_MSG_UNIMPLEMENTED);
247 translate(SSH2_MSG_DEBUG);
248 translate(SSH2_MSG_SERVICE_REQUEST);
249 translate(SSH2_MSG_SERVICE_ACCEPT);
250 translate(SSH2_MSG_KEXINIT);
251 translate(SSH2_MSG_NEWKEYS);
252 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
253 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
254 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD, SSH2_PKTCTX_DHGEX);
255 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
256 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
257 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
258 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
259 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
260 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
261 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
262 translate(SSH2_MSG_USERAUTH_REQUEST);
263 translate(SSH2_MSG_USERAUTH_FAILURE);
264 translate(SSH2_MSG_USERAUTH_SUCCESS);
265 translate(SSH2_MSG_USERAUTH_BANNER);
266 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
267 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
268 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
269 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
270 translate(SSH2_MSG_GLOBAL_REQUEST);
271 translate(SSH2_MSG_REQUEST_SUCCESS);
272 translate(SSH2_MSG_REQUEST_FAILURE);
273 translate(SSH2_MSG_CHANNEL_OPEN);
274 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
275 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
276 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
277 translate(SSH2_MSG_CHANNEL_DATA);
278 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
279 translate(SSH2_MSG_CHANNEL_EOF);
280 translate(SSH2_MSG_CHANNEL_CLOSE);
281 translate(SSH2_MSG_CHANNEL_REQUEST);
282 translate(SSH2_MSG_CHANNEL_SUCCESS);
283 translate(SSH2_MSG_CHANNEL_FAILURE);
289 /* Enumeration values for fields in SSH-1 packets */
291 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
295 * Coroutine mechanics for the sillier bits of the code. If these
296 * macros look impenetrable to you, you might find it helpful to
299 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
301 * which explains the theory behind these macros.
303 * In particular, if you are getting `case expression not constant'
304 * errors when building with MS Visual Studio, this is because MS's
305 * Edit and Continue debugging feature causes their compiler to
306 * violate ANSI C. To disable Edit and Continue debugging:
308 * - right-click ssh.c in the FileView
310 * - select the C/C++ tab and the General category
311 * - under `Debug info:', select anything _other_ than `Program
312 * Database for Edit and Continue'.
314 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
315 #define crBeginState crBegin(s->crLine)
316 #define crStateP(t, v) \
318 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
320 #define crState(t) crStateP(t, ssh->t)
321 #define crFinish(z) } *crLine = 0; return (z); }
322 #define crFinishV } *crLine = 0; return; }
323 #define crFinishFree(z) } sfree(s); return (z); }
324 #define crFinishFreeV } sfree(s); return; }
325 #define crReturn(z) \
327 *crLine =__LINE__; return (z); case __LINE__:;\
331 *crLine=__LINE__; return; case __LINE__:;\
333 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
334 #define crStopV do{ *crLine = 0; return; }while(0)
335 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
336 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
340 static struct Packet *ssh1_pkt_init(int pkt_type);
341 static struct Packet *ssh2_pkt_init(int pkt_type);
342 static void ssh_pkt_ensure(struct Packet *, int length);
343 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
344 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
345 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
346 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
347 static void ssh_pkt_addstring_start(struct Packet *);
348 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
349 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
350 static void ssh_pkt_addstring(struct Packet *, const char *data);
351 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
352 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
353 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
354 static int ssh2_pkt_construct(Ssh, struct Packet *);
355 static void ssh2_pkt_send(Ssh, struct Packet *);
356 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
357 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
358 struct Packet *pktin);
359 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
360 struct Packet *pktin);
361 static void ssh2_channel_check_close(struct ssh_channel *c);
362 static void ssh_channel_destroy(struct ssh_channel *c);
365 * Buffer management constants. There are several of these for
366 * various different purposes:
368 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
369 * on a local data stream before we throttle the whole SSH
370 * connection (in SSH-1 only). Throttling the whole connection is
371 * pretty drastic so we set this high in the hope it won't
374 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
375 * on the SSH connection itself before we defensively throttle
376 * _all_ local data streams. This is pretty drastic too (though
377 * thankfully unlikely in SSH-2 since the window mechanism should
378 * ensure that the server never has any need to throttle its end
379 * of the connection), so we set this high as well.
381 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
384 * - OUR_V2_BIGWIN is the window size we advertise for the only
385 * channel in a simple connection. It must be <= INT_MAX.
387 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
388 * to the remote side. This actually has nothing to do with the
389 * size of the _packet_, but is instead a limit on the amount
390 * of data we're willing to receive in a single SSH2 channel
393 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
394 * _packet_ we're prepared to cope with. It must be a multiple
395 * of the cipher block size, and must be at least 35000.
398 #define SSH1_BUFFER_LIMIT 32768
399 #define SSH_MAX_BACKLOG 32768
400 #define OUR_V2_WINSIZE 16384
401 #define OUR_V2_BIGWIN 0x7fffffff
402 #define OUR_V2_MAXPKT 0x4000UL
403 #define OUR_V2_PACKETLIMIT 0x9000UL
405 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
407 const static struct ssh_mac *macs[] = {
408 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
410 const static struct ssh_mac *buggymacs[] = {
411 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
414 static void *ssh_comp_none_init(void)
418 static void ssh_comp_none_cleanup(void *handle)
421 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
422 unsigned char **outblock, int *outlen)
426 static int ssh_comp_none_disable(void *handle)
430 const static struct ssh_compress ssh_comp_none = {
432 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
433 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
434 ssh_comp_none_disable, NULL
436 extern const struct ssh_compress ssh_zlib;
437 const static struct ssh_compress *compressions[] = {
438 &ssh_zlib, &ssh_comp_none
441 enum { /* channel types */
446 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
448 * CHAN_SHARING indicates a channel which is tracked here on
449 * behalf of a connection-sharing downstream. We do almost nothing
450 * with these channels ourselves: all messages relating to them
451 * get thrown straight to sshshare.c and passed on almost
452 * unmodified to downstream.
456 * CHAN_ZOMBIE is used to indicate a channel for which we've
457 * already destroyed the local data source: for instance, if a
458 * forwarded port experiences a socket error on the local side, we
459 * immediately destroy its local socket and turn the SSH channel
465 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
466 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
467 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
470 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
473 struct outstanding_channel_request {
474 cchandler_fn_t handler;
476 struct outstanding_channel_request *next;
480 * 2-3-4 tree storing channels.
483 Ssh ssh; /* pointer back to main context */
484 unsigned remoteid, localid;
486 /* True if we opened this channel but server hasn't confirmed. */
489 * In SSH-1, this value contains four bits:
491 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
492 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
493 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
494 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
496 * A channel is completely finished with when all four bits are set.
498 * In SSH-2, the four bits mean:
500 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
501 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
502 * 4 We have received SSH2_MSG_CHANNEL_EOF.
503 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
505 * A channel is completely finished with when we have both sent
506 * and received CLOSE.
508 * The symbolic constants below use the SSH-2 terminology, which
509 * is a bit confusing in SSH-1, but we have to use _something_.
511 #define CLOSES_SENT_EOF 1
512 #define CLOSES_SENT_CLOSE 2
513 #define CLOSES_RCVD_EOF 4
514 #define CLOSES_RCVD_CLOSE 8
518 * This flag indicates that an EOF is pending on the outgoing side
519 * of the channel: that is, wherever we're getting the data for
520 * this channel has sent us some data followed by EOF. We can't
521 * actually send the EOF until we've finished sending the data, so
522 * we set this flag instead to remind us to do so once our buffer
528 * True if this channel is causing the underlying connection to be
533 struct ssh2_data_channel {
535 unsigned remwindow, remmaxpkt;
536 /* locwindow is signed so we can cope with excess data. */
537 int locwindow, locmaxwin;
539 * remlocwin is the amount of local window that we think
540 * the remote end had available to it after it sent the
541 * last data packet or window adjust ack.
545 * These store the list of channel requests that haven't
548 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
549 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
553 struct ssh_agent_channel {
554 unsigned char *message;
555 unsigned char msglen[4];
556 unsigned lensofar, totallen;
557 int outstanding_requests;
559 struct ssh_x11_channel {
560 struct X11Connection *xconn;
563 struct ssh_pfd_channel {
564 struct PortForwarding *pf;
566 struct ssh_sharing_channel {
573 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
574 * use this structure in different ways, reflecting SSH-2's
575 * altogether saner approach to port forwarding.
577 * In SSH-1, you arrange a remote forwarding by sending the server
578 * the remote port number, and the local destination host:port.
579 * When a connection comes in, the server sends you back that
580 * host:port pair, and you connect to it. This is a ready-made
581 * security hole if you're not on the ball: a malicious server
582 * could send you back _any_ host:port pair, so if you trustingly
583 * connect to the address it gives you then you've just opened the
584 * entire inside of your corporate network just by connecting
585 * through it to a dodgy SSH server. Hence, we must store a list of
586 * host:port pairs we _are_ trying to forward to, and reject a
587 * connection request from the server if it's not in the list.
589 * In SSH-2, each side of the connection minds its own business and
590 * doesn't send unnecessary information to the other. You arrange a
591 * remote forwarding by sending the server just the remote port
592 * number. When a connection comes in, the server tells you which
593 * of its ports was connected to; and _you_ have to remember what
594 * local host:port pair went with that port number.
596 * Hence, in SSH-1 this structure is indexed by destination
597 * host:port pair, whereas in SSH-2 it is indexed by source port.
599 struct ssh_portfwd; /* forward declaration */
601 struct ssh_rportfwd {
602 unsigned sport, dport;
606 struct ssh_portfwd *pfrec;
609 static void free_rportfwd(struct ssh_rportfwd *pf)
612 sfree(pf->sportdesc);
620 * Separately to the rportfwd tree (which is for looking up port
621 * open requests from the server), a tree of _these_ structures is
622 * used to keep track of all the currently open port forwardings,
623 * so that we can reconfigure in mid-session if the user requests
627 enum { DESTROY, KEEP, CREATE } status;
629 unsigned sport, dport;
632 struct ssh_rportfwd *remote;
634 struct PortListener *local;
636 #define free_portfwd(pf) ( \
637 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
638 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
641 long length; /* length of packet: see below */
642 long forcepad; /* SSH-2: force padding to at least this length */
643 int type; /* only used for incoming packets */
644 unsigned long sequence; /* SSH-2 incoming sequence number */
645 unsigned char *data; /* allocated storage */
646 unsigned char *body; /* offset of payload within `data' */
647 long savedpos; /* dual-purpose saved packet position: see below */
648 long maxlen; /* amount of storage allocated for `data' */
649 long encrypted_len; /* for SSH-2 total-size counting */
652 * A note on the 'length' and 'savedpos' fields above.
654 * Incoming packets are set up so that pkt->length is measured
655 * relative to pkt->body, which itself points to a few bytes after
656 * pkt->data (skipping some uninteresting header fields including
657 * the packet type code). The ssh_pkt_get* functions all expect
658 * this setup, and they also use pkt->savedpos to indicate how far
659 * through the packet being decoded they've got - and that, too,
660 * is an offset from pkt->body rather than pkt->data.
662 * During construction of an outgoing packet, however, pkt->length
663 * is measured relative to the base pointer pkt->data, and
664 * pkt->body is not really used for anything until the packet is
665 * ready for sending. In this mode, pkt->savedpos is reused as a
666 * temporary variable by the addstring functions, which write out
667 * a string length field and then keep going back and updating it
668 * as more data is appended to the subsequent string data field;
669 * pkt->savedpos stores the offset (again relative to pkt->data)
670 * of the start of the string data field.
673 /* Extra metadata used in SSH packet logging mode, allowing us to
674 * log in the packet header line that the packet came from a
675 * connection-sharing downstream and what if anything unusual was
676 * done to it. The additional_log_text field is expected to be a
677 * static string - it will not be freed. */
678 unsigned downstream_id;
679 const char *additional_log_text;
682 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
683 struct Packet *pktin);
684 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
685 struct Packet *pktin);
686 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
687 struct Packet *pktin);
688 static void ssh1_protocol_setup(Ssh ssh);
689 static void ssh2_protocol_setup(Ssh ssh);
690 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
691 static void ssh_size(void *handle, int width, int height);
692 static void ssh_special(void *handle, Telnet_Special);
693 static int ssh2_try_send(struct ssh_channel *c);
694 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
695 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
696 static void ssh2_set_window(struct ssh_channel *c, int newwin);
697 static int ssh_sendbuffer(void *handle);
698 static int ssh_do_close(Ssh ssh, int notify_exit);
699 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
700 static int ssh2_pkt_getbool(struct Packet *pkt);
701 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
702 static void ssh2_timer(void *ctx, unsigned long now);
703 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
704 struct Packet *pktin);
705 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
707 struct rdpkt1_state_tag {
708 long len, pad, biglen, to_read;
709 unsigned long realcrc, gotcrc;
713 struct Packet *pktin;
716 struct rdpkt2_state_tag {
717 long len, pad, payload, packetlen, maclen;
720 unsigned long incoming_sequence;
721 struct Packet *pktin;
724 struct rdpkt2_bare_state_tag {
728 unsigned long incoming_sequence;
729 struct Packet *pktin;
732 struct queued_handler;
733 struct queued_handler {
735 chandler_fn_t handler;
737 struct queued_handler *next;
741 const struct plug_function_table *fn;
742 /* the above field _must_ be first in the structure */
752 unsigned char session_key[32];
754 int v1_remote_protoflags;
755 int v1_local_protoflags;
756 int agentfwd_enabled;
759 const struct ssh_cipher *cipher;
762 const struct ssh2_cipher *cscipher, *sccipher;
763 void *cs_cipher_ctx, *sc_cipher_ctx;
764 const struct ssh_mac *csmac, *scmac;
765 void *cs_mac_ctx, *sc_mac_ctx;
766 const struct ssh_compress *cscomp, *sccomp;
767 void *cs_comp_ctx, *sc_comp_ctx;
768 const struct ssh_kex *kex;
769 const struct ssh_signkey *hostkey;
770 char *hostkey_str; /* string representation, for easy checking in rekeys */
771 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
772 int v2_session_id_len;
776 int attempting_connshare;
782 int echoing, editing;
786 int ospeed, ispeed; /* temporaries */
787 int term_width, term_height;
789 tree234 *channels; /* indexed by local id */
790 struct ssh_channel *mainchan; /* primary session channel */
791 int ncmode; /* is primary channel direct-tcpip? */
796 tree234 *rportfwds, *portfwds;
800 SSH_STATE_BEFORE_SIZE,
806 int size_needed, eof_needed;
807 int sent_console_eof;
808 int got_pty; /* affects EOF behaviour on main channel */
810 struct Packet **queue;
811 int queuelen, queuesize;
813 unsigned char *deferred_send_data;
814 int deferred_len, deferred_size;
817 * Gross hack: pscp will try to start SFTP but fall back to
818 * scp1 if that fails. This variable is the means by which
819 * scp.c can reach into the SSH code and find out which one it
824 bufchain banner; /* accumulates banners during do_ssh2_authconn */
829 struct X11Display *x11disp;
830 struct X11FakeAuth *x11auth;
831 tree234 *x11authtree;
834 int conn_throttle_count;
837 int v1_stdout_throttling;
838 unsigned long v2_outgoing_sequence;
840 int ssh1_rdpkt_crstate;
841 int ssh2_rdpkt_crstate;
842 int ssh2_bare_rdpkt_crstate;
843 int ssh_gotdata_crstate;
844 int do_ssh1_connection_crstate;
846 void *do_ssh_init_state;
847 void *do_ssh1_login_state;
848 void *do_ssh2_transport_state;
849 void *do_ssh2_authconn_state;
850 void *do_ssh_connection_init_state;
852 struct rdpkt1_state_tag rdpkt1_state;
853 struct rdpkt2_state_tag rdpkt2_state;
854 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
856 /* SSH-1 and SSH-2 use this for different things, but both use it */
857 int protocol_initial_phase_done;
859 void (*protocol) (Ssh ssh, void *vin, int inlen,
861 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
862 int (*do_ssh_init)(Ssh ssh, unsigned char c);
865 * We maintain our own copy of a Conf structure here. That way,
866 * when we're passed a new one for reconfiguration, we can check
867 * the differences and potentially reconfigure port forwardings
868 * etc in mid-session.
873 * Values cached out of conf so as to avoid the tree234 lookup
874 * cost every time they're used.
879 * Dynamically allocated username string created during SSH
880 * login. Stored in here rather than in the coroutine state so
881 * that it'll be reliably freed if we shut down the SSH session
882 * at some unexpected moment.
887 * Used to transfer data back from async callbacks.
889 void *agent_response;
890 int agent_response_len;
894 * The SSH connection can be set as `frozen', meaning we are
895 * not currently accepting incoming data from the network. This
896 * is slightly more serious than setting the _socket_ as
897 * frozen, because we may already have had data passed to us
898 * from the network which we need to delay processing until
899 * after the freeze is lifted, so we also need a bufchain to
903 bufchain queued_incoming_data;
906 * Dispatch table for packet types that we may have to deal
909 handler_fn_t packet_dispatch[256];
912 * Queues of one-off handler functions for success/failure
913 * indications from a request.
915 struct queued_handler *qhead, *qtail;
916 handler_fn_t q_saved_handler1, q_saved_handler2;
919 * This module deals with sending keepalives.
924 * Track incoming and outgoing data sizes and time, for
927 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
928 unsigned long max_data_size;
930 unsigned long next_rekey, last_rekey;
931 char *deferred_rekey_reason; /* points to STATIC string; don't free */
934 * Fully qualified host name, which we need if doing GSSAPI.
940 * GSSAPI libraries for this session.
942 struct ssh_gss_liblist *gsslibs;
946 #define logevent(s) logevent(ssh->frontend, s)
948 /* logevent, only printf-formatted. */
949 static void logeventf(Ssh ssh, const char *fmt, ...)
955 buf = dupvprintf(fmt, ap);
961 static void bomb_out(Ssh ssh, char *text)
963 ssh_do_close(ssh, FALSE);
965 connection_fatal(ssh->frontend, "%s", text);
969 #define bombout(msg) bomb_out(ssh, dupprintf msg)
971 /* Helper function for common bits of parsing ttymodes. */
972 static void parse_ttymodes(Ssh ssh,
973 void (*do_mode)(void *data, char *mode, char *val),
978 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
980 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
982 * val[0] is either 'V', indicating that an explicit value
983 * follows it, or 'A' indicating that we should pass the
984 * value through from the local environment via get_ttymode.
987 val = get_ttymode(ssh->frontend, key);
989 do_mode(data, key, val);
993 do_mode(data, key, val + 1); /* skip the 'V' */
997 static int ssh_channelcmp(void *av, void *bv)
999 struct ssh_channel *a = (struct ssh_channel *) av;
1000 struct ssh_channel *b = (struct ssh_channel *) bv;
1001 if (a->localid < b->localid)
1003 if (a->localid > b->localid)
1007 static int ssh_channelfind(void *av, void *bv)
1009 unsigned *a = (unsigned *) av;
1010 struct ssh_channel *b = (struct ssh_channel *) bv;
1011 if (*a < b->localid)
1013 if (*a > b->localid)
1018 static int ssh_rportcmp_ssh1(void *av, void *bv)
1020 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1021 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1023 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1024 return i < 0 ? -1 : +1;
1025 if (a->dport > b->dport)
1027 if (a->dport < b->dport)
1032 static int ssh_rportcmp_ssh2(void *av, void *bv)
1034 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1035 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1037 if ( (i = strcmp(a->shost, b->shost)) != 0)
1038 return i < 0 ? -1 : +1;
1039 if (a->sport > b->sport)
1041 if (a->sport < b->sport)
1047 * Special form of strcmp which can cope with NULL inputs. NULL is
1048 * defined to sort before even the empty string.
1050 static int nullstrcmp(const char *a, const char *b)
1052 if (a == NULL && b == NULL)
1058 return strcmp(a, b);
1061 static int ssh_portcmp(void *av, void *bv)
1063 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1064 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1066 if (a->type > b->type)
1068 if (a->type < b->type)
1070 if (a->addressfamily > b->addressfamily)
1072 if (a->addressfamily < b->addressfamily)
1074 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1075 return i < 0 ? -1 : +1;
1076 if (a->sport > b->sport)
1078 if (a->sport < b->sport)
1080 if (a->type != 'D') {
1081 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1082 return i < 0 ? -1 : +1;
1083 if (a->dport > b->dport)
1085 if (a->dport < b->dport)
1091 static int alloc_channel_id(Ssh ssh)
1093 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1094 unsigned low, high, mid;
1096 struct ssh_channel *c;
1099 * First-fit allocation of channel numbers: always pick the
1100 * lowest unused one. To do this, binary-search using the
1101 * counted B-tree to find the largest channel ID which is in a
1102 * contiguous sequence from the beginning. (Precisely
1103 * everything in that sequence must have ID equal to its tree
1104 * index plus CHANNEL_NUMBER_OFFSET.)
1106 tsize = count234(ssh->channels);
1110 while (high - low > 1) {
1111 mid = (high + low) / 2;
1112 c = index234(ssh->channels, mid);
1113 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1114 low = mid; /* this one is fine */
1116 high = mid; /* this one is past it */
1119 * Now low points to either -1, or the tree index of the
1120 * largest ID in the initial sequence.
1123 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1124 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1126 return low + 1 + CHANNEL_NUMBER_OFFSET;
1129 static void c_write_stderr(int trusted, const char *buf, int len)
1132 for (i = 0; i < len; i++)
1133 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1134 fputc(buf[i], stderr);
1137 static void c_write(Ssh ssh, const char *buf, int len)
1139 if (flags & FLAG_STDERR)
1140 c_write_stderr(1, buf, len);
1142 from_backend(ssh->frontend, 1, buf, len);
1145 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1147 if (flags & FLAG_STDERR)
1148 c_write_stderr(0, buf, len);
1150 from_backend_untrusted(ssh->frontend, buf, len);
1153 static void c_write_str(Ssh ssh, const char *buf)
1155 c_write(ssh, buf, strlen(buf));
1158 static void ssh_free_packet(struct Packet *pkt)
1163 static struct Packet *ssh_new_packet(void)
1165 struct Packet *pkt = snew(struct Packet);
1167 pkt->body = pkt->data = NULL;
1173 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1176 struct logblank_t blanks[4];
1182 if (ssh->logomitdata &&
1183 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1184 pkt->type == SSH1_SMSG_STDERR_DATA ||
1185 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1186 /* "Session data" packets - omit the data string. */
1187 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1188 ssh_pkt_getuint32(pkt); /* skip channel id */
1189 blanks[nblanks].offset = pkt->savedpos + 4;
1190 blanks[nblanks].type = PKTLOG_OMIT;
1191 ssh_pkt_getstring(pkt, &str, &slen);
1193 blanks[nblanks].len = slen;
1197 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1198 ssh1_pkt_type(pkt->type),
1199 pkt->body, pkt->length, nblanks, blanks, NULL,
1203 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1206 struct logblank_t blanks[4];
1211 * For outgoing packets, pkt->length represents the length of the
1212 * whole packet starting at pkt->data (including some header), and
1213 * pkt->body refers to the point within that where the log-worthy
1214 * payload begins. However, incoming packets expect pkt->length to
1215 * represent only the payload length (that is, it's measured from
1216 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1217 * packet to conform to the incoming-packet semantics, so that we
1218 * can analyse it with the ssh_pkt_get functions.
1220 pkt->length -= (pkt->body - pkt->data);
1223 if (ssh->logomitdata &&
1224 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1225 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1226 /* "Session data" packets - omit the data string. */
1227 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1228 ssh_pkt_getuint32(pkt); /* skip channel id */
1229 blanks[nblanks].offset = pkt->savedpos + 4;
1230 blanks[nblanks].type = PKTLOG_OMIT;
1231 ssh_pkt_getstring(pkt, &str, &slen);
1233 blanks[nblanks].len = slen;
1238 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1239 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1240 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1241 conf_get_int(ssh->conf, CONF_logomitpass)) {
1242 /* If this is a password or similar packet, blank the password(s). */
1243 blanks[nblanks].offset = 0;
1244 blanks[nblanks].len = pkt->length;
1245 blanks[nblanks].type = PKTLOG_BLANK;
1247 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1248 conf_get_int(ssh->conf, CONF_logomitpass)) {
1250 * If this is an X forwarding request packet, blank the fake
1253 * Note that while we blank the X authentication data here, we
1254 * don't take any special action to blank the start of an X11
1255 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1256 * an X connection without having session blanking enabled is
1257 * likely to leak your cookie into the log.
1260 ssh_pkt_getstring(pkt, &str, &slen);
1261 blanks[nblanks].offset = pkt->savedpos;
1262 blanks[nblanks].type = PKTLOG_BLANK;
1263 ssh_pkt_getstring(pkt, &str, &slen);
1265 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1270 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1271 ssh1_pkt_type(pkt->data[12]),
1272 pkt->body, pkt->length,
1273 nblanks, blanks, NULL, 0, NULL);
1276 * Undo the above adjustment of pkt->length, to put the packet
1277 * back in the state we found it.
1279 pkt->length += (pkt->body - pkt->data);
1283 * Collect incoming data in the incoming packet buffer.
1284 * Decipher and verify the packet when it is completely read.
1285 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1286 * Update the *data and *datalen variables.
1287 * Return a Packet structure when a packet is completed.
1289 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1291 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1293 crBegin(ssh->ssh1_rdpkt_crstate);
1295 st->pktin = ssh_new_packet();
1297 st->pktin->type = 0;
1298 st->pktin->length = 0;
1300 for (st->i = st->len = 0; st->i < 4; st->i++) {
1301 while ((*datalen) == 0)
1303 st->len = (st->len << 8) + **data;
1304 (*data)++, (*datalen)--;
1307 st->pad = 8 - (st->len % 8);
1308 st->biglen = st->len + st->pad;
1309 st->pktin->length = st->len - 5;
1311 if (st->biglen < 0) {
1312 bombout(("Extremely large packet length from server suggests"
1313 " data stream corruption"));
1314 ssh_free_packet(st->pktin);
1318 st->pktin->maxlen = st->biglen;
1319 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1321 st->to_read = st->biglen;
1322 st->p = st->pktin->data;
1323 while (st->to_read > 0) {
1324 st->chunk = st->to_read;
1325 while ((*datalen) == 0)
1327 if (st->chunk > (*datalen))
1328 st->chunk = (*datalen);
1329 memcpy(st->p, *data, st->chunk);
1331 *datalen -= st->chunk;
1333 st->to_read -= st->chunk;
1336 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1337 st->biglen, NULL)) {
1338 bombout(("Network attack (CRC compensation) detected!"));
1339 ssh_free_packet(st->pktin);
1344 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1346 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1347 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1348 if (st->gotcrc != st->realcrc) {
1349 bombout(("Incorrect CRC received on packet"));
1350 ssh_free_packet(st->pktin);
1354 st->pktin->body = st->pktin->data + st->pad + 1;
1356 if (ssh->v1_compressing) {
1357 unsigned char *decompblk;
1359 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1360 st->pktin->body - 1, st->pktin->length + 1,
1361 &decompblk, &decomplen)) {
1362 bombout(("Zlib decompression encountered invalid data"));
1363 ssh_free_packet(st->pktin);
1367 if (st->pktin->maxlen < st->pad + decomplen) {
1368 st->pktin->maxlen = st->pad + decomplen;
1369 st->pktin->data = sresize(st->pktin->data,
1370 st->pktin->maxlen + APIEXTRA,
1372 st->pktin->body = st->pktin->data + st->pad + 1;
1375 memcpy(st->pktin->body - 1, decompblk, decomplen);
1377 st->pktin->length = decomplen - 1;
1380 st->pktin->type = st->pktin->body[-1];
1383 * Now pktin->body and pktin->length identify the semantic content
1384 * of the packet, excluding the initial type byte.
1388 ssh1_log_incoming_packet(ssh, st->pktin);
1390 st->pktin->savedpos = 0;
1392 crFinish(st->pktin);
1395 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1398 struct logblank_t blanks[4];
1404 if (ssh->logomitdata &&
1405 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1406 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1407 /* "Session data" packets - omit the data string. */
1408 ssh_pkt_getuint32(pkt); /* skip channel id */
1409 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1410 ssh_pkt_getuint32(pkt); /* skip extended data type */
1411 blanks[nblanks].offset = pkt->savedpos + 4;
1412 blanks[nblanks].type = PKTLOG_OMIT;
1413 ssh_pkt_getstring(pkt, &str, &slen);
1415 blanks[nblanks].len = slen;
1420 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1421 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1422 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1426 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1429 struct logblank_t blanks[4];
1434 * For outgoing packets, pkt->length represents the length of the
1435 * whole packet starting at pkt->data (including some header), and
1436 * pkt->body refers to the point within that where the log-worthy
1437 * payload begins. However, incoming packets expect pkt->length to
1438 * represent only the payload length (that is, it's measured from
1439 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1440 * packet to conform to the incoming-packet semantics, so that we
1441 * can analyse it with the ssh_pkt_get functions.
1443 pkt->length -= (pkt->body - pkt->data);
1446 if (ssh->logomitdata &&
1447 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1448 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1449 /* "Session data" packets - omit the data string. */
1450 ssh_pkt_getuint32(pkt); /* skip channel id */
1451 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1452 ssh_pkt_getuint32(pkt); /* skip extended data type */
1453 blanks[nblanks].offset = pkt->savedpos + 4;
1454 blanks[nblanks].type = PKTLOG_OMIT;
1455 ssh_pkt_getstring(pkt, &str, &slen);
1457 blanks[nblanks].len = slen;
1462 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1463 conf_get_int(ssh->conf, CONF_logomitpass)) {
1464 /* If this is a password packet, blank the password(s). */
1466 ssh_pkt_getstring(pkt, &str, &slen);
1467 ssh_pkt_getstring(pkt, &str, &slen);
1468 ssh_pkt_getstring(pkt, &str, &slen);
1469 if (slen == 8 && !memcmp(str, "password", 8)) {
1470 ssh2_pkt_getbool(pkt);
1471 /* Blank the password field. */
1472 blanks[nblanks].offset = pkt->savedpos;
1473 blanks[nblanks].type = PKTLOG_BLANK;
1474 ssh_pkt_getstring(pkt, &str, &slen);
1476 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1478 /* If there's another password field beyond it (change of
1479 * password), blank that too. */
1480 ssh_pkt_getstring(pkt, &str, &slen);
1482 blanks[nblanks-1].len =
1483 pkt->savedpos - blanks[nblanks].offset;
1486 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1487 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1488 conf_get_int(ssh->conf, CONF_logomitpass)) {
1489 /* If this is a keyboard-interactive response packet, blank
1492 ssh_pkt_getuint32(pkt);
1493 blanks[nblanks].offset = pkt->savedpos;
1494 blanks[nblanks].type = PKTLOG_BLANK;
1496 ssh_pkt_getstring(pkt, &str, &slen);
1500 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1502 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1503 conf_get_int(ssh->conf, CONF_logomitpass)) {
1505 * If this is an X forwarding request packet, blank the fake
1508 * Note that while we blank the X authentication data here, we
1509 * don't take any special action to blank the start of an X11
1510 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1511 * an X connection without having session blanking enabled is
1512 * likely to leak your cookie into the log.
1515 ssh_pkt_getuint32(pkt);
1516 ssh_pkt_getstring(pkt, &str, &slen);
1517 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1518 ssh2_pkt_getbool(pkt);
1519 ssh2_pkt_getbool(pkt);
1520 ssh_pkt_getstring(pkt, &str, &slen);
1521 blanks[nblanks].offset = pkt->savedpos;
1522 blanks[nblanks].type = PKTLOG_BLANK;
1523 ssh_pkt_getstring(pkt, &str, &slen);
1525 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1531 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1532 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1533 pkt->body, pkt->length, nblanks, blanks,
1534 &ssh->v2_outgoing_sequence,
1535 pkt->downstream_id, pkt->additional_log_text);
1538 * Undo the above adjustment of pkt->length, to put the packet
1539 * back in the state we found it.
1541 pkt->length += (pkt->body - pkt->data);
1544 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1546 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1548 crBegin(ssh->ssh2_rdpkt_crstate);
1550 st->pktin = ssh_new_packet();
1552 st->pktin->type = 0;
1553 st->pktin->length = 0;
1555 st->cipherblk = ssh->sccipher->blksize;
1558 if (st->cipherblk < 8)
1560 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1562 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1565 * When dealing with a CBC-mode cipher, we want to avoid the
1566 * possibility of an attacker's tweaking the ciphertext stream
1567 * so as to cause us to feed the same block to the block
1568 * cipher more than once and thus leak information
1569 * (VU#958563). The way we do this is not to take any
1570 * decisions on the basis of anything we've decrypted until
1571 * we've verified it with a MAC. That includes the packet
1572 * length, so we just read data and check the MAC repeatedly,
1573 * and when the MAC passes, see if the length we've got is
1577 /* May as well allocate the whole lot now. */
1578 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1581 /* Read an amount corresponding to the MAC. */
1582 for (st->i = 0; st->i < st->maclen; st->i++) {
1583 while ((*datalen) == 0)
1585 st->pktin->data[st->i] = *(*data)++;
1591 unsigned char seq[4];
1592 ssh->scmac->start(ssh->sc_mac_ctx);
1593 PUT_32BIT(seq, st->incoming_sequence);
1594 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1597 for (;;) { /* Once around this loop per cipher block. */
1598 /* Read another cipher-block's worth, and tack it onto the end. */
1599 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1600 while ((*datalen) == 0)
1602 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1605 /* Decrypt one more block (a little further back in the stream). */
1606 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1607 st->pktin->data + st->packetlen,
1609 /* Feed that block to the MAC. */
1610 ssh->scmac->bytes(ssh->sc_mac_ctx,
1611 st->pktin->data + st->packetlen, st->cipherblk);
1612 st->packetlen += st->cipherblk;
1613 /* See if that gives us a valid packet. */
1614 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1615 st->pktin->data + st->packetlen) &&
1616 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1619 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1620 bombout(("No valid incoming packet found"));
1621 ssh_free_packet(st->pktin);
1625 st->pktin->maxlen = st->packetlen + st->maclen;
1626 st->pktin->data = sresize(st->pktin->data,
1627 st->pktin->maxlen + APIEXTRA,
1630 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1633 * Acquire and decrypt the first block of the packet. This will
1634 * contain the length and padding details.
1636 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1637 while ((*datalen) == 0)
1639 st->pktin->data[st->i] = *(*data)++;
1644 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1645 st->pktin->data, st->cipherblk);
1648 * Now get the length figure.
1650 st->len = toint(GET_32BIT(st->pktin->data));
1653 * _Completely_ silly lengths should be stomped on before they
1654 * do us any more damage.
1656 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1657 (st->len + 4) % st->cipherblk != 0) {
1658 bombout(("Incoming packet was garbled on decryption"));
1659 ssh_free_packet(st->pktin);
1664 * So now we can work out the total packet length.
1666 st->packetlen = st->len + 4;
1669 * Allocate memory for the rest of the packet.
1671 st->pktin->maxlen = st->packetlen + st->maclen;
1672 st->pktin->data = sresize(st->pktin->data,
1673 st->pktin->maxlen + APIEXTRA,
1677 * Read and decrypt the remainder of the packet.
1679 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1681 while ((*datalen) == 0)
1683 st->pktin->data[st->i] = *(*data)++;
1686 /* Decrypt everything _except_ the MAC. */
1688 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1689 st->pktin->data + st->cipherblk,
1690 st->packetlen - st->cipherblk);
1696 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1697 st->len + 4, st->incoming_sequence)) {
1698 bombout(("Incorrect MAC received on packet"));
1699 ssh_free_packet(st->pktin);
1703 /* Get and sanity-check the amount of random padding. */
1704 st->pad = st->pktin->data[4];
1705 if (st->pad < 4 || st->len - st->pad < 1) {
1706 bombout(("Invalid padding length on received packet"));
1707 ssh_free_packet(st->pktin);
1711 * This enables us to deduce the payload length.
1713 st->payload = st->len - st->pad - 1;
1715 st->pktin->length = st->payload + 5;
1716 st->pktin->encrypted_len = st->packetlen;
1718 st->pktin->sequence = st->incoming_sequence++;
1720 st->pktin->length = st->packetlen - st->pad;
1721 assert(st->pktin->length >= 0);
1724 * Decompress packet payload.
1727 unsigned char *newpayload;
1730 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1731 st->pktin->data + 5, st->pktin->length - 5,
1732 &newpayload, &newlen)) {
1733 if (st->pktin->maxlen < newlen + 5) {
1734 st->pktin->maxlen = newlen + 5;
1735 st->pktin->data = sresize(st->pktin->data,
1736 st->pktin->maxlen + APIEXTRA,
1739 st->pktin->length = 5 + newlen;
1740 memcpy(st->pktin->data + 5, newpayload, newlen);
1746 * pktin->body and pktin->length should identify the semantic
1747 * content of the packet, excluding the initial type byte.
1749 st->pktin->type = st->pktin->data[5];
1750 st->pktin->body = st->pktin->data + 6;
1751 st->pktin->length -= 6;
1752 assert(st->pktin->length >= 0); /* one last double-check */
1755 ssh2_log_incoming_packet(ssh, st->pktin);
1757 st->pktin->savedpos = 0;
1759 crFinish(st->pktin);
1762 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh, unsigned char **data,
1765 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1767 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1770 * Read the packet length field.
1772 for (st->i = 0; st->i < 4; st->i++) {
1773 while ((*datalen) == 0)
1775 st->length[st->i] = *(*data)++;
1779 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1780 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1781 bombout(("Invalid packet length received"));
1785 st->pktin = ssh_new_packet();
1786 st->pktin->data = snewn(st->packetlen, unsigned char);
1788 st->pktin->encrypted_len = st->packetlen;
1790 st->pktin->sequence = st->incoming_sequence++;
1793 * Read the remainder of the packet.
1795 for (st->i = 0; st->i < st->packetlen; st->i++) {
1796 while ((*datalen) == 0)
1798 st->pktin->data[st->i] = *(*data)++;
1803 * pktin->body and pktin->length should identify the semantic
1804 * content of the packet, excluding the initial type byte.
1806 st->pktin->type = st->pktin->data[0];
1807 st->pktin->body = st->pktin->data + 1;
1808 st->pktin->length = st->packetlen - 1;
1811 * Log incoming packet, possibly omitting sensitive fields.
1814 ssh2_log_incoming_packet(ssh, st->pktin);
1816 st->pktin->savedpos = 0;
1818 crFinish(st->pktin);
1821 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1823 int pad, biglen, i, pktoffs;
1827 * XXX various versions of SC (including 8.8.4) screw up the
1828 * register allocation in this function and use the same register
1829 * (D6) for len and as a temporary, with predictable results. The
1830 * following sledgehammer prevents this.
1837 ssh1_log_outgoing_packet(ssh, pkt);
1839 if (ssh->v1_compressing) {
1840 unsigned char *compblk;
1842 zlib_compress_block(ssh->cs_comp_ctx,
1843 pkt->data + 12, pkt->length - 12,
1844 &compblk, &complen);
1845 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1846 memcpy(pkt->data + 12, compblk, complen);
1848 pkt->length = complen + 12;
1851 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1853 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1854 pad = 8 - (len % 8);
1856 biglen = len + pad; /* len(padding+type+data+CRC) */
1858 for (i = pktoffs; i < 4+8; i++)
1859 pkt->data[i] = random_byte();
1860 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1861 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1862 PUT_32BIT(pkt->data + pktoffs, len);
1865 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1866 pkt->data + pktoffs + 4, biglen);
1868 if (offset_p) *offset_p = pktoffs;
1869 return biglen + 4; /* len(length+padding+type+data+CRC) */
1872 static int s_write(Ssh ssh, void *data, int len)
1875 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1876 0, NULL, NULL, 0, NULL);
1879 return sk_write(ssh->s, (char *)data, len);
1882 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1884 int len, backlog, offset;
1885 len = s_wrpkt_prepare(ssh, pkt, &offset);
1886 backlog = s_write(ssh, pkt->data + offset, len);
1887 if (backlog > SSH_MAX_BACKLOG)
1888 ssh_throttle_all(ssh, 1, backlog);
1889 ssh_free_packet(pkt);
1892 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1895 len = s_wrpkt_prepare(ssh, pkt, &offset);
1896 if (ssh->deferred_len + len > ssh->deferred_size) {
1897 ssh->deferred_size = ssh->deferred_len + len + 128;
1898 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1902 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1903 pkt->data + offset, len);
1904 ssh->deferred_len += len;
1905 ssh_free_packet(pkt);
1909 * Construct a SSH-1 packet with the specified contents.
1910 * (This all-at-once interface used to be the only one, but now SSH-1
1911 * packets can also be constructed incrementally.)
1913 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1919 pkt = ssh1_pkt_init(pkttype);
1921 while ((argtype = va_arg(ap, int)) != PKT_END) {
1922 unsigned char *argp, argchar;
1924 unsigned long argint;
1927 /* Actual fields in the packet */
1929 argint = va_arg(ap, int);
1930 ssh_pkt_adduint32(pkt, argint);
1933 argchar = (unsigned char) va_arg(ap, int);
1934 ssh_pkt_addbyte(pkt, argchar);
1937 argp = va_arg(ap, unsigned char *);
1938 arglen = va_arg(ap, int);
1939 ssh_pkt_adddata(pkt, argp, arglen);
1942 sargp = va_arg(ap, char *);
1943 ssh_pkt_addstring(pkt, sargp);
1946 bn = va_arg(ap, Bignum);
1947 ssh1_pkt_addmp(pkt, bn);
1955 static void send_packet(Ssh ssh, int pkttype, ...)
1959 va_start(ap, pkttype);
1960 pkt = construct_packet(ssh, pkttype, ap);
1965 static void defer_packet(Ssh ssh, int pkttype, ...)
1969 va_start(ap, pkttype);
1970 pkt = construct_packet(ssh, pkttype, ap);
1972 s_wrpkt_defer(ssh, pkt);
1975 static int ssh_versioncmp(char *a, char *b)
1978 unsigned long av, bv;
1980 av = strtoul(a, &ae, 10);
1981 bv = strtoul(b, &be, 10);
1983 return (av < bv ? -1 : +1);
1988 av = strtoul(ae, &ae, 10);
1989 bv = strtoul(be, &be, 10);
1991 return (av < bv ? -1 : +1);
1996 * Utility routines for putting an SSH-protocol `string' and
1997 * `uint32' into a hash state.
1999 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2001 unsigned char lenblk[4];
2002 PUT_32BIT(lenblk, len);
2003 h->bytes(s, lenblk, 4);
2004 h->bytes(s, str, len);
2007 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2009 unsigned char intblk[4];
2010 PUT_32BIT(intblk, i);
2011 h->bytes(s, intblk, 4);
2015 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2017 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2019 if (pkt->maxlen < length) {
2020 unsigned char *body = pkt->body;
2021 int offset = body ? body - pkt->data : 0;
2022 pkt->maxlen = length + 256;
2023 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2024 if (body) pkt->body = pkt->data + offset;
2027 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2030 ssh_pkt_ensure(pkt, pkt->length);
2031 memcpy(pkt->data + pkt->length - len, data, len);
2033 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2035 ssh_pkt_adddata(pkt, &byte, 1);
2037 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2039 ssh_pkt_adddata(pkt, &value, 1);
2041 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2044 PUT_32BIT(x, value);
2045 ssh_pkt_adddata(pkt, x, 4);
2047 static void ssh_pkt_addstring_start(struct Packet *pkt)
2049 ssh_pkt_adduint32(pkt, 0);
2050 pkt->savedpos = pkt->length;
2052 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2054 ssh_pkt_adddata(pkt, data, strlen(data));
2055 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2057 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2060 ssh_pkt_adddata(pkt, data, len);
2061 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2063 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2065 ssh_pkt_addstring_start(pkt);
2066 ssh_pkt_addstring_str(pkt, data);
2068 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2070 int len = ssh1_bignum_length(b);
2071 unsigned char *data = snewn(len, unsigned char);
2072 (void) ssh1_write_bignum(data, b);
2073 ssh_pkt_adddata(pkt, data, len);
2076 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2079 int i, n = (bignum_bitcount(b) + 7) / 8;
2080 p = snewn(n + 1, unsigned char);
2082 for (i = 1; i <= n; i++)
2083 p[i] = bignum_byte(b, n - i);
2085 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2087 memmove(p, p + i, n + 1 - i);
2091 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2095 p = ssh2_mpint_fmt(b, &len);
2096 ssh_pkt_addstring_start(pkt);
2097 ssh_pkt_addstring_data(pkt, (char *)p, len);
2101 static struct Packet *ssh1_pkt_init(int pkt_type)
2103 struct Packet *pkt = ssh_new_packet();
2104 pkt->length = 4 + 8; /* space for length + max padding */
2105 ssh_pkt_addbyte(pkt, pkt_type);
2106 pkt->body = pkt->data + pkt->length;
2107 pkt->type = pkt_type;
2108 pkt->downstream_id = 0;
2109 pkt->additional_log_text = NULL;
2113 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2114 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2115 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2116 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2117 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2118 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2119 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2120 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2121 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2123 static struct Packet *ssh2_pkt_init(int pkt_type)
2125 struct Packet *pkt = ssh_new_packet();
2126 pkt->length = 5; /* space for packet length + padding length */
2128 pkt->type = pkt_type;
2129 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2130 pkt->body = pkt->data + pkt->length; /* after packet type */
2131 pkt->downstream_id = 0;
2132 pkt->additional_log_text = NULL;
2137 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2138 * put the MAC on it. Final packet, ready to be sent, is stored in
2139 * pkt->data. Total length is returned.
2141 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2143 int cipherblk, maclen, padding, i;
2146 ssh2_log_outgoing_packet(ssh, pkt);
2148 if (ssh->bare_connection) {
2150 * Trivial packet construction for the bare connection
2153 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2154 pkt->body = pkt->data + 1;
2155 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2156 return pkt->length - 1;
2160 * Compress packet payload.
2163 unsigned char *newpayload;
2166 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2168 &newpayload, &newlen)) {
2170 ssh2_pkt_adddata(pkt, newpayload, newlen);
2176 * Add padding. At least four bytes, and must also bring total
2177 * length (minus MAC) up to a multiple of the block size.
2178 * If pkt->forcepad is set, make sure the packet is at least that size
2181 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2182 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2184 if (pkt->length + padding < pkt->forcepad)
2185 padding = pkt->forcepad - pkt->length;
2187 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
2188 assert(padding <= 255);
2189 maclen = ssh->csmac ? ssh->csmac->len : 0;
2190 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2191 pkt->data[4] = padding;
2192 for (i = 0; i < padding; i++)
2193 pkt->data[pkt->length + i] = random_byte();
2194 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2196 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2197 pkt->length + padding,
2198 ssh->v2_outgoing_sequence);
2199 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2202 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2203 pkt->data, pkt->length + padding);
2205 pkt->encrypted_len = pkt->length + padding;
2207 /* Ready-to-send packet starts at pkt->data. We return length. */
2208 pkt->body = pkt->data;
2209 return pkt->length + padding + maclen;
2213 * Routines called from the main SSH code to send packets. There
2214 * are quite a few of these, because we have two separate
2215 * mechanisms for delaying the sending of packets:
2217 * - In order to send an IGNORE message and a password message in
2218 * a single fixed-length blob, we require the ability to
2219 * concatenate the encrypted forms of those two packets _into_ a
2220 * single blob and then pass it to our <network.h> transport
2221 * layer in one go. Hence, there's a deferment mechanism which
2222 * works after packet encryption.
2224 * - In order to avoid sending any connection-layer messages
2225 * during repeat key exchange, we have to queue up any such
2226 * outgoing messages _before_ they are encrypted (and in
2227 * particular before they're allocated sequence numbers), and
2228 * then send them once we've finished.
2230 * I call these mechanisms `defer' and `queue' respectively, so as
2231 * to distinguish them reasonably easily.
2233 * The functions send_noqueue() and defer_noqueue() free the packet
2234 * structure they are passed. Every outgoing packet goes through
2235 * precisely one of these functions in its life; packets passed to
2236 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2237 * these or get queued, and then when the queue is later emptied
2238 * the packets are all passed to defer_noqueue().
2240 * When using a CBC-mode cipher, it's necessary to ensure that an
2241 * attacker can't provide data to be encrypted using an IV that they
2242 * know. We ensure this by prefixing each packet that might contain
2243 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2244 * mechanism, so in this case send_noqueue() ends up redirecting to
2245 * defer_noqueue(). If you don't like this inefficiency, don't use
2249 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2250 static void ssh_pkt_defersend(Ssh);
2253 * Send an SSH-2 packet immediately, without queuing or deferring.
2255 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2259 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2260 /* We need to send two packets, so use the deferral mechanism. */
2261 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2262 ssh_pkt_defersend(ssh);
2265 len = ssh2_pkt_construct(ssh, pkt);
2266 backlog = s_write(ssh, pkt->body, len);
2267 if (backlog > SSH_MAX_BACKLOG)
2268 ssh_throttle_all(ssh, 1, backlog);
2270 ssh->outgoing_data_size += pkt->encrypted_len;
2271 if (!ssh->kex_in_progress &&
2272 !ssh->bare_connection &&
2273 ssh->max_data_size != 0 &&
2274 ssh->outgoing_data_size > ssh->max_data_size)
2275 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2277 ssh_free_packet(pkt);
2281 * Defer an SSH-2 packet.
2283 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2286 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2287 ssh->deferred_len == 0 && !noignore &&
2288 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2290 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2291 * get encrypted with a known IV.
2293 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2294 ssh2_pkt_addstring_start(ipkt);
2295 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2297 len = ssh2_pkt_construct(ssh, pkt);
2298 if (ssh->deferred_len + len > ssh->deferred_size) {
2299 ssh->deferred_size = ssh->deferred_len + len + 128;
2300 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2304 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2305 ssh->deferred_len += len;
2306 ssh->deferred_data_size += pkt->encrypted_len;
2307 ssh_free_packet(pkt);
2311 * Queue an SSH-2 packet.
2313 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2315 assert(ssh->queueing);
2317 if (ssh->queuelen >= ssh->queuesize) {
2318 ssh->queuesize = ssh->queuelen + 32;
2319 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2322 ssh->queue[ssh->queuelen++] = pkt;
2326 * Either queue or send a packet, depending on whether queueing is
2329 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2332 ssh2_pkt_queue(ssh, pkt);
2334 ssh2_pkt_send_noqueue(ssh, pkt);
2338 * Either queue or defer a packet, depending on whether queueing is
2341 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2344 ssh2_pkt_queue(ssh, pkt);
2346 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2350 * Send the whole deferred data block constructed by
2351 * ssh2_pkt_defer() or SSH-1's defer_packet().
2353 * The expected use of the defer mechanism is that you call
2354 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2355 * not currently queueing, this simply sets up deferred_send_data
2356 * and then sends it. If we _are_ currently queueing, the calls to
2357 * ssh2_pkt_defer() put the deferred packets on to the queue
2358 * instead, and therefore ssh_pkt_defersend() has no deferred data
2359 * to send. Hence, there's no need to make it conditional on
2362 static void ssh_pkt_defersend(Ssh ssh)
2365 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2366 ssh->deferred_len = ssh->deferred_size = 0;
2367 sfree(ssh->deferred_send_data);
2368 ssh->deferred_send_data = NULL;
2369 if (backlog > SSH_MAX_BACKLOG)
2370 ssh_throttle_all(ssh, 1, backlog);
2372 ssh->outgoing_data_size += ssh->deferred_data_size;
2373 if (!ssh->kex_in_progress &&
2374 !ssh->bare_connection &&
2375 ssh->max_data_size != 0 &&
2376 ssh->outgoing_data_size > ssh->max_data_size)
2377 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2378 ssh->deferred_data_size = 0;
2382 * Send a packet whose length needs to be disguised (typically
2383 * passwords or keyboard-interactive responses).
2385 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2391 * The simplest way to do this is to adjust the
2392 * variable-length padding field in the outgoing packet.
2394 * Currently compiled out, because some Cisco SSH servers
2395 * don't like excessively padded packets (bah, why's it
2398 pkt->forcepad = padsize;
2399 ssh2_pkt_send(ssh, pkt);
2404 * If we can't do that, however, an alternative approach is
2405 * to use the pkt_defer mechanism to bundle the packet
2406 * tightly together with an SSH_MSG_IGNORE such that their
2407 * combined length is a constant. So first we construct the
2408 * final form of this packet and defer its sending.
2410 ssh2_pkt_defer(ssh, pkt);
2413 * Now construct an SSH_MSG_IGNORE which includes a string
2414 * that's an exact multiple of the cipher block size. (If
2415 * the cipher is NULL so that the block size is
2416 * unavailable, we don't do this trick at all, because we
2417 * gain nothing by it.)
2419 if (ssh->cscipher &&
2420 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2423 stringlen = (256 - ssh->deferred_len);
2424 stringlen += ssh->cscipher->blksize - 1;
2425 stringlen -= (stringlen % ssh->cscipher->blksize);
2428 * Temporarily disable actual compression, so we
2429 * can guarantee to get this string exactly the
2430 * length we want it. The compression-disabling
2431 * routine should return an integer indicating how
2432 * many bytes we should adjust our string length
2436 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2438 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2439 ssh2_pkt_addstring_start(pkt);
2440 for (i = 0; i < stringlen; i++) {
2441 char c = (char) random_byte();
2442 ssh2_pkt_addstring_data(pkt, &c, 1);
2444 ssh2_pkt_defer(ssh, pkt);
2446 ssh_pkt_defersend(ssh);
2451 * Send all queued SSH-2 packets. We send them by means of
2452 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2453 * packets that needed to be lumped together.
2455 static void ssh2_pkt_queuesend(Ssh ssh)
2459 assert(!ssh->queueing);
2461 for (i = 0; i < ssh->queuelen; i++)
2462 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2465 ssh_pkt_defersend(ssh);
2469 void bndebug(char *string, Bignum b)
2473 p = ssh2_mpint_fmt(b, &len);
2474 debug(("%s", string));
2475 for (i = 0; i < len; i++)
2476 debug((" %02x", p[i]));
2482 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2486 p = ssh2_mpint_fmt(b, &len);
2487 hash_string(h, s, p, len);
2492 * Packet decode functions for both SSH-1 and SSH-2.
2494 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2496 unsigned long value;
2497 if (pkt->length - pkt->savedpos < 4)
2498 return 0; /* arrgh, no way to decline (FIXME?) */
2499 value = GET_32BIT(pkt->body + pkt->savedpos);
2503 static int ssh2_pkt_getbool(struct Packet *pkt)
2505 unsigned long value;
2506 if (pkt->length - pkt->savedpos < 1)
2507 return 0; /* arrgh, no way to decline (FIXME?) */
2508 value = pkt->body[pkt->savedpos] != 0;
2512 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2517 if (pkt->length - pkt->savedpos < 4)
2519 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2524 if (pkt->length - pkt->savedpos < *length)
2526 *p = (char *)(pkt->body + pkt->savedpos);
2527 pkt->savedpos += *length;
2529 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2531 if (pkt->length - pkt->savedpos < length)
2533 pkt->savedpos += length;
2534 return pkt->body + (pkt->savedpos - length);
2536 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2537 unsigned char **keystr)
2541 j = makekey(pkt->body + pkt->savedpos,
2542 pkt->length - pkt->savedpos,
2549 assert(pkt->savedpos < pkt->length);
2553 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2558 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2559 pkt->length - pkt->savedpos, &b);
2567 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2573 ssh_pkt_getstring(pkt, &p, &length);
2578 b = bignum_from_bytes((unsigned char *)p, length);
2583 * Helper function to add an SSH-2 signature blob to a packet.
2584 * Expects to be shown the public key blob as well as the signature
2585 * blob. Normally works just like ssh2_pkt_addstring, but will
2586 * fiddle with the signature packet if necessary for
2587 * BUG_SSH2_RSA_PADDING.
2589 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2590 void *pkblob_v, int pkblob_len,
2591 void *sigblob_v, int sigblob_len)
2593 unsigned char *pkblob = (unsigned char *)pkblob_v;
2594 unsigned char *sigblob = (unsigned char *)sigblob_v;
2596 /* dmemdump(pkblob, pkblob_len); */
2597 /* dmemdump(sigblob, sigblob_len); */
2600 * See if this is in fact an ssh-rsa signature and a buggy
2601 * server; otherwise we can just do this the easy way.
2603 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2604 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2605 int pos, len, siglen;
2608 * Find the byte length of the modulus.
2611 pos = 4+7; /* skip over "ssh-rsa" */
2612 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2613 if (len < 0 || len > pkblob_len - pos - 4)
2615 pos += 4 + len; /* skip over exponent */
2616 if (pkblob_len - pos < 4)
2618 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2619 if (len < 0 || len > pkblob_len - pos - 4)
2621 pos += 4; /* find modulus itself */
2622 while (len > 0 && pkblob[pos] == 0)
2624 /* debug(("modulus length is %d\n", len)); */
2627 * Now find the signature integer.
2629 pos = 4+7; /* skip over "ssh-rsa" */
2630 if (sigblob_len < pos+4)
2632 siglen = toint(GET_32BIT(sigblob+pos));
2633 if (siglen != sigblob_len - pos - 4)
2635 /* debug(("signature length is %d\n", siglen)); */
2637 if (len != siglen) {
2638 unsigned char newlen[4];
2639 ssh2_pkt_addstring_start(pkt);
2640 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2641 /* dmemdump(sigblob, pos); */
2642 pos += 4; /* point to start of actual sig */
2643 PUT_32BIT(newlen, len);
2644 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2645 /* dmemdump(newlen, 4); */
2647 while (len-- > siglen) {
2648 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2649 /* dmemdump(newlen, 1); */
2651 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2652 /* dmemdump(sigblob+pos, siglen); */
2656 /* Otherwise fall through and do it the easy way. We also come
2657 * here as a fallback if we discover above that the key blob
2658 * is misformatted in some way. */
2662 ssh2_pkt_addstring_start(pkt);
2663 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2667 * Examine the remote side's version string and compare it against
2668 * a list of known buggy implementations.
2670 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2672 char *imp; /* pointer to implementation part */
2674 imp += strcspn(imp, "-");
2676 imp += strcspn(imp, "-");
2679 ssh->remote_bugs = 0;
2682 * General notes on server version strings:
2683 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2684 * here -- in particular, we've heard of one that's perfectly happy
2685 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2686 * so we can't distinguish them.
2688 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2689 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2690 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2691 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2692 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2693 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2695 * These versions don't support SSH1_MSG_IGNORE, so we have
2696 * to use a different defence against password length
2699 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2700 logevent("We believe remote version has SSH-1 ignore bug");
2703 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2704 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2705 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2707 * These versions need a plain password sent; they can't
2708 * handle having a null and a random length of data after
2711 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2712 logevent("We believe remote version needs a plain SSH-1 password");
2715 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2716 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2717 (!strcmp(imp, "Cisco-1.25")))) {
2719 * These versions apparently have no clue whatever about
2720 * RSA authentication and will panic and die if they see
2721 * an AUTH_RSA message.
2723 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2724 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2727 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2728 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2729 !wc_match("* VShell", imp) &&
2730 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2731 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2732 wc_match("2.1 *", imp)))) {
2734 * These versions have the HMAC bug.
2736 ssh->remote_bugs |= BUG_SSH2_HMAC;
2737 logevent("We believe remote version has SSH-2 HMAC bug");
2740 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2741 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2742 !wc_match("* VShell", imp) &&
2743 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2745 * These versions have the key-derivation bug (failing to
2746 * include the literal shared secret in the hashes that
2747 * generate the keys).
2749 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2750 logevent("We believe remote version has SSH-2 key-derivation bug");
2753 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2754 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2755 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2756 wc_match("OpenSSH_3.[0-2]*", imp) ||
2757 wc_match("mod_sftp/0.[0-8]*", imp) ||
2758 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2760 * These versions have the SSH-2 RSA padding bug.
2762 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2763 logevent("We believe remote version has SSH-2 RSA padding bug");
2766 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2767 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2768 wc_match("OpenSSH_2.[0-2]*", imp))) {
2770 * These versions have the SSH-2 session-ID bug in
2771 * public-key authentication.
2773 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2774 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2777 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2778 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2779 (wc_match("DigiSSH_2.0", imp) ||
2780 wc_match("OpenSSH_2.[0-4]*", imp) ||
2781 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2782 wc_match("Sun_SSH_1.0", imp) ||
2783 wc_match("Sun_SSH_1.0.1", imp) ||
2784 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2785 wc_match("WeOnlyDo-*", imp)))) {
2787 * These versions have the SSH-2 rekey bug.
2789 ssh->remote_bugs |= BUG_SSH2_REKEY;
2790 logevent("We believe remote version has SSH-2 rekey bug");
2793 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2794 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2795 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2796 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2798 * This version ignores our makpkt and needs to be throttled.
2800 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2801 logevent("We believe remote version ignores SSH-2 maximum packet size");
2804 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2806 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2807 * none detected automatically.
2809 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2810 logevent("We believe remote version has SSH-2 ignore bug");
2813 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2814 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2815 (wc_match("OpenSSH_2.[235]*", imp)))) {
2817 * These versions only support the original (pre-RFC4419)
2818 * SSH-2 GEX request.
2820 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2821 logevent("We believe remote version has outdated SSH-2 GEX");
2824 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2826 * Servers that don't support our winadj request for one
2827 * reason or another. Currently, none detected automatically.
2829 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2830 logevent("We believe remote version has winadj bug");
2833 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
2834 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
2835 (wc_match("OpenSSH_[2-5].*", imp) ||
2836 wc_match("OpenSSH_6.[0-6]*", imp) ||
2837 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
2838 wc_match("dropbear_0.5[01]*", imp)))) {
2840 * These versions have the SSH-2 channel request bug.
2841 * OpenSSH 6.7 and above do not:
2842 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
2843 * dropbear_0.52 and above do not:
2844 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
2846 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
2847 logevent("We believe remote version has SSH-2 channel request bug");
2852 * The `software version' part of an SSH version string is required
2853 * to contain no spaces or minus signs.
2855 static void ssh_fix_verstring(char *str)
2857 /* Eat "<protoversion>-". */
2858 while (*str && *str != '-') str++;
2859 assert(*str == '-'); str++;
2861 /* Convert minus signs and spaces in the remaining string into
2864 if (*str == '-' || *str == ' ')
2871 * Send an appropriate SSH version string.
2873 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
2877 if (ssh->version == 2) {
2879 * Construct a v2 version string.
2881 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
2884 * Construct a v1 version string.
2886 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
2887 verstring = dupprintf("SSH-%s-%s\012",
2888 (ssh_versioncmp(svers, "1.5") <= 0 ?
2893 ssh_fix_verstring(verstring + strlen(protoname));
2895 if (ssh->version == 2) {
2898 * Record our version string.
2900 len = strcspn(verstring, "\015\012");
2901 ssh->v_c = snewn(len + 1, char);
2902 memcpy(ssh->v_c, verstring, len);
2906 logeventf(ssh, "We claim version: %.*s",
2907 strcspn(verstring, "\015\012"), verstring);
2908 s_write(ssh, verstring, strlen(verstring));
2912 static int do_ssh_init(Ssh ssh, unsigned char c)
2914 static const char protoname[] = "SSH-";
2916 struct do_ssh_init_state {
2925 crState(do_ssh_init_state);
2929 /* Search for a line beginning with the protocol name prefix in
2932 for (s->i = 0; protoname[s->i]; s->i++) {
2933 if ((char)c != protoname[s->i]) goto no;
2943 s->vstrsize = sizeof(protoname) + 16;
2944 s->vstring = snewn(s->vstrsize, char);
2945 strcpy(s->vstring, protoname);
2946 s->vslen = strlen(protoname);
2949 if (s->vslen >= s->vstrsize - 1) {
2951 s->vstring = sresize(s->vstring, s->vstrsize, char);
2953 s->vstring[s->vslen++] = c;
2956 s->version[s->i] = '\0';
2958 } else if (s->i < sizeof(s->version) - 1)
2959 s->version[s->i++] = c;
2960 } else if (c == '\012')
2962 crReturn(1); /* get another char */
2965 ssh->agentfwd_enabled = FALSE;
2966 ssh->rdpkt2_state.incoming_sequence = 0;
2968 s->vstring[s->vslen] = 0;
2969 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2970 logeventf(ssh, "Server version: %s", s->vstring);
2971 ssh_detect_bugs(ssh, s->vstring);
2974 * Decide which SSH protocol version to support.
2977 /* Anything strictly below "2.0" means protocol 1 is supported. */
2978 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2979 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2980 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2982 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2983 bombout(("SSH protocol version 1 required by configuration but "
2984 "not provided by server"));
2987 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2988 bombout(("SSH protocol version 2 required by configuration but "
2989 "not provided by server"));
2993 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2998 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3000 /* Send the version string, if we haven't already */
3001 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3002 ssh_send_verstring(ssh, protoname, s->version);
3004 if (ssh->version == 2) {
3007 * Record their version string.
3009 len = strcspn(s->vstring, "\015\012");
3010 ssh->v_s = snewn(len + 1, char);
3011 memcpy(ssh->v_s, s->vstring, len);
3015 * Initialise SSH-2 protocol.
3017 ssh->protocol = ssh2_protocol;
3018 ssh2_protocol_setup(ssh);
3019 ssh->s_rdpkt = ssh2_rdpkt;
3022 * Initialise SSH-1 protocol.
3024 ssh->protocol = ssh1_protocol;
3025 ssh1_protocol_setup(ssh);
3026 ssh->s_rdpkt = ssh1_rdpkt;
3028 if (ssh->version == 2)
3029 do_ssh2_transport(ssh, NULL, -1, NULL);
3031 update_specials_menu(ssh->frontend);
3032 ssh->state = SSH_STATE_BEFORE_SIZE;
3033 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3040 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3043 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3044 * the ssh-connection part, extracted and given a trivial binary
3045 * packet protocol, so we replace 'SSH-' at the start with a new
3046 * name. In proper SSH style (though of course this part of the
3047 * proper SSH protocol _isn't_ subject to this kind of
3048 * DNS-domain-based extension), we define the new name in our
3051 static const char protoname[] =
3052 "SSHCONNECTION@putty.projects.tartarus.org-";
3054 struct do_ssh_connection_init_state {
3062 crState(do_ssh_connection_init_state);
3066 /* Search for a line beginning with the protocol name prefix in
3069 for (s->i = 0; protoname[s->i]; s->i++) {
3070 if ((char)c != protoname[s->i]) goto no;
3080 s->vstrsize = sizeof(protoname) + 16;
3081 s->vstring = snewn(s->vstrsize, char);
3082 strcpy(s->vstring, protoname);
3083 s->vslen = strlen(protoname);
3086 if (s->vslen >= s->vstrsize - 1) {
3088 s->vstring = sresize(s->vstring, s->vstrsize, char);
3090 s->vstring[s->vslen++] = c;
3093 s->version[s->i] = '\0';
3095 } else if (s->i < sizeof(s->version) - 1)
3096 s->version[s->i++] = c;
3097 } else if (c == '\012')
3099 crReturn(1); /* get another char */
3102 ssh->agentfwd_enabled = FALSE;
3103 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3105 s->vstring[s->vslen] = 0;
3106 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3107 logeventf(ssh, "Server version: %s", s->vstring);
3108 ssh_detect_bugs(ssh, s->vstring);
3111 * Decide which SSH protocol version to support. This is easy in
3112 * bare ssh-connection mode: only 2.0 is legal.
3114 if (ssh_versioncmp(s->version, "2.0") < 0) {
3115 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3118 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3119 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3125 logeventf(ssh, "Using bare ssh-connection protocol");
3127 /* Send the version string, if we haven't already */
3128 ssh_send_verstring(ssh, protoname, s->version);
3131 * Initialise bare connection protocol.
3133 ssh->protocol = ssh2_bare_connection_protocol;
3134 ssh2_bare_connection_protocol_setup(ssh);
3135 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3137 update_specials_menu(ssh->frontend);
3138 ssh->state = SSH_STATE_BEFORE_SIZE;
3139 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3142 * Get authconn (really just conn) under way.
3144 do_ssh2_authconn(ssh, NULL, 0, NULL);
3151 static void ssh_process_incoming_data(Ssh ssh,
3152 unsigned char **data, int *datalen)
3154 struct Packet *pktin;
3156 pktin = ssh->s_rdpkt(ssh, data, datalen);
3158 ssh->protocol(ssh, NULL, 0, pktin);
3159 ssh_free_packet(pktin);
3163 static void ssh_queue_incoming_data(Ssh ssh,
3164 unsigned char **data, int *datalen)
3166 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3171 static void ssh_process_queued_incoming_data(Ssh ssh)
3174 unsigned char *data;
3177 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3178 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3182 while (!ssh->frozen && len > 0)
3183 ssh_process_incoming_data(ssh, &data, &len);
3186 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3190 static void ssh_set_frozen(Ssh ssh, int frozen)
3193 sk_set_frozen(ssh->s, frozen);
3194 ssh->frozen = frozen;
3197 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
3199 /* Log raw data, if we're in that mode. */
3201 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3202 0, NULL, NULL, 0, NULL);
3204 crBegin(ssh->ssh_gotdata_crstate);
3207 * To begin with, feed the characters one by one to the
3208 * protocol initialisation / selection function do_ssh_init().
3209 * When that returns 0, we're done with the initial greeting
3210 * exchange and can move on to packet discipline.
3213 int ret; /* need not be kept across crReturn */
3215 crReturnV; /* more data please */
3216 ret = ssh->do_ssh_init(ssh, *data);
3224 * We emerge from that loop when the initial negotiation is
3225 * over and we have selected an s_rdpkt function. Now pass
3226 * everything to s_rdpkt, and then pass the resulting packets
3227 * to the proper protocol handler.
3231 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3233 ssh_queue_incoming_data(ssh, &data, &datalen);
3234 /* This uses up all data and cannot cause anything interesting
3235 * to happen; indeed, for anything to happen at all, we must
3236 * return, so break out. */
3238 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3239 /* This uses up some or all data, and may freeze the
3241 ssh_process_queued_incoming_data(ssh);
3243 /* This uses up some or all data, and may freeze the
3245 ssh_process_incoming_data(ssh, &data, &datalen);
3247 /* FIXME this is probably EBW. */
3248 if (ssh->state == SSH_STATE_CLOSED)
3251 /* We're out of data. Go and get some more. */
3257 static int ssh_do_close(Ssh ssh, int notify_exit)
3260 struct ssh_channel *c;
3262 ssh->state = SSH_STATE_CLOSED;
3263 expire_timer_context(ssh);
3268 notify_remote_exit(ssh->frontend);
3273 * Now we must shut down any port- and X-forwarded channels going
3274 * through this connection.
3276 if (ssh->channels) {
3277 while (NULL != (c = index234(ssh->channels, 0))) {
3280 x11_close(c->u.x11.xconn);
3283 case CHAN_SOCKDATA_DORMANT:
3284 pfd_close(c->u.pfd.pf);
3287 del234(ssh->channels, c); /* moving next one to index 0 */
3288 if (ssh->version == 2)
3289 bufchain_clear(&c->v.v2.outbuffer);
3294 * Go through port-forwardings, and close any associated
3295 * listening sockets.
3297 if (ssh->portfwds) {
3298 struct ssh_portfwd *pf;
3299 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3300 /* Dispose of any listening socket. */
3302 pfl_terminate(pf->local);
3303 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3306 freetree234(ssh->portfwds);
3307 ssh->portfwds = NULL;
3311 * Also stop attempting to connection-share.
3313 if (ssh->connshare) {
3314 sharestate_free(ssh->connshare);
3315 ssh->connshare = NULL;
3321 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3322 const char *error_msg, int error_code)
3324 Ssh ssh = (Ssh) plug;
3325 char addrbuf[256], *msg;
3327 if (ssh->attempting_connshare) {
3329 * While we're attempting connection sharing, don't loudly log
3330 * everything that happens. Real TCP connections need to be
3331 * logged when we _start_ trying to connect, because it might
3332 * be ages before they respond if something goes wrong; but
3333 * connection sharing is local and quick to respond, and it's
3334 * sufficient to simply wait and see whether it worked
3338 sk_getaddr(addr, addrbuf, lenof(addrbuf));
3341 if (sk_addr_needs_port(addr)) {
3342 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
3344 msg = dupprintf("Connecting to %s", addrbuf);
3347 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
3355 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3356 const char *ds_err, const char *us_err)
3358 if (event == SHARE_NONE) {
3359 /* In this case, 'logtext' is an error message indicating a
3360 * reason why connection sharing couldn't be set up _at all_.
3361 * Failing that, ds_err and us_err indicate why we couldn't be
3362 * a downstream and an upstream respectively. */
3364 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3367 logeventf(ssh, "Could not set up connection sharing"
3368 " as downstream: %s", ds_err);
3370 logeventf(ssh, "Could not set up connection sharing"
3371 " as upstream: %s", us_err);
3373 } else if (event == SHARE_DOWNSTREAM) {
3374 /* In this case, 'logtext' is a local endpoint address */
3375 logeventf(ssh, "Using existing shared connection at %s", logtext);
3376 /* Also we should mention this in the console window to avoid
3377 * confusing users as to why this window doesn't behave the
3379 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3380 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3382 } else if (event == SHARE_UPSTREAM) {
3383 /* In this case, 'logtext' is a local endpoint address too */
3384 logeventf(ssh, "Sharing this connection at %s", logtext);
3388 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3391 Ssh ssh = (Ssh) plug;
3392 int need_notify = ssh_do_close(ssh, FALSE);
3395 if (!ssh->close_expected)
3396 error_msg = "Server unexpectedly closed network connection";
3398 error_msg = "Server closed network connection";
3401 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3405 notify_remote_exit(ssh->frontend);
3408 logevent(error_msg);
3409 if (!ssh->close_expected || !ssh->clean_exit)
3410 connection_fatal(ssh->frontend, "%s", error_msg);
3414 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3416 Ssh ssh = (Ssh) plug;
3417 ssh_gotdata(ssh, (unsigned char *)data, len);
3418 if (ssh->state == SSH_STATE_CLOSED) {
3419 ssh_do_close(ssh, TRUE);
3425 static void ssh_sent(Plug plug, int bufsize)
3427 Ssh ssh = (Ssh) plug;
3429 * If the send backlog on the SSH socket itself clears, we
3430 * should unthrottle the whole world if it was throttled.
3432 if (bufsize < SSH_MAX_BACKLOG)
3433 ssh_throttle_all(ssh, 0, bufsize);
3437 * Connect to specified host and port.
3438 * Returns an error message, or NULL on success.
3439 * Also places the canonical host name into `realhost'. It must be
3440 * freed by the caller.
3442 static const char *connect_to_host(Ssh ssh, char *host, int port,
3443 char **realhost, int nodelay, int keepalive)
3445 static const struct plug_function_table fn_table = {
3456 int addressfamily, sshprot;
3458 loghost = conf_get_str(ssh->conf, CONF_loghost);
3463 tmphost = dupstr(loghost);
3464 ssh->savedport = 22; /* default ssh port */
3467 * A colon suffix on the hostname string also lets us affect
3468 * savedport. (Unless there are multiple colons, in which case
3469 * we assume this is an unbracketed IPv6 literal.)
3471 colon = host_strrchr(tmphost, ':');
3472 if (colon && colon == host_strchr(tmphost, ':')) {
3475 ssh->savedport = atoi(colon);
3478 ssh->savedhost = host_strduptrim(tmphost);
3481 ssh->savedhost = host_strduptrim(host);
3483 port = 22; /* default ssh port */
3484 ssh->savedport = port;
3487 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3490 * Try connection-sharing, in case that means we don't open a
3491 * socket after all. ssh_connection_sharing_init will connect to a
3492 * previously established upstream if it can, and failing that,
3493 * establish a listening socket for _us_ to be the upstream. In
3494 * the latter case it will return NULL just as if it had done
3495 * nothing, because here we only need to care if we're a
3496 * downstream and need to do our connection setup differently.
3498 ssh->connshare = NULL;
3499 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3500 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3501 ssh->conf, ssh, &ssh->connshare);
3502 ssh->attempting_connshare = FALSE;
3503 if (ssh->s != NULL) {
3505 * We are a downstream.
3507 ssh->bare_connection = TRUE;
3508 ssh->do_ssh_init = do_ssh_connection_init;
3509 ssh->fullhostname = NULL;
3510 *realhost = dupstr(host); /* best we can do */
3513 * We're not a downstream, so open a normal socket.
3515 ssh->do_ssh_init = do_ssh_init;
3520 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3521 logeventf(ssh, "Looking up host \"%s\"%s", host,
3522 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3523 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3524 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3525 if ((err = sk_addr_error(addr)) != NULL) {
3529 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3531 ssh->s = new_connection(addr, *realhost, port,
3532 0, 1, nodelay, keepalive,
3533 (Plug) ssh, ssh->conf);
3534 if ((err = sk_socket_error(ssh->s)) != NULL) {
3536 notify_remote_exit(ssh->frontend);
3542 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3543 * send the version string too.
3545 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3548 if (sshprot == 3 && !ssh->bare_connection) {
3550 ssh_send_verstring(ssh, "SSH-", NULL);
3554 * loghost, if configured, overrides realhost.
3558 *realhost = dupstr(loghost);
3565 * Throttle or unthrottle the SSH connection.
3567 static void ssh_throttle_conn(Ssh ssh, int adjust)
3569 int old_count = ssh->conn_throttle_count;
3570 ssh->conn_throttle_count += adjust;
3571 assert(ssh->conn_throttle_count >= 0);
3572 if (ssh->conn_throttle_count && !old_count) {
3573 ssh_set_frozen(ssh, 1);
3574 } else if (!ssh->conn_throttle_count && old_count) {
3575 ssh_set_frozen(ssh, 0);
3580 * Throttle or unthrottle _all_ local data streams (for when sends
3581 * on the SSH connection itself back up).
3583 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3586 struct ssh_channel *c;
3588 if (enable == ssh->throttled_all)
3590 ssh->throttled_all = enable;
3591 ssh->overall_bufsize = bufsize;
3594 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3596 case CHAN_MAINSESSION:
3598 * This is treated separately, outside the switch.
3602 x11_override_throttle(c->u.x11.xconn, enable);
3605 /* Agent channels require no buffer management. */
3608 pfd_override_throttle(c->u.pfd.pf, enable);
3614 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3616 Ssh ssh = (Ssh) sshv;
3618 ssh->agent_response = reply;
3619 ssh->agent_response_len = replylen;
3621 if (ssh->version == 1)
3622 do_ssh1_login(ssh, NULL, -1, NULL);
3624 do_ssh2_authconn(ssh, NULL, -1, NULL);
3627 static void ssh_dialog_callback(void *sshv, int ret)
3629 Ssh ssh = (Ssh) sshv;
3631 ssh->user_response = ret;
3633 if (ssh->version == 1)
3634 do_ssh1_login(ssh, NULL, -1, NULL);
3636 do_ssh2_transport(ssh, NULL, -1, NULL);
3639 * This may have unfrozen the SSH connection, so do a
3642 ssh_process_queued_incoming_data(ssh);
3645 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3647 struct ssh_channel *c = (struct ssh_channel *)cv;
3649 void *sentreply = reply;
3651 c->u.a.outstanding_requests--;
3653 /* Fake SSH_AGENT_FAILURE. */
3654 sentreply = "\0\0\0\1\5";
3657 if (ssh->version == 2) {
3658 ssh2_add_channel_data(c, sentreply, replylen);
3661 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3662 PKT_INT, c->remoteid,
3664 PKT_DATA, sentreply, replylen,
3670 * If we've already seen an incoming EOF but haven't sent an
3671 * outgoing one, this may be the moment to send it.
3673 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3674 sshfwd_write_eof(c);
3678 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3679 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3680 * => log `wire_reason'.
3682 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3683 int code, int clean_exit)
3687 client_reason = wire_reason;
3689 error = dupprintf("Disconnected: %s", client_reason);
3691 error = dupstr("Disconnected");
3693 if (ssh->version == 1) {
3694 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3696 } else if (ssh->version == 2) {
3697 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3698 ssh2_pkt_adduint32(pktout, code);
3699 ssh2_pkt_addstring(pktout, wire_reason);
3700 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3701 ssh2_pkt_send_noqueue(ssh, pktout);
3704 ssh->close_expected = TRUE;
3705 ssh->clean_exit = clean_exit;
3706 ssh_closing((Plug)ssh, error, 0, 0);
3710 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3711 const struct ssh_signkey *ssh2keytype,
3714 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3715 return -1; /* no manual keys configured */
3720 * The fingerprint string we've been given will have things
3721 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3722 * narrow down to just the colon-separated hex block at the
3723 * end of the string.
3725 const char *p = strrchr(fingerprint, ' ');
3726 fingerprint = p ? p+1 : fingerprint;
3727 /* Quick sanity checks, including making sure it's in lowercase */
3728 assert(strlen(fingerprint) == 16*3 - 1);
3729 assert(fingerprint[2] == ':');
3730 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3732 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3734 return 1; /* success */
3739 * Construct the base64-encoded public key blob and see if
3742 unsigned char *binblob;
3744 int binlen, atoms, i;
3745 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3746 atoms = (binlen + 2) / 3;
3747 base64blob = snewn(atoms * 4 + 1, char);
3748 for (i = 0; i < atoms; i++)
3749 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3750 base64blob[atoms * 4] = '\0';
3752 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3755 return 1; /* success */
3764 * Handle the key exchange and user authentication phases.
3766 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3767 struct Packet *pktin)
3770 unsigned char cookie[8], *ptr;
3771 struct MD5Context md5c;
3772 struct do_ssh1_login_state {
3775 unsigned char *rsabuf, *keystr1, *keystr2;
3776 unsigned long supported_ciphers_mask, supported_auths_mask;
3777 int tried_publickey, tried_agent;
3778 int tis_auth_refused, ccard_auth_refused;
3779 unsigned char session_id[16];
3781 void *publickey_blob;
3782 int publickey_bloblen;
3783 char *publickey_comment;
3784 int publickey_encrypted;
3785 prompts_t *cur_prompt;
3788 unsigned char request[5], *response, *p;
3798 struct RSAKey servkey, hostkey;
3800 crState(do_ssh1_login_state);
3807 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3808 bombout(("Public key packet not received"));
3812 logevent("Received public keys");
3814 ptr = ssh_pkt_getdata(pktin, 8);
3816 bombout(("SSH-1 public key packet stopped before random cookie"));
3819 memcpy(cookie, ptr, 8);
3821 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3822 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3823 bombout(("Failed to read SSH-1 public keys from public key packet"));
3828 * Log the host key fingerprint.
3832 logevent("Host key fingerprint is:");
3833 strcpy(logmsg, " ");
3834 s->hostkey.comment = NULL;
3835 rsa_fingerprint(logmsg + strlen(logmsg),
3836 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3840 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3841 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3842 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3843 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3844 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3846 ssh->v1_local_protoflags =
3847 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3848 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3851 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3852 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3853 MD5Update(&md5c, cookie, 8);
3854 MD5Final(s->session_id, &md5c);
3856 for (i = 0; i < 32; i++)
3857 ssh->session_key[i] = random_byte();
3860 * Verify that the `bits' and `bytes' parameters match.
3862 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3863 s->servkey.bits > s->servkey.bytes * 8) {
3864 bombout(("SSH-1 public keys were badly formatted"));
3868 s->len = (s->hostkey.bytes > s->servkey.bytes ?
3869 s->hostkey.bytes : s->servkey.bytes);
3871 s->rsabuf = snewn(s->len, unsigned char);
3874 * Verify the host key.
3878 * First format the key into a string.
3880 int len = rsastr_len(&s->hostkey);
3881 char fingerprint[100];
3882 char *keystr = snewn(len, char);
3883 rsastr_fmt(keystr, &s->hostkey);
3884 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
3886 /* First check against manually configured host keys. */
3887 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
3888 if (s->dlgret == 0) { /* did not match */
3889 bombout(("Host key did not appear in manually configured list"));
3892 } else if (s->dlgret < 0) { /* none configured; use standard handling */
3893 ssh_set_frozen(ssh, 1);
3894 s->dlgret = verify_ssh_host_key(ssh->frontend,
3895 ssh->savedhost, ssh->savedport,
3896 "rsa", keystr, fingerprint,
3897 ssh_dialog_callback, ssh);
3899 if (s->dlgret < 0) {
3903 bombout(("Unexpected data from server while waiting"
3904 " for user host key response"));
3907 } while (pktin || inlen > 0);
3908 s->dlgret = ssh->user_response;
3910 ssh_set_frozen(ssh, 0);
3912 if (s->dlgret == 0) {
3913 ssh_disconnect(ssh, "User aborted at host key verification",
3922 for (i = 0; i < 32; i++) {
3923 s->rsabuf[i] = ssh->session_key[i];
3925 s->rsabuf[i] ^= s->session_id[i];
3928 if (s->hostkey.bytes > s->servkey.bytes) {
3929 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
3931 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
3933 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
3935 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
3938 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3942 logevent("Encrypted session key");
3945 int cipher_chosen = 0, warn = 0;
3946 char *cipher_string = NULL;
3948 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3949 int next_cipher = conf_get_int_int(ssh->conf,
3950 CONF_ssh_cipherlist, i);
3951 if (next_cipher == CIPHER_WARN) {
3952 /* If/when we choose a cipher, warn about it */
3954 } else if (next_cipher == CIPHER_AES) {
3955 /* XXX Probably don't need to mention this. */
3956 logevent("AES not supported in SSH-1, skipping");
3958 switch (next_cipher) {
3959 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3960 cipher_string = "3DES"; break;
3961 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3962 cipher_string = "Blowfish"; break;
3963 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3964 cipher_string = "single-DES"; break;
3966 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3970 if (!cipher_chosen) {
3971 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3972 bombout(("Server violates SSH-1 protocol by not "
3973 "supporting 3DES encryption"));
3975 /* shouldn't happen */
3976 bombout(("No supported ciphers found"));
3980 /* Warn about chosen cipher if necessary. */
3982 ssh_set_frozen(ssh, 1);
3983 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3984 ssh_dialog_callback, ssh);
3985 if (s->dlgret < 0) {
3989 bombout(("Unexpected data from server while waiting"
3990 " for user response"));
3993 } while (pktin || inlen > 0);
3994 s->dlgret = ssh->user_response;
3996 ssh_set_frozen(ssh, 0);
3997 if (s->dlgret == 0) {
3998 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4005 switch (s->cipher_type) {
4006 case SSH_CIPHER_3DES:
4007 logevent("Using 3DES encryption");
4009 case SSH_CIPHER_DES:
4010 logevent("Using single-DES encryption");
4012 case SSH_CIPHER_BLOWFISH:
4013 logevent("Using Blowfish encryption");
4017 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4018 PKT_CHAR, s->cipher_type,
4019 PKT_DATA, cookie, 8,
4020 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4021 PKT_DATA, s->rsabuf, s->len,
4022 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4024 logevent("Trying to enable encryption...");
4028 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4029 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4031 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4032 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4033 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4035 ssh->crcda_ctx = crcda_make_context();
4036 logevent("Installing CRC compensation attack detector");
4038 if (s->servkey.modulus) {
4039 sfree(s->servkey.modulus);
4040 s->servkey.modulus = NULL;
4042 if (s->servkey.exponent) {
4043 sfree(s->servkey.exponent);
4044 s->servkey.exponent = NULL;
4046 if (s->hostkey.modulus) {
4047 sfree(s->hostkey.modulus);
4048 s->hostkey.modulus = NULL;
4050 if (s->hostkey.exponent) {
4051 sfree(s->hostkey.exponent);
4052 s->hostkey.exponent = NULL;
4056 if (pktin->type != SSH1_SMSG_SUCCESS) {
4057 bombout(("Encryption not successfully enabled"));
4061 logevent("Successfully started encryption");
4063 fflush(stdout); /* FIXME eh? */
4065 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4066 int ret; /* need not be kept over crReturn */
4067 s->cur_prompt = new_prompts(ssh->frontend);
4068 s->cur_prompt->to_server = TRUE;
4069 s->cur_prompt->name = dupstr("SSH login name");
4070 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4071 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4074 crWaitUntil(!pktin);
4075 ret = get_userpass_input(s->cur_prompt, in, inlen);
4080 * Failed to get a username. Terminate.
4082 free_prompts(s->cur_prompt);
4083 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4086 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4087 free_prompts(s->cur_prompt);
4090 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4092 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4094 if (flags & FLAG_INTERACTIVE &&
4095 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4096 c_write_str(ssh, userlog);
4097 c_write_str(ssh, "\r\n");
4105 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4106 /* We must not attempt PK auth. Pretend we've already tried it. */
4107 s->tried_publickey = s->tried_agent = 1;
4109 s->tried_publickey = s->tried_agent = 0;
4111 s->tis_auth_refused = s->ccard_auth_refused = 0;
4113 * Load the public half of any configured keyfile for later use.
4115 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4116 if (!filename_is_null(s->keyfile)) {
4118 logeventf(ssh, "Reading private key file \"%.150s\"",
4119 filename_to_str(s->keyfile));
4120 keytype = key_type(s->keyfile);
4121 if (keytype == SSH_KEYTYPE_SSH1) {
4123 if (rsakey_pubblob(s->keyfile,
4124 &s->publickey_blob, &s->publickey_bloblen,
4125 &s->publickey_comment, &error)) {
4126 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
4130 logeventf(ssh, "Unable to load private key (%s)", error);
4131 msgbuf = dupprintf("Unable to load private key file "
4132 "\"%.150s\" (%s)\r\n",
4133 filename_to_str(s->keyfile),
4135 c_write_str(ssh, msgbuf);
4137 s->publickey_blob = NULL;
4141 logeventf(ssh, "Unable to use this key file (%s)",
4142 key_type_to_str(keytype));
4143 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4145 filename_to_str(s->keyfile),
4146 key_type_to_str(keytype));
4147 c_write_str(ssh, msgbuf);
4149 s->publickey_blob = NULL;
4152 s->publickey_blob = NULL;
4154 while (pktin->type == SSH1_SMSG_FAILURE) {
4155 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4157 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4159 * Attempt RSA authentication using Pageant.
4165 logevent("Pageant is running. Requesting keys.");
4167 /* Request the keys held by the agent. */
4168 PUT_32BIT(s->request, 1);
4169 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4170 if (!agent_query(s->request, 5, &r, &s->responselen,
4171 ssh_agent_callback, ssh)) {
4175 bombout(("Unexpected data from server while waiting"
4176 " for agent response"));
4179 } while (pktin || inlen > 0);
4180 r = ssh->agent_response;
4181 s->responselen = ssh->agent_response_len;
4183 s->response = (unsigned char *) r;
4184 if (s->response && s->responselen >= 5 &&
4185 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4186 s->p = s->response + 5;
4187 s->nkeys = toint(GET_32BIT(s->p));
4189 logeventf(ssh, "Pageant reported negative key count %d",
4194 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4195 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4196 unsigned char *pkblob = s->p;
4200 do { /* do while (0) to make breaking easy */
4201 n = ssh1_read_bignum
4202 (s->p, toint(s->responselen-(s->p-s->response)),
4207 n = ssh1_read_bignum
4208 (s->p, toint(s->responselen-(s->p-s->response)),
4213 if (s->responselen - (s->p-s->response) < 4)
4215 s->commentlen = toint(GET_32BIT(s->p));
4217 if (s->commentlen < 0 ||
4218 toint(s->responselen - (s->p-s->response)) <
4221 s->commentp = (char *)s->p;
4222 s->p += s->commentlen;
4226 logevent("Pageant key list packet was truncated");
4230 if (s->publickey_blob) {
4231 if (!memcmp(pkblob, s->publickey_blob,
4232 s->publickey_bloblen)) {
4233 logeventf(ssh, "Pageant key #%d matches "
4234 "configured key file", s->keyi);
4235 s->tried_publickey = 1;
4237 /* Skip non-configured key */
4240 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4241 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4242 PKT_BIGNUM, s->key.modulus, PKT_END);
4244 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4245 logevent("Key refused");
4248 logevent("Received RSA challenge");
4249 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4250 bombout(("Server's RSA challenge was badly formatted"));
4255 char *agentreq, *q, *ret;
4258 len = 1 + 4; /* message type, bit count */
4259 len += ssh1_bignum_length(s->key.exponent);
4260 len += ssh1_bignum_length(s->key.modulus);
4261 len += ssh1_bignum_length(s->challenge);
4262 len += 16; /* session id */
4263 len += 4; /* response format */
4264 agentreq = snewn(4 + len, char);
4265 PUT_32BIT(agentreq, len);
4267 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4268 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4270 q += ssh1_write_bignum(q, s->key.exponent);
4271 q += ssh1_write_bignum(q, s->key.modulus);
4272 q += ssh1_write_bignum(q, s->challenge);
4273 memcpy(q, s->session_id, 16);
4275 PUT_32BIT(q, 1); /* response format */
4276 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4277 ssh_agent_callback, ssh)) {
4282 bombout(("Unexpected data from server"
4283 " while waiting for agent"
4287 } while (pktin || inlen > 0);
4288 vret = ssh->agent_response;
4289 retlen = ssh->agent_response_len;
4294 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4295 logevent("Sending Pageant's response");
4296 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4297 PKT_DATA, ret + 5, 16,
4301 if (pktin->type == SSH1_SMSG_SUCCESS) {
4303 ("Pageant's response accepted");
4304 if (flags & FLAG_VERBOSE) {
4305 c_write_str(ssh, "Authenticated using"
4307 c_write(ssh, s->commentp,
4309 c_write_str(ssh, "\" from agent\r\n");
4314 ("Pageant's response not accepted");
4317 ("Pageant failed to answer challenge");
4321 logevent("No reply received from Pageant");
4324 freebn(s->key.exponent);
4325 freebn(s->key.modulus);
4326 freebn(s->challenge);
4331 if (s->publickey_blob && !s->tried_publickey)
4332 logevent("Configured key file not in Pageant");
4334 logevent("Failed to get reply from Pageant");
4339 if (s->publickey_blob && !s->tried_publickey) {
4341 * Try public key authentication with the specified
4344 int got_passphrase; /* need not be kept over crReturn */
4345 if (flags & FLAG_VERBOSE)
4346 c_write_str(ssh, "Trying public key authentication.\r\n");
4347 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4348 logeventf(ssh, "Trying public key \"%s\"",
4349 filename_to_str(s->keyfile));
4350 s->tried_publickey = 1;
4351 got_passphrase = FALSE;
4352 while (!got_passphrase) {
4354 * Get a passphrase, if necessary.
4356 char *passphrase = NULL; /* only written after crReturn */
4358 if (!s->publickey_encrypted) {
4359 if (flags & FLAG_VERBOSE)
4360 c_write_str(ssh, "No passphrase required.\r\n");
4363 int ret; /* need not be kept over crReturn */
4364 s->cur_prompt = new_prompts(ssh->frontend);
4365 s->cur_prompt->to_server = FALSE;
4366 s->cur_prompt->name = dupstr("SSH key passphrase");
4367 add_prompt(s->cur_prompt,
4368 dupprintf("Passphrase for key \"%.100s\": ",
4369 s->publickey_comment), FALSE);
4370 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4373 crWaitUntil(!pktin);
4374 ret = get_userpass_input(s->cur_prompt, in, inlen);
4378 /* Failed to get a passphrase. Terminate. */
4379 free_prompts(s->cur_prompt);
4380 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4384 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4385 free_prompts(s->cur_prompt);
4388 * Try decrypting key with passphrase.
4390 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4391 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4394 smemclr(passphrase, strlen(passphrase));
4398 /* Correct passphrase. */
4399 got_passphrase = TRUE;
4400 } else if (ret == 0) {
4401 c_write_str(ssh, "Couldn't load private key from ");
4402 c_write_str(ssh, filename_to_str(s->keyfile));
4403 c_write_str(ssh, " (");
4404 c_write_str(ssh, error);
4405 c_write_str(ssh, ").\r\n");
4406 got_passphrase = FALSE;
4407 break; /* go and try something else */
4408 } else if (ret == -1) {
4409 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4410 got_passphrase = FALSE;
4413 assert(0 && "unexpected return from loadrsakey()");
4414 got_passphrase = FALSE; /* placate optimisers */
4418 if (got_passphrase) {
4421 * Send a public key attempt.
4423 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4424 PKT_BIGNUM, s->key.modulus, PKT_END);
4427 if (pktin->type == SSH1_SMSG_FAILURE) {
4428 c_write_str(ssh, "Server refused our public key.\r\n");
4429 continue; /* go and try something else */
4431 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4432 bombout(("Bizarre response to offer of public key"));
4438 unsigned char buffer[32];
4439 Bignum challenge, response;
4441 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4442 bombout(("Server's RSA challenge was badly formatted"));
4445 response = rsadecrypt(challenge, &s->key);
4446 freebn(s->key.private_exponent);/* burn the evidence */
4448 for (i = 0; i < 32; i++) {
4449 buffer[i] = bignum_byte(response, 31 - i);
4453 MD5Update(&md5c, buffer, 32);
4454 MD5Update(&md5c, s->session_id, 16);
4455 MD5Final(buffer, &md5c);
4457 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4458 PKT_DATA, buffer, 16, PKT_END);
4465 if (pktin->type == SSH1_SMSG_FAILURE) {
4466 if (flags & FLAG_VERBOSE)
4467 c_write_str(ssh, "Failed to authenticate with"
4468 " our public key.\r\n");
4469 continue; /* go and try something else */
4470 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4471 bombout(("Bizarre response to RSA authentication response"));
4475 break; /* we're through! */
4481 * Otherwise, try various forms of password-like authentication.
4483 s->cur_prompt = new_prompts(ssh->frontend);
4485 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4486 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4487 !s->tis_auth_refused) {
4488 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4489 logevent("Requested TIS authentication");
4490 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4492 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4493 logevent("TIS authentication declined");
4494 if (flags & FLAG_INTERACTIVE)
4495 c_write_str(ssh, "TIS authentication refused.\r\n");
4496 s->tis_auth_refused = 1;
4501 char *instr_suf, *prompt;
4503 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4505 bombout(("TIS challenge packet was badly formed"));
4508 logevent("Received TIS challenge");
4509 s->cur_prompt->to_server = TRUE;
4510 s->cur_prompt->name = dupstr("SSH TIS authentication");
4511 /* Prompt heuristic comes from OpenSSH */
4512 if (memchr(challenge, '\n', challengelen)) {
4513 instr_suf = dupstr("");
4514 prompt = dupprintf("%.*s", challengelen, challenge);
4516 instr_suf = dupprintf("%.*s", challengelen, challenge);
4517 prompt = dupstr("Response: ");
4519 s->cur_prompt->instruction =
4520 dupprintf("Using TIS authentication.%s%s",
4521 (*instr_suf) ? "\n" : "",
4523 s->cur_prompt->instr_reqd = TRUE;
4524 add_prompt(s->cur_prompt, prompt, FALSE);
4528 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4529 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4530 !s->ccard_auth_refused) {
4531 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4532 logevent("Requested CryptoCard authentication");
4533 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4535 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4536 logevent("CryptoCard authentication declined");
4537 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4538 s->ccard_auth_refused = 1;
4543 char *instr_suf, *prompt;
4545 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4547 bombout(("CryptoCard challenge packet was badly formed"));
4550 logevent("Received CryptoCard challenge");
4551 s->cur_prompt->to_server = TRUE;
4552 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4553 s->cur_prompt->name_reqd = FALSE;
4554 /* Prompt heuristic comes from OpenSSH */
4555 if (memchr(challenge, '\n', challengelen)) {
4556 instr_suf = dupstr("");
4557 prompt = dupprintf("%.*s", challengelen, challenge);
4559 instr_suf = dupprintf("%.*s", challengelen, challenge);
4560 prompt = dupstr("Response: ");
4562 s->cur_prompt->instruction =
4563 dupprintf("Using CryptoCard authentication.%s%s",
4564 (*instr_suf) ? "\n" : "",
4566 s->cur_prompt->instr_reqd = TRUE;
4567 add_prompt(s->cur_prompt, prompt, FALSE);
4571 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4572 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4573 bombout(("No supported authentication methods available"));
4576 s->cur_prompt->to_server = TRUE;
4577 s->cur_prompt->name = dupstr("SSH password");
4578 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4579 ssh->username, ssh->savedhost),
4584 * Show password prompt, having first obtained it via a TIS
4585 * or CryptoCard exchange if we're doing TIS or CryptoCard
4589 int ret; /* need not be kept over crReturn */
4590 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4593 crWaitUntil(!pktin);
4594 ret = get_userpass_input(s->cur_prompt, in, inlen);
4599 * Failed to get a password (for example
4600 * because one was supplied on the command line
4601 * which has already failed to work). Terminate.
4603 free_prompts(s->cur_prompt);
4604 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4609 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4611 * Defence against traffic analysis: we send a
4612 * whole bunch of packets containing strings of
4613 * different lengths. One of these strings is the
4614 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4615 * The others are all random data in
4616 * SSH1_MSG_IGNORE packets. This way a passive
4617 * listener can't tell which is the password, and
4618 * hence can't deduce the password length.
4620 * Anybody with a password length greater than 16
4621 * bytes is going to have enough entropy in their
4622 * password that a listener won't find it _that_
4623 * much help to know how long it is. So what we'll
4626 * - if password length < 16, we send 15 packets
4627 * containing string lengths 1 through 15
4629 * - otherwise, we let N be the nearest multiple
4630 * of 8 below the password length, and send 8
4631 * packets containing string lengths N through
4632 * N+7. This won't obscure the order of
4633 * magnitude of the password length, but it will
4634 * introduce a bit of extra uncertainty.
4636 * A few servers can't deal with SSH1_MSG_IGNORE, at
4637 * least in this context. For these servers, we need
4638 * an alternative defence. We make use of the fact
4639 * that the password is interpreted as a C string:
4640 * so we can append a NUL, then some random data.
4642 * A few servers can deal with neither SSH1_MSG_IGNORE
4643 * here _nor_ a padded password string.
4644 * For these servers we are left with no defences
4645 * against password length sniffing.
4647 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4648 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4650 * The server can deal with SSH1_MSG_IGNORE, so
4651 * we can use the primary defence.
4653 int bottom, top, pwlen, i;
4656 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4658 bottom = 0; /* zero length passwords are OK! :-) */
4661 bottom = pwlen & ~7;
4665 assert(pwlen >= bottom && pwlen <= top);
4667 randomstr = snewn(top + 1, char);
4669 for (i = bottom; i <= top; i++) {
4671 defer_packet(ssh, s->pwpkt_type,
4672 PKT_STR,s->cur_prompt->prompts[0]->result,
4675 for (j = 0; j < i; j++) {
4677 randomstr[j] = random_byte();
4678 } while (randomstr[j] == '\0');
4680 randomstr[i] = '\0';
4681 defer_packet(ssh, SSH1_MSG_IGNORE,
4682 PKT_STR, randomstr, PKT_END);
4685 logevent("Sending password with camouflage packets");
4686 ssh_pkt_defersend(ssh);
4689 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4691 * The server can't deal with SSH1_MSG_IGNORE
4692 * but can deal with padded passwords, so we
4693 * can use the secondary defence.
4699 len = strlen(s->cur_prompt->prompts[0]->result);
4700 if (len < sizeof(string)) {
4702 strcpy(string, s->cur_prompt->prompts[0]->result);
4703 len++; /* cover the zero byte */
4704 while (len < sizeof(string)) {
4705 string[len++] = (char) random_byte();
4708 ss = s->cur_prompt->prompts[0]->result;
4710 logevent("Sending length-padded password");
4711 send_packet(ssh, s->pwpkt_type,
4712 PKT_INT, len, PKT_DATA, ss, len,
4716 * The server is believed unable to cope with
4717 * any of our password camouflage methods.
4720 len = strlen(s->cur_prompt->prompts[0]->result);
4721 logevent("Sending unpadded password");
4722 send_packet(ssh, s->pwpkt_type,
4724 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4728 send_packet(ssh, s->pwpkt_type,
4729 PKT_STR, s->cur_prompt->prompts[0]->result,
4732 logevent("Sent password");
4733 free_prompts(s->cur_prompt);
4735 if (pktin->type == SSH1_SMSG_FAILURE) {
4736 if (flags & FLAG_VERBOSE)
4737 c_write_str(ssh, "Access denied\r\n");
4738 logevent("Authentication refused");
4739 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4740 bombout(("Strange packet received, type %d", pktin->type));
4746 if (s->publickey_blob) {
4747 sfree(s->publickey_blob);
4748 sfree(s->publickey_comment);
4751 logevent("Authentication successful");
4756 static void ssh_channel_try_eof(struct ssh_channel *c)
4759 assert(c->pending_eof); /* precondition for calling us */
4761 return; /* can't close: not even opened yet */
4762 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4763 return; /* can't send EOF: pending outgoing data */
4765 c->pending_eof = FALSE; /* we're about to send it */
4766 if (ssh->version == 1) {
4767 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4769 c->closes |= CLOSES_SENT_EOF;
4771 struct Packet *pktout;
4772 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4773 ssh2_pkt_adduint32(pktout, c->remoteid);
4774 ssh2_pkt_send(ssh, pktout);
4775 c->closes |= CLOSES_SENT_EOF;
4776 ssh2_channel_check_close(c);
4780 Conf *sshfwd_get_conf(struct ssh_channel *c)
4786 void sshfwd_write_eof(struct ssh_channel *c)
4790 if (ssh->state == SSH_STATE_CLOSED)
4793 if (c->closes & CLOSES_SENT_EOF)
4796 c->pending_eof = TRUE;
4797 ssh_channel_try_eof(c);
4800 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4804 if (ssh->state == SSH_STATE_CLOSED)
4809 x11_close(c->u.x11.xconn);
4810 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4814 case CHAN_SOCKDATA_DORMANT:
4815 pfd_close(c->u.pfd.pf);
4816 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4819 c->type = CHAN_ZOMBIE;
4820 c->pending_eof = FALSE; /* this will confuse a zombie channel */
4822 ssh2_channel_check_close(c);
4825 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4829 if (ssh->state == SSH_STATE_CLOSED)
4832 if (ssh->version == 1) {
4833 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4834 PKT_INT, c->remoteid,
4835 PKT_INT, len, PKT_DATA, buf, len,
4838 * In SSH-1 we can return 0 here - implying that forwarded
4839 * connections are never individually throttled - because
4840 * the only circumstance that can cause throttling will be
4841 * the whole SSH connection backing up, in which case
4842 * _everything_ will be throttled as a whole.
4846 ssh2_add_channel_data(c, buf, len);
4847 return ssh2_try_send(c);
4851 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4856 if (ssh->state == SSH_STATE_CLOSED)
4859 if (ssh->version == 1) {
4860 buflimit = SSH1_BUFFER_LIMIT;
4862 buflimit = c->v.v2.locmaxwin;
4863 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4865 if (c->throttling_conn && bufsize <= buflimit) {
4866 c->throttling_conn = 0;
4867 ssh_throttle_conn(ssh, -1);
4871 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4873 struct queued_handler *qh = ssh->qhead;
4877 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4880 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4881 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4884 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4885 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4889 ssh->qhead = qh->next;
4891 if (ssh->qhead->msg1 > 0) {
4892 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4893 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4895 if (ssh->qhead->msg2 > 0) {
4896 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4897 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4900 ssh->qhead = ssh->qtail = NULL;
4903 qh->handler(ssh, pktin, qh->ctx);
4908 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4909 chandler_fn_t handler, void *ctx)
4911 struct queued_handler *qh;
4913 qh = snew(struct queued_handler);
4916 qh->handler = handler;
4920 if (ssh->qtail == NULL) {
4924 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4925 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4928 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4929 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4932 ssh->qtail->next = qh;
4937 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4939 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4941 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4942 SSH2_MSG_REQUEST_SUCCESS)) {
4943 logeventf(ssh, "Remote port forwarding from %s enabled",
4946 logeventf(ssh, "Remote port forwarding from %s refused",
4949 rpf = del234(ssh->rportfwds, pf);
4951 pf->pfrec->remote = NULL;
4956 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
4959 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
4962 pf->share_ctx = share_ctx;
4963 pf->shost = dupstr(shost);
4965 pf->sportdesc = NULL;
4966 if (!ssh->rportfwds) {
4967 assert(ssh->version == 2);
4968 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4970 if (add234(ssh->rportfwds, pf) != pf) {
4978 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
4981 share_got_pkt_from_server(ctx, pktin->type,
4982 pktin->body, pktin->length);
4985 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
4987 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
4988 ssh_sharing_global_request_response, share_ctx);
4991 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4993 struct ssh_portfwd *epf;
4997 if (!ssh->portfwds) {
4998 ssh->portfwds = newtree234(ssh_portcmp);
5001 * Go through the existing port forwardings and tag them
5002 * with status==DESTROY. Any that we want to keep will be
5003 * re-enabled (status==KEEP) as we go through the
5004 * configuration and find out which bits are the same as
5007 struct ssh_portfwd *epf;
5009 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5010 epf->status = DESTROY;
5013 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5015 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5016 char *kp, *kp2, *vp, *vp2;
5017 char address_family, type;
5018 int sport,dport,sserv,dserv;
5019 char *sports, *dports, *saddr, *host;
5023 address_family = 'A';
5025 if (*kp == 'A' || *kp == '4' || *kp == '6')
5026 address_family = *kp++;
5027 if (*kp == 'L' || *kp == 'R')
5030 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5032 * There's a colon in the middle of the source port
5033 * string, which means that the part before it is
5034 * actually a source address.
5036 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5037 saddr = host_strduptrim(saddr_tmp);
5044 sport = atoi(sports);
5048 sport = net_service_lookup(sports);
5050 logeventf(ssh, "Service lookup failed for source"
5051 " port \"%s\"", sports);
5055 if (type == 'L' && !strcmp(val, "D")) {
5056 /* dynamic forwarding */
5063 /* ordinary forwarding */
5065 vp2 = vp + host_strcspn(vp, ":");
5066 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5070 dport = atoi(dports);
5074 dport = net_service_lookup(dports);
5076 logeventf(ssh, "Service lookup failed for destination"
5077 " port \"%s\"", dports);
5082 if (sport && dport) {
5083 /* Set up a description of the source port. */
5084 struct ssh_portfwd *pfrec, *epfrec;
5086 pfrec = snew(struct ssh_portfwd);
5088 pfrec->saddr = saddr;
5089 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5090 pfrec->sport = sport;
5091 pfrec->daddr = host;
5092 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5093 pfrec->dport = dport;
5094 pfrec->local = NULL;
5095 pfrec->remote = NULL;
5096 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5097 address_family == '6' ? ADDRTYPE_IPV6 :
5100 epfrec = add234(ssh->portfwds, pfrec);
5101 if (epfrec != pfrec) {
5102 if (epfrec->status == DESTROY) {
5104 * We already have a port forwarding up and running
5105 * with precisely these parameters. Hence, no need
5106 * to do anything; simply re-tag the existing one
5109 epfrec->status = KEEP;
5112 * Anything else indicates that there was a duplicate
5113 * in our input, which we'll silently ignore.
5115 free_portfwd(pfrec);
5117 pfrec->status = CREATE;
5126 * Now go through and destroy any port forwardings which were
5129 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5130 if (epf->status == DESTROY) {
5133 message = dupprintf("%s port forwarding from %s%s%d",
5134 epf->type == 'L' ? "local" :
5135 epf->type == 'R' ? "remote" : "dynamic",
5136 epf->saddr ? epf->saddr : "",
5137 epf->saddr ? ":" : "",
5140 if (epf->type != 'D') {
5141 char *msg2 = dupprintf("%s to %s:%d", message,
5142 epf->daddr, epf->dport);
5147 logeventf(ssh, "Cancelling %s", message);
5150 /* epf->remote or epf->local may be NULL if setting up a
5151 * forwarding failed. */
5153 struct ssh_rportfwd *rpf = epf->remote;
5154 struct Packet *pktout;
5157 * Cancel the port forwarding at the server
5160 if (ssh->version == 1) {
5162 * We cannot cancel listening ports on the
5163 * server side in SSH-1! There's no message
5164 * to support it. Instead, we simply remove
5165 * the rportfwd record from the local end
5166 * so that any connections the server tries
5167 * to make on it are rejected.
5170 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5171 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5172 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5174 ssh2_pkt_addstring(pktout, epf->saddr);
5175 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5176 /* XXX: rport_acceptall may not represent
5177 * what was used to open the original connection,
5178 * since it's reconfigurable. */
5179 ssh2_pkt_addstring(pktout, "");
5181 ssh2_pkt_addstring(pktout, "localhost");
5183 ssh2_pkt_adduint32(pktout, epf->sport);
5184 ssh2_pkt_send(ssh, pktout);
5187 del234(ssh->rportfwds, rpf);
5189 } else if (epf->local) {
5190 pfl_terminate(epf->local);
5193 delpos234(ssh->portfwds, i);
5195 i--; /* so we don't skip one in the list */
5199 * And finally, set up any new port forwardings (status==CREATE).
5201 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5202 if (epf->status == CREATE) {
5203 char *sportdesc, *dportdesc;
5204 sportdesc = dupprintf("%s%s%s%s%d%s",
5205 epf->saddr ? epf->saddr : "",
5206 epf->saddr ? ":" : "",
5207 epf->sserv ? epf->sserv : "",
5208 epf->sserv ? "(" : "",
5210 epf->sserv ? ")" : "");
5211 if (epf->type == 'D') {
5214 dportdesc = dupprintf("%s:%s%s%d%s",
5216 epf->dserv ? epf->dserv : "",
5217 epf->dserv ? "(" : "",
5219 epf->dserv ? ")" : "");
5222 if (epf->type == 'L') {
5223 char *err = pfl_listen(epf->daddr, epf->dport,
5224 epf->saddr, epf->sport,
5225 ssh, conf, &epf->local,
5226 epf->addressfamily);
5228 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5229 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5230 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5231 sportdesc, dportdesc,
5232 err ? " failed: " : "", err ? err : "");
5235 } else if (epf->type == 'D') {
5236 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5237 ssh, conf, &epf->local,
5238 epf->addressfamily);
5240 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5241 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5242 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5244 err ? " failed: " : "", err ? err : "");
5249 struct ssh_rportfwd *pf;
5252 * Ensure the remote port forwardings tree exists.
5254 if (!ssh->rportfwds) {
5255 if (ssh->version == 1)
5256 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5258 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5261 pf = snew(struct ssh_rportfwd);
5262 pf->share_ctx = NULL;
5263 pf->dhost = dupstr(epf->daddr);
5264 pf->dport = epf->dport;
5266 pf->shost = dupstr(epf->saddr);
5267 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5268 pf->shost = dupstr("");
5270 pf->shost = dupstr("localhost");
5272 pf->sport = epf->sport;
5273 if (add234(ssh->rportfwds, pf) != pf) {
5274 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5275 epf->daddr, epf->dport);
5278 logeventf(ssh, "Requesting remote port %s"
5279 " forward to %s", sportdesc, dportdesc);
5281 pf->sportdesc = sportdesc;
5286 if (ssh->version == 1) {
5287 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5288 PKT_INT, epf->sport,
5289 PKT_STR, epf->daddr,
5290 PKT_INT, epf->dport,
5292 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5294 ssh_rportfwd_succfail, pf);
5296 struct Packet *pktout;
5297 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5298 ssh2_pkt_addstring(pktout, "tcpip-forward");
5299 ssh2_pkt_addbool(pktout, 1);/* want reply */
5300 ssh2_pkt_addstring(pktout, pf->shost);
5301 ssh2_pkt_adduint32(pktout, pf->sport);
5302 ssh2_pkt_send(ssh, pktout);
5304 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5305 SSH2_MSG_REQUEST_FAILURE,
5306 ssh_rportfwd_succfail, pf);
5315 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5318 int stringlen, bufsize;
5320 ssh_pkt_getstring(pktin, &string, &stringlen);
5321 if (string == NULL) {
5322 bombout(("Incoming terminal data packet was badly formed"));
5326 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5328 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5329 ssh->v1_stdout_throttling = 1;
5330 ssh_throttle_conn(ssh, +1);
5334 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5336 /* Remote side is trying to open a channel to talk to our
5337 * X-Server. Give them back a local channel number. */
5338 struct ssh_channel *c;
5339 int remoteid = ssh_pkt_getuint32(pktin);
5341 logevent("Received X11 connect request");
5342 /* Refuse if X11 forwarding is disabled. */
5343 if (!ssh->X11_fwd_enabled) {
5344 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5345 PKT_INT, remoteid, PKT_END);
5346 logevent("Rejected X11 connect request");
5348 c = snew(struct ssh_channel);
5351 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5352 c->remoteid = remoteid;
5353 c->halfopen = FALSE;
5354 c->localid = alloc_channel_id(ssh);
5356 c->pending_eof = FALSE;
5357 c->throttling_conn = 0;
5358 c->type = CHAN_X11; /* identify channel type */
5359 add234(ssh->channels, c);
5360 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5361 PKT_INT, c->remoteid, PKT_INT,
5362 c->localid, PKT_END);
5363 logevent("Opened X11 forward channel");
5367 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5369 /* Remote side is trying to open a channel to talk to our
5370 * agent. Give them back a local channel number. */
5371 struct ssh_channel *c;
5372 int remoteid = ssh_pkt_getuint32(pktin);
5374 /* Refuse if agent forwarding is disabled. */
5375 if (!ssh->agentfwd_enabled) {
5376 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5377 PKT_INT, remoteid, PKT_END);
5379 c = snew(struct ssh_channel);
5381 c->remoteid = remoteid;
5382 c->halfopen = FALSE;
5383 c->localid = alloc_channel_id(ssh);
5385 c->pending_eof = FALSE;
5386 c->throttling_conn = 0;
5387 c->type = CHAN_AGENT; /* identify channel type */
5388 c->u.a.lensofar = 0;
5389 c->u.a.message = NULL;
5390 c->u.a.outstanding_requests = 0;
5391 add234(ssh->channels, c);
5392 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5393 PKT_INT, c->remoteid, PKT_INT, c->localid,
5398 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5400 /* Remote side is trying to open a channel to talk to a
5401 * forwarded port. Give them back a local channel number. */
5402 struct ssh_rportfwd pf, *pfp;
5408 remoteid = ssh_pkt_getuint32(pktin);
5409 ssh_pkt_getstring(pktin, &host, &hostsize);
5410 port = ssh_pkt_getuint32(pktin);
5412 pf.dhost = dupprintf("%.*s", hostsize, host);
5414 pfp = find234(ssh->rportfwds, &pf, NULL);
5417 logeventf(ssh, "Rejected remote port open request for %s:%d",
5419 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5420 PKT_INT, remoteid, PKT_END);
5422 struct ssh_channel *c = snew(struct ssh_channel);
5425 logeventf(ssh, "Received remote port open request for %s:%d",
5427 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5428 c, ssh->conf, pfp->pfrec->addressfamily);
5430 logeventf(ssh, "Port open failed: %s", err);
5433 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5434 PKT_INT, remoteid, PKT_END);
5436 c->remoteid = remoteid;
5437 c->halfopen = FALSE;
5438 c->localid = alloc_channel_id(ssh);
5440 c->pending_eof = FALSE;
5441 c->throttling_conn = 0;
5442 c->type = CHAN_SOCKDATA; /* identify channel type */
5443 add234(ssh->channels, c);
5444 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5445 PKT_INT, c->remoteid, PKT_INT,
5446 c->localid, PKT_END);
5447 logevent("Forwarded port opened successfully");
5454 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5456 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5457 unsigned int localid = ssh_pkt_getuint32(pktin);
5458 struct ssh_channel *c;
5460 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5461 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5462 c->remoteid = localid;
5463 c->halfopen = FALSE;
5464 c->type = CHAN_SOCKDATA;
5465 c->throttling_conn = 0;
5466 pfd_confirm(c->u.pfd.pf);
5469 if (c && c->pending_eof) {
5471 * We have a pending close on this channel,
5472 * which we decided on before the server acked
5473 * the channel open. So now we know the
5474 * remoteid, we can close it again.
5476 ssh_channel_try_eof(c);
5480 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5482 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5483 struct ssh_channel *c;
5485 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5486 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5487 logevent("Forwarded connection refused by server");
5488 pfd_close(c->u.pfd.pf);
5489 del234(ssh->channels, c);
5494 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5496 /* Remote side closes a channel. */
5497 unsigned i = ssh_pkt_getuint32(pktin);
5498 struct ssh_channel *c;
5499 c = find234(ssh->channels, &i, ssh_channelfind);
5500 if (c && !c->halfopen) {
5502 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5503 !(c->closes & CLOSES_RCVD_EOF)) {
5505 * Received CHANNEL_CLOSE, which we translate into
5508 int send_close = FALSE;
5510 c->closes |= CLOSES_RCVD_EOF;
5515 x11_send_eof(c->u.x11.xconn);
5521 pfd_send_eof(c->u.pfd.pf);
5530 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5531 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5533 c->closes |= CLOSES_SENT_EOF;
5537 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5538 !(c->closes & CLOSES_RCVD_CLOSE)) {
5540 if (!(c->closes & CLOSES_SENT_EOF)) {
5541 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5542 " for which we never sent CHANNEL_CLOSE\n", i));
5545 c->closes |= CLOSES_RCVD_CLOSE;
5548 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5549 !(c->closes & CLOSES_SENT_CLOSE)) {
5550 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5551 PKT_INT, c->remoteid, PKT_END);
5552 c->closes |= CLOSES_SENT_CLOSE;
5555 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5556 ssh_channel_destroy(c);
5558 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5559 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5560 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5565 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5567 /* Data sent down one of our channels. */
5568 int i = ssh_pkt_getuint32(pktin);
5571 struct ssh_channel *c;
5573 ssh_pkt_getstring(pktin, &p, &len);
5575 c = find234(ssh->channels, &i, ssh_channelfind);
5580 bufsize = x11_send(c->u.x11.xconn, p, len);
5583 bufsize = pfd_send(c->u.pfd.pf, p, len);
5586 /* Data for an agent message. Buffer it. */
5588 if (c->u.a.lensofar < 4) {
5589 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5590 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5594 c->u.a.lensofar += l;
5596 if (c->u.a.lensofar == 4) {
5598 4 + GET_32BIT(c->u.a.msglen);
5599 c->u.a.message = snewn(c->u.a.totallen,
5601 memcpy(c->u.a.message, c->u.a.msglen, 4);
5603 if (c->u.a.lensofar >= 4 && len > 0) {
5605 min(c->u.a.totallen - c->u.a.lensofar,
5607 memcpy(c->u.a.message + c->u.a.lensofar, p,
5611 c->u.a.lensofar += l;
5613 if (c->u.a.lensofar == c->u.a.totallen) {
5616 c->u.a.outstanding_requests++;
5617 if (agent_query(c->u.a.message,
5620 ssh_agentf_callback, c))
5621 ssh_agentf_callback(c, reply, replylen);
5622 sfree(c->u.a.message);
5623 c->u.a.lensofar = 0;
5626 bufsize = 0; /* agent channels never back up */
5629 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5630 c->throttling_conn = 1;
5631 ssh_throttle_conn(ssh, +1);
5636 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5638 ssh->exitcode = ssh_pkt_getuint32(pktin);
5639 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5640 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5642 * In case `helpful' firewalls or proxies tack
5643 * extra human-readable text on the end of the
5644 * session which we might mistake for another
5645 * encrypted packet, we close the session once
5646 * we've sent EXIT_CONFIRMATION.
5648 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5651 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5652 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5654 struct Packet *pktout = (struct Packet *)data;
5656 unsigned int arg = 0;
5657 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5658 if (i == lenof(ssh_ttymodes)) return;
5659 switch (ssh_ttymodes[i].type) {
5661 arg = ssh_tty_parse_specchar(val);
5664 arg = ssh_tty_parse_boolean(val);
5667 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5668 ssh2_pkt_addbyte(pktout, arg);
5671 int ssh_agent_forwarding_permitted(Ssh ssh)
5673 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5676 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5677 struct Packet *pktin)
5679 crBegin(ssh->do_ssh1_connection_crstate);
5681 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5682 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5683 ssh1_smsg_stdout_stderr_data;
5685 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5686 ssh1_msg_channel_open_confirmation;
5687 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5688 ssh1_msg_channel_open_failure;
5689 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5690 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5691 ssh1_msg_channel_close;
5692 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5693 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5695 if (ssh_agent_forwarding_permitted(ssh)) {
5696 logevent("Requesting agent forwarding");
5697 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5701 if (pktin->type != SSH1_SMSG_SUCCESS
5702 && pktin->type != SSH1_SMSG_FAILURE) {
5703 bombout(("Protocol confusion"));
5705 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5706 logevent("Agent forwarding refused");
5708 logevent("Agent forwarding enabled");
5709 ssh->agentfwd_enabled = TRUE;
5710 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5714 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5716 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5718 if (!ssh->x11disp) {
5719 /* FIXME: return an error message from x11_setup_display */
5720 logevent("X11 forwarding not enabled: unable to"
5721 " initialise X display");
5723 ssh->x11auth = x11_invent_fake_auth
5724 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5725 ssh->x11auth->disp = ssh->x11disp;
5727 logevent("Requesting X11 forwarding");
5728 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5729 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5730 PKT_STR, ssh->x11auth->protoname,
5731 PKT_STR, ssh->x11auth->datastring,
5732 PKT_INT, ssh->x11disp->screennum,
5735 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5736 PKT_STR, ssh->x11auth->protoname,
5737 PKT_STR, ssh->x11auth->datastring,
5743 if (pktin->type != SSH1_SMSG_SUCCESS
5744 && pktin->type != SSH1_SMSG_FAILURE) {
5745 bombout(("Protocol confusion"));
5747 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5748 logevent("X11 forwarding refused");
5750 logevent("X11 forwarding enabled");
5751 ssh->X11_fwd_enabled = TRUE;
5752 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5757 ssh_setup_portfwd(ssh, ssh->conf);
5758 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5760 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5762 /* Unpick the terminal-speed string. */
5763 /* XXX perhaps we should allow no speeds to be sent. */
5764 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5765 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5766 /* Send the pty request. */
5767 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5768 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5769 ssh_pkt_adduint32(pkt, ssh->term_height);
5770 ssh_pkt_adduint32(pkt, ssh->term_width);
5771 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5772 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5773 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5774 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5775 ssh_pkt_adduint32(pkt, ssh->ispeed);
5776 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5777 ssh_pkt_adduint32(pkt, ssh->ospeed);
5778 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5780 ssh->state = SSH_STATE_INTERMED;
5784 if (pktin->type != SSH1_SMSG_SUCCESS
5785 && pktin->type != SSH1_SMSG_FAILURE) {
5786 bombout(("Protocol confusion"));
5788 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5789 c_write_str(ssh, "Server refused to allocate pty\r\n");
5790 ssh->editing = ssh->echoing = 1;
5792 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5793 ssh->ospeed, ssh->ispeed);
5794 ssh->got_pty = TRUE;
5797 ssh->editing = ssh->echoing = 1;
5800 if (conf_get_int(ssh->conf, CONF_compression)) {
5801 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5805 if (pktin->type != SSH1_SMSG_SUCCESS
5806 && pktin->type != SSH1_SMSG_FAILURE) {
5807 bombout(("Protocol confusion"));
5809 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5810 c_write_str(ssh, "Server refused to compress\r\n");
5812 logevent("Started compression");
5813 ssh->v1_compressing = TRUE;
5814 ssh->cs_comp_ctx = zlib_compress_init();
5815 logevent("Initialised zlib (RFC1950) compression");
5816 ssh->sc_comp_ctx = zlib_decompress_init();
5817 logevent("Initialised zlib (RFC1950) decompression");
5821 * Start the shell or command.
5823 * Special case: if the first-choice command is an SSH-2
5824 * subsystem (hence not usable here) and the second choice
5825 * exists, we fall straight back to that.
5828 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5830 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5831 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5832 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5833 ssh->fallback_cmd = TRUE;
5836 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5838 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5839 logevent("Started session");
5842 ssh->state = SSH_STATE_SESSION;
5843 if (ssh->size_needed)
5844 ssh_size(ssh, ssh->term_width, ssh->term_height);
5845 if (ssh->eof_needed)
5846 ssh_special(ssh, TS_EOF);
5849 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5851 ssh->channels = newtree234(ssh_channelcmp);
5855 * By this point, most incoming packets are already being
5856 * handled by the dispatch table, and we need only pay
5857 * attention to the unusual ones.
5862 if (pktin->type == SSH1_SMSG_SUCCESS) {
5863 /* may be from EXEC_SHELL on some servers */
5864 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5865 /* may be from EXEC_SHELL on some servers
5866 * if no pty is available or in other odd cases. Ignore */
5868 bombout(("Strange packet received: type %d", pktin->type));
5873 int len = min(inlen, 512);
5874 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5875 PKT_INT, len, PKT_DATA, in, len,
5887 * Handle the top-level SSH-2 protocol.
5889 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5894 ssh_pkt_getstring(pktin, &msg, &msglen);
5895 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5898 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5900 /* log reason code in disconnect message */
5904 ssh_pkt_getstring(pktin, &msg, &msglen);
5905 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5908 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5910 /* Do nothing, because we're ignoring it! Duhh. */
5913 static void ssh1_protocol_setup(Ssh ssh)
5918 * Most messages are handled by the coroutines.
5920 for (i = 0; i < 256; i++)
5921 ssh->packet_dispatch[i] = NULL;
5924 * These special message types we install handlers for.
5926 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5927 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5928 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5931 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5932 struct Packet *pktin)
5934 unsigned char *in=(unsigned char*)vin;
5935 if (ssh->state == SSH_STATE_CLOSED)
5938 if (pktin && ssh->packet_dispatch[pktin->type]) {
5939 ssh->packet_dispatch[pktin->type](ssh, pktin);
5943 if (!ssh->protocol_initial_phase_done) {
5944 if (do_ssh1_login(ssh, in, inlen, pktin))
5945 ssh->protocol_initial_phase_done = TRUE;
5950 do_ssh1_connection(ssh, in, inlen, pktin);
5954 * Utility routine for decoding comma-separated strings in KEXINIT.
5956 static int in_commasep_string(char *needle, char *haystack, int haylen)
5959 if (!needle || !haystack) /* protect against null pointers */
5961 needlen = strlen(needle);
5964 * Is it at the start of the string?
5966 if (haylen >= needlen && /* haystack is long enough */
5967 !memcmp(needle, haystack, needlen) && /* initial match */
5968 (haylen == needlen || haystack[needlen] == ',')
5969 /* either , or EOS follows */
5973 * If not, search for the next comma and resume after that.
5974 * If no comma found, terminate.
5976 while (haylen > 0 && *haystack != ',')
5977 haylen--, haystack++;
5980 haylen--, haystack++; /* skip over comma itself */
5985 * Similar routine for checking whether we have the first string in a list.
5987 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5990 if (!needle || !haystack) /* protect against null pointers */
5992 needlen = strlen(needle);
5994 * Is it at the start of the string?
5996 if (haylen >= needlen && /* haystack is long enough */
5997 !memcmp(needle, haystack, needlen) && /* initial match */
5998 (haylen == needlen || haystack[needlen] == ',')
5999 /* either , or EOS follows */
6007 * SSH-2 key creation method.
6008 * (Currently assumes 2 lots of any hash are sufficient to generate
6009 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
6011 #define SSH2_MKKEY_ITERS (2)
6012 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
6013 unsigned char *keyspace)
6015 const struct ssh_hash *h = ssh->kex->hash;
6017 /* First hlen bytes. */
6019 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6020 hash_mpint(h, s, K);
6021 h->bytes(s, H, h->hlen);
6022 h->bytes(s, &chr, 1);
6023 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6024 h->final(s, keyspace);
6025 /* Next hlen bytes. */
6027 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6028 hash_mpint(h, s, K);
6029 h->bytes(s, H, h->hlen);
6030 h->bytes(s, keyspace, h->hlen);
6031 h->final(s, keyspace + h->hlen);
6035 * Handle the SSH-2 transport layer.
6037 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
6038 struct Packet *pktin)
6040 unsigned char *in = (unsigned char *)vin;
6041 struct do_ssh2_transport_state {
6043 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
6044 Bignum p, g, e, f, K;
6047 int kex_init_value, kex_reply_value;
6048 const struct ssh_mac **maclist;
6050 const struct ssh2_cipher *cscipher_tobe;
6051 const struct ssh2_cipher *sccipher_tobe;
6052 const struct ssh_mac *csmac_tobe;
6053 const struct ssh_mac *scmac_tobe;
6054 const struct ssh_compress *cscomp_tobe;
6055 const struct ssh_compress *sccomp_tobe;
6056 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6057 int hostkeylen, siglen, rsakeylen;
6058 void *hkey; /* actual host key */
6059 void *rsakey; /* for RSA kex */
6060 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6061 int n_preferred_kex;
6062 const struct ssh_kexes *preferred_kex[KEX_MAX];
6063 int n_preferred_ciphers;
6064 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6065 const struct ssh_compress *preferred_comp;
6066 int userauth_succeeded; /* for delayed compression */
6067 int pending_compression;
6068 int got_session_id, activated_authconn;
6069 struct Packet *pktout;
6074 crState(do_ssh2_transport_state);
6076 assert(!ssh->bare_connection);
6080 s->cscipher_tobe = s->sccipher_tobe = NULL;
6081 s->csmac_tobe = s->scmac_tobe = NULL;
6082 s->cscomp_tobe = s->sccomp_tobe = NULL;
6084 s->got_session_id = s->activated_authconn = FALSE;
6085 s->userauth_succeeded = FALSE;
6086 s->pending_compression = FALSE;
6089 * Be prepared to work around the buggy MAC problem.
6091 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6092 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6094 s->maclist = macs, s->nmacs = lenof(macs);
6097 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6099 int i, j, k, commalist_started;
6102 * Set up the preferred key exchange. (NULL => warn below here)
6104 s->n_preferred_kex = 0;
6105 for (i = 0; i < KEX_MAX; i++) {
6106 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6108 s->preferred_kex[s->n_preferred_kex++] =
6109 &ssh_diffiehellman_gex;
6112 s->preferred_kex[s->n_preferred_kex++] =
6113 &ssh_diffiehellman_group14;
6116 s->preferred_kex[s->n_preferred_kex++] =
6117 &ssh_diffiehellman_group1;
6120 s->preferred_kex[s->n_preferred_kex++] =
6124 /* Flag for later. Don't bother if it's the last in
6126 if (i < KEX_MAX - 1) {
6127 s->preferred_kex[s->n_preferred_kex++] = NULL;
6134 * Set up the preferred ciphers. (NULL => warn below here)
6136 s->n_preferred_ciphers = 0;
6137 for (i = 0; i < CIPHER_MAX; i++) {
6138 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6139 case CIPHER_BLOWFISH:
6140 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6143 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6144 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6148 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6151 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6153 case CIPHER_ARCFOUR:
6154 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6157 /* Flag for later. Don't bother if it's the last in
6159 if (i < CIPHER_MAX - 1) {
6160 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6167 * Set up preferred compression.
6169 if (conf_get_int(ssh->conf, CONF_compression))
6170 s->preferred_comp = &ssh_zlib;
6172 s->preferred_comp = &ssh_comp_none;
6175 * Enable queueing of outgoing auth- or connection-layer
6176 * packets while we are in the middle of a key exchange.
6178 ssh->queueing = TRUE;
6181 * Flag that KEX is in progress.
6183 ssh->kex_in_progress = TRUE;
6186 * Construct and send our key exchange packet.
6188 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6189 for (i = 0; i < 16; i++)
6190 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6191 /* List key exchange algorithms. */
6192 ssh2_pkt_addstring_start(s->pktout);
6193 commalist_started = 0;
6194 for (i = 0; i < s->n_preferred_kex; i++) {
6195 const struct ssh_kexes *k = s->preferred_kex[i];
6196 if (!k) continue; /* warning flag */
6197 for (j = 0; j < k->nkexes; j++) {
6198 if (commalist_started)
6199 ssh2_pkt_addstring_str(s->pktout, ",");
6200 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
6201 commalist_started = 1;
6204 /* List server host key algorithms. */
6205 if (!s->got_session_id) {
6207 * In the first key exchange, we list all the algorithms
6208 * we're prepared to cope with.
6210 ssh2_pkt_addstring_start(s->pktout);
6211 for (i = 0; i < lenof(hostkey_algs); i++) {
6212 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
6213 if (i < lenof(hostkey_algs) - 1)
6214 ssh2_pkt_addstring_str(s->pktout, ",");
6218 * In subsequent key exchanges, we list only the kex
6219 * algorithm that was selected in the first key exchange,
6220 * so that we keep getting the same host key and hence
6221 * don't have to interrupt the user's session to ask for
6225 ssh2_pkt_addstring(s->pktout, ssh->hostkey->name);
6227 /* List encryption algorithms (client->server then server->client). */
6228 for (k = 0; k < 2; k++) {
6229 ssh2_pkt_addstring_start(s->pktout);
6230 commalist_started = 0;
6231 for (i = 0; i < s->n_preferred_ciphers; i++) {
6232 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6233 if (!c) continue; /* warning flag */
6234 for (j = 0; j < c->nciphers; j++) {
6235 if (commalist_started)
6236 ssh2_pkt_addstring_str(s->pktout, ",");
6237 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
6238 commalist_started = 1;
6242 /* List MAC algorithms (client->server then server->client). */
6243 for (j = 0; j < 2; j++) {
6244 ssh2_pkt_addstring_start(s->pktout);
6245 for (i = 0; i < s->nmacs; i++) {
6246 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
6247 if (i < s->nmacs - 1)
6248 ssh2_pkt_addstring_str(s->pktout, ",");
6251 /* List client->server compression algorithms,
6252 * then server->client compression algorithms. (We use the
6253 * same set twice.) */
6254 for (j = 0; j < 2; j++) {
6255 ssh2_pkt_addstring_start(s->pktout);
6256 assert(lenof(compressions) > 1);
6257 /* Prefer non-delayed versions */
6258 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
6259 /* We don't even list delayed versions of algorithms until
6260 * they're allowed to be used, to avoid a race. See the end of
6262 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6263 ssh2_pkt_addstring_str(s->pktout, ",");
6264 ssh2_pkt_addstring_str(s->pktout,
6265 s->preferred_comp->delayed_name);
6267 for (i = 0; i < lenof(compressions); i++) {
6268 const struct ssh_compress *c = compressions[i];
6269 if (c != s->preferred_comp) {
6270 ssh2_pkt_addstring_str(s->pktout, ",");
6271 ssh2_pkt_addstring_str(s->pktout, c->name);
6272 if (s->userauth_succeeded && c->delayed_name) {
6273 ssh2_pkt_addstring_str(s->pktout, ",");
6274 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
6279 /* List client->server languages. Empty list. */
6280 ssh2_pkt_addstring_start(s->pktout);
6281 /* List server->client languages. Empty list. */
6282 ssh2_pkt_addstring_start(s->pktout);
6283 /* First KEX packet does _not_ follow, because we're not that brave. */
6284 ssh2_pkt_addbool(s->pktout, FALSE);
6286 ssh2_pkt_adduint32(s->pktout, 0);
6289 s->our_kexinitlen = s->pktout->length - 5;
6290 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6291 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6293 ssh2_pkt_send_noqueue(ssh, s->pktout);
6296 crWaitUntilV(pktin);
6299 * Now examine the other side's KEXINIT to see what we're up
6303 char *str, *preferred;
6306 if (pktin->type != SSH2_MSG_KEXINIT) {
6307 bombout(("expected key exchange packet from server"));
6311 ssh->hostkey = NULL;
6312 s->cscipher_tobe = NULL;
6313 s->sccipher_tobe = NULL;
6314 s->csmac_tobe = NULL;
6315 s->scmac_tobe = NULL;
6316 s->cscomp_tobe = NULL;
6317 s->sccomp_tobe = NULL;
6318 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
6320 pktin->savedpos += 16; /* skip garbage cookie */
6321 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
6323 bombout(("KEXINIT packet was incomplete"));
6328 for (i = 0; i < s->n_preferred_kex; i++) {
6329 const struct ssh_kexes *k = s->preferred_kex[i];
6333 for (j = 0; j < k->nkexes; j++) {
6334 if (!preferred) preferred = k->list[j]->name;
6335 if (in_commasep_string(k->list[j]->name, str, len)) {
6336 ssh->kex = k->list[j];
6345 bombout(("Couldn't agree a key exchange algorithm"
6346 " (available: %.*s)", len, str));
6350 * Note that the server's guess is considered wrong if it doesn't match
6351 * the first algorithm in our list, even if it's still the algorithm
6354 s->guessok = first_in_commasep_string(preferred, str, len);
6355 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
6357 bombout(("KEXINIT packet was incomplete"));
6360 for (i = 0; i < lenof(hostkey_algs); i++) {
6361 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
6362 ssh->hostkey = hostkey_algs[i];
6366 if (!ssh->hostkey) {
6367 bombout(("Couldn't agree a host key algorithm"
6368 " (available: %.*s)", len, str));
6372 s->guessok = s->guessok &&
6373 first_in_commasep_string(hostkey_algs[0]->name, str, len);
6374 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
6376 bombout(("KEXINIT packet was incomplete"));
6379 for (i = 0; i < s->n_preferred_ciphers; i++) {
6380 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6382 s->warn_cscipher = TRUE;
6384 for (j = 0; j < c->nciphers; j++) {
6385 if (in_commasep_string(c->list[j]->name, str, len)) {
6386 s->cscipher_tobe = c->list[j];
6391 if (s->cscipher_tobe)
6394 if (!s->cscipher_tobe) {
6395 bombout(("Couldn't agree a client-to-server cipher"
6396 " (available: %.*s)", len, str));
6400 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
6402 bombout(("KEXINIT packet was incomplete"));
6405 for (i = 0; i < s->n_preferred_ciphers; i++) {
6406 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6408 s->warn_sccipher = TRUE;
6410 for (j = 0; j < c->nciphers; j++) {
6411 if (in_commasep_string(c->list[j]->name, str, len)) {
6412 s->sccipher_tobe = c->list[j];
6417 if (s->sccipher_tobe)
6420 if (!s->sccipher_tobe) {
6421 bombout(("Couldn't agree a server-to-client cipher"
6422 " (available: %.*s)", len, str));
6426 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
6428 bombout(("KEXINIT packet was incomplete"));
6431 for (i = 0; i < s->nmacs; i++) {
6432 if (in_commasep_string(s->maclist[i]->name, str, len)) {
6433 s->csmac_tobe = s->maclist[i];
6437 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
6439 bombout(("KEXINIT packet was incomplete"));
6442 for (i = 0; i < s->nmacs; i++) {
6443 if (in_commasep_string(s->maclist[i]->name, str, len)) {
6444 s->scmac_tobe = s->maclist[i];
6448 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
6450 bombout(("KEXINIT packet was incomplete"));
6453 for (i = 0; i < lenof(compressions) + 1; i++) {
6454 const struct ssh_compress *c =
6455 i == 0 ? s->preferred_comp : compressions[i - 1];
6456 if (in_commasep_string(c->name, str, len)) {
6459 } else if (in_commasep_string(c->delayed_name, str, len)) {
6460 if (s->userauth_succeeded) {
6464 s->pending_compression = TRUE; /* try this later */
6468 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
6470 bombout(("KEXINIT packet was incomplete"));
6473 for (i = 0; i < lenof(compressions) + 1; i++) {
6474 const struct ssh_compress *c =
6475 i == 0 ? s->preferred_comp : compressions[i - 1];
6476 if (in_commasep_string(c->name, str, len)) {
6479 } else if (in_commasep_string(c->delayed_name, str, len)) {
6480 if (s->userauth_succeeded) {
6484 s->pending_compression = TRUE; /* try this later */
6488 if (s->pending_compression) {
6489 logevent("Server supports delayed compression; "
6490 "will try this later");
6492 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6493 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6494 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6496 ssh->exhash = ssh->kex->hash->init();
6497 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6498 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6499 hash_string(ssh->kex->hash, ssh->exhash,
6500 s->our_kexinit, s->our_kexinitlen);
6501 sfree(s->our_kexinit);
6502 /* Include the type byte in the hash of server's KEXINIT */
6503 hash_string(ssh->kex->hash, ssh->exhash,
6504 pktin->body - 1, pktin->length + 1);
6507 ssh_set_frozen(ssh, 1);
6508 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6510 ssh_dialog_callback, ssh);
6511 if (s->dlgret < 0) {
6515 bombout(("Unexpected data from server while"
6516 " waiting for user response"));
6519 } while (pktin || inlen > 0);
6520 s->dlgret = ssh->user_response;
6522 ssh_set_frozen(ssh, 0);
6523 if (s->dlgret == 0) {
6524 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6530 if (s->warn_cscipher) {
6531 ssh_set_frozen(ssh, 1);
6532 s->dlgret = askalg(ssh->frontend,
6533 "client-to-server cipher",
6534 s->cscipher_tobe->name,
6535 ssh_dialog_callback, ssh);
6536 if (s->dlgret < 0) {
6540 bombout(("Unexpected data from server while"
6541 " waiting for user response"));
6544 } while (pktin || inlen > 0);
6545 s->dlgret = ssh->user_response;
6547 ssh_set_frozen(ssh, 0);
6548 if (s->dlgret == 0) {
6549 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6555 if (s->warn_sccipher) {
6556 ssh_set_frozen(ssh, 1);
6557 s->dlgret = askalg(ssh->frontend,
6558 "server-to-client cipher",
6559 s->sccipher_tobe->name,
6560 ssh_dialog_callback, ssh);
6561 if (s->dlgret < 0) {
6565 bombout(("Unexpected data from server while"
6566 " waiting for user response"));
6569 } while (pktin || inlen > 0);
6570 s->dlgret = ssh->user_response;
6572 ssh_set_frozen(ssh, 0);
6573 if (s->dlgret == 0) {
6574 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6580 if (s->ignorepkt) /* first_kex_packet_follows */
6581 crWaitUntilV(pktin); /* Ignore packet */
6584 if (ssh->kex->main_type == KEXTYPE_DH) {
6586 * Work out the number of bits of key we will need from the
6587 * key exchange. We start with the maximum key length of
6593 csbits = s->cscipher_tobe->keylen;
6594 scbits = s->sccipher_tobe->keylen;
6595 s->nbits = (csbits > scbits ? csbits : scbits);
6597 /* The keys only have hlen-bit entropy, since they're based on
6598 * a hash. So cap the key size at hlen bits. */
6599 if (s->nbits > ssh->kex->hash->hlen * 8)
6600 s->nbits = ssh->kex->hash->hlen * 8;
6603 * If we're doing Diffie-Hellman group exchange, start by
6604 * requesting a group.
6606 if (!ssh->kex->pdata) {
6607 logevent("Doing Diffie-Hellman group exchange");
6608 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6610 * Work out how big a DH group we will need to allow that
6613 s->pbits = 512 << ((s->nbits - 1) / 64);
6614 if (s->pbits < DH_MIN_SIZE)
6615 s->pbits = DH_MIN_SIZE;
6616 if (s->pbits > DH_MAX_SIZE)
6617 s->pbits = DH_MAX_SIZE;
6618 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6619 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6620 ssh2_pkt_adduint32(s->pktout, s->pbits);
6622 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6623 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6624 ssh2_pkt_adduint32(s->pktout, s->pbits);
6625 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6627 ssh2_pkt_send_noqueue(ssh, s->pktout);
6629 crWaitUntilV(pktin);
6630 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6631 bombout(("expected key exchange group packet from server"));
6634 s->p = ssh2_pkt_getmp(pktin);
6635 s->g = ssh2_pkt_getmp(pktin);
6636 if (!s->p || !s->g) {
6637 bombout(("unable to read mp-ints from incoming group packet"));
6640 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6641 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6642 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6644 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6645 ssh->kex_ctx = dh_setup_group(ssh->kex);
6646 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6647 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6648 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6649 ssh->kex->groupname);
6652 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6653 ssh->kex->hash->text_name);
6655 * Now generate and send e for Diffie-Hellman.
6657 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6658 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6659 s->pktout = ssh2_pkt_init(s->kex_init_value);
6660 ssh2_pkt_addmp(s->pktout, s->e);
6661 ssh2_pkt_send_noqueue(ssh, s->pktout);
6663 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6664 crWaitUntilV(pktin);
6665 if (pktin->type != s->kex_reply_value) {
6666 bombout(("expected key exchange reply packet from server"));
6669 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6670 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6671 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6672 s->f = ssh2_pkt_getmp(pktin);
6674 bombout(("unable to parse key exchange reply packet"));
6677 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6680 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
6682 bombout(("key exchange reply failed validation: %s", err));
6686 s->K = dh_find_K(ssh->kex_ctx, s->f);
6688 /* We assume everything from now on will be quick, and it might
6689 * involve user interaction. */
6690 set_busy_status(ssh->frontend, BUSY_NOT);
6692 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6693 if (!ssh->kex->pdata) {
6694 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6695 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
6696 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6697 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6698 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
6699 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6700 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6702 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6703 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6705 dh_cleanup(ssh->kex_ctx);
6707 if (!ssh->kex->pdata) {
6712 logeventf(ssh, "Doing RSA key exchange with hash %s",
6713 ssh->kex->hash->text_name);
6714 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6716 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6719 crWaitUntilV(pktin);
6720 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6721 bombout(("expected RSA public key packet from server"));
6725 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6726 hash_string(ssh->kex->hash, ssh->exhash,
6727 s->hostkeydata, s->hostkeylen);
6728 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6732 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6733 s->rsakeydata = snewn(s->rsakeylen, char);
6734 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6737 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6739 sfree(s->rsakeydata);
6740 bombout(("unable to parse RSA public key from server"));
6744 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6747 * Next, set up a shared secret K, of precisely KLEN -
6748 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6749 * RSA key modulus and HLEN is the bit length of the hash
6753 int klen = ssh_rsakex_klen(s->rsakey);
6754 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6756 unsigned char *kstr1, *kstr2, *outstr;
6757 int kstr1len, kstr2len, outstrlen;
6759 s->K = bn_power_2(nbits - 1);
6761 for (i = 0; i < nbits; i++) {
6763 byte = random_byte();
6765 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6769 * Encode this as an mpint.
6771 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6772 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6773 PUT_32BIT(kstr2, kstr1len);
6774 memcpy(kstr2 + 4, kstr1, kstr1len);
6777 * Encrypt it with the given RSA key.
6779 outstrlen = (klen + 7) / 8;
6780 outstr = snewn(outstrlen, unsigned char);
6781 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6782 outstr, outstrlen, s->rsakey);
6785 * And send it off in a return packet.
6787 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6788 ssh2_pkt_addstring_start(s->pktout);
6789 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6790 ssh2_pkt_send_noqueue(ssh, s->pktout);
6792 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6799 ssh_rsakex_freekey(s->rsakey);
6801 crWaitUntilV(pktin);
6802 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6803 sfree(s->rsakeydata);
6804 bombout(("expected signature packet from server"));
6808 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6810 sfree(s->rsakeydata);
6813 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6814 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6815 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6817 ssh->kex_ctx = NULL;
6820 debug(("Exchange hash is:\n"));
6821 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6825 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6826 (char *)s->exchange_hash,
6827 ssh->kex->hash->hlen)) {
6828 bombout(("Server's host key did not match the signature supplied"));
6832 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6833 if (!s->got_session_id) {
6835 * Authenticate remote host: verify host key. (We've already
6836 * checked the signature of the exchange hash.)
6838 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6839 logevent("Host key fingerprint is:");
6840 logevent(s->fingerprint);
6841 /* First check against manually configured host keys. */
6842 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
6843 ssh->hostkey, s->hkey);
6844 if (s->dlgret == 0) { /* did not match */
6845 bombout(("Host key did not appear in manually configured list"));
6847 } else if (s->dlgret < 0) { /* none configured; use standard handling */
6848 ssh_set_frozen(ssh, 1);
6849 s->dlgret = verify_ssh_host_key(ssh->frontend,
6850 ssh->savedhost, ssh->savedport,
6851 ssh->hostkey->keytype, s->keystr,
6853 ssh_dialog_callback, ssh);
6854 if (s->dlgret < 0) {
6858 bombout(("Unexpected data from server while waiting"
6859 " for user host key response"));
6862 } while (pktin || inlen > 0);
6863 s->dlgret = ssh->user_response;
6865 ssh_set_frozen(ssh, 0);
6866 if (s->dlgret == 0) {
6867 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
6872 sfree(s->fingerprint);
6874 * Save this host key, to check against the one presented in
6875 * subsequent rekeys.
6877 ssh->hostkey_str = s->keystr;
6880 * In a rekey, we never present an interactive host key
6881 * verification request to the user. Instead, we simply
6882 * enforce that the key we're seeing this time is identical to
6883 * the one we saw before.
6885 if (strcmp(ssh->hostkey_str, s->keystr)) {
6886 bombout(("Host key was different in repeat key exchange"));
6891 ssh->hostkey->freekey(s->hkey);
6894 * The exchange hash from the very first key exchange is also
6895 * the session id, used in session key construction and
6898 if (!s->got_session_id) {
6899 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6900 memcpy(ssh->v2_session_id, s->exchange_hash,
6901 sizeof(s->exchange_hash));
6902 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6903 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6904 s->got_session_id = TRUE;
6908 * Send SSH2_MSG_NEWKEYS.
6910 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6911 ssh2_pkt_send_noqueue(ssh, s->pktout);
6912 ssh->outgoing_data_size = 0; /* start counting from here */
6915 * We've sent client NEWKEYS, so create and initialise
6916 * client-to-server session keys.
6918 if (ssh->cs_cipher_ctx)
6919 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6920 ssh->cscipher = s->cscipher_tobe;
6921 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6923 if (ssh->cs_mac_ctx)
6924 ssh->csmac->free_context(ssh->cs_mac_ctx);
6925 ssh->csmac = s->csmac_tobe;
6926 ssh->cs_mac_ctx = ssh->csmac->make_context();
6928 if (ssh->cs_comp_ctx)
6929 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6930 ssh->cscomp = s->cscomp_tobe;
6931 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6934 * Set IVs on client-to-server keys. Here we use the exchange
6935 * hash from the _first_ key exchange.
6938 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6939 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6940 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6941 assert((ssh->cscipher->keylen+7) / 8 <=
6942 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6943 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6944 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6945 assert(ssh->cscipher->blksize <=
6946 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6947 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6948 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6949 assert(ssh->csmac->len <=
6950 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6951 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6952 smemclr(keyspace, sizeof(keyspace));
6955 logeventf(ssh, "Initialised %.200s client->server encryption",
6956 ssh->cscipher->text_name);
6957 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6958 ssh->csmac->text_name);
6959 if (ssh->cscomp->text_name)
6960 logeventf(ssh, "Initialised %s compression",
6961 ssh->cscomp->text_name);
6964 * Now our end of the key exchange is complete, we can send all
6965 * our queued higher-layer packets.
6967 ssh->queueing = FALSE;
6968 ssh2_pkt_queuesend(ssh);
6971 * Expect SSH2_MSG_NEWKEYS from server.
6973 crWaitUntilV(pktin);
6974 if (pktin->type != SSH2_MSG_NEWKEYS) {
6975 bombout(("expected new-keys packet from server"));
6978 ssh->incoming_data_size = 0; /* start counting from here */
6981 * We've seen server NEWKEYS, so create and initialise
6982 * server-to-client session keys.
6984 if (ssh->sc_cipher_ctx)
6985 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6986 ssh->sccipher = s->sccipher_tobe;
6987 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6989 if (ssh->sc_mac_ctx)
6990 ssh->scmac->free_context(ssh->sc_mac_ctx);
6991 ssh->scmac = s->scmac_tobe;
6992 ssh->sc_mac_ctx = ssh->scmac->make_context();
6994 if (ssh->sc_comp_ctx)
6995 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6996 ssh->sccomp = s->sccomp_tobe;
6997 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7000 * Set IVs on server-to-client keys. Here we use the exchange
7001 * hash from the _first_ key exchange.
7004 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
7005 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7006 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
7007 assert((ssh->sccipher->keylen+7) / 8 <=
7008 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7009 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
7010 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
7011 assert(ssh->sccipher->blksize <=
7012 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7013 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
7014 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
7015 assert(ssh->scmac->len <=
7016 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7017 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
7018 smemclr(keyspace, sizeof(keyspace));
7020 logeventf(ssh, "Initialised %.200s server->client encryption",
7021 ssh->sccipher->text_name);
7022 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
7023 ssh->scmac->text_name);
7024 if (ssh->sccomp->text_name)
7025 logeventf(ssh, "Initialised %s decompression",
7026 ssh->sccomp->text_name);
7029 * Free shared secret.
7034 * Key exchange is over. Loop straight back round if we have a
7035 * deferred rekey reason.
7037 if (ssh->deferred_rekey_reason) {
7038 logevent(ssh->deferred_rekey_reason);
7040 ssh->deferred_rekey_reason = NULL;
7041 goto begin_key_exchange;
7045 * Otherwise, schedule a timer for our next rekey.
7047 ssh->kex_in_progress = FALSE;
7048 ssh->last_rekey = GETTICKCOUNT();
7049 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7050 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7054 * Now we're encrypting. Begin returning 1 to the protocol main
7055 * function so that other things can run on top of the
7056 * transport. If we ever see a KEXINIT, we must go back to the
7059 * We _also_ go back to the start if we see pktin==NULL and
7060 * inlen negative, because this is a special signal meaning
7061 * `initiate client-driven rekey', and `in' contains a message
7062 * giving the reason for the rekey.
7064 * inlen==-1 means always initiate a rekey;
7065 * inlen==-2 means that userauth has completed successfully and
7066 * we should consider rekeying (for delayed compression).
7068 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7069 (!pktin && inlen < 0))) {
7071 if (!ssh->protocol_initial_phase_done) {
7072 ssh->protocol_initial_phase_done = TRUE;
7074 * Allow authconn to initialise itself.
7076 do_ssh2_authconn(ssh, NULL, 0, NULL);
7081 logevent("Server initiated key re-exchange");
7085 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7086 * delayed compression, if it's available.
7088 * draft-miller-secsh-compression-delayed-00 says that you
7089 * negotiate delayed compression in the first key exchange, and
7090 * both sides start compressing when the server has sent
7091 * USERAUTH_SUCCESS. This has a race condition -- the server
7092 * can't know when the client has seen it, and thus which incoming
7093 * packets it should treat as compressed.
7095 * Instead, we do the initial key exchange without offering the
7096 * delayed methods, but note if the server offers them; when we
7097 * get here, if a delayed method was available that was higher
7098 * on our list than what we got, we initiate a rekey in which we
7099 * _do_ list the delayed methods (and hopefully get it as a
7100 * result). Subsequent rekeys will do the same.
7102 assert(!s->userauth_succeeded); /* should only happen once */
7103 s->userauth_succeeded = TRUE;
7104 if (!s->pending_compression)
7105 /* Can't see any point rekeying. */
7106 goto wait_for_rekey; /* this is utterly horrid */
7107 /* else fall through to rekey... */
7108 s->pending_compression = FALSE;
7111 * Now we've decided to rekey.
7113 * Special case: if the server bug is set that doesn't
7114 * allow rekeying, we give a different log message and
7115 * continue waiting. (If such a server _initiates_ a rekey,
7116 * we process it anyway!)
7118 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7119 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7121 /* Reset the counters, so that at least this message doesn't
7122 * hit the event log _too_ often. */
7123 ssh->outgoing_data_size = 0;
7124 ssh->incoming_data_size = 0;
7125 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7127 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7130 goto wait_for_rekey; /* this is still utterly horrid */
7132 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7135 goto begin_key_exchange;
7141 * Add data to an SSH-2 channel output buffer.
7143 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
7146 bufchain_add(&c->v.v2.outbuffer, buf, len);
7150 * Attempt to send data on an SSH-2 channel.
7152 static int ssh2_try_send(struct ssh_channel *c)
7155 struct Packet *pktout;
7158 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7161 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7162 if ((unsigned)len > c->v.v2.remwindow)
7163 len = c->v.v2.remwindow;
7164 if ((unsigned)len > c->v.v2.remmaxpkt)
7165 len = c->v.v2.remmaxpkt;
7166 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7167 ssh2_pkt_adduint32(pktout, c->remoteid);
7168 ssh2_pkt_addstring_start(pktout);
7169 ssh2_pkt_addstring_data(pktout, data, len);
7170 ssh2_pkt_send(ssh, pktout);
7171 bufchain_consume(&c->v.v2.outbuffer, len);
7172 c->v.v2.remwindow -= len;
7176 * After having sent as much data as we can, return the amount
7179 ret = bufchain_size(&c->v.v2.outbuffer);
7182 * And if there's no data pending but we need to send an EOF, send
7185 if (!ret && c->pending_eof)
7186 ssh_channel_try_eof(c);
7191 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7194 if (c->closes & CLOSES_SENT_EOF)
7195 return; /* don't send on channels we've EOFed */
7196 bufsize = ssh2_try_send(c);
7199 case CHAN_MAINSESSION:
7200 /* stdin need not receive an unthrottle
7201 * notification since it will be polled */
7204 x11_unthrottle(c->u.x11.xconn);
7207 /* agent sockets are request/response and need no
7208 * buffer management */
7211 pfd_unthrottle(c->u.pfd.pf);
7217 static int ssh_is_simple(Ssh ssh)
7220 * We use the 'simple' variant of the SSH protocol if we're asked
7221 * to, except not if we're also doing connection-sharing (either
7222 * tunnelling our packets over an upstream or expecting to be
7223 * tunnelled over ourselves), since then the assumption that we
7224 * have only one channel to worry about is not true after all.
7226 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7227 !ssh->bare_connection && !ssh->connshare);
7231 * Set up most of a new ssh_channel for SSH-2.
7233 static void ssh2_channel_init(struct ssh_channel *c)
7236 c->localid = alloc_channel_id(ssh);
7238 c->pending_eof = FALSE;
7239 c->throttling_conn = FALSE;
7240 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7241 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7242 c->v.v2.chanreq_head = NULL;
7243 c->v.v2.throttle_state = UNTHROTTLED;
7244 bufchain_init(&c->v.v2.outbuffer);
7248 * Construct the common parts of a CHANNEL_OPEN.
7250 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c, char *type)
7252 struct Packet *pktout;
7254 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7255 ssh2_pkt_addstring(pktout, type);
7256 ssh2_pkt_adduint32(pktout, c->localid);
7257 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7258 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7263 * CHANNEL_FAILURE doesn't come with any indication of what message
7264 * caused it, so we have to keep track of the outstanding
7265 * CHANNEL_REQUESTs ourselves.
7267 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7268 cchandler_fn_t handler, void *ctx)
7270 struct outstanding_channel_request *ocr =
7271 snew(struct outstanding_channel_request);
7273 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7274 ocr->handler = handler;
7277 if (!c->v.v2.chanreq_head)
7278 c->v.v2.chanreq_head = ocr;
7280 c->v.v2.chanreq_tail->next = ocr;
7281 c->v.v2.chanreq_tail = ocr;
7285 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7286 * NULL then a reply will be requested and the handler will be called
7287 * when it arrives. The returned packet is ready to have any
7288 * request-specific data added and be sent. Note that if a handler is
7289 * provided, it's essential that the request actually be sent.
7291 * The handler will usually be passed the response packet in pktin. If
7292 * pktin is NULL, this means that no reply will ever be forthcoming
7293 * (e.g. because the entire connection is being destroyed, or because
7294 * the server initiated channel closure before we saw the response)
7295 * and the handler should free any storage it's holding.
7297 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c, char *type,
7298 cchandler_fn_t handler, void *ctx)
7300 struct Packet *pktout;
7302 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7303 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7304 ssh2_pkt_adduint32(pktout, c->remoteid);
7305 ssh2_pkt_addstring(pktout, type);
7306 ssh2_pkt_addbool(pktout, handler != NULL);
7307 if (handler != NULL)
7308 ssh2_queue_chanreq_handler(c, handler, ctx);
7313 * Potentially enlarge the window on an SSH-2 channel.
7315 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7317 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7322 * Never send WINDOW_ADJUST for a channel that the remote side has
7323 * already sent EOF on; there's no point, since it won't be
7324 * sending any more data anyway. Ditto if _we've_ already sent
7327 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7331 * Also, never widen the window for an X11 channel when we're
7332 * still waiting to see its initial auth and may yet hand it off
7335 if (c->type == CHAN_X11 && c->u.x11.initial)
7339 * If the remote end has a habit of ignoring maxpkt, limit the
7340 * window so that it has no choice (assuming it doesn't ignore the
7343 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7344 newwin = OUR_V2_MAXPKT;
7347 * Only send a WINDOW_ADJUST if there's significantly more window
7348 * available than the other end thinks there is. This saves us
7349 * sending a WINDOW_ADJUST for every character in a shell session.
7351 * "Significant" is arbitrarily defined as half the window size.
7353 if (newwin / 2 >= c->v.v2.locwindow) {
7354 struct Packet *pktout;
7358 * In order to keep track of how much window the client
7359 * actually has available, we'd like it to acknowledge each
7360 * WINDOW_ADJUST. We can't do that directly, so we accompany
7361 * it with a CHANNEL_REQUEST that has to be acknowledged.
7363 * This is only necessary if we're opening the window wide.
7364 * If we're not, then throughput is being constrained by
7365 * something other than the maximum window size anyway.
7367 if (newwin == c->v.v2.locmaxwin &&
7368 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7369 up = snew(unsigned);
7370 *up = newwin - c->v.v2.locwindow;
7371 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7372 ssh2_handle_winadj_response, up);
7373 ssh2_pkt_send(ssh, pktout);
7375 if (c->v.v2.throttle_state != UNTHROTTLED)
7376 c->v.v2.throttle_state = UNTHROTTLING;
7378 /* Pretend the WINDOW_ADJUST was acked immediately. */
7379 c->v.v2.remlocwin = newwin;
7380 c->v.v2.throttle_state = THROTTLED;
7382 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7383 ssh2_pkt_adduint32(pktout, c->remoteid);
7384 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7385 ssh2_pkt_send(ssh, pktout);
7386 c->v.v2.locwindow = newwin;
7391 * Find the channel associated with a message. If there's no channel,
7392 * or it's not properly open, make a noise about it and return NULL.
7394 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7396 unsigned localid = ssh_pkt_getuint32(pktin);
7397 struct ssh_channel *c;
7399 c = find234(ssh->channels, &localid, ssh_channelfind);
7401 (c->type != CHAN_SHARING && c->halfopen &&
7402 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7403 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7404 char *buf = dupprintf("Received %s for %s channel %u",
7405 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7407 c ? "half-open" : "nonexistent", localid);
7408 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7415 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7416 struct Packet *pktin, void *ctx)
7418 unsigned *sizep = ctx;
7421 * Winadj responses should always be failures. However, at least
7422 * one server ("boks_sshd") is known to return SUCCESS for channel
7423 * requests it's never heard of, such as "winadj@putty". Raised
7424 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7425 * life, we don't worry about what kind of response we got.
7428 c->v.v2.remlocwin += *sizep;
7431 * winadj messages are only sent when the window is fully open, so
7432 * if we get an ack of one, we know any pending unthrottle is
7435 if (c->v.v2.throttle_state == UNTHROTTLING)
7436 c->v.v2.throttle_state = UNTHROTTLED;
7439 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
7441 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
7442 struct outstanding_channel_request *ocr;
7445 if (c->type == CHAN_SHARING) {
7446 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7447 pktin->body, pktin->length);
7450 ocr = c->v.v2.chanreq_head;
7452 ssh2_msg_unexpected(ssh, pktin);
7455 ocr->handler(c, pktin, ocr->ctx);
7456 c->v.v2.chanreq_head = ocr->next;
7459 * We may now initiate channel-closing procedures, if that
7460 * CHANNEL_REQUEST was the last thing outstanding before we send
7463 ssh2_channel_check_close(c);
7466 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
7468 struct ssh_channel *c;
7469 c = ssh2_channel_msg(ssh, pktin);
7472 if (c->type == CHAN_SHARING) {
7473 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7474 pktin->body, pktin->length);
7477 if (!(c->closes & CLOSES_SENT_EOF)) {
7478 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
7479 ssh2_try_send_and_unthrottle(ssh, c);
7483 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
7487 struct ssh_channel *c;
7488 c = ssh2_channel_msg(ssh, pktin);
7491 if (c->type == CHAN_SHARING) {
7492 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7493 pktin->body, pktin->length);
7496 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
7497 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
7498 return; /* extended but not stderr */
7499 ssh_pkt_getstring(pktin, &data, &length);
7502 c->v.v2.locwindow -= length;
7503 c->v.v2.remlocwin -= length;
7505 case CHAN_MAINSESSION:
7507 from_backend(ssh->frontend, pktin->type ==
7508 SSH2_MSG_CHANNEL_EXTENDED_DATA,
7512 bufsize = x11_send(c->u.x11.xconn, data, length);
7515 bufsize = pfd_send(c->u.pfd.pf, data, length);
7518 while (length > 0) {
7519 if (c->u.a.lensofar < 4) {
7520 unsigned int l = min(4 - c->u.a.lensofar,
7522 memcpy(c->u.a.msglen + c->u.a.lensofar,
7526 c->u.a.lensofar += l;
7528 if (c->u.a.lensofar == 4) {
7530 4 + GET_32BIT(c->u.a.msglen);
7531 c->u.a.message = snewn(c->u.a.totallen,
7533 memcpy(c->u.a.message, c->u.a.msglen, 4);
7535 if (c->u.a.lensofar >= 4 && length > 0) {
7537 min(c->u.a.totallen - c->u.a.lensofar,
7539 memcpy(c->u.a.message + c->u.a.lensofar,
7543 c->u.a.lensofar += l;
7545 if (c->u.a.lensofar == c->u.a.totallen) {
7548 c->u.a.outstanding_requests++;
7549 if (agent_query(c->u.a.message,
7552 ssh_agentf_callback, c))
7553 ssh_agentf_callback(c, reply, replylen);
7554 sfree(c->u.a.message);
7555 c->u.a.message = NULL;
7556 c->u.a.lensofar = 0;
7563 * If it looks like the remote end hit the end of its window,
7564 * and we didn't want it to do that, think about using a
7567 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
7568 c->v.v2.locmaxwin < 0x40000000)
7569 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
7571 * If we are not buffering too much data,
7572 * enlarge the window again at the remote side.
7573 * If we are buffering too much, we may still
7574 * need to adjust the window if the server's
7577 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7578 c->v.v2.locmaxwin - bufsize : 0);
7580 * If we're either buffering way too much data, or if we're
7581 * buffering anything at all and we're in "simple" mode,
7582 * throttle the whole channel.
7584 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
7585 && !c->throttling_conn) {
7586 c->throttling_conn = 1;
7587 ssh_throttle_conn(ssh, +1);
7592 static void ssh_check_termination(Ssh ssh)
7594 if (ssh->version == 2 &&
7595 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7596 count234(ssh->channels) == 0 &&
7597 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
7599 * We used to send SSH_MSG_DISCONNECT here, because I'd
7600 * believed that _every_ conforming SSH-2 connection had to
7601 * end with a disconnect being sent by at least one side;
7602 * apparently I was wrong and it's perfectly OK to
7603 * unceremoniously slam the connection shut when you're done,
7604 * and indeed OpenSSH feels this is more polite than sending a
7605 * DISCONNECT. So now we don't.
7607 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7611 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id)
7613 logeventf(ssh, "Connection sharing downstream #%u connected", id);
7616 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
7618 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
7619 ssh_check_termination(ssh);
7622 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
7627 va_start(ap, logfmt);
7628 buf = dupvprintf(logfmt, ap);
7631 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
7633 logeventf(ssh, "Connection sharing: %s", buf);
7637 static void ssh_channel_destroy(struct ssh_channel *c)
7642 case CHAN_MAINSESSION:
7643 ssh->mainchan = NULL;
7644 update_specials_menu(ssh->frontend);
7647 if (c->u.x11.xconn != NULL)
7648 x11_close(c->u.x11.xconn);
7649 logevent("Forwarded X11 connection terminated");
7652 sfree(c->u.a.message);
7655 if (c->u.pfd.pf != NULL)
7656 pfd_close(c->u.pfd.pf);
7657 logevent("Forwarded port closed");
7661 del234(ssh->channels, c);
7662 if (ssh->version == 2) {
7663 bufchain_clear(&c->v.v2.outbuffer);
7664 assert(c->v.v2.chanreq_head == NULL);
7669 * If that was the last channel left open, we might need to
7672 ssh_check_termination(ssh);
7675 static void ssh2_channel_check_close(struct ssh_channel *c)
7678 struct Packet *pktout;
7682 * If we've sent out our own CHANNEL_OPEN but not yet seen
7683 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
7684 * it's too early to be sending close messages of any kind.
7689 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
7690 c->type == CHAN_ZOMBIE) &&
7691 !c->v.v2.chanreq_head &&
7692 !(c->closes & CLOSES_SENT_CLOSE)) {
7694 * We have both sent and received EOF (or the channel is a
7695 * zombie), and we have no outstanding channel requests, which
7696 * means the channel is in final wind-up. But we haven't sent
7697 * CLOSE, so let's do so now.
7699 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
7700 ssh2_pkt_adduint32(pktout, c->remoteid);
7701 ssh2_pkt_send(ssh, pktout);
7702 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
7705 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
7706 assert(c->v.v2.chanreq_head == NULL);
7708 * We have both sent and received CLOSE, which means we're
7709 * completely done with the channel.
7711 ssh_channel_destroy(c);
7715 static void ssh2_channel_got_eof(struct ssh_channel *c)
7717 if (c->closes & CLOSES_RCVD_EOF)
7718 return; /* already seen EOF */
7719 c->closes |= CLOSES_RCVD_EOF;
7721 if (c->type == CHAN_X11) {
7722 x11_send_eof(c->u.x11.xconn);
7723 } else if (c->type == CHAN_AGENT) {
7724 if (c->u.a.outstanding_requests == 0) {
7725 /* Manufacture an outgoing EOF in response to the incoming one. */
7726 sshfwd_write_eof(c);
7728 } else if (c->type == CHAN_SOCKDATA) {
7729 pfd_send_eof(c->u.pfd.pf);
7730 } else if (c->type == CHAN_MAINSESSION) {
7733 if (!ssh->sent_console_eof &&
7734 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
7736 * Either from_backend_eof told us that the front end
7737 * wants us to close the outgoing side of the connection
7738 * as soon as we see EOF from the far end, or else we've
7739 * unilaterally decided to do that because we've allocated
7740 * a remote pty and hence EOF isn't a particularly
7741 * meaningful concept.
7743 sshfwd_write_eof(c);
7745 ssh->sent_console_eof = TRUE;
7748 ssh2_channel_check_close(c);
7751 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
7753 struct ssh_channel *c;
7755 c = ssh2_channel_msg(ssh, pktin);
7758 if (c->type == CHAN_SHARING) {
7759 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7760 pktin->body, pktin->length);
7763 ssh2_channel_got_eof(c);
7766 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7768 struct ssh_channel *c;
7770 c = ssh2_channel_msg(ssh, pktin);
7773 if (c->type == CHAN_SHARING) {
7774 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7775 pktin->body, pktin->length);
7780 * When we receive CLOSE on a channel, we assume it comes with an
7781 * implied EOF if we haven't seen EOF yet.
7783 ssh2_channel_got_eof(c);
7785 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
7787 * It also means we stop expecting to see replies to any
7788 * outstanding channel requests, so clean those up too.
7789 * (ssh_chanreq_init will enforce by assertion that we don't
7790 * subsequently put anything back on this list.)
7792 while (c->v.v2.chanreq_head) {
7793 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
7794 ocr->handler(c, NULL, ocr->ctx);
7795 c->v.v2.chanreq_head = ocr->next;
7801 * And we also send an outgoing EOF, if we haven't already, on the
7802 * assumption that CLOSE is a pretty forceful announcement that
7803 * the remote side is doing away with the entire channel. (If it
7804 * had wanted to send us EOF and continue receiving data from us,
7805 * it would have just sent CHANNEL_EOF.)
7807 if (!(c->closes & CLOSES_SENT_EOF)) {
7809 * Make sure we don't read any more from whatever our local
7810 * data source is for this channel.
7813 case CHAN_MAINSESSION:
7814 ssh->send_ok = 0; /* stop trying to read from stdin */
7817 x11_override_throttle(c->u.x11.xconn, 1);
7820 pfd_override_throttle(c->u.pfd.pf, 1);
7825 * Abandon any buffered data we still wanted to send to this
7826 * channel. Receiving a CHANNEL_CLOSE is an indication that
7827 * the server really wants to get on and _destroy_ this
7828 * channel, and it isn't going to send us any further
7829 * WINDOW_ADJUSTs to permit us to send pending stuff.
7831 bufchain_clear(&c->v.v2.outbuffer);
7834 * Send outgoing EOF.
7836 sshfwd_write_eof(c);
7840 * Now process the actual close.
7842 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7843 c->closes |= CLOSES_RCVD_CLOSE;
7844 ssh2_channel_check_close(c);
7848 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7850 struct ssh_channel *c;
7852 c = ssh2_channel_msg(ssh, pktin);
7855 if (c->type == CHAN_SHARING) {
7856 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7857 pktin->body, pktin->length);
7860 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7861 c->remoteid = ssh_pkt_getuint32(pktin);
7862 c->halfopen = FALSE;
7863 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7864 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7866 if (c->type == CHAN_SOCKDATA_DORMANT) {
7867 c->type = CHAN_SOCKDATA;
7869 pfd_confirm(c->u.pfd.pf);
7870 } else if (c->type == CHAN_ZOMBIE) {
7872 * This case can occur if a local socket error occurred
7873 * between us sending out CHANNEL_OPEN and receiving
7874 * OPEN_CONFIRMATION. In this case, all we can do is
7875 * immediately initiate close proceedings now that we know the
7876 * server's id to put in the close message.
7878 ssh2_channel_check_close(c);
7881 * We never expect to receive OPEN_CONFIRMATION for any
7882 * *other* channel type (since only local-to-remote port
7883 * forwardings cause us to send CHANNEL_OPEN after the main
7884 * channel is live - all other auxiliary channel types are
7885 * initiated from the server end). It's safe to enforce this
7886 * by assertion rather than by ssh_disconnect, because the
7887 * real point is that we never constructed a half-open channel
7888 * structure in the first place with any type other than the
7891 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
7895 ssh_channel_try_eof(c); /* in case we had a pending EOF */
7898 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7900 static const char *const reasons[] = {
7901 "<unknown reason code>",
7902 "Administratively prohibited",
7904 "Unknown channel type",
7905 "Resource shortage",
7907 unsigned reason_code;
7908 char *reason_string;
7910 struct ssh_channel *c;
7912 c = ssh2_channel_msg(ssh, pktin);
7915 if (c->type == CHAN_SHARING) {
7916 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7917 pktin->body, pktin->length);
7920 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7922 if (c->type == CHAN_SOCKDATA_DORMANT) {
7923 reason_code = ssh_pkt_getuint32(pktin);
7924 if (reason_code >= lenof(reasons))
7925 reason_code = 0; /* ensure reasons[reason_code] in range */
7926 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7927 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7928 reasons[reason_code], reason_length, reason_string);
7930 pfd_close(c->u.pfd.pf);
7931 } else if (c->type == CHAN_ZOMBIE) {
7933 * This case can occur if a local socket error occurred
7934 * between us sending out CHANNEL_OPEN and receiving
7935 * OPEN_FAILURE. In this case, we need do nothing except allow
7936 * the code below to throw the half-open channel away.
7940 * We never expect to receive OPEN_FAILURE for any *other*
7941 * channel type (since only local-to-remote port forwardings
7942 * cause us to send CHANNEL_OPEN after the main channel is
7943 * live - all other auxiliary channel types are initiated from
7944 * the server end). It's safe to enforce this by assertion
7945 * rather than by ssh_disconnect, because the real point is
7946 * that we never constructed a half-open channel structure in
7947 * the first place with any type other than the above.
7949 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
7952 del234(ssh->channels, c);
7956 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7959 int typelen, want_reply;
7960 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7961 struct ssh_channel *c;
7962 struct Packet *pktout;
7964 c = ssh2_channel_msg(ssh, pktin);
7967 if (c->type == CHAN_SHARING) {
7968 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7969 pktin->body, pktin->length);
7972 ssh_pkt_getstring(pktin, &type, &typelen);
7973 want_reply = ssh2_pkt_getbool(pktin);
7975 if (c->closes & CLOSES_SENT_CLOSE) {
7977 * We don't reply to channel requests after we've sent
7978 * CHANNEL_CLOSE for the channel, because our reply might
7979 * cross in the network with the other side's CHANNEL_CLOSE
7980 * and arrive after they have wound the channel up completely.
7986 * Having got the channel number, we now look at
7987 * the request type string to see if it's something
7990 if (c == ssh->mainchan) {
7992 * We recognise "exit-status" and "exit-signal" on
7993 * the primary channel.
7995 if (typelen == 11 &&
7996 !memcmp(type, "exit-status", 11)) {
7998 ssh->exitcode = ssh_pkt_getuint32(pktin);
7999 logeventf(ssh, "Server sent command exit status %d",
8001 reply = SSH2_MSG_CHANNEL_SUCCESS;
8003 } else if (typelen == 11 &&
8004 !memcmp(type, "exit-signal", 11)) {
8006 int is_plausible = TRUE, is_int = FALSE;
8007 char *fmt_sig = "", *fmt_msg = "";
8009 int msglen = 0, core = FALSE;
8010 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8011 * provide an `int' for the signal, despite its
8012 * having been a `string' in the drafts of RFC 4254 since at
8013 * least 2001. (Fixed in session.c 1.147.) Try to
8014 * infer which we can safely parse it as. */
8016 unsigned char *p = pktin->body +
8018 long len = pktin->length - pktin->savedpos;
8019 unsigned long num = GET_32BIT(p); /* what is it? */
8020 /* If it's 0, it hardly matters; assume string */
8024 int maybe_int = FALSE, maybe_str = FALSE;
8025 #define CHECK_HYPOTHESIS(offset, result) \
8028 int q = toint(offset); \
8029 if (q >= 0 && q+4 <= len) { \
8030 q = toint(q + 4 + GET_32BIT(p+q)); \
8031 if (q >= 0 && q+4 <= len && \
8032 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8037 CHECK_HYPOTHESIS(4+1, maybe_int);
8038 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8039 #undef CHECK_HYPOTHESIS
8040 if (maybe_int && !maybe_str)
8042 else if (!maybe_int && maybe_str)
8045 /* Crikey. Either or neither. Panic. */
8046 is_plausible = FALSE;
8049 ssh->exitcode = 128; /* means `unknown signal' */
8052 /* Old non-standard OpenSSH. */
8053 int signum = ssh_pkt_getuint32(pktin);
8054 fmt_sig = dupprintf(" %d", signum);
8055 ssh->exitcode = 128 + signum;
8057 /* As per RFC 4254. */
8060 ssh_pkt_getstring(pktin, &sig, &siglen);
8061 /* Signal name isn't supposed to be blank, but
8062 * let's cope gracefully if it is. */
8064 fmt_sig = dupprintf(" \"%.*s\"",
8069 * Really hideous method of translating the
8070 * signal description back into a locally
8071 * meaningful number.
8076 #define TRANSLATE_SIGNAL(s) \
8077 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8078 ssh->exitcode = 128 + SIG ## s
8080 TRANSLATE_SIGNAL(ABRT);
8083 TRANSLATE_SIGNAL(ALRM);
8086 TRANSLATE_SIGNAL(FPE);
8089 TRANSLATE_SIGNAL(HUP);
8092 TRANSLATE_SIGNAL(ILL);
8095 TRANSLATE_SIGNAL(INT);
8098 TRANSLATE_SIGNAL(KILL);
8101 TRANSLATE_SIGNAL(PIPE);
8104 TRANSLATE_SIGNAL(QUIT);
8107 TRANSLATE_SIGNAL(SEGV);
8110 TRANSLATE_SIGNAL(TERM);
8113 TRANSLATE_SIGNAL(USR1);
8116 TRANSLATE_SIGNAL(USR2);
8118 #undef TRANSLATE_SIGNAL
8120 ssh->exitcode = 128;
8122 core = ssh2_pkt_getbool(pktin);
8123 ssh_pkt_getstring(pktin, &msg, &msglen);
8125 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8127 /* ignore lang tag */
8128 } /* else don't attempt to parse */
8129 logeventf(ssh, "Server exited on signal%s%s%s",
8130 fmt_sig, core ? " (core dumped)" : "",
8132 if (*fmt_sig) sfree(fmt_sig);
8133 if (*fmt_msg) sfree(fmt_msg);
8134 reply = SSH2_MSG_CHANNEL_SUCCESS;
8139 * This is a channel request we don't know
8140 * about, so we now either ignore the request
8141 * or respond with CHANNEL_FAILURE, depending
8144 reply = SSH2_MSG_CHANNEL_FAILURE;
8147 pktout = ssh2_pkt_init(reply);
8148 ssh2_pkt_adduint32(pktout, c->remoteid);
8149 ssh2_pkt_send(ssh, pktout);
8153 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8156 int typelen, want_reply;
8157 struct Packet *pktout;
8159 ssh_pkt_getstring(pktin, &type, &typelen);
8160 want_reply = ssh2_pkt_getbool(pktin);
8163 * We currently don't support any global requests
8164 * at all, so we either ignore the request or
8165 * respond with REQUEST_FAILURE, depending on
8169 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8170 ssh2_pkt_send(ssh, pktout);
8174 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8178 struct X11FakeAuth *auth;
8181 * Make up a new set of fake X11 auth data, and add it to the tree
8182 * of currently valid ones with an indication of the sharing
8183 * context that it's relevant to.
8185 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8186 auth->share_cs = share_cs;
8187 auth->share_chan = share_chan;
8192 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8194 del234(ssh->x11authtree, auth);
8195 x11_free_fake_auth(auth);
8198 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8206 struct ssh_channel *c;
8207 unsigned remid, winsize, pktsize;
8208 unsigned our_winsize_override = 0;
8209 struct Packet *pktout;
8211 ssh_pkt_getstring(pktin, &type, &typelen);
8212 c = snew(struct ssh_channel);
8215 remid = ssh_pkt_getuint32(pktin);
8216 winsize = ssh_pkt_getuint32(pktin);
8217 pktsize = ssh_pkt_getuint32(pktin);
8219 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8222 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8223 addrstr = snewn(peeraddrlen+1, char);
8224 memcpy(addrstr, peeraddr, peeraddrlen);
8225 addrstr[peeraddrlen] = '\0';
8226 peerport = ssh_pkt_getuint32(pktin);
8228 logeventf(ssh, "Received X11 connect request from %s:%d",
8231 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8232 error = "X11 forwarding is not enabled";
8234 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8237 c->u.x11.initial = TRUE;
8240 * If we are a connection-sharing upstream, then we should
8241 * initially present a very small window, adequate to take
8242 * the X11 initial authorisation packet but not much more.
8243 * Downstream will then present us a larger window (by
8244 * fiat of the connection-sharing protocol) and we can
8245 * guarantee to send a positive-valued WINDOW_ADJUST.
8248 our_winsize_override = 128;
8250 logevent("Opened X11 forward channel");
8254 } else if (typelen == 15 &&
8255 !memcmp(type, "forwarded-tcpip", 15)) {
8256 struct ssh_rportfwd pf, *realpf;
8259 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8260 pf.shost = dupprintf("%.*s", shostlen, shost);
8261 pf.sport = ssh_pkt_getuint32(pktin);
8262 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8263 peerport = ssh_pkt_getuint32(pktin);
8264 realpf = find234(ssh->rportfwds, &pf, NULL);
8265 logeventf(ssh, "Received remote port %s:%d open request "
8266 "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
8269 if (realpf == NULL) {
8270 error = "Remote port is not recognised";
8274 if (realpf->share_ctx) {
8276 * This port forwarding is on behalf of a
8277 * connection-sharing downstream, so abandon our own
8278 * channel-open procedure and just pass the message on
8281 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8282 pktin->body, pktin->length);
8287 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8288 c, ssh->conf, realpf->pfrec->addressfamily);
8289 logeventf(ssh, "Attempting to forward remote port to "
8290 "%s:%d", realpf->dhost, realpf->dport);
8292 logeventf(ssh, "Port open failed: %s", err);
8294 error = "Port open failed";
8296 logevent("Forwarded port opened successfully");
8297 c->type = CHAN_SOCKDATA;
8300 } else if (typelen == 22 &&
8301 !memcmp(type, "auth-agent@openssh.com", 22)) {
8302 if (!ssh->agentfwd_enabled)
8303 error = "Agent forwarding is not enabled";
8305 c->type = CHAN_AGENT; /* identify channel type */
8306 c->u.a.lensofar = 0;
8307 c->u.a.message = NULL;
8308 c->u.a.outstanding_requests = 0;
8311 error = "Unsupported channel type requested";
8314 c->remoteid = remid;
8315 c->halfopen = FALSE;
8317 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8318 ssh2_pkt_adduint32(pktout, c->remoteid);
8319 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8320 ssh2_pkt_addstring(pktout, error);
8321 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8322 ssh2_pkt_send(ssh, pktout);
8323 logeventf(ssh, "Rejected channel open: %s", error);
8326 ssh2_channel_init(c);
8327 c->v.v2.remwindow = winsize;
8328 c->v.v2.remmaxpkt = pktsize;
8329 if (our_winsize_override) {
8330 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8331 our_winsize_override;
8333 add234(ssh->channels, c);
8334 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8335 ssh2_pkt_adduint32(pktout, c->remoteid);
8336 ssh2_pkt_adduint32(pktout, c->localid);
8337 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8338 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8339 ssh2_pkt_send(ssh, pktout);
8343 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8344 void *share_cs, void *share_chan,
8345 const char *peer_addr, int peer_port,
8346 int endian, int protomajor, int protominor,
8347 const void *initial_data, int initial_len)
8350 * This function is called when we've just discovered that an X
8351 * forwarding channel on which we'd been handling the initial auth
8352 * ourselves turns out to be destined for a connection-sharing
8353 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8354 * that we completely stop tracking windows and buffering data and
8355 * just pass more or less unmodified SSH messages back and forth.
8357 c->type = CHAN_SHARING;
8358 c->u.sharing.ctx = share_cs;
8359 share_setup_x11_channel(share_cs, share_chan,
8360 c->localid, c->remoteid, c->v.v2.remwindow,
8361 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8362 peer_addr, peer_port, endian,
8363 protomajor, protominor,
8364 initial_data, initial_len);
8367 void sshfwd_x11_is_local(struct ssh_channel *c)
8370 * This function is called when we've just discovered that an X
8371 * forwarding channel is _not_ destined for a connection-sharing
8372 * downstream but we're going to handle it ourselves. We stop
8373 * presenting a cautiously small window and go into ordinary data
8376 c->u.x11.initial = FALSE;
8377 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8381 * Buffer banner messages for later display at some convenient point,
8382 * if we're going to display them.
8384 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8386 /* Arbitrary limit to prevent unbounded inflation of buffer */
8387 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8388 bufchain_size(&ssh->banner) <= 131072) {
8389 char *banner = NULL;
8391 ssh_pkt_getstring(pktin, &banner, &size);
8393 bufchain_add(&ssh->banner, banner, size);
8397 /* Helper function to deal with sending tty modes for "pty-req" */
8398 static void ssh2_send_ttymode(void *data, char *mode, char *val)
8400 struct Packet *pktout = (struct Packet *)data;
8402 unsigned int arg = 0;
8403 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
8404 if (i == lenof(ssh_ttymodes)) return;
8405 switch (ssh_ttymodes[i].type) {
8407 arg = ssh_tty_parse_specchar(val);
8410 arg = ssh_tty_parse_boolean(val);
8413 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
8414 ssh2_pkt_adduint32(pktout, arg);
8417 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8420 struct ssh2_setup_x11_state {
8424 struct Packet *pktout;
8425 crStateP(ssh2_setup_x11_state, ctx);
8429 logevent("Requesting X11 forwarding");
8430 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8432 ssh2_pkt_addbool(pktout, 0); /* many connections */
8433 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8434 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8435 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8436 ssh2_pkt_send(ssh, pktout);
8438 /* Wait to be called back with either a response packet, or NULL
8439 * meaning clean up and free our data */
8443 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8444 logevent("X11 forwarding enabled");
8445 ssh->X11_fwd_enabled = TRUE;
8447 logevent("X11 forwarding refused");
8453 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8456 struct ssh2_setup_agent_state {
8460 struct Packet *pktout;
8461 crStateP(ssh2_setup_agent_state, ctx);
8465 logevent("Requesting OpenSSH-style agent forwarding");
8466 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8467 ssh2_setup_agent, s);
8468 ssh2_pkt_send(ssh, pktout);
8470 /* Wait to be called back with either a response packet, or NULL
8471 * meaning clean up and free our data */
8475 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8476 logevent("Agent forwarding enabled");
8477 ssh->agentfwd_enabled = TRUE;
8479 logevent("Agent forwarding refused");
8485 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8488 struct ssh2_setup_pty_state {
8492 struct Packet *pktout;
8493 crStateP(ssh2_setup_pty_state, ctx);
8497 /* Unpick the terminal-speed string. */
8498 /* XXX perhaps we should allow no speeds to be sent. */
8499 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8500 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8501 /* Build the pty request. */
8502 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
8504 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
8505 ssh2_pkt_adduint32(pktout, ssh->term_width);
8506 ssh2_pkt_adduint32(pktout, ssh->term_height);
8507 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
8508 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
8509 ssh2_pkt_addstring_start(pktout);
8510 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
8511 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
8512 ssh2_pkt_adduint32(pktout, ssh->ispeed);
8513 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
8514 ssh2_pkt_adduint32(pktout, ssh->ospeed);
8515 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
8516 ssh2_pkt_send(ssh, pktout);
8517 ssh->state = SSH_STATE_INTERMED;
8519 /* Wait to be called back with either a response packet, or NULL
8520 * meaning clean up and free our data */
8524 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8525 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8526 ssh->ospeed, ssh->ispeed);
8527 ssh->got_pty = TRUE;
8529 c_write_str(ssh, "Server refused to allocate pty\r\n");
8530 ssh->editing = ssh->echoing = 1;
8537 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
8540 struct ssh2_setup_env_state {
8542 int num_env, env_left, env_ok;
8545 struct Packet *pktout;
8546 crStateP(ssh2_setup_env_state, ctx);
8551 * Send environment variables.
8553 * Simplest thing here is to send all the requests at once, and
8554 * then wait for a whole bunch of successes or failures.
8560 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
8562 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
8563 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
8564 ssh2_pkt_addstring(pktout, key);
8565 ssh2_pkt_addstring(pktout, val);
8566 ssh2_pkt_send(ssh, pktout);
8571 logeventf(ssh, "Sent %d environment variables", s->num_env);
8576 s->env_left = s->num_env;
8578 while (s->env_left > 0) {
8579 /* Wait to be called back with either a response packet,
8580 * or NULL meaning clean up and free our data */
8582 if (!pktin) goto out;
8583 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
8588 if (s->env_ok == s->num_env) {
8589 logevent("All environment variables successfully set");
8590 } else if (s->env_ok == 0) {
8591 logevent("All environment variables refused");
8592 c_write_str(ssh, "Server refused to set environment variables\r\n");
8594 logeventf(ssh, "%d environment variables refused",
8595 s->num_env - s->env_ok);
8596 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8604 * Handle the SSH-2 userauth and connection layers.
8606 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
8608 do_ssh2_authconn(ssh, NULL, 0, pktin);
8611 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
8615 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
8618 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
8619 struct Packet *pktin)
8621 struct do_ssh2_authconn_state {
8625 AUTH_TYPE_PUBLICKEY,
8626 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
8627 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
8629 AUTH_TYPE_GSSAPI, /* always QUIET */
8630 AUTH_TYPE_KEYBOARD_INTERACTIVE,
8631 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
8633 int done_service_req;
8634 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
8635 int tried_pubkey_config, done_agent;
8640 int kbd_inter_refused;
8641 int we_are_in, userauth_success;
8642 prompts_t *cur_prompt;
8647 void *publickey_blob;
8648 int publickey_bloblen;
8649 int publickey_encrypted;
8650 char *publickey_algorithm;
8651 char *publickey_comment;
8652 unsigned char agent_request[5], *agent_response, *agentp;
8653 int agent_responselen;
8654 unsigned char *pkblob_in_agent;
8656 char *pkblob, *alg, *commentp;
8657 int pklen, alglen, commentlen;
8658 int siglen, retlen, len;
8659 char *q, *agentreq, *ret;
8661 struct Packet *pktout;
8664 struct ssh_gss_library *gsslib;
8665 Ssh_gss_ctx gss_ctx;
8666 Ssh_gss_buf gss_buf;
8667 Ssh_gss_buf gss_rcvtok, gss_sndtok;
8668 Ssh_gss_name gss_srv_name;
8669 Ssh_gss_stat gss_stat;
8672 crState(do_ssh2_authconn_state);
8676 /* Register as a handler for all the messages this coroutine handles. */
8677 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
8678 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
8679 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
8680 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
8681 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
8682 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
8683 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
8684 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
8685 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
8686 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
8687 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
8688 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
8689 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
8690 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
8691 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
8692 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
8693 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
8694 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
8695 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
8696 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
8698 s->done_service_req = FALSE;
8699 s->we_are_in = s->userauth_success = FALSE;
8700 s->agent_response = NULL;
8702 s->tried_gssapi = FALSE;
8705 if (!ssh->bare_connection) {
8706 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
8708 * Request userauth protocol, and await a response to it.
8710 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8711 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
8712 ssh2_pkt_send(ssh, s->pktout);
8713 crWaitUntilV(pktin);
8714 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
8715 s->done_service_req = TRUE;
8717 if (!s->done_service_req) {
8719 * Request connection protocol directly, without authentication.
8721 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8722 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8723 ssh2_pkt_send(ssh, s->pktout);
8724 crWaitUntilV(pktin);
8725 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
8726 s->we_are_in = TRUE; /* no auth required */
8728 bombout(("Server refused service request"));
8733 s->we_are_in = TRUE;
8736 /* Arrange to be able to deal with any BANNERs that come in.
8737 * (We do this now as packets may come in during the next bit.) */
8738 bufchain_init(&ssh->banner);
8739 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
8740 ssh2_msg_userauth_banner;
8743 * Misc one-time setup for authentication.
8745 s->publickey_blob = NULL;
8746 if (!s->we_are_in) {
8749 * Load the public half of any configured public key file
8752 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8753 if (!filename_is_null(s->keyfile)) {
8755 logeventf(ssh, "Reading private key file \"%.150s\"",
8756 filename_to_str(s->keyfile));
8757 keytype = key_type(s->keyfile);
8758 if (keytype == SSH_KEYTYPE_SSH2) {
8761 ssh2_userkey_loadpub(s->keyfile,
8762 &s->publickey_algorithm,
8763 &s->publickey_bloblen,
8764 &s->publickey_comment, &error);
8765 if (s->publickey_blob) {
8766 s->publickey_encrypted =
8767 ssh2_userkey_encrypted(s->keyfile, NULL);
8770 logeventf(ssh, "Unable to load private key (%s)",
8772 msgbuf = dupprintf("Unable to load private key file "
8773 "\"%.150s\" (%s)\r\n",
8774 filename_to_str(s->keyfile),
8776 c_write_str(ssh, msgbuf);
8781 logeventf(ssh, "Unable to use this key file (%s)",
8782 key_type_to_str(keytype));
8783 msgbuf = dupprintf("Unable to use key file \"%.150s\""
8785 filename_to_str(s->keyfile),
8786 key_type_to_str(keytype));
8787 c_write_str(ssh, msgbuf);
8789 s->publickey_blob = NULL;
8794 * Find out about any keys Pageant has (but if there's a
8795 * public key configured, filter out all others).
8798 s->agent_response = NULL;
8799 s->pkblob_in_agent = NULL;
8800 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
8804 logevent("Pageant is running. Requesting keys.");
8806 /* Request the keys held by the agent. */
8807 PUT_32BIT(s->agent_request, 1);
8808 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
8809 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
8810 ssh_agent_callback, ssh)) {
8814 bombout(("Unexpected data from server while"
8815 " waiting for agent response"));
8818 } while (pktin || inlen > 0);
8819 r = ssh->agent_response;
8820 s->agent_responselen = ssh->agent_response_len;
8822 s->agent_response = (unsigned char *) r;
8823 if (s->agent_response && s->agent_responselen >= 5 &&
8824 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
8827 p = s->agent_response + 5;
8828 s->nkeys = toint(GET_32BIT(p));
8831 * Vet the Pageant response to ensure that the key
8832 * count and blob lengths make sense.
8835 logeventf(ssh, "Pageant response contained a negative"
8836 " key count %d", s->nkeys);
8838 goto done_agent_query;
8840 unsigned char *q = p + 4;
8841 int lenleft = s->agent_responselen - 5 - 4;
8843 for (keyi = 0; keyi < s->nkeys; keyi++) {
8844 int bloblen, commentlen;
8846 logeventf(ssh, "Pageant response was truncated");
8848 goto done_agent_query;
8850 bloblen = toint(GET_32BIT(q));
8851 if (bloblen < 0 || bloblen > lenleft) {
8852 logeventf(ssh, "Pageant response was truncated");
8854 goto done_agent_query;
8856 lenleft -= 4 + bloblen;
8858 commentlen = toint(GET_32BIT(q));
8859 if (commentlen < 0 || commentlen > lenleft) {
8860 logeventf(ssh, "Pageant response was truncated");
8862 goto done_agent_query;
8864 lenleft -= 4 + commentlen;
8865 q += 4 + commentlen;
8870 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
8871 if (s->publickey_blob) {
8872 /* See if configured key is in agent. */
8873 for (keyi = 0; keyi < s->nkeys; keyi++) {
8874 s->pklen = toint(GET_32BIT(p));
8875 if (s->pklen == s->publickey_bloblen &&
8876 !memcmp(p+4, s->publickey_blob,
8877 s->publickey_bloblen)) {
8878 logeventf(ssh, "Pageant key #%d matches "
8879 "configured key file", keyi);
8881 s->pkblob_in_agent = p;
8885 p += toint(GET_32BIT(p)) + 4; /* comment */
8887 if (!s->pkblob_in_agent) {
8888 logevent("Configured key file not in Pageant");
8893 logevent("Failed to get reply from Pageant");
8901 * We repeat this whole loop, including the username prompt,
8902 * until we manage a successful authentication. If the user
8903 * types the wrong _password_, they can be sent back to the
8904 * beginning to try another username, if this is configured on.
8905 * (If they specify a username in the config, they are never
8906 * asked, even if they do give a wrong password.)
8908 * I think this best serves the needs of
8910 * - the people who have no configuration, no keys, and just
8911 * want to try repeated (username,password) pairs until they
8912 * type both correctly
8914 * - people who have keys and configuration but occasionally
8915 * need to fall back to passwords
8917 * - people with a key held in Pageant, who might not have
8918 * logged in to a particular machine before; so they want to
8919 * type a username, and then _either_ their key will be
8920 * accepted, _or_ they will type a password. If they mistype
8921 * the username they will want to be able to get back and
8924 s->got_username = FALSE;
8925 while (!s->we_are_in) {
8929 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
8931 * We got a username last time round this loop, and
8932 * with change_username turned off we don't try to get
8935 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
8936 int ret; /* need not be kept over crReturn */
8937 s->cur_prompt = new_prompts(ssh->frontend);
8938 s->cur_prompt->to_server = TRUE;
8939 s->cur_prompt->name = dupstr("SSH login name");
8940 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
8941 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8944 crWaitUntilV(!pktin);
8945 ret = get_userpass_input(s->cur_prompt, in, inlen);
8950 * get_userpass_input() failed to get a username.
8953 free_prompts(s->cur_prompt);
8954 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
8957 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
8958 free_prompts(s->cur_prompt);
8961 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
8962 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
8963 c_write_str(ssh, stuff);
8967 s->got_username = TRUE;
8970 * Send an authentication request using method "none": (a)
8971 * just in case it succeeds, and (b) so that we know what
8972 * authentication methods we can usefully try next.
8974 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8976 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8977 ssh2_pkt_addstring(s->pktout, ssh->username);
8978 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
8979 ssh2_pkt_addstring(s->pktout, "none"); /* method */
8980 ssh2_pkt_send(ssh, s->pktout);
8981 s->type = AUTH_TYPE_NONE;
8983 s->we_are_in = FALSE;
8985 s->tried_pubkey_config = FALSE;
8986 s->kbd_inter_refused = FALSE;
8988 /* Reset agent request state. */
8989 s->done_agent = FALSE;
8990 if (s->agent_response) {
8991 if (s->pkblob_in_agent) {
8992 s->agentp = s->pkblob_in_agent;
8994 s->agentp = s->agent_response + 5 + 4;
9000 char *methods = NULL;
9004 * Wait for the result of the last authentication request.
9007 crWaitUntilV(pktin);
9009 * Now is a convenient point to spew any banner material
9010 * that we've accumulated. (This should ensure that when
9011 * we exit the auth loop, we haven't any left to deal
9015 int size = bufchain_size(&ssh->banner);
9017 * Don't show the banner if we're operating in
9018 * non-verbose non-interactive mode. (It's probably
9019 * a script, which means nobody will read the
9020 * banner _anyway_, and moreover the printing of
9021 * the banner will screw up processing on the
9022 * output of (say) plink.)
9024 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9025 char *banner = snewn(size, char);
9026 bufchain_fetch(&ssh->banner, banner, size);
9027 c_write_untrusted(ssh, banner, size);
9030 bufchain_clear(&ssh->banner);
9032 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9033 logevent("Access granted");
9034 s->we_are_in = s->userauth_success = TRUE;
9038 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9039 bombout(("Strange packet received during authentication: "
9040 "type %d", pktin->type));
9047 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9048 * we can look at the string in it and know what we can
9049 * helpfully try next.
9051 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9052 ssh_pkt_getstring(pktin, &methods, &methlen);
9053 if (!ssh2_pkt_getbool(pktin)) {
9055 * We have received an unequivocal Access
9056 * Denied. This can translate to a variety of
9057 * messages, or no message at all.
9059 * For forms of authentication which are attempted
9060 * implicitly, by which I mean without printing
9061 * anything in the window indicating that we're
9062 * trying them, we should never print 'Access
9065 * If we do print a message saying that we're
9066 * attempting some kind of authentication, it's OK
9067 * to print a followup message saying it failed -
9068 * but the message may sometimes be more specific
9069 * than simply 'Access denied'.
9071 * Additionally, if we'd just tried password
9072 * authentication, we should break out of this
9073 * whole loop so as to go back to the username
9074 * prompt (iff we're configured to allow
9075 * username change attempts).
9077 if (s->type == AUTH_TYPE_NONE) {
9079 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9080 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9081 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9082 c_write_str(ssh, "Server refused our key\r\n");
9083 logevent("Server refused our key");
9084 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9085 /* This _shouldn't_ happen except by a
9086 * protocol bug causing client and server to
9087 * disagree on what is a correct signature. */
9088 c_write_str(ssh, "Server refused public-key signature"
9089 " despite accepting key!\r\n");
9090 logevent("Server refused public-key signature"
9091 " despite accepting key!");
9092 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9093 /* quiet, so no c_write */
9094 logevent("Server refused keyboard-interactive authentication");
9095 } else if (s->type==AUTH_TYPE_GSSAPI) {
9096 /* always quiet, so no c_write */
9097 /* also, the code down in the GSSAPI block has
9098 * already logged this in the Event Log */
9099 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9100 logevent("Keyboard-interactive authentication failed");
9101 c_write_str(ssh, "Access denied\r\n");
9103 assert(s->type == AUTH_TYPE_PASSWORD);
9104 logevent("Password authentication failed");
9105 c_write_str(ssh, "Access denied\r\n");
9107 if (conf_get_int(ssh->conf, CONF_change_username)) {
9108 /* XXX perhaps we should allow
9109 * keyboard-interactive to do this too? */
9110 s->we_are_in = FALSE;
9115 c_write_str(ssh, "Further authentication required\r\n");
9116 logevent("Further authentication required");
9120 in_commasep_string("publickey", methods, methlen);
9122 in_commasep_string("password", methods, methlen);
9123 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9124 in_commasep_string("keyboard-interactive", methods, methlen);
9127 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9128 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9129 in_commasep_string("gssapi-with-mic", methods, methlen) &&
9130 ssh->gsslibs->nlibraries > 0;
9134 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9136 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9139 * Attempt public-key authentication using a key from Pageant.
9142 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9144 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9146 /* Unpack key from agent response */
9147 s->pklen = toint(GET_32BIT(s->agentp));
9149 s->pkblob = (char *)s->agentp;
9150 s->agentp += s->pklen;
9151 s->alglen = toint(GET_32BIT(s->pkblob));
9152 s->alg = s->pkblob + 4;
9153 s->commentlen = toint(GET_32BIT(s->agentp));
9155 s->commentp = (char *)s->agentp;
9156 s->agentp += s->commentlen;
9157 /* s->agentp now points at next key, if any */
9159 /* See if server will accept it */
9160 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9161 ssh2_pkt_addstring(s->pktout, ssh->username);
9162 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9163 /* service requested */
9164 ssh2_pkt_addstring(s->pktout, "publickey");
9166 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9167 ssh2_pkt_addstring_start(s->pktout);
9168 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9169 ssh2_pkt_addstring_start(s->pktout);
9170 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9171 ssh2_pkt_send(ssh, s->pktout);
9172 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9174 crWaitUntilV(pktin);
9175 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9177 /* Offer of key refused. */
9184 if (flags & FLAG_VERBOSE) {
9185 c_write_str(ssh, "Authenticating with "
9187 c_write(ssh, s->commentp, s->commentlen);
9188 c_write_str(ssh, "\" from agent\r\n");
9192 * Server is willing to accept the key.
9193 * Construct a SIGN_REQUEST.
9195 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9196 ssh2_pkt_addstring(s->pktout, ssh->username);
9197 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9198 /* service requested */
9199 ssh2_pkt_addstring(s->pktout, "publickey");
9201 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9202 ssh2_pkt_addstring_start(s->pktout);
9203 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9204 ssh2_pkt_addstring_start(s->pktout);
9205 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9207 /* Ask agent for signature. */
9208 s->siglen = s->pktout->length - 5 + 4 +
9209 ssh->v2_session_id_len;
9210 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9212 s->len = 1; /* message type */
9213 s->len += 4 + s->pklen; /* key blob */
9214 s->len += 4 + s->siglen; /* data to sign */
9215 s->len += 4; /* flags */
9216 s->agentreq = snewn(4 + s->len, char);
9217 PUT_32BIT(s->agentreq, s->len);
9218 s->q = s->agentreq + 4;
9219 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9220 PUT_32BIT(s->q, s->pklen);
9222 memcpy(s->q, s->pkblob, s->pklen);
9224 PUT_32BIT(s->q, s->siglen);
9226 /* Now the data to be signed... */
9227 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9228 PUT_32BIT(s->q, ssh->v2_session_id_len);
9231 memcpy(s->q, ssh->v2_session_id,
9232 ssh->v2_session_id_len);
9233 s->q += ssh->v2_session_id_len;
9234 memcpy(s->q, s->pktout->data + 5,
9235 s->pktout->length - 5);
9236 s->q += s->pktout->length - 5;
9237 /* And finally the (zero) flags word. */
9239 if (!agent_query(s->agentreq, s->len + 4,
9241 ssh_agent_callback, ssh)) {
9245 bombout(("Unexpected data from server"
9246 " while waiting for agent"
9250 } while (pktin || inlen > 0);
9251 vret = ssh->agent_response;
9252 s->retlen = ssh->agent_response_len;
9257 if (s->retlen >= 9 &&
9258 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9259 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9260 logevent("Sending Pageant's response");
9261 ssh2_add_sigblob(ssh, s->pktout,
9262 s->pkblob, s->pklen,
9264 GET_32BIT(s->ret + 5));
9265 ssh2_pkt_send(ssh, s->pktout);
9266 s->type = AUTH_TYPE_PUBLICKEY;
9268 /* FIXME: less drastic response */
9269 bombout(("Pageant failed to answer challenge"));
9275 /* Do we have any keys left to try? */
9276 if (s->pkblob_in_agent) {
9277 s->done_agent = TRUE;
9278 s->tried_pubkey_config = TRUE;
9281 if (s->keyi >= s->nkeys)
9282 s->done_agent = TRUE;
9285 } else if (s->can_pubkey && s->publickey_blob &&
9286 !s->tried_pubkey_config) {
9288 struct ssh2_userkey *key; /* not live over crReturn */
9289 char *passphrase; /* not live over crReturn */
9291 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9293 s->tried_pubkey_config = TRUE;
9296 * Try the public key supplied in the configuration.
9298 * First, offer the public blob to see if the server is
9299 * willing to accept it.
9301 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9302 ssh2_pkt_addstring(s->pktout, ssh->username);
9303 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9304 /* service requested */
9305 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9306 ssh2_pkt_addbool(s->pktout, FALSE);
9307 /* no signature included */
9308 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9309 ssh2_pkt_addstring_start(s->pktout);
9310 ssh2_pkt_addstring_data(s->pktout,
9311 (char *)s->publickey_blob,
9312 s->publickey_bloblen);
9313 ssh2_pkt_send(ssh, s->pktout);
9314 logevent("Offered public key");
9316 crWaitUntilV(pktin);
9317 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9318 /* Key refused. Give up. */
9319 s->gotit = TRUE; /* reconsider message next loop */
9320 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9321 continue; /* process this new message */
9323 logevent("Offer of public key accepted");
9326 * Actually attempt a serious authentication using
9329 if (flags & FLAG_VERBOSE) {
9330 c_write_str(ssh, "Authenticating with public key \"");
9331 c_write_str(ssh, s->publickey_comment);
9332 c_write_str(ssh, "\"\r\n");
9336 const char *error; /* not live over crReturn */
9337 if (s->publickey_encrypted) {
9339 * Get a passphrase from the user.
9341 int ret; /* need not be kept over crReturn */
9342 s->cur_prompt = new_prompts(ssh->frontend);
9343 s->cur_prompt->to_server = FALSE;
9344 s->cur_prompt->name = dupstr("SSH key passphrase");
9345 add_prompt(s->cur_prompt,
9346 dupprintf("Passphrase for key \"%.100s\": ",
9347 s->publickey_comment),
9349 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9352 crWaitUntilV(!pktin);
9353 ret = get_userpass_input(s->cur_prompt,
9358 /* Failed to get a passphrase. Terminate. */
9359 free_prompts(s->cur_prompt);
9360 ssh_disconnect(ssh, NULL,
9361 "Unable to authenticate",
9362 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9367 dupstr(s->cur_prompt->prompts[0]->result);
9368 free_prompts(s->cur_prompt);
9370 passphrase = NULL; /* no passphrase needed */
9374 * Try decrypting the key.
9376 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9377 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9379 /* burn the evidence */
9380 smemclr(passphrase, strlen(passphrase));
9383 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9385 (key == SSH2_WRONG_PASSPHRASE)) {
9386 c_write_str(ssh, "Wrong passphrase\r\n");
9388 /* and loop again */
9390 c_write_str(ssh, "Unable to load private key (");
9391 c_write_str(ssh, error);
9392 c_write_str(ssh, ")\r\n");
9394 break; /* try something else */
9400 unsigned char *pkblob, *sigblob, *sigdata;
9401 int pkblob_len, sigblob_len, sigdata_len;
9405 * We have loaded the private key and the server
9406 * has announced that it's willing to accept it.
9407 * Hallelujah. Generate a signature and send it.
9409 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9410 ssh2_pkt_addstring(s->pktout, ssh->username);
9411 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9412 /* service requested */
9413 ssh2_pkt_addstring(s->pktout, "publickey");
9415 ssh2_pkt_addbool(s->pktout, TRUE);
9416 /* signature follows */
9417 ssh2_pkt_addstring(s->pktout, key->alg->name);
9418 pkblob = key->alg->public_blob(key->data,
9420 ssh2_pkt_addstring_start(s->pktout);
9421 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9425 * The data to be signed is:
9429 * followed by everything so far placed in the
9432 sigdata_len = s->pktout->length - 5 + 4 +
9433 ssh->v2_session_id_len;
9434 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9436 sigdata = snewn(sigdata_len, unsigned char);
9438 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9439 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9442 memcpy(sigdata+p, ssh->v2_session_id,
9443 ssh->v2_session_id_len);
9444 p += ssh->v2_session_id_len;
9445 memcpy(sigdata+p, s->pktout->data + 5,
9446 s->pktout->length - 5);
9447 p += s->pktout->length - 5;
9448 assert(p == sigdata_len);
9449 sigblob = key->alg->sign(key->data, (char *)sigdata,
9450 sigdata_len, &sigblob_len);
9451 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9452 sigblob, sigblob_len);
9457 ssh2_pkt_send(ssh, s->pktout);
9458 logevent("Sent public key signature");
9459 s->type = AUTH_TYPE_PUBLICKEY;
9460 key->alg->freekey(key->data);
9464 } else if (s->can_gssapi && !s->tried_gssapi) {
9466 /* GSSAPI Authentication */
9471 s->type = AUTH_TYPE_GSSAPI;
9472 s->tried_gssapi = TRUE;
9474 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9477 * Pick the highest GSS library on the preference
9483 for (i = 0; i < ngsslibs; i++) {
9484 int want_id = conf_get_int_int(ssh->conf,
9485 CONF_ssh_gsslist, i);
9486 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
9487 if (ssh->gsslibs->libraries[j].id == want_id) {
9488 s->gsslib = &ssh->gsslibs->libraries[j];
9489 goto got_gsslib; /* double break */
9494 * We always expect to have found something in
9495 * the above loop: we only came here if there
9496 * was at least one viable GSS library, and the
9497 * preference list should always mention
9498 * everything and only change the order.
9503 if (s->gsslib->gsslogmsg)
9504 logevent(s->gsslib->gsslogmsg);
9506 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
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 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
9511 logevent("Attempting GSSAPI authentication");
9513 /* add mechanism info */
9514 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
9516 /* number of GSSAPI mechanisms */
9517 ssh2_pkt_adduint32(s->pktout,1);
9519 /* length of OID + 2 */
9520 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
9521 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
9524 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
9526 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
9528 ssh2_pkt_send(ssh, s->pktout);
9529 crWaitUntilV(pktin);
9530 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
9531 logevent("GSSAPI authentication request refused");
9535 /* check returned packet ... */
9537 ssh_pkt_getstring(pktin, &data, &len);
9538 s->gss_rcvtok.value = data;
9539 s->gss_rcvtok.length = len;
9540 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
9541 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
9542 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
9543 memcmp((char *)s->gss_rcvtok.value + 2,
9544 s->gss_buf.value,s->gss_buf.length) ) {
9545 logevent("GSSAPI authentication - wrong response from server");
9549 /* now start running */
9550 s->gss_stat = s->gsslib->import_name(s->gsslib,
9553 if (s->gss_stat != SSH_GSS_OK) {
9554 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
9555 logevent("GSSAPI import name failed - Bad service name");
9557 logevent("GSSAPI import name failed");
9561 /* fetch TGT into GSS engine */
9562 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
9564 if (s->gss_stat != SSH_GSS_OK) {
9565 logevent("GSSAPI authentication failed to get credentials");
9566 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9570 /* initial tokens are empty */
9571 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
9572 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
9574 /* now enter the loop */
9576 s->gss_stat = s->gsslib->init_sec_context
9580 conf_get_int(ssh->conf, CONF_gssapifwd),
9584 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
9585 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
9586 logevent("GSSAPI authentication initialisation failed");
9588 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
9589 &s->gss_buf) == SSH_GSS_OK) {
9590 logevent(s->gss_buf.value);
9591 sfree(s->gss_buf.value);
9596 logevent("GSSAPI authentication initialised");
9598 /* Client and server now exchange tokens until GSSAPI
9599 * no longer says CONTINUE_NEEDED */
9601 if (s->gss_sndtok.length != 0) {
9602 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
9603 ssh_pkt_addstring_start(s->pktout);
9604 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
9605 ssh2_pkt_send(ssh, s->pktout);
9606 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
9609 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
9610 crWaitUntilV(pktin);
9611 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
9612 logevent("GSSAPI authentication - bad server response");
9613 s->gss_stat = SSH_GSS_FAILURE;
9616 ssh_pkt_getstring(pktin, &data, &len);
9617 s->gss_rcvtok.value = data;
9618 s->gss_rcvtok.length = len;
9620 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
9622 if (s->gss_stat != SSH_GSS_OK) {
9623 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9624 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9627 logevent("GSSAPI authentication loop finished OK");
9629 /* Now send the MIC */
9631 s->pktout = ssh2_pkt_init(0);
9632 micoffset = s->pktout->length;
9633 ssh_pkt_addstring_start(s->pktout);
9634 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
9635 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
9636 ssh_pkt_addstring(s->pktout, ssh->username);
9637 ssh_pkt_addstring(s->pktout, "ssh-connection");
9638 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
9640 s->gss_buf.value = (char *)s->pktout->data + micoffset;
9641 s->gss_buf.length = s->pktout->length - micoffset;
9643 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
9644 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
9645 ssh_pkt_addstring_start(s->pktout);
9646 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
9647 ssh2_pkt_send(ssh, s->pktout);
9648 s->gsslib->free_mic(s->gsslib, &mic);
9652 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9653 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9656 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
9659 * Keyboard-interactive authentication.
9662 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
9664 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
9666 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9667 ssh2_pkt_addstring(s->pktout, ssh->username);
9668 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9669 /* service requested */
9670 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
9672 ssh2_pkt_addstring(s->pktout, ""); /* lang */
9673 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
9674 ssh2_pkt_send(ssh, s->pktout);
9676 logevent("Attempting keyboard-interactive authentication");
9678 crWaitUntilV(pktin);
9679 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
9680 /* Server is not willing to do keyboard-interactive
9681 * at all (or, bizarrely but legally, accepts the
9682 * user without actually issuing any prompts).
9683 * Give up on it entirely. */
9685 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
9686 s->kbd_inter_refused = TRUE; /* don't try it again */
9691 * Loop while the server continues to send INFO_REQUESTs.
9693 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
9695 char *name, *inst, *lang;
9696 int name_len, inst_len, lang_len;
9700 * We've got a fresh USERAUTH_INFO_REQUEST.
9701 * Get the preamble and start building a prompt.
9703 ssh_pkt_getstring(pktin, &name, &name_len);
9704 ssh_pkt_getstring(pktin, &inst, &inst_len);
9705 ssh_pkt_getstring(pktin, &lang, &lang_len);
9706 s->cur_prompt = new_prompts(ssh->frontend);
9707 s->cur_prompt->to_server = TRUE;
9710 * Get any prompt(s) from the packet.
9712 s->num_prompts = ssh_pkt_getuint32(pktin);
9713 for (i = 0; i < s->num_prompts; i++) {
9717 static char noprompt[] =
9718 "<server failed to send prompt>: ";
9720 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9721 echo = ssh2_pkt_getbool(pktin);
9724 prompt_len = lenof(noprompt)-1;
9726 add_prompt(s->cur_prompt,
9727 dupprintf("%.*s", prompt_len, prompt),
9732 /* FIXME: better prefix to distinguish from
9734 s->cur_prompt->name =
9735 dupprintf("SSH server: %.*s", name_len, name);
9736 s->cur_prompt->name_reqd = TRUE;
9738 s->cur_prompt->name =
9739 dupstr("SSH server authentication");
9740 s->cur_prompt->name_reqd = FALSE;
9742 /* We add a prefix to try to make it clear that a prompt
9743 * has come from the server.
9744 * FIXME: ugly to print "Using..." in prompt _every_
9745 * time round. Can this be done more subtly? */
9746 /* Special case: for reasons best known to themselves,
9747 * some servers send k-i requests with no prompts and
9748 * nothing to display. Keep quiet in this case. */
9749 if (s->num_prompts || name_len || inst_len) {
9750 s->cur_prompt->instruction =
9751 dupprintf("Using keyboard-interactive authentication.%s%.*s",
9752 inst_len ? "\n" : "", inst_len, inst);
9753 s->cur_prompt->instr_reqd = TRUE;
9755 s->cur_prompt->instr_reqd = FALSE;
9759 * Display any instructions, and get the user's
9763 int ret; /* not live over crReturn */
9764 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9767 crWaitUntilV(!pktin);
9768 ret = get_userpass_input(s->cur_prompt, in, inlen);
9773 * Failed to get responses. Terminate.
9775 free_prompts(s->cur_prompt);
9776 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9777 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9784 * Send the response(s) to the server.
9786 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
9787 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
9788 for (i=0; i < s->num_prompts; i++) {
9789 ssh2_pkt_addstring(s->pktout,
9790 s->cur_prompt->prompts[i]->result);
9792 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9795 * Free the prompts structure from this iteration.
9796 * If there's another, a new one will be allocated
9797 * when we return to the top of this while loop.
9799 free_prompts(s->cur_prompt);
9802 * Get the next packet in case it's another
9805 crWaitUntilV(pktin);
9810 * We should have SUCCESS or FAILURE now.
9814 } else if (s->can_passwd) {
9817 * Plain old password authentication.
9819 int ret; /* not live over crReturn */
9820 int changereq_first_time; /* not live over crReturn */
9822 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
9824 s->cur_prompt = new_prompts(ssh->frontend);
9825 s->cur_prompt->to_server = TRUE;
9826 s->cur_prompt->name = dupstr("SSH password");
9827 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
9832 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9835 crWaitUntilV(!pktin);
9836 ret = get_userpass_input(s->cur_prompt, in, inlen);
9841 * Failed to get responses. Terminate.
9843 free_prompts(s->cur_prompt);
9844 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9845 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9850 * Squirrel away the password. (We may need it later if
9851 * asked to change it.)
9853 s->password = dupstr(s->cur_prompt->prompts[0]->result);
9854 free_prompts(s->cur_prompt);
9857 * Send the password packet.
9859 * We pad out the password packet to 256 bytes to make
9860 * it harder for an attacker to find the length of the
9863 * Anyone using a password longer than 256 bytes
9864 * probably doesn't have much to worry about from
9865 * people who find out how long their password is!
9867 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9868 ssh2_pkt_addstring(s->pktout, ssh->username);
9869 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9870 /* service requested */
9871 ssh2_pkt_addstring(s->pktout, "password");
9872 ssh2_pkt_addbool(s->pktout, FALSE);
9873 ssh2_pkt_addstring(s->pktout, s->password);
9874 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9875 logevent("Sent password");
9876 s->type = AUTH_TYPE_PASSWORD;
9879 * Wait for next packet, in case it's a password change
9882 crWaitUntilV(pktin);
9883 changereq_first_time = TRUE;
9885 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
9888 * We're being asked for a new password
9889 * (perhaps not for the first time).
9890 * Loop until the server accepts it.
9893 int got_new = FALSE; /* not live over crReturn */
9894 char *prompt; /* not live over crReturn */
9895 int prompt_len; /* not live over crReturn */
9899 if (changereq_first_time)
9900 msg = "Server requested password change";
9902 msg = "Server rejected new password";
9904 c_write_str(ssh, msg);
9905 c_write_str(ssh, "\r\n");
9908 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9910 s->cur_prompt = new_prompts(ssh->frontend);
9911 s->cur_prompt->to_server = TRUE;
9912 s->cur_prompt->name = dupstr("New SSH password");
9913 s->cur_prompt->instruction =
9914 dupprintf("%.*s", prompt_len, prompt);
9915 s->cur_prompt->instr_reqd = TRUE;
9917 * There's no explicit requirement in the protocol
9918 * for the "old" passwords in the original and
9919 * password-change messages to be the same, and
9920 * apparently some Cisco kit supports password change
9921 * by the user entering a blank password originally
9922 * and the real password subsequently, so,
9923 * reluctantly, we prompt for the old password again.
9925 * (On the other hand, some servers don't even bother
9926 * to check this field.)
9928 add_prompt(s->cur_prompt,
9929 dupstr("Current password (blank for previously entered password): "),
9931 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
9933 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
9937 * Loop until the user manages to enter the same
9942 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9945 crWaitUntilV(!pktin);
9946 ret = get_userpass_input(s->cur_prompt, in, inlen);
9951 * Failed to get responses. Terminate.
9953 /* burn the evidence */
9954 free_prompts(s->cur_prompt);
9955 smemclr(s->password, strlen(s->password));
9957 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9958 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9964 * If the user specified a new original password
9965 * (IYSWIM), overwrite any previously specified
9967 * (A side effect is that the user doesn't have to
9968 * re-enter it if they louse up the new password.)
9970 if (s->cur_prompt->prompts[0]->result[0]) {
9971 smemclr(s->password, strlen(s->password));
9972 /* burn the evidence */
9975 dupstr(s->cur_prompt->prompts[0]->result);
9979 * Check the two new passwords match.
9981 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
9982 s->cur_prompt->prompts[2]->result)
9985 /* They don't. Silly user. */
9986 c_write_str(ssh, "Passwords do not match\r\n");
9991 * Send the new password (along with the old one).
9992 * (see above for padding rationale)
9994 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9995 ssh2_pkt_addstring(s->pktout, ssh->username);
9996 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9997 /* service requested */
9998 ssh2_pkt_addstring(s->pktout, "password");
9999 ssh2_pkt_addbool(s->pktout, TRUE);
10000 ssh2_pkt_addstring(s->pktout, s->password);
10001 ssh2_pkt_addstring(s->pktout,
10002 s->cur_prompt->prompts[1]->result);
10003 free_prompts(s->cur_prompt);
10004 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10005 logevent("Sent new password");
10008 * Now see what the server has to say about it.
10009 * (If it's CHANGEREQ again, it's not happy with the
10012 crWaitUntilV(pktin);
10013 changereq_first_time = FALSE;
10018 * We need to reexamine the current pktin at the top
10019 * of the loop. Either:
10020 * - we weren't asked to change password at all, in
10021 * which case it's a SUCCESS or FAILURE with the
10023 * - we sent a new password, and the server was
10024 * either OK with it (SUCCESS or FAILURE w/partial
10025 * success) or unhappy with the _old_ password
10026 * (FAILURE w/o partial success)
10027 * In any of these cases, we go back to the top of
10028 * the loop and start again.
10033 * We don't need the old password any more, in any
10034 * case. Burn the evidence.
10036 smemclr(s->password, strlen(s->password));
10037 sfree(s->password);
10040 char *str = dupprintf("No supported authentication methods available"
10041 " (server sent: %.*s)",
10044 ssh_disconnect(ssh, str,
10045 "No supported authentication methods available",
10046 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10056 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10058 /* Clear up various bits and pieces from authentication. */
10059 if (s->publickey_blob) {
10060 sfree(s->publickey_blob);
10061 sfree(s->publickey_comment);
10063 if (s->agent_response)
10064 sfree(s->agent_response);
10066 if (s->userauth_success && !ssh->bare_connection) {
10068 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10069 * packets since. Signal the transport layer to consider enacting
10070 * delayed compression.
10072 * (Relying on we_are_in is not sufficient, as
10073 * draft-miller-secsh-compression-delayed is quite clear that it
10074 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10075 * become set for other reasons.)
10077 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10080 ssh->channels = newtree234(ssh_channelcmp);
10083 * Set up handlers for some connection protocol messages, so we
10084 * don't have to handle them repeatedly in this coroutine.
10086 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10087 ssh2_msg_channel_window_adjust;
10088 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10089 ssh2_msg_global_request;
10092 * Create the main session channel.
10094 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10095 ssh->mainchan = NULL;
10097 ssh->mainchan = snew(struct ssh_channel);
10098 ssh->mainchan->ssh = ssh;
10099 ssh2_channel_init(ssh->mainchan);
10101 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10103 * Just start a direct-tcpip channel and use it as the main
10106 ssh_send_port_open(ssh->mainchan,
10107 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10108 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10110 ssh->ncmode = TRUE;
10112 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10113 logevent("Opening session as main channel");
10114 ssh2_pkt_send(ssh, s->pktout);
10115 ssh->ncmode = FALSE;
10117 crWaitUntilV(pktin);
10118 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10119 bombout(("Server refused to open channel"));
10121 /* FIXME: error data comes back in FAILURE packet */
10123 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10124 bombout(("Server's channel confirmation cited wrong channel"));
10127 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10128 ssh->mainchan->halfopen = FALSE;
10129 ssh->mainchan->type = CHAN_MAINSESSION;
10130 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10131 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10132 add234(ssh->channels, ssh->mainchan);
10133 update_specials_menu(ssh->frontend);
10134 logevent("Opened main channel");
10138 * Now we have a channel, make dispatch table entries for
10139 * general channel-based messages.
10141 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10142 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10143 ssh2_msg_channel_data;
10144 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10145 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10146 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10147 ssh2_msg_channel_open_confirmation;
10148 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10149 ssh2_msg_channel_open_failure;
10150 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10151 ssh2_msg_channel_request;
10152 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10153 ssh2_msg_channel_open;
10154 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10155 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10158 * Now the connection protocol is properly up and running, with
10159 * all those dispatch table entries, so it's safe to let
10160 * downstreams start trying to open extra channels through us.
10162 if (ssh->connshare)
10163 share_activate(ssh->connshare, ssh->v_s);
10165 if (ssh->mainchan && ssh_is_simple(ssh)) {
10167 * This message indicates to the server that we promise
10168 * not to try to run any other channel in parallel with
10169 * this one, so it's safe for it to advertise a very large
10170 * window and leave the flow control to TCP.
10172 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10173 "simple@putty.projects.tartarus.org",
10175 ssh2_pkt_send(ssh, s->pktout);
10179 * Enable port forwardings.
10181 ssh_setup_portfwd(ssh, ssh->conf);
10183 if (ssh->mainchan && !ssh->ncmode) {
10185 * Send the CHANNEL_REQUESTS for the main session channel.
10186 * Each one is handled by its own little asynchronous
10190 /* Potentially enable X11 forwarding. */
10191 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10193 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10195 if (!ssh->x11disp) {
10196 /* FIXME: return an error message from x11_setup_display */
10197 logevent("X11 forwarding not enabled: unable to"
10198 " initialise X display");
10200 ssh->x11auth = x11_invent_fake_auth
10201 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10202 ssh->x11auth->disp = ssh->x11disp;
10204 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10208 /* Potentially enable agent forwarding. */
10209 if (ssh_agent_forwarding_permitted(ssh))
10210 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10212 /* Now allocate a pty for the session. */
10213 if (!conf_get_int(ssh->conf, CONF_nopty))
10214 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10216 /* Send environment variables. */
10217 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10220 * Start a shell or a remote command. We may have to attempt
10221 * this twice if the config data has provided a second choice
10228 if (ssh->fallback_cmd) {
10229 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10230 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10232 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10233 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10237 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10238 ssh2_response_authconn, NULL);
10239 ssh2_pkt_addstring(s->pktout, cmd);
10241 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10242 ssh2_response_authconn, NULL);
10243 ssh2_pkt_addstring(s->pktout, cmd);
10245 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10246 ssh2_response_authconn, NULL);
10248 ssh2_pkt_send(ssh, s->pktout);
10250 crWaitUntilV(pktin);
10252 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10253 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10254 bombout(("Unexpected response to shell/command request:"
10255 " packet type %d", pktin->type));
10259 * We failed to start the command. If this is the
10260 * fallback command, we really are finished; if it's
10261 * not, and if the fallback command exists, try falling
10262 * back to it before complaining.
10264 if (!ssh->fallback_cmd &&
10265 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10266 logevent("Primary command failed; attempting fallback");
10267 ssh->fallback_cmd = TRUE;
10270 bombout(("Server refused to start a shell/command"));
10273 logevent("Started a shell/command");
10278 ssh->editing = ssh->echoing = TRUE;
10281 ssh->state = SSH_STATE_SESSION;
10282 if (ssh->size_needed)
10283 ssh_size(ssh, ssh->term_width, ssh->term_height);
10284 if (ssh->eof_needed)
10285 ssh_special(ssh, TS_EOF);
10291 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
10296 s->try_send = FALSE;
10300 * _All_ the connection-layer packets we expect to
10301 * receive are now handled by the dispatch table.
10302 * Anything that reaches here must be bogus.
10305 bombout(("Strange packet received: type %d", pktin->type));
10307 } else if (ssh->mainchan) {
10309 * We have spare data. Add it to the channel buffer.
10311 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
10312 s->try_send = TRUE;
10316 struct ssh_channel *c;
10318 * Try to send data on all channels if we can.
10320 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
10321 ssh2_try_send_and_unthrottle(ssh, c);
10329 * Handlers for SSH-2 messages that might arrive at any moment.
10331 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10333 /* log reason code in disconnect message */
10335 int reason, msglen;
10337 reason = ssh_pkt_getuint32(pktin);
10338 ssh_pkt_getstring(pktin, &msg, &msglen);
10340 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10341 buf = dupprintf("Received disconnect message (%s)",
10342 ssh2_disconnect_reasons[reason]);
10344 buf = dupprintf("Received disconnect message (unknown"
10345 " type %d)", reason);
10349 buf = dupprintf("Disconnection message text: %.*s",
10352 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10354 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10355 ssh2_disconnect_reasons[reason] : "unknown",
10360 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10362 /* log the debug message */
10366 /* XXX maybe we should actually take notice of the return value */
10367 ssh2_pkt_getbool(pktin);
10368 ssh_pkt_getstring(pktin, &msg, &msglen);
10370 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
10373 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10375 do_ssh2_transport(ssh, NULL, 0, pktin);
10379 * Called if we receive a packet that isn't allowed by the protocol.
10380 * This only applies to packets whose meaning PuTTY understands.
10381 * Entirely unknown packets are handled below.
10383 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10385 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10386 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10388 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10392 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10394 struct Packet *pktout;
10395 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10396 ssh2_pkt_adduint32(pktout, pktin->sequence);
10398 * UNIMPLEMENTED messages MUST appear in the same order as the
10399 * messages they respond to. Hence, never queue them.
10401 ssh2_pkt_send_noqueue(ssh, pktout);
10405 * Handle the top-level SSH-2 protocol.
10407 static void ssh2_protocol_setup(Ssh ssh)
10412 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10414 for (i = 0; i < 256; i++)
10415 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10418 * Initially, we only accept transport messages (and a few generic
10419 * ones). do_ssh2_authconn will add more when it starts.
10420 * Messages that are understood but not currently acceptable go to
10421 * ssh2_msg_unexpected.
10423 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10424 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10425 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10426 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10427 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10428 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10429 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10430 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10431 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10432 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10433 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10434 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10435 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10436 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10437 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10438 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10439 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10440 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10441 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10442 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10443 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10444 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10445 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10446 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10447 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10448 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10449 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10450 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10451 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10452 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10453 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10454 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10455 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10458 * These messages have a special handler from the start.
10460 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10461 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10462 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10465 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10470 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10472 for (i = 0; i < 256; i++)
10473 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10476 * Initially, we set all ssh-connection messages to 'unexpected';
10477 * do_ssh2_authconn will fill things in properly. We also handle a
10478 * couple of messages from the transport protocol which aren't
10479 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10482 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10483 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10484 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10485 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10486 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10487 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10488 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10489 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10490 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10491 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10492 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10493 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10494 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10495 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10497 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10500 * These messages have a special handler from the start.
10502 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10503 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
10504 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10507 static void ssh2_timer(void *ctx, unsigned long now)
10509 Ssh ssh = (Ssh)ctx;
10511 if (ssh->state == SSH_STATE_CLOSED)
10514 if (!ssh->kex_in_progress && !ssh->bare_connection &&
10515 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
10516 now == ssh->next_rekey) {
10517 do_ssh2_transport(ssh, "timeout", -1, NULL);
10521 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
10522 struct Packet *pktin)
10524 unsigned char *in = (unsigned char *)vin;
10525 if (ssh->state == SSH_STATE_CLOSED)
10529 ssh->incoming_data_size += pktin->encrypted_len;
10530 if (!ssh->kex_in_progress &&
10531 ssh->max_data_size != 0 &&
10532 ssh->incoming_data_size > ssh->max_data_size)
10533 do_ssh2_transport(ssh, "too much data received", -1, NULL);
10537 ssh->packet_dispatch[pktin->type](ssh, pktin);
10538 else if (!ssh->protocol_initial_phase_done)
10539 do_ssh2_transport(ssh, in, inlen, pktin);
10541 do_ssh2_authconn(ssh, in, inlen, pktin);
10544 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
10545 struct Packet *pktin)
10547 unsigned char *in = (unsigned char *)vin;
10548 if (ssh->state == SSH_STATE_CLOSED)
10552 ssh->packet_dispatch[pktin->type](ssh, pktin);
10554 do_ssh2_authconn(ssh, in, inlen, pktin);
10557 static void ssh_cache_conf_values(Ssh ssh)
10559 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
10563 * Called to set up the connection.
10565 * Returns an error message, or NULL on success.
10567 static const char *ssh_init(void *frontend_handle, void **backend_handle,
10568 Conf *conf, char *host, int port, char **realhost,
10569 int nodelay, int keepalive)
10574 ssh = snew(struct ssh_tag);
10575 ssh->conf = conf_copy(conf);
10576 ssh_cache_conf_values(ssh);
10577 ssh->version = 0; /* when not ready yet */
10579 ssh->cipher = NULL;
10580 ssh->v1_cipher_ctx = NULL;
10581 ssh->crcda_ctx = NULL;
10582 ssh->cscipher = NULL;
10583 ssh->cs_cipher_ctx = NULL;
10584 ssh->sccipher = NULL;
10585 ssh->sc_cipher_ctx = NULL;
10587 ssh->cs_mac_ctx = NULL;
10589 ssh->sc_mac_ctx = NULL;
10590 ssh->cscomp = NULL;
10591 ssh->cs_comp_ctx = NULL;
10592 ssh->sccomp = NULL;
10593 ssh->sc_comp_ctx = NULL;
10595 ssh->kex_ctx = NULL;
10596 ssh->hostkey = NULL;
10597 ssh->hostkey_str = NULL;
10598 ssh->exitcode = -1;
10599 ssh->close_expected = FALSE;
10600 ssh->clean_exit = FALSE;
10601 ssh->state = SSH_STATE_PREPACKET;
10602 ssh->size_needed = FALSE;
10603 ssh->eof_needed = FALSE;
10605 ssh->logctx = NULL;
10606 ssh->deferred_send_data = NULL;
10607 ssh->deferred_len = 0;
10608 ssh->deferred_size = 0;
10609 ssh->fallback_cmd = 0;
10610 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
10611 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
10612 ssh->x11disp = NULL;
10613 ssh->x11auth = NULL;
10614 ssh->x11authtree = newtree234(x11_authcmp);
10615 ssh->v1_compressing = FALSE;
10616 ssh->v2_outgoing_sequence = 0;
10617 ssh->ssh1_rdpkt_crstate = 0;
10618 ssh->ssh2_rdpkt_crstate = 0;
10619 ssh->ssh2_bare_rdpkt_crstate = 0;
10620 ssh->ssh_gotdata_crstate = 0;
10621 ssh->do_ssh1_connection_crstate = 0;
10622 ssh->do_ssh_init_state = NULL;
10623 ssh->do_ssh_connection_init_state = NULL;
10624 ssh->do_ssh1_login_state = NULL;
10625 ssh->do_ssh2_transport_state = NULL;
10626 ssh->do_ssh2_authconn_state = NULL;
10629 ssh->mainchan = NULL;
10630 ssh->throttled_all = 0;
10631 ssh->v1_stdout_throttling = 0;
10633 ssh->queuelen = ssh->queuesize = 0;
10634 ssh->queueing = FALSE;
10635 ssh->qhead = ssh->qtail = NULL;
10636 ssh->deferred_rekey_reason = NULL;
10637 bufchain_init(&ssh->queued_incoming_data);
10638 ssh->frozen = FALSE;
10639 ssh->username = NULL;
10640 ssh->sent_console_eof = FALSE;
10641 ssh->got_pty = FALSE;
10642 ssh->bare_connection = FALSE;
10643 ssh->X11_fwd_enabled = FALSE;
10644 ssh->connshare = NULL;
10645 ssh->attempting_connshare = FALSE;
10647 *backend_handle = ssh;
10650 if (crypto_startup() == 0)
10651 return "Microsoft high encryption pack not installed!";
10654 ssh->frontend = frontend_handle;
10655 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
10656 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
10658 ssh->channels = NULL;
10659 ssh->rportfwds = NULL;
10660 ssh->portfwds = NULL;
10665 ssh->conn_throttle_count = 0;
10666 ssh->overall_bufsize = 0;
10667 ssh->fallback_cmd = 0;
10669 ssh->protocol = NULL;
10671 ssh->protocol_initial_phase_done = FALSE;
10673 ssh->pinger = NULL;
10675 ssh->incoming_data_size = ssh->outgoing_data_size =
10676 ssh->deferred_data_size = 0L;
10677 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10678 CONF_ssh_rekey_data));
10679 ssh->kex_in_progress = FALSE;
10682 ssh->gsslibs = NULL;
10685 random_ref(); /* do this now - may be needed by sharing setup code */
10687 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
10696 static void ssh_free(void *handle)
10698 Ssh ssh = (Ssh) handle;
10699 struct ssh_channel *c;
10700 struct ssh_rportfwd *pf;
10701 struct X11FakeAuth *auth;
10703 if (ssh->v1_cipher_ctx)
10704 ssh->cipher->free_context(ssh->v1_cipher_ctx);
10705 if (ssh->cs_cipher_ctx)
10706 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
10707 if (ssh->sc_cipher_ctx)
10708 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
10709 if (ssh->cs_mac_ctx)
10710 ssh->csmac->free_context(ssh->cs_mac_ctx);
10711 if (ssh->sc_mac_ctx)
10712 ssh->scmac->free_context(ssh->sc_mac_ctx);
10713 if (ssh->cs_comp_ctx) {
10715 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
10717 zlib_compress_cleanup(ssh->cs_comp_ctx);
10719 if (ssh->sc_comp_ctx) {
10721 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
10723 zlib_decompress_cleanup(ssh->sc_comp_ctx);
10726 dh_cleanup(ssh->kex_ctx);
10727 sfree(ssh->savedhost);
10729 while (ssh->queuelen-- > 0)
10730 ssh_free_packet(ssh->queue[ssh->queuelen]);
10733 while (ssh->qhead) {
10734 struct queued_handler *qh = ssh->qhead;
10735 ssh->qhead = qh->next;
10738 ssh->qhead = ssh->qtail = NULL;
10740 if (ssh->channels) {
10741 while ((c = delpos234(ssh->channels, 0)) != NULL) {
10744 if (c->u.x11.xconn != NULL)
10745 x11_close(c->u.x11.xconn);
10747 case CHAN_SOCKDATA:
10748 case CHAN_SOCKDATA_DORMANT:
10749 if (c->u.pfd.pf != NULL)
10750 pfd_close(c->u.pfd.pf);
10753 if (ssh->version == 2) {
10754 struct outstanding_channel_request *ocr, *nocr;
10755 ocr = c->v.v2.chanreq_head;
10757 ocr->handler(c, NULL, ocr->ctx);
10762 bufchain_clear(&c->v.v2.outbuffer);
10766 freetree234(ssh->channels);
10767 ssh->channels = NULL;
10770 if (ssh->connshare)
10771 sharestate_free(ssh->connshare);
10773 if (ssh->rportfwds) {
10774 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
10776 freetree234(ssh->rportfwds);
10777 ssh->rportfwds = NULL;
10779 sfree(ssh->deferred_send_data);
10781 x11_free_display(ssh->x11disp);
10782 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
10783 x11_free_fake_auth(auth);
10784 freetree234(ssh->x11authtree);
10785 sfree(ssh->do_ssh_init_state);
10786 sfree(ssh->do_ssh1_login_state);
10787 sfree(ssh->do_ssh2_transport_state);
10788 sfree(ssh->do_ssh2_authconn_state);
10791 sfree(ssh->fullhostname);
10792 sfree(ssh->hostkey_str);
10793 if (ssh->crcda_ctx) {
10794 crcda_free_context(ssh->crcda_ctx);
10795 ssh->crcda_ctx = NULL;
10798 ssh_do_close(ssh, TRUE);
10799 expire_timer_context(ssh);
10801 pinger_free(ssh->pinger);
10802 bufchain_clear(&ssh->queued_incoming_data);
10803 sfree(ssh->username);
10804 conf_free(ssh->conf);
10807 ssh_gss_cleanup(ssh->gsslibs);
10815 * Reconfigure the SSH backend.
10817 static void ssh_reconfig(void *handle, Conf *conf)
10819 Ssh ssh = (Ssh) handle;
10820 char *rekeying = NULL, rekey_mandatory = FALSE;
10821 unsigned long old_max_data_size;
10824 pinger_reconfig(ssh->pinger, ssh->conf, conf);
10826 ssh_setup_portfwd(ssh, conf);
10828 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
10829 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
10831 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
10832 unsigned long now = GETTICKCOUNT();
10834 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
10835 rekeying = "timeout shortened";
10837 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
10841 old_max_data_size = ssh->max_data_size;
10842 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10843 CONF_ssh_rekey_data));
10844 if (old_max_data_size != ssh->max_data_size &&
10845 ssh->max_data_size != 0) {
10846 if (ssh->outgoing_data_size > ssh->max_data_size ||
10847 ssh->incoming_data_size > ssh->max_data_size)
10848 rekeying = "data limit lowered";
10851 if (conf_get_int(ssh->conf, CONF_compression) !=
10852 conf_get_int(conf, CONF_compression)) {
10853 rekeying = "compression setting changed";
10854 rekey_mandatory = TRUE;
10857 for (i = 0; i < CIPHER_MAX; i++)
10858 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
10859 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
10860 rekeying = "cipher settings changed";
10861 rekey_mandatory = TRUE;
10863 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
10864 conf_get_int(conf, CONF_ssh2_des_cbc)) {
10865 rekeying = "cipher settings changed";
10866 rekey_mandatory = TRUE;
10869 conf_free(ssh->conf);
10870 ssh->conf = conf_copy(conf);
10871 ssh_cache_conf_values(ssh);
10873 if (!ssh->bare_connection && rekeying) {
10874 if (!ssh->kex_in_progress) {
10875 do_ssh2_transport(ssh, rekeying, -1, NULL);
10876 } else if (rekey_mandatory) {
10877 ssh->deferred_rekey_reason = rekeying;
10883 * Called to send data down the SSH connection.
10885 static int ssh_send(void *handle, char *buf, int len)
10887 Ssh ssh = (Ssh) handle;
10889 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10892 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
10894 return ssh_sendbuffer(ssh);
10898 * Called to query the current amount of buffered stdin data.
10900 static int ssh_sendbuffer(void *handle)
10902 Ssh ssh = (Ssh) handle;
10903 int override_value;
10905 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10909 * If the SSH socket itself has backed up, add the total backup
10910 * size on that to any individual buffer on the stdin channel.
10912 override_value = 0;
10913 if (ssh->throttled_all)
10914 override_value = ssh->overall_bufsize;
10916 if (ssh->version == 1) {
10917 return override_value;
10918 } else if (ssh->version == 2) {
10919 if (!ssh->mainchan)
10920 return override_value;
10922 return (override_value +
10923 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
10930 * Called to set the size of the window from SSH's POV.
10932 static void ssh_size(void *handle, int width, int height)
10934 Ssh ssh = (Ssh) handle;
10935 struct Packet *pktout;
10937 ssh->term_width = width;
10938 ssh->term_height = height;
10940 switch (ssh->state) {
10941 case SSH_STATE_BEFORE_SIZE:
10942 case SSH_STATE_PREPACKET:
10943 case SSH_STATE_CLOSED:
10944 break; /* do nothing */
10945 case SSH_STATE_INTERMED:
10946 ssh->size_needed = TRUE; /* buffer for later */
10948 case SSH_STATE_SESSION:
10949 if (!conf_get_int(ssh->conf, CONF_nopty)) {
10950 if (ssh->version == 1) {
10951 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
10952 PKT_INT, ssh->term_height,
10953 PKT_INT, ssh->term_width,
10954 PKT_INT, 0, PKT_INT, 0, PKT_END);
10955 } else if (ssh->mainchan) {
10956 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
10958 ssh2_pkt_adduint32(pktout, ssh->term_width);
10959 ssh2_pkt_adduint32(pktout, ssh->term_height);
10960 ssh2_pkt_adduint32(pktout, 0);
10961 ssh2_pkt_adduint32(pktout, 0);
10962 ssh2_pkt_send(ssh, pktout);
10970 * Return a list of the special codes that make sense in this
10973 static const struct telnet_special *ssh_get_specials(void *handle)
10975 static const struct telnet_special ssh1_ignore_special[] = {
10976 {"IGNORE message", TS_NOP}
10978 static const struct telnet_special ssh2_ignore_special[] = {
10979 {"IGNORE message", TS_NOP},
10981 static const struct telnet_special ssh2_rekey_special[] = {
10982 {"Repeat key exchange", TS_REKEY},
10984 static const struct telnet_special ssh2_session_specials[] = {
10987 /* These are the signal names defined by RFC 4254.
10988 * They include all the ISO C signals, but are a subset of the POSIX
10989 * required signals. */
10990 {"SIGINT (Interrupt)", TS_SIGINT},
10991 {"SIGTERM (Terminate)", TS_SIGTERM},
10992 {"SIGKILL (Kill)", TS_SIGKILL},
10993 {"SIGQUIT (Quit)", TS_SIGQUIT},
10994 {"SIGHUP (Hangup)", TS_SIGHUP},
10995 {"More signals", TS_SUBMENU},
10996 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
10997 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
10998 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
10999 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11000 {NULL, TS_EXITMENU}
11002 static const struct telnet_special specials_end[] = {
11003 {NULL, TS_EXITMENU}
11005 /* XXX review this length for any changes: */
11006 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
11007 lenof(ssh2_rekey_special) +
11008 lenof(ssh2_session_specials) +
11009 lenof(specials_end)];
11010 Ssh ssh = (Ssh) handle;
11012 #define ADD_SPECIALS(name) \
11014 assert((i + lenof(name)) <= lenof(ssh_specials)); \
11015 memcpy(&ssh_specials[i], name, sizeof name); \
11016 i += lenof(name); \
11019 if (ssh->version == 1) {
11020 /* Don't bother offering IGNORE if we've decided the remote
11021 * won't cope with it, since we wouldn't bother sending it if
11023 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11024 ADD_SPECIALS(ssh1_ignore_special);
11025 } else if (ssh->version == 2) {
11026 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11027 ADD_SPECIALS(ssh2_ignore_special);
11028 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11029 ADD_SPECIALS(ssh2_rekey_special);
11031 ADD_SPECIALS(ssh2_session_specials);
11032 } /* else we're not ready yet */
11035 ADD_SPECIALS(specials_end);
11036 return ssh_specials;
11040 #undef ADD_SPECIALS
11044 * Send special codes. TS_EOF is useful for `plink', so you
11045 * can send an EOF and collect resulting output (e.g. `plink
11048 static void ssh_special(void *handle, Telnet_Special code)
11050 Ssh ssh = (Ssh) handle;
11051 struct Packet *pktout;
11053 if (code == TS_EOF) {
11054 if (ssh->state != SSH_STATE_SESSION) {
11056 * Buffer the EOF in case we are pre-SESSION, so we can
11057 * send it as soon as we reach SESSION.
11059 if (code == TS_EOF)
11060 ssh->eof_needed = TRUE;
11063 if (ssh->version == 1) {
11064 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11065 } else if (ssh->mainchan) {
11066 sshfwd_write_eof(ssh->mainchan);
11067 ssh->send_ok = 0; /* now stop trying to read from stdin */
11069 logevent("Sent EOF message");
11070 } else if (code == TS_PING || code == TS_NOP) {
11071 if (ssh->state == SSH_STATE_CLOSED
11072 || ssh->state == SSH_STATE_PREPACKET) return;
11073 if (ssh->version == 1) {
11074 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11075 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11077 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11078 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11079 ssh2_pkt_addstring_start(pktout);
11080 ssh2_pkt_send_noqueue(ssh, pktout);
11083 } else if (code == TS_REKEY) {
11084 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11085 ssh->version == 2) {
11086 do_ssh2_transport(ssh, "at user request", -1, NULL);
11088 } else if (code == TS_BRK) {
11089 if (ssh->state == SSH_STATE_CLOSED
11090 || ssh->state == SSH_STATE_PREPACKET) return;
11091 if (ssh->version == 1) {
11092 logevent("Unable to send BREAK signal in SSH-1");
11093 } else if (ssh->mainchan) {
11094 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11095 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11096 ssh2_pkt_send(ssh, pktout);
11099 /* Is is a POSIX signal? */
11100 char *signame = NULL;
11101 if (code == TS_SIGABRT) signame = "ABRT";
11102 if (code == TS_SIGALRM) signame = "ALRM";
11103 if (code == TS_SIGFPE) signame = "FPE";
11104 if (code == TS_SIGHUP) signame = "HUP";
11105 if (code == TS_SIGILL) signame = "ILL";
11106 if (code == TS_SIGINT) signame = "INT";
11107 if (code == TS_SIGKILL) signame = "KILL";
11108 if (code == TS_SIGPIPE) signame = "PIPE";
11109 if (code == TS_SIGQUIT) signame = "QUIT";
11110 if (code == TS_SIGSEGV) signame = "SEGV";
11111 if (code == TS_SIGTERM) signame = "TERM";
11112 if (code == TS_SIGUSR1) signame = "USR1";
11113 if (code == TS_SIGUSR2) signame = "USR2";
11114 /* The SSH-2 protocol does in principle support arbitrary named
11115 * signals, including signame@domain, but we don't support those. */
11117 /* It's a signal. */
11118 if (ssh->version == 2 && ssh->mainchan) {
11119 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11120 ssh2_pkt_addstring(pktout, signame);
11121 ssh2_pkt_send(ssh, pktout);
11122 logeventf(ssh, "Sent signal SIG%s", signame);
11125 /* Never heard of it. Do nothing */
11130 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11132 Ssh ssh = (Ssh) handle;
11133 struct ssh_channel *c;
11134 c = snew(struct ssh_channel);
11137 ssh2_channel_init(c);
11138 c->halfopen = TRUE;
11139 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11141 add234(ssh->channels, c);
11145 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11147 struct ssh_channel *c;
11148 c = snew(struct ssh_channel);
11151 ssh2_channel_init(c);
11152 c->type = CHAN_SHARING;
11153 c->u.sharing.ctx = sharing_ctx;
11154 add234(ssh->channels, c);
11158 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11160 struct ssh_channel *c;
11162 c = find234(ssh->channels, &localid, ssh_channelfind);
11164 ssh_channel_destroy(c);
11167 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11168 const void *data, int datalen,
11169 const char *additional_log_text)
11171 struct Packet *pkt;
11173 pkt = ssh2_pkt_init(type);
11174 pkt->downstream_id = id;
11175 pkt->additional_log_text = additional_log_text;
11176 ssh2_pkt_adddata(pkt, data, datalen);
11177 ssh2_pkt_send(ssh, pkt);
11181 * This is called when stdout/stderr (the entity to which
11182 * from_backend sends data) manages to clear some backlog.
11184 static void ssh_unthrottle(void *handle, int bufsize)
11186 Ssh ssh = (Ssh) handle;
11189 if (ssh->version == 1) {
11190 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11191 ssh->v1_stdout_throttling = 0;
11192 ssh_throttle_conn(ssh, -1);
11195 if (ssh->mainchan) {
11196 ssh2_set_window(ssh->mainchan,
11197 bufsize < ssh->mainchan->v.v2.locmaxwin ?
11198 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11199 if (ssh_is_simple(ssh))
11202 buflimit = ssh->mainchan->v.v2.locmaxwin;
11203 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11204 ssh->mainchan->throttling_conn = 0;
11205 ssh_throttle_conn(ssh, -1);
11211 * Now process any SSH connection data that was stashed in our
11212 * queue while we were frozen.
11214 ssh_process_queued_incoming_data(ssh);
11217 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
11219 struct ssh_channel *c = (struct ssh_channel *)channel;
11221 struct Packet *pktout;
11223 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11225 if (ssh->version == 1) {
11226 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11227 PKT_INT, c->localid,
11230 /* PKT_STR, <org:orgport>, */
11233 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11235 char *trimmed_host = host_strduptrim(hostname);
11236 ssh2_pkt_addstring(pktout, trimmed_host);
11237 sfree(trimmed_host);
11239 ssh2_pkt_adduint32(pktout, port);
11241 * We make up values for the originator data; partly it's
11242 * too much hassle to keep track, and partly I'm not
11243 * convinced the server should be told details like that
11244 * about my local network configuration.
11245 * The "originator IP address" is syntactically a numeric
11246 * IP address, and some servers (e.g., Tectia) get upset
11247 * if it doesn't match this syntax.
11249 ssh2_pkt_addstring(pktout, "0.0.0.0");
11250 ssh2_pkt_adduint32(pktout, 0);
11251 ssh2_pkt_send(ssh, pktout);
11255 static int ssh_connected(void *handle)
11257 Ssh ssh = (Ssh) handle;
11258 return ssh->s != NULL;
11261 static int ssh_sendok(void *handle)
11263 Ssh ssh = (Ssh) handle;
11264 return ssh->send_ok;
11267 static int ssh_ldisc(void *handle, int option)
11269 Ssh ssh = (Ssh) handle;
11270 if (option == LD_ECHO)
11271 return ssh->echoing;
11272 if (option == LD_EDIT)
11273 return ssh->editing;
11277 static void ssh_provide_ldisc(void *handle, void *ldisc)
11279 Ssh ssh = (Ssh) handle;
11280 ssh->ldisc = ldisc;
11283 static void ssh_provide_logctx(void *handle, void *logctx)
11285 Ssh ssh = (Ssh) handle;
11286 ssh->logctx = logctx;
11289 static int ssh_return_exitcode(void *handle)
11291 Ssh ssh = (Ssh) handle;
11292 if (ssh->s != NULL)
11295 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11299 * cfg_info for SSH is the protocol running in this session.
11300 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11301 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11303 static int ssh_cfg_info(void *handle)
11305 Ssh ssh = (Ssh) handle;
11306 if (ssh->version == 0)
11307 return 0; /* don't know yet */
11308 else if (ssh->bare_connection)
11311 return ssh->version;
11315 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11316 * that fails. This variable is the means by which scp.c can reach
11317 * into the SSH code and find out which one it got.
11319 extern int ssh_fallback_cmd(void *handle)
11321 Ssh ssh = (Ssh) handle;
11322 return ssh->fallback_cmd;
11325 Backend ssh_backend = {
11335 ssh_return_exitcode,
11339 ssh_provide_logctx,