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
80 * Codes for terminal modes.
81 * Most of these are the same in SSH-1 and SSH-2.
82 * This list is derived from RFC 4254 and
86 const char* const mode;
88 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
90 /* "V" prefix discarded for special characters relative to SSH specs */
91 { "INTR", 1, TTY_OP_CHAR },
92 { "QUIT", 2, TTY_OP_CHAR },
93 { "ERASE", 3, TTY_OP_CHAR },
94 { "KILL", 4, TTY_OP_CHAR },
95 { "EOF", 5, TTY_OP_CHAR },
96 { "EOL", 6, TTY_OP_CHAR },
97 { "EOL2", 7, TTY_OP_CHAR },
98 { "START", 8, TTY_OP_CHAR },
99 { "STOP", 9, TTY_OP_CHAR },
100 { "SUSP", 10, TTY_OP_CHAR },
101 { "DSUSP", 11, TTY_OP_CHAR },
102 { "REPRINT", 12, TTY_OP_CHAR },
103 { "WERASE", 13, TTY_OP_CHAR },
104 { "LNEXT", 14, TTY_OP_CHAR },
105 { "FLUSH", 15, TTY_OP_CHAR },
106 { "SWTCH", 16, TTY_OP_CHAR },
107 { "STATUS", 17, TTY_OP_CHAR },
108 { "DISCARD", 18, TTY_OP_CHAR },
109 { "IGNPAR", 30, TTY_OP_BOOL },
110 { "PARMRK", 31, TTY_OP_BOOL },
111 { "INPCK", 32, TTY_OP_BOOL },
112 { "ISTRIP", 33, TTY_OP_BOOL },
113 { "INLCR", 34, TTY_OP_BOOL },
114 { "IGNCR", 35, TTY_OP_BOOL },
115 { "ICRNL", 36, TTY_OP_BOOL },
116 { "IUCLC", 37, TTY_OP_BOOL },
117 { "IXON", 38, TTY_OP_BOOL },
118 { "IXANY", 39, TTY_OP_BOOL },
119 { "IXOFF", 40, TTY_OP_BOOL },
120 { "IMAXBEL", 41, TTY_OP_BOOL },
121 { "ISIG", 50, TTY_OP_BOOL },
122 { "ICANON", 51, TTY_OP_BOOL },
123 { "XCASE", 52, TTY_OP_BOOL },
124 { "ECHO", 53, TTY_OP_BOOL },
125 { "ECHOE", 54, TTY_OP_BOOL },
126 { "ECHOK", 55, TTY_OP_BOOL },
127 { "ECHONL", 56, TTY_OP_BOOL },
128 { "NOFLSH", 57, TTY_OP_BOOL },
129 { "TOSTOP", 58, TTY_OP_BOOL },
130 { "IEXTEN", 59, TTY_OP_BOOL },
131 { "ECHOCTL", 60, TTY_OP_BOOL },
132 { "ECHOKE", 61, TTY_OP_BOOL },
133 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
134 { "OPOST", 70, TTY_OP_BOOL },
135 { "OLCUC", 71, TTY_OP_BOOL },
136 { "ONLCR", 72, TTY_OP_BOOL },
137 { "OCRNL", 73, TTY_OP_BOOL },
138 { "ONOCR", 74, TTY_OP_BOOL },
139 { "ONLRET", 75, TTY_OP_BOOL },
140 { "CS7", 90, TTY_OP_BOOL },
141 { "CS8", 91, TTY_OP_BOOL },
142 { "PARENB", 92, TTY_OP_BOOL },
143 { "PARODD", 93, TTY_OP_BOOL }
146 /* Miscellaneous other tty-related constants. */
147 #define SSH_TTY_OP_END 0
148 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
149 #define SSH1_TTY_OP_ISPEED 192
150 #define SSH1_TTY_OP_OSPEED 193
151 #define SSH2_TTY_OP_ISPEED 128
152 #define SSH2_TTY_OP_OSPEED 129
154 /* Helper functions for parsing tty-related config. */
155 static unsigned int ssh_tty_parse_specchar(char *s)
160 ret = ctrlparse(s, &next);
161 if (!next) ret = s[0];
163 ret = 255; /* special value meaning "don't set" */
167 static unsigned int ssh_tty_parse_boolean(char *s)
169 if (stricmp(s, "yes") == 0 ||
170 stricmp(s, "on") == 0 ||
171 stricmp(s, "true") == 0 ||
172 stricmp(s, "+") == 0)
174 else if (stricmp(s, "no") == 0 ||
175 stricmp(s, "off") == 0 ||
176 stricmp(s, "false") == 0 ||
177 stricmp(s, "-") == 0)
178 return 0; /* false */
180 return (atoi(s) != 0);
183 #define translate(x) if (type == x) return #x
184 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
185 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
186 static char *ssh1_pkt_type(int type)
188 translate(SSH1_MSG_DISCONNECT);
189 translate(SSH1_SMSG_PUBLIC_KEY);
190 translate(SSH1_CMSG_SESSION_KEY);
191 translate(SSH1_CMSG_USER);
192 translate(SSH1_CMSG_AUTH_RSA);
193 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
194 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
195 translate(SSH1_CMSG_AUTH_PASSWORD);
196 translate(SSH1_CMSG_REQUEST_PTY);
197 translate(SSH1_CMSG_WINDOW_SIZE);
198 translate(SSH1_CMSG_EXEC_SHELL);
199 translate(SSH1_CMSG_EXEC_CMD);
200 translate(SSH1_SMSG_SUCCESS);
201 translate(SSH1_SMSG_FAILURE);
202 translate(SSH1_CMSG_STDIN_DATA);
203 translate(SSH1_SMSG_STDOUT_DATA);
204 translate(SSH1_SMSG_STDERR_DATA);
205 translate(SSH1_CMSG_EOF);
206 translate(SSH1_SMSG_EXIT_STATUS);
207 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
208 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
209 translate(SSH1_MSG_CHANNEL_DATA);
210 translate(SSH1_MSG_CHANNEL_CLOSE);
211 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
212 translate(SSH1_SMSG_X11_OPEN);
213 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
214 translate(SSH1_MSG_PORT_OPEN);
215 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
216 translate(SSH1_SMSG_AGENT_OPEN);
217 translate(SSH1_MSG_IGNORE);
218 translate(SSH1_CMSG_EXIT_CONFIRMATION);
219 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
220 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
221 translate(SSH1_MSG_DEBUG);
222 translate(SSH1_CMSG_REQUEST_COMPRESSION);
223 translate(SSH1_CMSG_AUTH_TIS);
224 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
225 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
226 translate(SSH1_CMSG_AUTH_CCARD);
227 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
228 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
231 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
233 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
234 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
235 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
236 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
237 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
238 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
239 translate(SSH2_MSG_DISCONNECT);
240 translate(SSH2_MSG_IGNORE);
241 translate(SSH2_MSG_UNIMPLEMENTED);
242 translate(SSH2_MSG_DEBUG);
243 translate(SSH2_MSG_SERVICE_REQUEST);
244 translate(SSH2_MSG_SERVICE_ACCEPT);
245 translate(SSH2_MSG_KEXINIT);
246 translate(SSH2_MSG_NEWKEYS);
247 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
248 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
249 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
250 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
251 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
252 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
253 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
254 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
255 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
256 translate(SSH2_MSG_USERAUTH_REQUEST);
257 translate(SSH2_MSG_USERAUTH_FAILURE);
258 translate(SSH2_MSG_USERAUTH_SUCCESS);
259 translate(SSH2_MSG_USERAUTH_BANNER);
260 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
261 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
262 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
263 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
264 translate(SSH2_MSG_GLOBAL_REQUEST);
265 translate(SSH2_MSG_REQUEST_SUCCESS);
266 translate(SSH2_MSG_REQUEST_FAILURE);
267 translate(SSH2_MSG_CHANNEL_OPEN);
268 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
269 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
270 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
271 translate(SSH2_MSG_CHANNEL_DATA);
272 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
273 translate(SSH2_MSG_CHANNEL_EOF);
274 translate(SSH2_MSG_CHANNEL_CLOSE);
275 translate(SSH2_MSG_CHANNEL_REQUEST);
276 translate(SSH2_MSG_CHANNEL_SUCCESS);
277 translate(SSH2_MSG_CHANNEL_FAILURE);
283 /* Enumeration values for fields in SSH-1 packets */
285 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
289 * Coroutine mechanics for the sillier bits of the code. If these
290 * macros look impenetrable to you, you might find it helpful to
293 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
295 * which explains the theory behind these macros.
297 * In particular, if you are getting `case expression not constant'
298 * errors when building with MS Visual Studio, this is because MS's
299 * Edit and Continue debugging feature causes their compiler to
300 * violate ANSI C. To disable Edit and Continue debugging:
302 * - right-click ssh.c in the FileView
304 * - select the C/C++ tab and the General category
305 * - under `Debug info:', select anything _other_ than `Program
306 * Database for Edit and Continue'.
308 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
309 #define crBeginState crBegin(s->crLine)
310 #define crStateP(t, v) \
312 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
314 #define crState(t) crStateP(t, ssh->t)
315 #define crFinish(z) } *crLine = 0; return (z); }
316 #define crFinishV } *crLine = 0; return; }
317 #define crFinishFree(z) } sfree(s); return (z); }
318 #define crFinishFreeV } sfree(s); return; }
319 #define crReturn(z) \
321 *crLine =__LINE__; return (z); case __LINE__:;\
325 *crLine=__LINE__; return; case __LINE__:;\
327 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
328 #define crStopV do{ *crLine = 0; return; }while(0)
329 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
330 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
334 static struct Packet *ssh1_pkt_init(int pkt_type);
335 static struct Packet *ssh2_pkt_init(int pkt_type);
336 static void ssh_pkt_ensure(struct Packet *, int length);
337 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
338 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
339 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
340 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
341 static void ssh_pkt_addstring_start(struct Packet *);
342 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
343 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
344 static void ssh_pkt_addstring(struct Packet *, const char *data);
345 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
346 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
347 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
348 static int ssh2_pkt_construct(Ssh, struct Packet *);
349 static void ssh2_pkt_send(Ssh, struct Packet *);
350 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
351 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
352 struct Packet *pktin);
353 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
354 struct Packet *pktin);
355 static void ssh2_channel_check_close(struct ssh_channel *c);
356 static void ssh_channel_destroy(struct ssh_channel *c);
359 * Buffer management constants. There are several of these for
360 * various different purposes:
362 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
363 * on a local data stream before we throttle the whole SSH
364 * connection (in SSH-1 only). Throttling the whole connection is
365 * pretty drastic so we set this high in the hope it won't
368 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
369 * on the SSH connection itself before we defensively throttle
370 * _all_ local data streams. This is pretty drastic too (though
371 * thankfully unlikely in SSH-2 since the window mechanism should
372 * ensure that the server never has any need to throttle its end
373 * of the connection), so we set this high as well.
375 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
378 * - OUR_V2_BIGWIN is the window size we advertise for the only
379 * channel in a simple connection. It must be <= INT_MAX.
381 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
382 * to the remote side. This actually has nothing to do with the
383 * size of the _packet_, but is instead a limit on the amount
384 * of data we're willing to receive in a single SSH2 channel
387 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
388 * _packet_ we're prepared to cope with. It must be a multiple
389 * of the cipher block size, and must be at least 35000.
392 #define SSH1_BUFFER_LIMIT 32768
393 #define SSH_MAX_BACKLOG 32768
394 #define OUR_V2_WINSIZE 16384
395 #define OUR_V2_BIGWIN 0x7fffffff
396 #define OUR_V2_MAXPKT 0x4000UL
397 #define OUR_V2_PACKETLIMIT 0x9000UL
399 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
401 const static struct ssh_mac *macs[] = {
402 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
404 const static struct ssh_mac *buggymacs[] = {
405 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
408 static void *ssh_comp_none_init(void)
412 static void ssh_comp_none_cleanup(void *handle)
415 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
416 unsigned char **outblock, int *outlen)
420 static int ssh_comp_none_disable(void *handle)
424 const static struct ssh_compress ssh_comp_none = {
426 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
427 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
428 ssh_comp_none_disable, NULL
430 extern const struct ssh_compress ssh_zlib;
431 const static struct ssh_compress *compressions[] = {
432 &ssh_zlib, &ssh_comp_none
435 enum { /* channel types */
440 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
442 * CHAN_SHARING indicates a channel which is tracked here on
443 * behalf of a connection-sharing downstream. We do almost nothing
444 * with these channels ourselves: all messages relating to them
445 * get thrown straight to sshshare.c and passed on almost
446 * unmodified to downstream.
450 * CHAN_ZOMBIE is used to indicate a channel for which we've
451 * already destroyed the local data source: for instance, if a
452 * forwarded port experiences a socket error on the local side, we
453 * immediately destroy its local socket and turn the SSH channel
459 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
460 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
461 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
464 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
467 struct outstanding_channel_request {
468 cchandler_fn_t handler;
470 struct outstanding_channel_request *next;
474 * 2-3-4 tree storing channels.
477 Ssh ssh; /* pointer back to main context */
478 unsigned remoteid, localid;
480 /* True if we opened this channel but server hasn't confirmed. */
483 * In SSH-1, this value contains four bits:
485 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
486 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
487 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
488 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
490 * A channel is completely finished with when all four bits are set.
492 * In SSH-2, the four bits mean:
494 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
495 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
496 * 4 We have received SSH2_MSG_CHANNEL_EOF.
497 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
499 * A channel is completely finished with when we have both sent
500 * and received CLOSE.
502 * The symbolic constants below use the SSH-2 terminology, which
503 * is a bit confusing in SSH-1, but we have to use _something_.
505 #define CLOSES_SENT_EOF 1
506 #define CLOSES_SENT_CLOSE 2
507 #define CLOSES_RCVD_EOF 4
508 #define CLOSES_RCVD_CLOSE 8
512 * This flag indicates that an EOF is pending on the outgoing side
513 * of the channel: that is, wherever we're getting the data for
514 * this channel has sent us some data followed by EOF. We can't
515 * actually send the EOF until we've finished sending the data, so
516 * we set this flag instead to remind us to do so once our buffer
522 * True if this channel is causing the underlying connection to be
527 struct ssh2_data_channel {
529 unsigned remwindow, remmaxpkt;
530 /* locwindow is signed so we can cope with excess data. */
531 int locwindow, locmaxwin;
533 * remlocwin is the amount of local window that we think
534 * the remote end had available to it after it sent the
535 * last data packet or window adjust ack.
539 * These store the list of channel requests that haven't
542 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
543 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
547 struct ssh_agent_channel {
548 unsigned char *message;
549 unsigned char msglen[4];
550 unsigned lensofar, totallen;
551 int outstanding_requests;
553 struct ssh_x11_channel {
554 struct X11Connection *xconn;
557 struct ssh_pfd_channel {
558 struct PortForwarding *pf;
560 struct ssh_sharing_channel {
567 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
568 * use this structure in different ways, reflecting SSH-2's
569 * altogether saner approach to port forwarding.
571 * In SSH-1, you arrange a remote forwarding by sending the server
572 * the remote port number, and the local destination host:port.
573 * When a connection comes in, the server sends you back that
574 * host:port pair, and you connect to it. This is a ready-made
575 * security hole if you're not on the ball: a malicious server
576 * could send you back _any_ host:port pair, so if you trustingly
577 * connect to the address it gives you then you've just opened the
578 * entire inside of your corporate network just by connecting
579 * through it to a dodgy SSH server. Hence, we must store a list of
580 * host:port pairs we _are_ trying to forward to, and reject a
581 * connection request from the server if it's not in the list.
583 * In SSH-2, each side of the connection minds its own business and
584 * doesn't send unnecessary information to the other. You arrange a
585 * remote forwarding by sending the server just the remote port
586 * number. When a connection comes in, the server tells you which
587 * of its ports was connected to; and _you_ have to remember what
588 * local host:port pair went with that port number.
590 * Hence, in SSH-1 this structure is indexed by destination
591 * host:port pair, whereas in SSH-2 it is indexed by source port.
593 struct ssh_portfwd; /* forward declaration */
595 struct ssh_rportfwd {
596 unsigned sport, dport;
600 struct ssh_portfwd *pfrec;
603 static void free_rportfwd(struct ssh_rportfwd *pf)
606 sfree(pf->sportdesc);
614 * Separately to the rportfwd tree (which is for looking up port
615 * open requests from the server), a tree of _these_ structures is
616 * used to keep track of all the currently open port forwardings,
617 * so that we can reconfigure in mid-session if the user requests
621 enum { DESTROY, KEEP, CREATE } status;
623 unsigned sport, dport;
626 struct ssh_rportfwd *remote;
628 struct PortListener *local;
630 #define free_portfwd(pf) ( \
631 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
632 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
635 long length; /* length of packet: see below */
636 long forcepad; /* SSH-2: force padding to at least this length */
637 int type; /* only used for incoming packets */
638 unsigned long sequence; /* SSH-2 incoming sequence number */
639 unsigned char *data; /* allocated storage */
640 unsigned char *body; /* offset of payload within `data' */
641 long savedpos; /* dual-purpose saved packet position: see below */
642 long maxlen; /* amount of storage allocated for `data' */
643 long encrypted_len; /* for SSH-2 total-size counting */
646 * A note on the 'length' and 'savedpos' fields above.
648 * Incoming packets are set up so that pkt->length is measured
649 * relative to pkt->body, which itself points to a few bytes after
650 * pkt->data (skipping some uninteresting header fields including
651 * the packet type code). The ssh_pkt_get* functions all expect
652 * this setup, and they also use pkt->savedpos to indicate how far
653 * through the packet being decoded they've got - and that, too,
654 * is an offset from pkt->body rather than pkt->data.
656 * During construction of an outgoing packet, however, pkt->length
657 * is measured relative to the base pointer pkt->data, and
658 * pkt->body is not really used for anything until the packet is
659 * ready for sending. In this mode, pkt->savedpos is reused as a
660 * temporary variable by the addstring functions, which write out
661 * a string length field and then keep going back and updating it
662 * as more data is appended to the subsequent string data field;
663 * pkt->savedpos stores the offset (again relative to pkt->data)
664 * of the start of the string data field.
667 /* Extra metadata used in SSH packet logging mode, allowing us to
668 * log in the packet header line that the packet came from a
669 * connection-sharing downstream and what if anything unusual was
670 * done to it. The additional_log_text field is expected to be a
671 * static string - it will not be freed. */
672 unsigned downstream_id;
673 const char *additional_log_text;
676 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
677 struct Packet *pktin);
678 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
679 struct Packet *pktin);
680 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
681 struct Packet *pktin);
682 static void ssh1_protocol_setup(Ssh ssh);
683 static void ssh2_protocol_setup(Ssh ssh);
684 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
685 static void ssh_size(void *handle, int width, int height);
686 static void ssh_special(void *handle, Telnet_Special);
687 static int ssh2_try_send(struct ssh_channel *c);
688 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
689 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
690 static void ssh2_set_window(struct ssh_channel *c, int newwin);
691 static int ssh_sendbuffer(void *handle);
692 static int ssh_do_close(Ssh ssh, int notify_exit);
693 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
694 static int ssh2_pkt_getbool(struct Packet *pkt);
695 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
696 static void ssh2_timer(void *ctx, unsigned long now);
697 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
698 struct Packet *pktin);
699 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
701 struct rdpkt1_state_tag {
702 long len, pad, biglen, to_read;
703 unsigned long realcrc, gotcrc;
707 struct Packet *pktin;
710 struct rdpkt2_state_tag {
711 long len, pad, payload, packetlen, maclen;
714 unsigned long incoming_sequence;
715 struct Packet *pktin;
718 struct rdpkt2_bare_state_tag {
722 unsigned long incoming_sequence;
723 struct Packet *pktin;
726 struct queued_handler;
727 struct queued_handler {
729 chandler_fn_t handler;
731 struct queued_handler *next;
735 const struct plug_function_table *fn;
736 /* the above field _must_ be first in the structure */
746 unsigned char session_key[32];
748 int v1_remote_protoflags;
749 int v1_local_protoflags;
750 int agentfwd_enabled;
753 const struct ssh_cipher *cipher;
756 const struct ssh2_cipher *cscipher, *sccipher;
757 void *cs_cipher_ctx, *sc_cipher_ctx;
758 const struct ssh_mac *csmac, *scmac;
759 void *cs_mac_ctx, *sc_mac_ctx;
760 const struct ssh_compress *cscomp, *sccomp;
761 void *cs_comp_ctx, *sc_comp_ctx;
762 const struct ssh_kex *kex;
763 const struct ssh_signkey *hostkey;
764 char *hostkey_str; /* string representation, for easy checking in rekeys */
765 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
766 int v2_session_id_len;
770 int attempting_connshare;
776 int echoing, editing;
780 int ospeed, ispeed; /* temporaries */
781 int term_width, term_height;
783 tree234 *channels; /* indexed by local id */
784 struct ssh_channel *mainchan; /* primary session channel */
785 int ncmode; /* is primary channel direct-tcpip? */
790 tree234 *rportfwds, *portfwds;
794 SSH_STATE_BEFORE_SIZE,
800 int size_needed, eof_needed;
801 int sent_console_eof;
802 int got_pty; /* affects EOF behaviour on main channel */
804 struct Packet **queue;
805 int queuelen, queuesize;
807 unsigned char *deferred_send_data;
808 int deferred_len, deferred_size;
811 * Gross hack: pscp will try to start SFTP but fall back to
812 * scp1 if that fails. This variable is the means by which
813 * scp.c can reach into the SSH code and find out which one it
818 bufchain banner; /* accumulates banners during do_ssh2_authconn */
823 struct X11Display *x11disp;
824 struct X11FakeAuth *x11auth;
825 tree234 *x11authtree;
828 int conn_throttle_count;
831 int v1_stdout_throttling;
832 unsigned long v2_outgoing_sequence;
834 int ssh1_rdpkt_crstate;
835 int ssh2_rdpkt_crstate;
836 int ssh2_bare_rdpkt_crstate;
837 int ssh_gotdata_crstate;
838 int do_ssh1_connection_crstate;
840 void *do_ssh_init_state;
841 void *do_ssh1_login_state;
842 void *do_ssh2_transport_state;
843 void *do_ssh2_authconn_state;
844 void *do_ssh_connection_init_state;
846 struct rdpkt1_state_tag rdpkt1_state;
847 struct rdpkt2_state_tag rdpkt2_state;
848 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
850 /* SSH-1 and SSH-2 use this for different things, but both use it */
851 int protocol_initial_phase_done;
853 void (*protocol) (Ssh ssh, void *vin, int inlen,
855 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
856 int (*do_ssh_init)(Ssh ssh, unsigned char c);
859 * We maintain our own copy of a Conf structure here. That way,
860 * when we're passed a new one for reconfiguration, we can check
861 * the differences and potentially reconfigure port forwardings
862 * etc in mid-session.
867 * Values cached out of conf so as to avoid the tree234 lookup
868 * cost every time they're used.
873 * Dynamically allocated username string created during SSH
874 * login. Stored in here rather than in the coroutine state so
875 * that it'll be reliably freed if we shut down the SSH session
876 * at some unexpected moment.
881 * Used to transfer data back from async callbacks.
883 void *agent_response;
884 int agent_response_len;
888 * The SSH connection can be set as `frozen', meaning we are
889 * not currently accepting incoming data from the network. This
890 * is slightly more serious than setting the _socket_ as
891 * frozen, because we may already have had data passed to us
892 * from the network which we need to delay processing until
893 * after the freeze is lifted, so we also need a bufchain to
897 bufchain queued_incoming_data;
900 * Dispatch table for packet types that we may have to deal
903 handler_fn_t packet_dispatch[256];
906 * Queues of one-off handler functions for success/failure
907 * indications from a request.
909 struct queued_handler *qhead, *qtail;
910 handler_fn_t q_saved_handler1, q_saved_handler2;
913 * This module deals with sending keepalives.
918 * Track incoming and outgoing data sizes and time, for
921 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
922 unsigned long max_data_size;
924 unsigned long next_rekey, last_rekey;
925 char *deferred_rekey_reason; /* points to STATIC string; don't free */
928 * Fully qualified host name, which we need if doing GSSAPI.
934 * GSSAPI libraries for this session.
936 struct ssh_gss_liblist *gsslibs;
940 #define logevent(s) logevent(ssh->frontend, s)
942 /* logevent, only printf-formatted. */
943 static void logeventf(Ssh ssh, const char *fmt, ...)
949 buf = dupvprintf(fmt, ap);
955 static void bomb_out(Ssh ssh, char *text)
957 ssh_do_close(ssh, FALSE);
959 connection_fatal(ssh->frontend, "%s", text);
963 #define bombout(msg) bomb_out(ssh, dupprintf msg)
965 /* Helper function for common bits of parsing ttymodes. */
966 static void parse_ttymodes(Ssh ssh,
967 void (*do_mode)(void *data, char *mode, char *val),
972 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
974 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
976 * val[0] is either 'V', indicating that an explicit value
977 * follows it, or 'A' indicating that we should pass the
978 * value through from the local environment via get_ttymode.
981 val = get_ttymode(ssh->frontend, key);
983 do_mode(data, key, val);
987 do_mode(data, key, val + 1); /* skip the 'V' */
991 static int ssh_channelcmp(void *av, void *bv)
993 struct ssh_channel *a = (struct ssh_channel *) av;
994 struct ssh_channel *b = (struct ssh_channel *) bv;
995 if (a->localid < b->localid)
997 if (a->localid > b->localid)
1001 static int ssh_channelfind(void *av, void *bv)
1003 unsigned *a = (unsigned *) av;
1004 struct ssh_channel *b = (struct ssh_channel *) bv;
1005 if (*a < b->localid)
1007 if (*a > b->localid)
1012 static int ssh_rportcmp_ssh1(void *av, void *bv)
1014 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1015 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1017 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1018 return i < 0 ? -1 : +1;
1019 if (a->dport > b->dport)
1021 if (a->dport < b->dport)
1026 static int ssh_rportcmp_ssh2(void *av, void *bv)
1028 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1029 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1031 if ( (i = strcmp(a->shost, b->shost)) != 0)
1032 return i < 0 ? -1 : +1;
1033 if (a->sport > b->sport)
1035 if (a->sport < b->sport)
1041 * Special form of strcmp which can cope with NULL inputs. NULL is
1042 * defined to sort before even the empty string.
1044 static int nullstrcmp(const char *a, const char *b)
1046 if (a == NULL && b == NULL)
1052 return strcmp(a, b);
1055 static int ssh_portcmp(void *av, void *bv)
1057 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1058 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1060 if (a->type > b->type)
1062 if (a->type < b->type)
1064 if (a->addressfamily > b->addressfamily)
1066 if (a->addressfamily < b->addressfamily)
1068 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1069 return i < 0 ? -1 : +1;
1070 if (a->sport > b->sport)
1072 if (a->sport < b->sport)
1074 if (a->type != 'D') {
1075 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1076 return i < 0 ? -1 : +1;
1077 if (a->dport > b->dport)
1079 if (a->dport < b->dport)
1085 static int alloc_channel_id(Ssh ssh)
1087 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1088 unsigned low, high, mid;
1090 struct ssh_channel *c;
1093 * First-fit allocation of channel numbers: always pick the
1094 * lowest unused one. To do this, binary-search using the
1095 * counted B-tree to find the largest channel ID which is in a
1096 * contiguous sequence from the beginning. (Precisely
1097 * everything in that sequence must have ID equal to its tree
1098 * index plus CHANNEL_NUMBER_OFFSET.)
1100 tsize = count234(ssh->channels);
1104 while (high - low > 1) {
1105 mid = (high + low) / 2;
1106 c = index234(ssh->channels, mid);
1107 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1108 low = mid; /* this one is fine */
1110 high = mid; /* this one is past it */
1113 * Now low points to either -1, or the tree index of the
1114 * largest ID in the initial sequence.
1117 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1118 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1120 return low + 1 + CHANNEL_NUMBER_OFFSET;
1123 static void c_write_stderr(int trusted, const char *buf, int len)
1126 for (i = 0; i < len; i++)
1127 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1128 fputc(buf[i], stderr);
1131 static void c_write(Ssh ssh, const char *buf, int len)
1133 if (flags & FLAG_STDERR)
1134 c_write_stderr(1, buf, len);
1136 from_backend(ssh->frontend, 1, buf, len);
1139 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1141 if (flags & FLAG_STDERR)
1142 c_write_stderr(0, buf, len);
1144 from_backend_untrusted(ssh->frontend, buf, len);
1147 static void c_write_str(Ssh ssh, const char *buf)
1149 c_write(ssh, buf, strlen(buf));
1152 static void ssh_free_packet(struct Packet *pkt)
1157 static struct Packet *ssh_new_packet(void)
1159 struct Packet *pkt = snew(struct Packet);
1161 pkt->body = pkt->data = NULL;
1167 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1170 struct logblank_t blanks[4];
1176 if (ssh->logomitdata &&
1177 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1178 pkt->type == SSH1_SMSG_STDERR_DATA ||
1179 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1180 /* "Session data" packets - omit the data string. */
1181 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1182 ssh_pkt_getuint32(pkt); /* skip channel id */
1183 blanks[nblanks].offset = pkt->savedpos + 4;
1184 blanks[nblanks].type = PKTLOG_OMIT;
1185 ssh_pkt_getstring(pkt, &str, &slen);
1187 blanks[nblanks].len = slen;
1191 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1192 ssh1_pkt_type(pkt->type),
1193 pkt->body, pkt->length, nblanks, blanks, NULL,
1197 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1200 struct logblank_t blanks[4];
1205 * For outgoing packets, pkt->length represents the length of the
1206 * whole packet starting at pkt->data (including some header), and
1207 * pkt->body refers to the point within that where the log-worthy
1208 * payload begins. However, incoming packets expect pkt->length to
1209 * represent only the payload length (that is, it's measured from
1210 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1211 * packet to conform to the incoming-packet semantics, so that we
1212 * can analyse it with the ssh_pkt_get functions.
1214 pkt->length -= (pkt->body - pkt->data);
1217 if (ssh->logomitdata &&
1218 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1219 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1220 /* "Session data" packets - omit the data string. */
1221 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1222 ssh_pkt_getuint32(pkt); /* skip channel id */
1223 blanks[nblanks].offset = pkt->savedpos + 4;
1224 blanks[nblanks].type = PKTLOG_OMIT;
1225 ssh_pkt_getstring(pkt, &str, &slen);
1227 blanks[nblanks].len = slen;
1232 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1233 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1234 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1235 conf_get_int(ssh->conf, CONF_logomitpass)) {
1236 /* If this is a password or similar packet, blank the password(s). */
1237 blanks[nblanks].offset = 0;
1238 blanks[nblanks].len = pkt->length;
1239 blanks[nblanks].type = PKTLOG_BLANK;
1241 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1242 conf_get_int(ssh->conf, CONF_logomitpass)) {
1244 * If this is an X forwarding request packet, blank the fake
1247 * Note that while we blank the X authentication data here, we
1248 * don't take any special action to blank the start of an X11
1249 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1250 * an X connection without having session blanking enabled is
1251 * likely to leak your cookie into the log.
1254 ssh_pkt_getstring(pkt, &str, &slen);
1255 blanks[nblanks].offset = pkt->savedpos;
1256 blanks[nblanks].type = PKTLOG_BLANK;
1257 ssh_pkt_getstring(pkt, &str, &slen);
1259 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1264 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1265 ssh1_pkt_type(pkt->data[12]),
1266 pkt->body, pkt->length,
1267 nblanks, blanks, NULL, 0, NULL);
1270 * Undo the above adjustment of pkt->length, to put the packet
1271 * back in the state we found it.
1273 pkt->length += (pkt->body - pkt->data);
1277 * Collect incoming data in the incoming packet buffer.
1278 * Decipher and verify the packet when it is completely read.
1279 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1280 * Update the *data and *datalen variables.
1281 * Return a Packet structure when a packet is completed.
1283 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1285 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1287 crBegin(ssh->ssh1_rdpkt_crstate);
1289 st->pktin = ssh_new_packet();
1291 st->pktin->type = 0;
1292 st->pktin->length = 0;
1294 for (st->i = st->len = 0; st->i < 4; st->i++) {
1295 while ((*datalen) == 0)
1297 st->len = (st->len << 8) + **data;
1298 (*data)++, (*datalen)--;
1301 st->pad = 8 - (st->len % 8);
1302 st->biglen = st->len + st->pad;
1303 st->pktin->length = st->len - 5;
1305 if (st->biglen < 0) {
1306 bombout(("Extremely large packet length from server suggests"
1307 " data stream corruption"));
1308 ssh_free_packet(st->pktin);
1312 st->pktin->maxlen = st->biglen;
1313 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1315 st->to_read = st->biglen;
1316 st->p = st->pktin->data;
1317 while (st->to_read > 0) {
1318 st->chunk = st->to_read;
1319 while ((*datalen) == 0)
1321 if (st->chunk > (*datalen))
1322 st->chunk = (*datalen);
1323 memcpy(st->p, *data, st->chunk);
1325 *datalen -= st->chunk;
1327 st->to_read -= st->chunk;
1330 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1331 st->biglen, NULL)) {
1332 bombout(("Network attack (CRC compensation) detected!"));
1333 ssh_free_packet(st->pktin);
1338 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1340 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1341 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1342 if (st->gotcrc != st->realcrc) {
1343 bombout(("Incorrect CRC received on packet"));
1344 ssh_free_packet(st->pktin);
1348 st->pktin->body = st->pktin->data + st->pad + 1;
1350 if (ssh->v1_compressing) {
1351 unsigned char *decompblk;
1353 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1354 st->pktin->body - 1, st->pktin->length + 1,
1355 &decompblk, &decomplen)) {
1356 bombout(("Zlib decompression encountered invalid data"));
1357 ssh_free_packet(st->pktin);
1361 if (st->pktin->maxlen < st->pad + decomplen) {
1362 st->pktin->maxlen = st->pad + decomplen;
1363 st->pktin->data = sresize(st->pktin->data,
1364 st->pktin->maxlen + APIEXTRA,
1366 st->pktin->body = st->pktin->data + st->pad + 1;
1369 memcpy(st->pktin->body - 1, decompblk, decomplen);
1371 st->pktin->length = decomplen - 1;
1374 st->pktin->type = st->pktin->body[-1];
1377 * Now pktin->body and pktin->length identify the semantic content
1378 * of the packet, excluding the initial type byte.
1382 ssh1_log_incoming_packet(ssh, st->pktin);
1384 st->pktin->savedpos = 0;
1386 crFinish(st->pktin);
1389 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1392 struct logblank_t blanks[4];
1398 if (ssh->logomitdata &&
1399 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1400 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1401 /* "Session data" packets - omit the data string. */
1402 ssh_pkt_getuint32(pkt); /* skip channel id */
1403 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1404 ssh_pkt_getuint32(pkt); /* skip extended data type */
1405 blanks[nblanks].offset = pkt->savedpos + 4;
1406 blanks[nblanks].type = PKTLOG_OMIT;
1407 ssh_pkt_getstring(pkt, &str, &slen);
1409 blanks[nblanks].len = slen;
1414 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1415 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1416 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1420 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1423 struct logblank_t blanks[4];
1428 * For outgoing packets, pkt->length represents the length of the
1429 * whole packet starting at pkt->data (including some header), and
1430 * pkt->body refers to the point within that where the log-worthy
1431 * payload begins. However, incoming packets expect pkt->length to
1432 * represent only the payload length (that is, it's measured from
1433 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1434 * packet to conform to the incoming-packet semantics, so that we
1435 * can analyse it with the ssh_pkt_get functions.
1437 pkt->length -= (pkt->body - pkt->data);
1440 if (ssh->logomitdata &&
1441 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1442 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1443 /* "Session data" packets - omit the data string. */
1444 ssh_pkt_getuint32(pkt); /* skip channel id */
1445 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1446 ssh_pkt_getuint32(pkt); /* skip extended data type */
1447 blanks[nblanks].offset = pkt->savedpos + 4;
1448 blanks[nblanks].type = PKTLOG_OMIT;
1449 ssh_pkt_getstring(pkt, &str, &slen);
1451 blanks[nblanks].len = slen;
1456 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1457 conf_get_int(ssh->conf, CONF_logomitpass)) {
1458 /* If this is a password packet, blank the password(s). */
1460 ssh_pkt_getstring(pkt, &str, &slen);
1461 ssh_pkt_getstring(pkt, &str, &slen);
1462 ssh_pkt_getstring(pkt, &str, &slen);
1463 if (slen == 8 && !memcmp(str, "password", 8)) {
1464 ssh2_pkt_getbool(pkt);
1465 /* Blank the password field. */
1466 blanks[nblanks].offset = pkt->savedpos;
1467 blanks[nblanks].type = PKTLOG_BLANK;
1468 ssh_pkt_getstring(pkt, &str, &slen);
1470 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1472 /* If there's another password field beyond it (change of
1473 * password), blank that too. */
1474 ssh_pkt_getstring(pkt, &str, &slen);
1476 blanks[nblanks-1].len =
1477 pkt->savedpos - blanks[nblanks].offset;
1480 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1481 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1482 conf_get_int(ssh->conf, CONF_logomitpass)) {
1483 /* If this is a keyboard-interactive response packet, blank
1486 ssh_pkt_getuint32(pkt);
1487 blanks[nblanks].offset = pkt->savedpos;
1488 blanks[nblanks].type = PKTLOG_BLANK;
1490 ssh_pkt_getstring(pkt, &str, &slen);
1494 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1496 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1497 conf_get_int(ssh->conf, CONF_logomitpass)) {
1499 * If this is an X forwarding request packet, blank the fake
1502 * Note that while we blank the X authentication data here, we
1503 * don't take any special action to blank the start of an X11
1504 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1505 * an X connection without having session blanking enabled is
1506 * likely to leak your cookie into the log.
1509 ssh_pkt_getuint32(pkt);
1510 ssh_pkt_getstring(pkt, &str, &slen);
1511 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1512 ssh2_pkt_getbool(pkt);
1513 ssh2_pkt_getbool(pkt);
1514 ssh_pkt_getstring(pkt, &str, &slen);
1515 blanks[nblanks].offset = pkt->savedpos;
1516 blanks[nblanks].type = PKTLOG_BLANK;
1517 ssh_pkt_getstring(pkt, &str, &slen);
1519 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1525 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1526 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1527 pkt->body, pkt->length, nblanks, blanks,
1528 &ssh->v2_outgoing_sequence,
1529 pkt->downstream_id, pkt->additional_log_text);
1532 * Undo the above adjustment of pkt->length, to put the packet
1533 * back in the state we found it.
1535 pkt->length += (pkt->body - pkt->data);
1538 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1540 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1542 crBegin(ssh->ssh2_rdpkt_crstate);
1544 st->pktin = ssh_new_packet();
1546 st->pktin->type = 0;
1547 st->pktin->length = 0;
1549 st->cipherblk = ssh->sccipher->blksize;
1552 if (st->cipherblk < 8)
1554 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1556 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1559 * When dealing with a CBC-mode cipher, we want to avoid the
1560 * possibility of an attacker's tweaking the ciphertext stream
1561 * so as to cause us to feed the same block to the block
1562 * cipher more than once and thus leak information
1563 * (VU#958563). The way we do this is not to take any
1564 * decisions on the basis of anything we've decrypted until
1565 * we've verified it with a MAC. That includes the packet
1566 * length, so we just read data and check the MAC repeatedly,
1567 * and when the MAC passes, see if the length we've got is
1571 /* May as well allocate the whole lot now. */
1572 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1575 /* Read an amount corresponding to the MAC. */
1576 for (st->i = 0; st->i < st->maclen; st->i++) {
1577 while ((*datalen) == 0)
1579 st->pktin->data[st->i] = *(*data)++;
1585 unsigned char seq[4];
1586 ssh->scmac->start(ssh->sc_mac_ctx);
1587 PUT_32BIT(seq, st->incoming_sequence);
1588 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1591 for (;;) { /* Once around this loop per cipher block. */
1592 /* Read another cipher-block's worth, and tack it onto the end. */
1593 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1594 while ((*datalen) == 0)
1596 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1599 /* Decrypt one more block (a little further back in the stream). */
1600 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1601 st->pktin->data + st->packetlen,
1603 /* Feed that block to the MAC. */
1604 ssh->scmac->bytes(ssh->sc_mac_ctx,
1605 st->pktin->data + st->packetlen, st->cipherblk);
1606 st->packetlen += st->cipherblk;
1607 /* See if that gives us a valid packet. */
1608 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1609 st->pktin->data + st->packetlen) &&
1610 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1613 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1614 bombout(("No valid incoming packet found"));
1615 ssh_free_packet(st->pktin);
1619 st->pktin->maxlen = st->packetlen + st->maclen;
1620 st->pktin->data = sresize(st->pktin->data,
1621 st->pktin->maxlen + APIEXTRA,
1624 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1627 * Acquire and decrypt the first block of the packet. This will
1628 * contain the length and padding details.
1630 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1631 while ((*datalen) == 0)
1633 st->pktin->data[st->i] = *(*data)++;
1638 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1639 st->pktin->data, st->cipherblk);
1642 * Now get the length figure.
1644 st->len = toint(GET_32BIT(st->pktin->data));
1647 * _Completely_ silly lengths should be stomped on before they
1648 * do us any more damage.
1650 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1651 (st->len + 4) % st->cipherblk != 0) {
1652 bombout(("Incoming packet was garbled on decryption"));
1653 ssh_free_packet(st->pktin);
1658 * So now we can work out the total packet length.
1660 st->packetlen = st->len + 4;
1663 * Allocate memory for the rest of the packet.
1665 st->pktin->maxlen = st->packetlen + st->maclen;
1666 st->pktin->data = sresize(st->pktin->data,
1667 st->pktin->maxlen + APIEXTRA,
1671 * Read and decrypt the remainder of the packet.
1673 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1675 while ((*datalen) == 0)
1677 st->pktin->data[st->i] = *(*data)++;
1680 /* Decrypt everything _except_ the MAC. */
1682 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1683 st->pktin->data + st->cipherblk,
1684 st->packetlen - st->cipherblk);
1690 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1691 st->len + 4, st->incoming_sequence)) {
1692 bombout(("Incorrect MAC received on packet"));
1693 ssh_free_packet(st->pktin);
1697 /* Get and sanity-check the amount of random padding. */
1698 st->pad = st->pktin->data[4];
1699 if (st->pad < 4 || st->len - st->pad < 1) {
1700 bombout(("Invalid padding length on received packet"));
1701 ssh_free_packet(st->pktin);
1705 * This enables us to deduce the payload length.
1707 st->payload = st->len - st->pad - 1;
1709 st->pktin->length = st->payload + 5;
1710 st->pktin->encrypted_len = st->packetlen;
1712 st->pktin->sequence = st->incoming_sequence++;
1714 st->pktin->length = st->packetlen - st->pad;
1715 assert(st->pktin->length >= 0);
1718 * Decompress packet payload.
1721 unsigned char *newpayload;
1724 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1725 st->pktin->data + 5, st->pktin->length - 5,
1726 &newpayload, &newlen)) {
1727 if (st->pktin->maxlen < newlen + 5) {
1728 st->pktin->maxlen = newlen + 5;
1729 st->pktin->data = sresize(st->pktin->data,
1730 st->pktin->maxlen + APIEXTRA,
1733 st->pktin->length = 5 + newlen;
1734 memcpy(st->pktin->data + 5, newpayload, newlen);
1740 * pktin->body and pktin->length should identify the semantic
1741 * content of the packet, excluding the initial type byte.
1743 st->pktin->type = st->pktin->data[5];
1744 st->pktin->body = st->pktin->data + 6;
1745 st->pktin->length -= 6;
1746 assert(st->pktin->length >= 0); /* one last double-check */
1749 ssh2_log_incoming_packet(ssh, st->pktin);
1751 st->pktin->savedpos = 0;
1753 crFinish(st->pktin);
1756 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh, unsigned char **data,
1759 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1761 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1764 * Read the packet length field.
1766 for (st->i = 0; st->i < 4; st->i++) {
1767 while ((*datalen) == 0)
1769 st->length[st->i] = *(*data)++;
1773 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1774 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1775 bombout(("Invalid packet length received"));
1779 st->pktin = ssh_new_packet();
1780 st->pktin->data = snewn(st->packetlen, unsigned char);
1782 st->pktin->encrypted_len = st->packetlen;
1784 st->pktin->sequence = st->incoming_sequence++;
1787 * Read the remainder of the packet.
1789 for (st->i = 0; st->i < st->packetlen; st->i++) {
1790 while ((*datalen) == 0)
1792 st->pktin->data[st->i] = *(*data)++;
1797 * pktin->body and pktin->length should identify the semantic
1798 * content of the packet, excluding the initial type byte.
1800 st->pktin->type = st->pktin->data[0];
1801 st->pktin->body = st->pktin->data + 1;
1802 st->pktin->length = st->packetlen - 1;
1805 * Log incoming packet, possibly omitting sensitive fields.
1808 ssh2_log_incoming_packet(ssh, st->pktin);
1810 st->pktin->savedpos = 0;
1812 crFinish(st->pktin);
1815 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1817 int pad, biglen, i, pktoffs;
1821 * XXX various versions of SC (including 8.8.4) screw up the
1822 * register allocation in this function and use the same register
1823 * (D6) for len and as a temporary, with predictable results. The
1824 * following sledgehammer prevents this.
1831 ssh1_log_outgoing_packet(ssh, pkt);
1833 if (ssh->v1_compressing) {
1834 unsigned char *compblk;
1836 zlib_compress_block(ssh->cs_comp_ctx,
1837 pkt->data + 12, pkt->length - 12,
1838 &compblk, &complen);
1839 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1840 memcpy(pkt->data + 12, compblk, complen);
1842 pkt->length = complen + 12;
1845 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1847 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1848 pad = 8 - (len % 8);
1850 biglen = len + pad; /* len(padding+type+data+CRC) */
1852 for (i = pktoffs; i < 4+8; i++)
1853 pkt->data[i] = random_byte();
1854 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1855 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1856 PUT_32BIT(pkt->data + pktoffs, len);
1859 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1860 pkt->data + pktoffs + 4, biglen);
1862 if (offset_p) *offset_p = pktoffs;
1863 return biglen + 4; /* len(length+padding+type+data+CRC) */
1866 static int s_write(Ssh ssh, void *data, int len)
1869 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1870 0, NULL, NULL, 0, NULL);
1873 return sk_write(ssh->s, (char *)data, len);
1876 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1878 int len, backlog, offset;
1879 len = s_wrpkt_prepare(ssh, pkt, &offset);
1880 backlog = s_write(ssh, pkt->data + offset, len);
1881 if (backlog > SSH_MAX_BACKLOG)
1882 ssh_throttle_all(ssh, 1, backlog);
1883 ssh_free_packet(pkt);
1886 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1889 len = s_wrpkt_prepare(ssh, pkt, &offset);
1890 if (ssh->deferred_len + len > ssh->deferred_size) {
1891 ssh->deferred_size = ssh->deferred_len + len + 128;
1892 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1896 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1897 pkt->data + offset, len);
1898 ssh->deferred_len += len;
1899 ssh_free_packet(pkt);
1903 * Construct a SSH-1 packet with the specified contents.
1904 * (This all-at-once interface used to be the only one, but now SSH-1
1905 * packets can also be constructed incrementally.)
1907 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1913 pkt = ssh1_pkt_init(pkttype);
1915 while ((argtype = va_arg(ap, int)) != PKT_END) {
1916 unsigned char *argp, argchar;
1918 unsigned long argint;
1921 /* Actual fields in the packet */
1923 argint = va_arg(ap, int);
1924 ssh_pkt_adduint32(pkt, argint);
1927 argchar = (unsigned char) va_arg(ap, int);
1928 ssh_pkt_addbyte(pkt, argchar);
1931 argp = va_arg(ap, unsigned char *);
1932 arglen = va_arg(ap, int);
1933 ssh_pkt_adddata(pkt, argp, arglen);
1936 sargp = va_arg(ap, char *);
1937 ssh_pkt_addstring(pkt, sargp);
1940 bn = va_arg(ap, Bignum);
1941 ssh1_pkt_addmp(pkt, bn);
1949 static void send_packet(Ssh ssh, int pkttype, ...)
1953 va_start(ap, pkttype);
1954 pkt = construct_packet(ssh, pkttype, ap);
1959 static void defer_packet(Ssh ssh, int pkttype, ...)
1963 va_start(ap, pkttype);
1964 pkt = construct_packet(ssh, pkttype, ap);
1966 s_wrpkt_defer(ssh, pkt);
1969 static int ssh_versioncmp(char *a, char *b)
1972 unsigned long av, bv;
1974 av = strtoul(a, &ae, 10);
1975 bv = strtoul(b, &be, 10);
1977 return (av < bv ? -1 : +1);
1982 av = strtoul(ae, &ae, 10);
1983 bv = strtoul(be, &be, 10);
1985 return (av < bv ? -1 : +1);
1990 * Utility routines for putting an SSH-protocol `string' and
1991 * `uint32' into a hash state.
1993 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1995 unsigned char lenblk[4];
1996 PUT_32BIT(lenblk, len);
1997 h->bytes(s, lenblk, 4);
1998 h->bytes(s, str, len);
2001 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2003 unsigned char intblk[4];
2004 PUT_32BIT(intblk, i);
2005 h->bytes(s, intblk, 4);
2009 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2011 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2013 if (pkt->maxlen < length) {
2014 unsigned char *body = pkt->body;
2015 int offset = body ? body - pkt->data : 0;
2016 pkt->maxlen = length + 256;
2017 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2018 if (body) pkt->body = pkt->data + offset;
2021 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2024 ssh_pkt_ensure(pkt, pkt->length);
2025 memcpy(pkt->data + pkt->length - len, data, len);
2027 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2029 ssh_pkt_adddata(pkt, &byte, 1);
2031 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2033 ssh_pkt_adddata(pkt, &value, 1);
2035 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2038 PUT_32BIT(x, value);
2039 ssh_pkt_adddata(pkt, x, 4);
2041 static void ssh_pkt_addstring_start(struct Packet *pkt)
2043 ssh_pkt_adduint32(pkt, 0);
2044 pkt->savedpos = pkt->length;
2046 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2048 ssh_pkt_adddata(pkt, data, strlen(data));
2049 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2051 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2054 ssh_pkt_adddata(pkt, data, len);
2055 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2057 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2059 ssh_pkt_addstring_start(pkt);
2060 ssh_pkt_addstring_str(pkt, data);
2062 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2064 int len = ssh1_bignum_length(b);
2065 unsigned char *data = snewn(len, unsigned char);
2066 (void) ssh1_write_bignum(data, b);
2067 ssh_pkt_adddata(pkt, data, len);
2070 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2073 int i, n = (bignum_bitcount(b) + 7) / 8;
2074 p = snewn(n + 1, unsigned char);
2076 for (i = 1; i <= n; i++)
2077 p[i] = bignum_byte(b, n - i);
2079 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2081 memmove(p, p + i, n + 1 - i);
2085 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2089 p = ssh2_mpint_fmt(b, &len);
2090 ssh_pkt_addstring_start(pkt);
2091 ssh_pkt_addstring_data(pkt, (char *)p, len);
2095 static struct Packet *ssh1_pkt_init(int pkt_type)
2097 struct Packet *pkt = ssh_new_packet();
2098 pkt->length = 4 + 8; /* space for length + max padding */
2099 ssh_pkt_addbyte(pkt, pkt_type);
2100 pkt->body = pkt->data + pkt->length;
2101 pkt->type = pkt_type;
2102 pkt->downstream_id = 0;
2103 pkt->additional_log_text = NULL;
2107 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2108 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2109 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2110 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2111 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2112 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2113 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2114 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2115 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2117 static struct Packet *ssh2_pkt_init(int pkt_type)
2119 struct Packet *pkt = ssh_new_packet();
2120 pkt->length = 5; /* space for packet length + padding length */
2122 pkt->type = pkt_type;
2123 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2124 pkt->body = pkt->data + pkt->length; /* after packet type */
2125 pkt->downstream_id = 0;
2126 pkt->additional_log_text = NULL;
2131 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2132 * put the MAC on it. Final packet, ready to be sent, is stored in
2133 * pkt->data. Total length is returned.
2135 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2137 int cipherblk, maclen, padding, i;
2140 ssh2_log_outgoing_packet(ssh, pkt);
2142 if (ssh->bare_connection) {
2144 * Trivial packet construction for the bare connection
2147 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2148 pkt->body = pkt->data + 1;
2149 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2150 return pkt->length - 1;
2154 * Compress packet payload.
2157 unsigned char *newpayload;
2160 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2162 &newpayload, &newlen)) {
2164 ssh2_pkt_adddata(pkt, newpayload, newlen);
2170 * Add padding. At least four bytes, and must also bring total
2171 * length (minus MAC) up to a multiple of the block size.
2172 * If pkt->forcepad is set, make sure the packet is at least that size
2175 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2176 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2178 if (pkt->length + padding < pkt->forcepad)
2179 padding = pkt->forcepad - pkt->length;
2181 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
2182 assert(padding <= 255);
2183 maclen = ssh->csmac ? ssh->csmac->len : 0;
2184 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2185 pkt->data[4] = padding;
2186 for (i = 0; i < padding; i++)
2187 pkt->data[pkt->length + i] = random_byte();
2188 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2190 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2191 pkt->length + padding,
2192 ssh->v2_outgoing_sequence);
2193 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2196 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2197 pkt->data, pkt->length + padding);
2199 pkt->encrypted_len = pkt->length + padding;
2201 /* Ready-to-send packet starts at pkt->data. We return length. */
2202 pkt->body = pkt->data;
2203 return pkt->length + padding + maclen;
2207 * Routines called from the main SSH code to send packets. There
2208 * are quite a few of these, because we have two separate
2209 * mechanisms for delaying the sending of packets:
2211 * - In order to send an IGNORE message and a password message in
2212 * a single fixed-length blob, we require the ability to
2213 * concatenate the encrypted forms of those two packets _into_ a
2214 * single blob and then pass it to our <network.h> transport
2215 * layer in one go. Hence, there's a deferment mechanism which
2216 * works after packet encryption.
2218 * - In order to avoid sending any connection-layer messages
2219 * during repeat key exchange, we have to queue up any such
2220 * outgoing messages _before_ they are encrypted (and in
2221 * particular before they're allocated sequence numbers), and
2222 * then send them once we've finished.
2224 * I call these mechanisms `defer' and `queue' respectively, so as
2225 * to distinguish them reasonably easily.
2227 * The functions send_noqueue() and defer_noqueue() free the packet
2228 * structure they are passed. Every outgoing packet goes through
2229 * precisely one of these functions in its life; packets passed to
2230 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2231 * these or get queued, and then when the queue is later emptied
2232 * the packets are all passed to defer_noqueue().
2234 * When using a CBC-mode cipher, it's necessary to ensure that an
2235 * attacker can't provide data to be encrypted using an IV that they
2236 * know. We ensure this by prefixing each packet that might contain
2237 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2238 * mechanism, so in this case send_noqueue() ends up redirecting to
2239 * defer_noqueue(). If you don't like this inefficiency, don't use
2243 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2244 static void ssh_pkt_defersend(Ssh);
2247 * Send an SSH-2 packet immediately, without queuing or deferring.
2249 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2253 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2254 /* We need to send two packets, so use the deferral mechanism. */
2255 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2256 ssh_pkt_defersend(ssh);
2259 len = ssh2_pkt_construct(ssh, pkt);
2260 backlog = s_write(ssh, pkt->body, len);
2261 if (backlog > SSH_MAX_BACKLOG)
2262 ssh_throttle_all(ssh, 1, backlog);
2264 ssh->outgoing_data_size += pkt->encrypted_len;
2265 if (!ssh->kex_in_progress &&
2266 !ssh->bare_connection &&
2267 ssh->max_data_size != 0 &&
2268 ssh->outgoing_data_size > ssh->max_data_size)
2269 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2271 ssh_free_packet(pkt);
2275 * Defer an SSH-2 packet.
2277 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2280 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2281 ssh->deferred_len == 0 && !noignore &&
2282 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2284 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2285 * get encrypted with a known IV.
2287 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2288 ssh2_pkt_addstring_start(ipkt);
2289 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2291 len = ssh2_pkt_construct(ssh, pkt);
2292 if (ssh->deferred_len + len > ssh->deferred_size) {
2293 ssh->deferred_size = ssh->deferred_len + len + 128;
2294 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2298 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2299 ssh->deferred_len += len;
2300 ssh->deferred_data_size += pkt->encrypted_len;
2301 ssh_free_packet(pkt);
2305 * Queue an SSH-2 packet.
2307 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2309 assert(ssh->queueing);
2311 if (ssh->queuelen >= ssh->queuesize) {
2312 ssh->queuesize = ssh->queuelen + 32;
2313 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2316 ssh->queue[ssh->queuelen++] = pkt;
2320 * Either queue or send a packet, depending on whether queueing is
2323 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2326 ssh2_pkt_queue(ssh, pkt);
2328 ssh2_pkt_send_noqueue(ssh, pkt);
2332 * Either queue or defer a packet, depending on whether queueing is
2335 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2338 ssh2_pkt_queue(ssh, pkt);
2340 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2344 * Send the whole deferred data block constructed by
2345 * ssh2_pkt_defer() or SSH-1's defer_packet().
2347 * The expected use of the defer mechanism is that you call
2348 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2349 * not currently queueing, this simply sets up deferred_send_data
2350 * and then sends it. If we _are_ currently queueing, the calls to
2351 * ssh2_pkt_defer() put the deferred packets on to the queue
2352 * instead, and therefore ssh_pkt_defersend() has no deferred data
2353 * to send. Hence, there's no need to make it conditional on
2356 static void ssh_pkt_defersend(Ssh ssh)
2359 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2360 ssh->deferred_len = ssh->deferred_size = 0;
2361 sfree(ssh->deferred_send_data);
2362 ssh->deferred_send_data = NULL;
2363 if (backlog > SSH_MAX_BACKLOG)
2364 ssh_throttle_all(ssh, 1, backlog);
2366 ssh->outgoing_data_size += ssh->deferred_data_size;
2367 if (!ssh->kex_in_progress &&
2368 !ssh->bare_connection &&
2369 ssh->max_data_size != 0 &&
2370 ssh->outgoing_data_size > ssh->max_data_size)
2371 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2372 ssh->deferred_data_size = 0;
2376 * Send a packet whose length needs to be disguised (typically
2377 * passwords or keyboard-interactive responses).
2379 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2385 * The simplest way to do this is to adjust the
2386 * variable-length padding field in the outgoing packet.
2388 * Currently compiled out, because some Cisco SSH servers
2389 * don't like excessively padded packets (bah, why's it
2392 pkt->forcepad = padsize;
2393 ssh2_pkt_send(ssh, pkt);
2398 * If we can't do that, however, an alternative approach is
2399 * to use the pkt_defer mechanism to bundle the packet
2400 * tightly together with an SSH_MSG_IGNORE such that their
2401 * combined length is a constant. So first we construct the
2402 * final form of this packet and defer its sending.
2404 ssh2_pkt_defer(ssh, pkt);
2407 * Now construct an SSH_MSG_IGNORE which includes a string
2408 * that's an exact multiple of the cipher block size. (If
2409 * the cipher is NULL so that the block size is
2410 * unavailable, we don't do this trick at all, because we
2411 * gain nothing by it.)
2413 if (ssh->cscipher &&
2414 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2417 stringlen = (256 - ssh->deferred_len);
2418 stringlen += ssh->cscipher->blksize - 1;
2419 stringlen -= (stringlen % ssh->cscipher->blksize);
2422 * Temporarily disable actual compression, so we
2423 * can guarantee to get this string exactly the
2424 * length we want it. The compression-disabling
2425 * routine should return an integer indicating how
2426 * many bytes we should adjust our string length
2430 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2432 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2433 ssh2_pkt_addstring_start(pkt);
2434 for (i = 0; i < stringlen; i++) {
2435 char c = (char) random_byte();
2436 ssh2_pkt_addstring_data(pkt, &c, 1);
2438 ssh2_pkt_defer(ssh, pkt);
2440 ssh_pkt_defersend(ssh);
2445 * Send all queued SSH-2 packets. We send them by means of
2446 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2447 * packets that needed to be lumped together.
2449 static void ssh2_pkt_queuesend(Ssh ssh)
2453 assert(!ssh->queueing);
2455 for (i = 0; i < ssh->queuelen; i++)
2456 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2459 ssh_pkt_defersend(ssh);
2463 void bndebug(char *string, Bignum b)
2467 p = ssh2_mpint_fmt(b, &len);
2468 debug(("%s", string));
2469 for (i = 0; i < len; i++)
2470 debug((" %02x", p[i]));
2476 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2480 p = ssh2_mpint_fmt(b, &len);
2481 hash_string(h, s, p, len);
2486 * Packet decode functions for both SSH-1 and SSH-2.
2488 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2490 unsigned long value;
2491 if (pkt->length - pkt->savedpos < 4)
2492 return 0; /* arrgh, no way to decline (FIXME?) */
2493 value = GET_32BIT(pkt->body + pkt->savedpos);
2497 static int ssh2_pkt_getbool(struct Packet *pkt)
2499 unsigned long value;
2500 if (pkt->length - pkt->savedpos < 1)
2501 return 0; /* arrgh, no way to decline (FIXME?) */
2502 value = pkt->body[pkt->savedpos] != 0;
2506 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2511 if (pkt->length - pkt->savedpos < 4)
2513 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2518 if (pkt->length - pkt->savedpos < *length)
2520 *p = (char *)(pkt->body + pkt->savedpos);
2521 pkt->savedpos += *length;
2523 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2525 if (pkt->length - pkt->savedpos < length)
2527 pkt->savedpos += length;
2528 return pkt->body + (pkt->savedpos - length);
2530 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2531 unsigned char **keystr)
2535 j = makekey(pkt->body + pkt->savedpos,
2536 pkt->length - pkt->savedpos,
2543 assert(pkt->savedpos < pkt->length);
2547 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2552 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2553 pkt->length - pkt->savedpos, &b);
2561 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2567 ssh_pkt_getstring(pkt, &p, &length);
2572 b = bignum_from_bytes((unsigned char *)p, length);
2577 * Helper function to add an SSH-2 signature blob to a packet.
2578 * Expects to be shown the public key blob as well as the signature
2579 * blob. Normally works just like ssh2_pkt_addstring, but will
2580 * fiddle with the signature packet if necessary for
2581 * BUG_SSH2_RSA_PADDING.
2583 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2584 void *pkblob_v, int pkblob_len,
2585 void *sigblob_v, int sigblob_len)
2587 unsigned char *pkblob = (unsigned char *)pkblob_v;
2588 unsigned char *sigblob = (unsigned char *)sigblob_v;
2590 /* dmemdump(pkblob, pkblob_len); */
2591 /* dmemdump(sigblob, sigblob_len); */
2594 * See if this is in fact an ssh-rsa signature and a buggy
2595 * server; otherwise we can just do this the easy way.
2597 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2598 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2599 int pos, len, siglen;
2602 * Find the byte length of the modulus.
2605 pos = 4+7; /* skip over "ssh-rsa" */
2606 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2607 if (len < 0 || len > pkblob_len - pos - 4)
2609 pos += 4 + len; /* skip over exponent */
2610 if (pkblob_len - pos < 4)
2612 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2613 if (len < 0 || len > pkblob_len - pos - 4)
2615 pos += 4; /* find modulus itself */
2616 while (len > 0 && pkblob[pos] == 0)
2618 /* debug(("modulus length is %d\n", len)); */
2621 * Now find the signature integer.
2623 pos = 4+7; /* skip over "ssh-rsa" */
2624 if (sigblob_len < pos+4)
2626 siglen = toint(GET_32BIT(sigblob+pos));
2627 if (siglen != sigblob_len - pos - 4)
2629 /* debug(("signature length is %d\n", siglen)); */
2631 if (len != siglen) {
2632 unsigned char newlen[4];
2633 ssh2_pkt_addstring_start(pkt);
2634 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2635 /* dmemdump(sigblob, pos); */
2636 pos += 4; /* point to start of actual sig */
2637 PUT_32BIT(newlen, len);
2638 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2639 /* dmemdump(newlen, 4); */
2641 while (len-- > siglen) {
2642 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2643 /* dmemdump(newlen, 1); */
2645 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2646 /* dmemdump(sigblob+pos, siglen); */
2650 /* Otherwise fall through and do it the easy way. We also come
2651 * here as a fallback if we discover above that the key blob
2652 * is misformatted in some way. */
2656 ssh2_pkt_addstring_start(pkt);
2657 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2661 * Examine the remote side's version string and compare it against
2662 * a list of known buggy implementations.
2664 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2666 char *imp; /* pointer to implementation part */
2668 imp += strcspn(imp, "-");
2670 imp += strcspn(imp, "-");
2673 ssh->remote_bugs = 0;
2676 * General notes on server version strings:
2677 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2678 * here -- in particular, we've heard of one that's perfectly happy
2679 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2680 * so we can't distinguish them.
2682 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2683 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2684 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2685 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2686 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2687 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2689 * These versions don't support SSH1_MSG_IGNORE, so we have
2690 * to use a different defence against password length
2693 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2694 logevent("We believe remote version has SSH-1 ignore bug");
2697 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2698 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2699 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2701 * These versions need a plain password sent; they can't
2702 * handle having a null and a random length of data after
2705 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2706 logevent("We believe remote version needs a plain SSH-1 password");
2709 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2710 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2711 (!strcmp(imp, "Cisco-1.25")))) {
2713 * These versions apparently have no clue whatever about
2714 * RSA authentication and will panic and die if they see
2715 * an AUTH_RSA message.
2717 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2718 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2721 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2722 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2723 !wc_match("* VShell", imp) &&
2724 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2725 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2726 wc_match("2.1 *", imp)))) {
2728 * These versions have the HMAC bug.
2730 ssh->remote_bugs |= BUG_SSH2_HMAC;
2731 logevent("We believe remote version has SSH-2 HMAC bug");
2734 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2735 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2736 !wc_match("* VShell", imp) &&
2737 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2739 * These versions have the key-derivation bug (failing to
2740 * include the literal shared secret in the hashes that
2741 * generate the keys).
2743 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2744 logevent("We believe remote version has SSH-2 key-derivation bug");
2747 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2748 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2749 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2750 wc_match("OpenSSH_3.[0-2]*", imp) ||
2751 wc_match("mod_sftp/0.[0-8]*", imp) ||
2752 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2754 * These versions have the SSH-2 RSA padding bug.
2756 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2757 logevent("We believe remote version has SSH-2 RSA padding bug");
2760 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2761 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2762 wc_match("OpenSSH_2.[0-2]*", imp))) {
2764 * These versions have the SSH-2 session-ID bug in
2765 * public-key authentication.
2767 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2768 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2771 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2772 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2773 (wc_match("DigiSSH_2.0", imp) ||
2774 wc_match("OpenSSH_2.[0-4]*", imp) ||
2775 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2776 wc_match("Sun_SSH_1.0", imp) ||
2777 wc_match("Sun_SSH_1.0.1", imp) ||
2778 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2779 wc_match("WeOnlyDo-*", imp)))) {
2781 * These versions have the SSH-2 rekey bug.
2783 ssh->remote_bugs |= BUG_SSH2_REKEY;
2784 logevent("We believe remote version has SSH-2 rekey bug");
2787 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2788 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2789 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2790 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2792 * This version ignores our makpkt and needs to be throttled.
2794 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2795 logevent("We believe remote version ignores SSH-2 maximum packet size");
2798 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2800 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2801 * none detected automatically.
2803 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2804 logevent("We believe remote version has SSH-2 ignore bug");
2807 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2809 * Servers that don't support our winadj request for one
2810 * reason or another. Currently, none detected automatically.
2812 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2813 logevent("We believe remote version has winadj bug");
2818 * The `software version' part of an SSH version string is required
2819 * to contain no spaces or minus signs.
2821 static void ssh_fix_verstring(char *str)
2823 /* Eat "<protoversion>-". */
2824 while (*str && *str != '-') str++;
2825 assert(*str == '-'); str++;
2827 /* Convert minus signs and spaces in the remaining string into
2830 if (*str == '-' || *str == ' ')
2837 * Send an appropriate SSH version string.
2839 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
2843 if (ssh->version == 2) {
2845 * Construct a v2 version string.
2847 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
2850 * Construct a v1 version string.
2852 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
2853 verstring = dupprintf("SSH-%s-%s\012",
2854 (ssh_versioncmp(svers, "1.5") <= 0 ?
2859 ssh_fix_verstring(verstring + strlen(protoname));
2861 if (ssh->version == 2) {
2864 * Record our version string.
2866 len = strcspn(verstring, "\015\012");
2867 ssh->v_c = snewn(len + 1, char);
2868 memcpy(ssh->v_c, verstring, len);
2872 logeventf(ssh, "We claim version: %.*s",
2873 strcspn(verstring, "\015\012"), verstring);
2874 s_write(ssh, verstring, strlen(verstring));
2878 static int do_ssh_init(Ssh ssh, unsigned char c)
2880 static const char protoname[] = "SSH-";
2882 struct do_ssh_init_state {
2891 crState(do_ssh_init_state);
2895 /* Search for a line beginning with the protocol name prefix in
2898 for (s->i = 0; protoname[s->i]; s->i++) {
2899 if ((char)c != protoname[s->i]) goto no;
2909 s->vstrsize = sizeof(protoname) + 16;
2910 s->vstring = snewn(s->vstrsize, char);
2911 strcpy(s->vstring, protoname);
2912 s->vslen = strlen(protoname);
2915 if (s->vslen >= s->vstrsize - 1) {
2917 s->vstring = sresize(s->vstring, s->vstrsize, char);
2919 s->vstring[s->vslen++] = c;
2922 s->version[s->i] = '\0';
2924 } else if (s->i < sizeof(s->version) - 1)
2925 s->version[s->i++] = c;
2926 } else if (c == '\012')
2928 crReturn(1); /* get another char */
2931 ssh->agentfwd_enabled = FALSE;
2932 ssh->rdpkt2_state.incoming_sequence = 0;
2934 s->vstring[s->vslen] = 0;
2935 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2936 logeventf(ssh, "Server version: %s", s->vstring);
2937 ssh_detect_bugs(ssh, s->vstring);
2940 * Decide which SSH protocol version to support.
2943 /* Anything strictly below "2.0" means protocol 1 is supported. */
2944 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2945 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2946 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2948 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2949 bombout(("SSH protocol version 1 required by user but not provided by server"));
2952 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2953 bombout(("SSH protocol version 2 required by user but not provided by server"));
2957 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2962 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2964 /* Send the version string, if we haven't already */
2965 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2966 ssh_send_verstring(ssh, protoname, s->version);
2968 if (ssh->version == 2) {
2971 * Record their version string.
2973 len = strcspn(s->vstring, "\015\012");
2974 ssh->v_s = snewn(len + 1, char);
2975 memcpy(ssh->v_s, s->vstring, len);
2979 * Initialise SSH-2 protocol.
2981 ssh->protocol = ssh2_protocol;
2982 ssh2_protocol_setup(ssh);
2983 ssh->s_rdpkt = ssh2_rdpkt;
2986 * Initialise SSH-1 protocol.
2988 ssh->protocol = ssh1_protocol;
2989 ssh1_protocol_setup(ssh);
2990 ssh->s_rdpkt = ssh1_rdpkt;
2992 if (ssh->version == 2)
2993 do_ssh2_transport(ssh, NULL, -1, NULL);
2995 update_specials_menu(ssh->frontend);
2996 ssh->state = SSH_STATE_BEFORE_SIZE;
2997 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3004 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3007 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3008 * the ssh-connection part, extracted and given a trivial binary
3009 * packet protocol, so we replace 'SSH-' at the start with a new
3010 * name. In proper SSH style (though of course this part of the
3011 * proper SSH protocol _isn't_ subject to this kind of
3012 * DNS-domain-based extension), we define the new name in our
3015 static const char protoname[] =
3016 "SSHCONNECTION@putty.projects.tartarus.org-";
3018 struct do_ssh_connection_init_state {
3026 crState(do_ssh_connection_init_state);
3030 /* Search for a line beginning with the protocol name prefix in
3033 for (s->i = 0; protoname[s->i]; s->i++) {
3034 if ((char)c != protoname[s->i]) goto no;
3044 s->vstrsize = sizeof(protoname) + 16;
3045 s->vstring = snewn(s->vstrsize, char);
3046 strcpy(s->vstring, protoname);
3047 s->vslen = strlen(protoname);
3050 if (s->vslen >= s->vstrsize - 1) {
3052 s->vstring = sresize(s->vstring, s->vstrsize, char);
3054 s->vstring[s->vslen++] = c;
3057 s->version[s->i] = '\0';
3059 } else if (s->i < sizeof(s->version) - 1)
3060 s->version[s->i++] = c;
3061 } else if (c == '\012')
3063 crReturn(1); /* get another char */
3066 ssh->agentfwd_enabled = FALSE;
3067 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3069 s->vstring[s->vslen] = 0;
3070 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3071 logeventf(ssh, "Server version: %s", s->vstring);
3072 ssh_detect_bugs(ssh, s->vstring);
3075 * Decide which SSH protocol version to support. This is easy in
3076 * bare ssh-connection mode: only 2.0 is legal.
3078 if (ssh_versioncmp(s->version, "2.0") < 0) {
3079 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3082 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3083 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3089 logeventf(ssh, "Using bare ssh-connection protocol");
3091 /* Send the version string, if we haven't already */
3092 ssh_send_verstring(ssh, protoname, s->version);
3095 * Initialise bare connection protocol.
3097 ssh->protocol = ssh2_bare_connection_protocol;
3098 ssh2_bare_connection_protocol_setup(ssh);
3099 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3101 update_specials_menu(ssh->frontend);
3102 ssh->state = SSH_STATE_BEFORE_SIZE;
3103 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3106 * Get authconn (really just conn) under way.
3108 do_ssh2_authconn(ssh, NULL, 0, NULL);
3115 static void ssh_process_incoming_data(Ssh ssh,
3116 unsigned char **data, int *datalen)
3118 struct Packet *pktin;
3120 pktin = ssh->s_rdpkt(ssh, data, datalen);
3122 ssh->protocol(ssh, NULL, 0, pktin);
3123 ssh_free_packet(pktin);
3127 static void ssh_queue_incoming_data(Ssh ssh,
3128 unsigned char **data, int *datalen)
3130 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3135 static void ssh_process_queued_incoming_data(Ssh ssh)
3138 unsigned char *data;
3141 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3142 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3146 while (!ssh->frozen && len > 0)
3147 ssh_process_incoming_data(ssh, &data, &len);
3150 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3154 static void ssh_set_frozen(Ssh ssh, int frozen)
3157 sk_set_frozen(ssh->s, frozen);
3158 ssh->frozen = frozen;
3161 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
3163 /* Log raw data, if we're in that mode. */
3165 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3166 0, NULL, NULL, 0, NULL);
3168 crBegin(ssh->ssh_gotdata_crstate);
3171 * To begin with, feed the characters one by one to the
3172 * protocol initialisation / selection function do_ssh_init().
3173 * When that returns 0, we're done with the initial greeting
3174 * exchange and can move on to packet discipline.
3177 int ret; /* need not be kept across crReturn */
3179 crReturnV; /* more data please */
3180 ret = ssh->do_ssh_init(ssh, *data);
3188 * We emerge from that loop when the initial negotiation is
3189 * over and we have selected an s_rdpkt function. Now pass
3190 * everything to s_rdpkt, and then pass the resulting packets
3191 * to the proper protocol handler.
3195 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3197 ssh_queue_incoming_data(ssh, &data, &datalen);
3198 /* This uses up all data and cannot cause anything interesting
3199 * to happen; indeed, for anything to happen at all, we must
3200 * return, so break out. */
3202 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3203 /* This uses up some or all data, and may freeze the
3205 ssh_process_queued_incoming_data(ssh);
3207 /* This uses up some or all data, and may freeze the
3209 ssh_process_incoming_data(ssh, &data, &datalen);
3211 /* FIXME this is probably EBW. */
3212 if (ssh->state == SSH_STATE_CLOSED)
3215 /* We're out of data. Go and get some more. */
3221 static int ssh_do_close(Ssh ssh, int notify_exit)
3224 struct ssh_channel *c;
3226 ssh->state = SSH_STATE_CLOSED;
3227 expire_timer_context(ssh);
3232 notify_remote_exit(ssh->frontend);
3237 * Now we must shut down any port- and X-forwarded channels going
3238 * through this connection.
3240 if (ssh->channels) {
3241 while (NULL != (c = index234(ssh->channels, 0))) {
3244 x11_close(c->u.x11.xconn);
3247 case CHAN_SOCKDATA_DORMANT:
3248 pfd_close(c->u.pfd.pf);
3251 del234(ssh->channels, c); /* moving next one to index 0 */
3252 if (ssh->version == 2)
3253 bufchain_clear(&c->v.v2.outbuffer);
3258 * Go through port-forwardings, and close any associated
3259 * listening sockets.
3261 if (ssh->portfwds) {
3262 struct ssh_portfwd *pf;
3263 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3264 /* Dispose of any listening socket. */
3266 pfl_terminate(pf->local);
3267 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3270 freetree234(ssh->portfwds);
3271 ssh->portfwds = NULL;
3277 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3278 const char *error_msg, int error_code)
3280 Ssh ssh = (Ssh) plug;
3281 char addrbuf[256], *msg;
3283 if (ssh->attempting_connshare) {
3285 * While we're attempting connection sharing, don't loudly log
3286 * everything that happens. Real TCP connections need to be
3287 * logged when we _start_ trying to connect, because it might
3288 * be ages before they respond if something goes wrong; but
3289 * connection sharing is local and quick to respond, and it's
3290 * sufficient to simply wait and see whether it worked
3294 sk_getaddr(addr, addrbuf, lenof(addrbuf));
3297 if (sk_addr_needs_port(addr)) {
3298 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
3300 msg = dupprintf("Connecting to %s", addrbuf);
3303 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
3311 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3312 const char *ds_err, const char *us_err)
3314 if (event == SHARE_NONE) {
3315 /* In this case, 'logtext' is an error message indicating a
3316 * reason why connection sharing couldn't be set up _at all_.
3317 * Failing that, ds_err and us_err indicate why we couldn't be
3318 * a downstream and an upstream respectively. */
3320 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3323 logeventf(ssh, "Could not set up connection sharing"
3324 " as downstream: %s", ds_err);
3326 logeventf(ssh, "Could not set up connection sharing"
3327 " as upstream: %s", us_err);
3329 } else if (event == SHARE_DOWNSTREAM) {
3330 /* In this case, 'logtext' is a local endpoint address */
3331 logeventf(ssh, "Using existing shared connection at %s", logtext);
3332 /* Also we should mention this in the console window to avoid
3333 * confusing users as to why this window doesn't behave the
3335 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3336 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3338 } else if (event == SHARE_UPSTREAM) {
3339 /* In this case, 'logtext' is a local endpoint address too */
3340 logeventf(ssh, "Sharing this connection at %s", logtext);
3344 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3347 Ssh ssh = (Ssh) plug;
3348 int need_notify = ssh_do_close(ssh, FALSE);
3351 if (!ssh->close_expected)
3352 error_msg = "Server unexpectedly closed network connection";
3354 error_msg = "Server closed network connection";
3357 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3361 notify_remote_exit(ssh->frontend);
3364 logevent(error_msg);
3365 if (!ssh->close_expected || !ssh->clean_exit)
3366 connection_fatal(ssh->frontend, "%s", error_msg);
3370 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3372 Ssh ssh = (Ssh) plug;
3373 ssh_gotdata(ssh, (unsigned char *)data, len);
3374 if (ssh->state == SSH_STATE_CLOSED) {
3375 ssh_do_close(ssh, TRUE);
3381 static void ssh_sent(Plug plug, int bufsize)
3383 Ssh ssh = (Ssh) plug;
3385 * If the send backlog on the SSH socket itself clears, we
3386 * should unthrottle the whole world if it was throttled.
3388 if (bufsize < SSH_MAX_BACKLOG)
3389 ssh_throttle_all(ssh, 0, bufsize);
3393 * Connect to specified host and port.
3394 * Returns an error message, or NULL on success.
3395 * Also places the canonical host name into `realhost'. It must be
3396 * freed by the caller.
3398 static const char *connect_to_host(Ssh ssh, char *host, int port,
3399 char **realhost, int nodelay, int keepalive)
3401 static const struct plug_function_table fn_table = {
3412 int addressfamily, sshprot;
3414 loghost = conf_get_str(ssh->conf, CONF_loghost);
3419 tmphost = dupstr(loghost);
3420 ssh->savedport = 22; /* default ssh port */
3423 * A colon suffix on the hostname string also lets us affect
3424 * savedport. (Unless there are multiple colons, in which case
3425 * we assume this is an unbracketed IPv6 literal.)
3427 colon = host_strrchr(tmphost, ':');
3428 if (colon && colon == host_strchr(tmphost, ':')) {
3431 ssh->savedport = atoi(colon);
3434 ssh->savedhost = host_strduptrim(tmphost);
3437 ssh->savedhost = host_strduptrim(host);
3439 port = 22; /* default ssh port */
3440 ssh->savedport = port;
3443 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3446 * Try connection-sharing, in case that means we don't open a
3447 * socket after all. ssh_connection_sharing_init will connect to a
3448 * previously established upstream if it can, and failing that,
3449 * establish a listening socket for _us_ to be the upstream. In
3450 * the latter case it will return NULL just as if it had done
3451 * nothing, because here we only need to care if we're a
3452 * downstream and need to do our connection setup differently.
3454 ssh->connshare = NULL;
3455 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3456 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3457 ssh->conf, ssh, &ssh->connshare);
3458 ssh->attempting_connshare = FALSE;
3459 if (ssh->s != NULL) {
3461 * We are a downstream.
3463 ssh->bare_connection = TRUE;
3464 ssh->do_ssh_init = do_ssh_connection_init;
3465 ssh->fullhostname = NULL;
3466 *realhost = dupstr(host); /* best we can do */
3469 * We're not a downstream, so open a normal socket.
3471 ssh->do_ssh_init = do_ssh_init;
3476 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3477 logeventf(ssh, "Looking up host \"%s\"%s", host,
3478 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3479 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3480 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3481 if ((err = sk_addr_error(addr)) != NULL) {
3485 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3487 ssh->s = new_connection(addr, *realhost, port,
3488 0, 1, nodelay, keepalive,
3489 (Plug) ssh, ssh->conf);
3490 if ((err = sk_socket_error(ssh->s)) != NULL) {
3492 notify_remote_exit(ssh->frontend);
3498 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3499 * send the version string too.
3501 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3504 if (sshprot == 3 && !ssh->bare_connection) {
3506 ssh_send_verstring(ssh, "SSH-", NULL);
3510 * loghost, if configured, overrides realhost.
3514 *realhost = dupstr(loghost);
3521 * Throttle or unthrottle the SSH connection.
3523 static void ssh_throttle_conn(Ssh ssh, int adjust)
3525 int old_count = ssh->conn_throttle_count;
3526 ssh->conn_throttle_count += adjust;
3527 assert(ssh->conn_throttle_count >= 0);
3528 if (ssh->conn_throttle_count && !old_count) {
3529 ssh_set_frozen(ssh, 1);
3530 } else if (!ssh->conn_throttle_count && old_count) {
3531 ssh_set_frozen(ssh, 0);
3536 * Throttle or unthrottle _all_ local data streams (for when sends
3537 * on the SSH connection itself back up).
3539 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3542 struct ssh_channel *c;
3544 if (enable == ssh->throttled_all)
3546 ssh->throttled_all = enable;
3547 ssh->overall_bufsize = bufsize;
3550 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3552 case CHAN_MAINSESSION:
3554 * This is treated separately, outside the switch.
3558 x11_override_throttle(c->u.x11.xconn, enable);
3561 /* Agent channels require no buffer management. */
3564 pfd_override_throttle(c->u.pfd.pf, enable);
3570 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3572 Ssh ssh = (Ssh) sshv;
3574 ssh->agent_response = reply;
3575 ssh->agent_response_len = replylen;
3577 if (ssh->version == 1)
3578 do_ssh1_login(ssh, NULL, -1, NULL);
3580 do_ssh2_authconn(ssh, NULL, -1, NULL);
3583 static void ssh_dialog_callback(void *sshv, int ret)
3585 Ssh ssh = (Ssh) sshv;
3587 ssh->user_response = ret;
3589 if (ssh->version == 1)
3590 do_ssh1_login(ssh, NULL, -1, NULL);
3592 do_ssh2_transport(ssh, NULL, -1, NULL);
3595 * This may have unfrozen the SSH connection, so do a
3598 ssh_process_queued_incoming_data(ssh);
3601 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3603 struct ssh_channel *c = (struct ssh_channel *)cv;
3605 void *sentreply = reply;
3607 c->u.a.outstanding_requests--;
3609 /* Fake SSH_AGENT_FAILURE. */
3610 sentreply = "\0\0\0\1\5";
3613 if (ssh->version == 2) {
3614 ssh2_add_channel_data(c, sentreply, replylen);
3617 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3618 PKT_INT, c->remoteid,
3620 PKT_DATA, sentreply, replylen,
3626 * If we've already seen an incoming EOF but haven't sent an
3627 * outgoing one, this may be the moment to send it.
3629 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3630 sshfwd_write_eof(c);
3634 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3635 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3636 * => log `wire_reason'.
3638 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3639 int code, int clean_exit)
3643 client_reason = wire_reason;
3645 error = dupprintf("Disconnected: %s", client_reason);
3647 error = dupstr("Disconnected");
3649 if (ssh->version == 1) {
3650 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3652 } else if (ssh->version == 2) {
3653 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3654 ssh2_pkt_adduint32(pktout, code);
3655 ssh2_pkt_addstring(pktout, wire_reason);
3656 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3657 ssh2_pkt_send_noqueue(ssh, pktout);
3660 ssh->close_expected = TRUE;
3661 ssh->clean_exit = clean_exit;
3662 ssh_closing((Plug)ssh, error, 0, 0);
3667 * Handle the key exchange and user authentication phases.
3669 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3670 struct Packet *pktin)
3673 unsigned char cookie[8], *ptr;
3674 struct MD5Context md5c;
3675 struct do_ssh1_login_state {
3678 unsigned char *rsabuf, *keystr1, *keystr2;
3679 unsigned long supported_ciphers_mask, supported_auths_mask;
3680 int tried_publickey, tried_agent;
3681 int tis_auth_refused, ccard_auth_refused;
3682 unsigned char session_id[16];
3684 void *publickey_blob;
3685 int publickey_bloblen;
3686 char *publickey_comment;
3687 int publickey_encrypted;
3688 prompts_t *cur_prompt;
3691 unsigned char request[5], *response, *p;
3701 struct RSAKey servkey, hostkey;
3703 crState(do_ssh1_login_state);
3710 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3711 bombout(("Public key packet not received"));
3715 logevent("Received public keys");
3717 ptr = ssh_pkt_getdata(pktin, 8);
3719 bombout(("SSH-1 public key packet stopped before random cookie"));
3722 memcpy(cookie, ptr, 8);
3724 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3725 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3726 bombout(("Failed to read SSH-1 public keys from public key packet"));
3731 * Log the host key fingerprint.
3735 logevent("Host key fingerprint is:");
3736 strcpy(logmsg, " ");
3737 s->hostkey.comment = NULL;
3738 rsa_fingerprint(logmsg + strlen(logmsg),
3739 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3743 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3744 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3745 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3746 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3747 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3749 ssh->v1_local_protoflags =
3750 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3751 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3754 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3755 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3756 MD5Update(&md5c, cookie, 8);
3757 MD5Final(s->session_id, &md5c);
3759 for (i = 0; i < 32; i++)
3760 ssh->session_key[i] = random_byte();
3763 * Verify that the `bits' and `bytes' parameters match.
3765 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3766 s->servkey.bits > s->servkey.bytes * 8) {
3767 bombout(("SSH-1 public keys were badly formatted"));
3771 s->len = (s->hostkey.bytes > s->servkey.bytes ?
3772 s->hostkey.bytes : s->servkey.bytes);
3774 s->rsabuf = snewn(s->len, unsigned char);
3777 * Verify the host key.
3781 * First format the key into a string.
3783 int len = rsastr_len(&s->hostkey);
3784 char fingerprint[100];
3785 char *keystr = snewn(len, char);
3786 rsastr_fmt(keystr, &s->hostkey);
3787 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
3789 ssh_set_frozen(ssh, 1);
3790 s->dlgret = verify_ssh_host_key(ssh->frontend,
3791 ssh->savedhost, ssh->savedport,
3792 "rsa", keystr, fingerprint,
3793 ssh_dialog_callback, ssh);
3795 if (s->dlgret < 0) {
3799 bombout(("Unexpected data from server while waiting"
3800 " for user host key response"));
3803 } while (pktin || inlen > 0);
3804 s->dlgret = ssh->user_response;
3806 ssh_set_frozen(ssh, 0);
3808 if (s->dlgret == 0) {
3809 ssh_disconnect(ssh, "User aborted at host key verification",
3815 for (i = 0; i < 32; i++) {
3816 s->rsabuf[i] = ssh->session_key[i];
3818 s->rsabuf[i] ^= s->session_id[i];
3821 if (s->hostkey.bytes > s->servkey.bytes) {
3822 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
3824 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
3826 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
3828 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
3831 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3835 logevent("Encrypted session key");
3838 int cipher_chosen = 0, warn = 0;
3839 char *cipher_string = NULL;
3841 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3842 int next_cipher = conf_get_int_int(ssh->conf,
3843 CONF_ssh_cipherlist, i);
3844 if (next_cipher == CIPHER_WARN) {
3845 /* If/when we choose a cipher, warn about it */
3847 } else if (next_cipher == CIPHER_AES) {
3848 /* XXX Probably don't need to mention this. */
3849 logevent("AES not supported in SSH-1, skipping");
3851 switch (next_cipher) {
3852 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3853 cipher_string = "3DES"; break;
3854 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3855 cipher_string = "Blowfish"; break;
3856 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3857 cipher_string = "single-DES"; break;
3859 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3863 if (!cipher_chosen) {
3864 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3865 bombout(("Server violates SSH-1 protocol by not "
3866 "supporting 3DES encryption"));
3868 /* shouldn't happen */
3869 bombout(("No supported ciphers found"));
3873 /* Warn about chosen cipher if necessary. */
3875 ssh_set_frozen(ssh, 1);
3876 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3877 ssh_dialog_callback, ssh);
3878 if (s->dlgret < 0) {
3882 bombout(("Unexpected data from server while waiting"
3883 " for user response"));
3886 } while (pktin || inlen > 0);
3887 s->dlgret = ssh->user_response;
3889 ssh_set_frozen(ssh, 0);
3890 if (s->dlgret == 0) {
3891 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3898 switch (s->cipher_type) {
3899 case SSH_CIPHER_3DES:
3900 logevent("Using 3DES encryption");
3902 case SSH_CIPHER_DES:
3903 logevent("Using single-DES encryption");
3905 case SSH_CIPHER_BLOWFISH:
3906 logevent("Using Blowfish encryption");
3910 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3911 PKT_CHAR, s->cipher_type,
3912 PKT_DATA, cookie, 8,
3913 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3914 PKT_DATA, s->rsabuf, s->len,
3915 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3917 logevent("Trying to enable encryption...");
3921 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3922 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3924 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3925 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
3926 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
3928 ssh->crcda_ctx = crcda_make_context();
3929 logevent("Installing CRC compensation attack detector");
3931 if (s->servkey.modulus) {
3932 sfree(s->servkey.modulus);
3933 s->servkey.modulus = NULL;
3935 if (s->servkey.exponent) {
3936 sfree(s->servkey.exponent);
3937 s->servkey.exponent = NULL;
3939 if (s->hostkey.modulus) {
3940 sfree(s->hostkey.modulus);
3941 s->hostkey.modulus = NULL;
3943 if (s->hostkey.exponent) {
3944 sfree(s->hostkey.exponent);
3945 s->hostkey.exponent = NULL;
3949 if (pktin->type != SSH1_SMSG_SUCCESS) {
3950 bombout(("Encryption not successfully enabled"));
3954 logevent("Successfully started encryption");
3956 fflush(stdout); /* FIXME eh? */
3958 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
3959 int ret; /* need not be kept over crReturn */
3960 s->cur_prompt = new_prompts(ssh->frontend);
3961 s->cur_prompt->to_server = TRUE;
3962 s->cur_prompt->name = dupstr("SSH login name");
3963 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
3964 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3967 crWaitUntil(!pktin);
3968 ret = get_userpass_input(s->cur_prompt, in, inlen);
3973 * Failed to get a username. Terminate.
3975 free_prompts(s->cur_prompt);
3976 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3979 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
3980 free_prompts(s->cur_prompt);
3983 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
3985 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
3987 if (flags & FLAG_INTERACTIVE &&
3988 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3989 c_write_str(ssh, userlog);
3990 c_write_str(ssh, "\r\n");
3998 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
3999 /* We must not attempt PK auth. Pretend we've already tried it. */
4000 s->tried_publickey = s->tried_agent = 1;
4002 s->tried_publickey = s->tried_agent = 0;
4004 s->tis_auth_refused = s->ccard_auth_refused = 0;
4006 * Load the public half of any configured keyfile for later use.
4008 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4009 if (!filename_is_null(s->keyfile)) {
4011 logeventf(ssh, "Reading private key file \"%.150s\"",
4012 filename_to_str(s->keyfile));
4013 keytype = key_type(s->keyfile);
4014 if (keytype == SSH_KEYTYPE_SSH1) {
4016 if (rsakey_pubblob(s->keyfile,
4017 &s->publickey_blob, &s->publickey_bloblen,
4018 &s->publickey_comment, &error)) {
4019 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
4023 logeventf(ssh, "Unable to load private key (%s)", error);
4024 msgbuf = dupprintf("Unable to load private key file "
4025 "\"%.150s\" (%s)\r\n",
4026 filename_to_str(s->keyfile),
4028 c_write_str(ssh, msgbuf);
4030 s->publickey_blob = NULL;
4034 logeventf(ssh, "Unable to use this key file (%s)",
4035 key_type_to_str(keytype));
4036 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4038 filename_to_str(s->keyfile),
4039 key_type_to_str(keytype));
4040 c_write_str(ssh, msgbuf);
4042 s->publickey_blob = NULL;
4045 s->publickey_blob = NULL;
4047 while (pktin->type == SSH1_SMSG_FAILURE) {
4048 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4050 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4052 * Attempt RSA authentication using Pageant.
4058 logevent("Pageant is running. Requesting keys.");
4060 /* Request the keys held by the agent. */
4061 PUT_32BIT(s->request, 1);
4062 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4063 if (!agent_query(s->request, 5, &r, &s->responselen,
4064 ssh_agent_callback, ssh)) {
4068 bombout(("Unexpected data from server while waiting"
4069 " for agent response"));
4072 } while (pktin || inlen > 0);
4073 r = ssh->agent_response;
4074 s->responselen = ssh->agent_response_len;
4076 s->response = (unsigned char *) r;
4077 if (s->response && s->responselen >= 5 &&
4078 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4079 s->p = s->response + 5;
4080 s->nkeys = toint(GET_32BIT(s->p));
4082 logeventf(ssh, "Pageant reported negative key count %d",
4087 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4088 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4089 unsigned char *pkblob = s->p;
4093 do { /* do while (0) to make breaking easy */
4094 n = ssh1_read_bignum
4095 (s->p, toint(s->responselen-(s->p-s->response)),
4100 n = ssh1_read_bignum
4101 (s->p, toint(s->responselen-(s->p-s->response)),
4106 if (s->responselen - (s->p-s->response) < 4)
4108 s->commentlen = toint(GET_32BIT(s->p));
4110 if (s->commentlen < 0 ||
4111 toint(s->responselen - (s->p-s->response)) <
4114 s->commentp = (char *)s->p;
4115 s->p += s->commentlen;
4119 logevent("Pageant key list packet was truncated");
4123 if (s->publickey_blob) {
4124 if (!memcmp(pkblob, s->publickey_blob,
4125 s->publickey_bloblen)) {
4126 logeventf(ssh, "Pageant key #%d matches "
4127 "configured key file", s->keyi);
4128 s->tried_publickey = 1;
4130 /* Skip non-configured key */
4133 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4134 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4135 PKT_BIGNUM, s->key.modulus, PKT_END);
4137 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4138 logevent("Key refused");
4141 logevent("Received RSA challenge");
4142 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4143 bombout(("Server's RSA challenge was badly formatted"));
4148 char *agentreq, *q, *ret;
4151 len = 1 + 4; /* message type, bit count */
4152 len += ssh1_bignum_length(s->key.exponent);
4153 len += ssh1_bignum_length(s->key.modulus);
4154 len += ssh1_bignum_length(s->challenge);
4155 len += 16; /* session id */
4156 len += 4; /* response format */
4157 agentreq = snewn(4 + len, char);
4158 PUT_32BIT(agentreq, len);
4160 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4161 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4163 q += ssh1_write_bignum(q, s->key.exponent);
4164 q += ssh1_write_bignum(q, s->key.modulus);
4165 q += ssh1_write_bignum(q, s->challenge);
4166 memcpy(q, s->session_id, 16);
4168 PUT_32BIT(q, 1); /* response format */
4169 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4170 ssh_agent_callback, ssh)) {
4175 bombout(("Unexpected data from server"
4176 " while waiting for agent"
4180 } while (pktin || inlen > 0);
4181 vret = ssh->agent_response;
4182 retlen = ssh->agent_response_len;
4187 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4188 logevent("Sending Pageant's response");
4189 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4190 PKT_DATA, ret + 5, 16,
4194 if (pktin->type == SSH1_SMSG_SUCCESS) {
4196 ("Pageant's response accepted");
4197 if (flags & FLAG_VERBOSE) {
4198 c_write_str(ssh, "Authenticated using"
4200 c_write(ssh, s->commentp,
4202 c_write_str(ssh, "\" from agent\r\n");
4207 ("Pageant's response not accepted");
4210 ("Pageant failed to answer challenge");
4214 logevent("No reply received from Pageant");
4217 freebn(s->key.exponent);
4218 freebn(s->key.modulus);
4219 freebn(s->challenge);
4224 if (s->publickey_blob && !s->tried_publickey)
4225 logevent("Configured key file not in Pageant");
4227 logevent("Failed to get reply from Pageant");
4232 if (s->publickey_blob && !s->tried_publickey) {
4234 * Try public key authentication with the specified
4237 int got_passphrase; /* need not be kept over crReturn */
4238 if (flags & FLAG_VERBOSE)
4239 c_write_str(ssh, "Trying public key authentication.\r\n");
4240 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4241 logeventf(ssh, "Trying public key \"%s\"",
4242 filename_to_str(s->keyfile));
4243 s->tried_publickey = 1;
4244 got_passphrase = FALSE;
4245 while (!got_passphrase) {
4247 * Get a passphrase, if necessary.
4249 char *passphrase = NULL; /* only written after crReturn */
4251 if (!s->publickey_encrypted) {
4252 if (flags & FLAG_VERBOSE)
4253 c_write_str(ssh, "No passphrase required.\r\n");
4256 int ret; /* need not be kept over crReturn */
4257 s->cur_prompt = new_prompts(ssh->frontend);
4258 s->cur_prompt->to_server = FALSE;
4259 s->cur_prompt->name = dupstr("SSH key passphrase");
4260 add_prompt(s->cur_prompt,
4261 dupprintf("Passphrase for key \"%.100s\": ",
4262 s->publickey_comment), FALSE);
4263 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4266 crWaitUntil(!pktin);
4267 ret = get_userpass_input(s->cur_prompt, in, inlen);
4271 /* Failed to get a passphrase. Terminate. */
4272 free_prompts(s->cur_prompt);
4273 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4277 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4278 free_prompts(s->cur_prompt);
4281 * Try decrypting key with passphrase.
4283 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4284 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4287 smemclr(passphrase, strlen(passphrase));
4291 /* Correct passphrase. */
4292 got_passphrase = TRUE;
4293 } else if (ret == 0) {
4294 c_write_str(ssh, "Couldn't load private key from ");
4295 c_write_str(ssh, filename_to_str(s->keyfile));
4296 c_write_str(ssh, " (");
4297 c_write_str(ssh, error);
4298 c_write_str(ssh, ").\r\n");
4299 got_passphrase = FALSE;
4300 break; /* go and try something else */
4301 } else if (ret == -1) {
4302 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4303 got_passphrase = FALSE;
4306 assert(0 && "unexpected return from loadrsakey()");
4307 got_passphrase = FALSE; /* placate optimisers */
4311 if (got_passphrase) {
4314 * Send a public key attempt.
4316 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4317 PKT_BIGNUM, s->key.modulus, PKT_END);
4320 if (pktin->type == SSH1_SMSG_FAILURE) {
4321 c_write_str(ssh, "Server refused our public key.\r\n");
4322 continue; /* go and try something else */
4324 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4325 bombout(("Bizarre response to offer of public key"));
4331 unsigned char buffer[32];
4332 Bignum challenge, response;
4334 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4335 bombout(("Server's RSA challenge was badly formatted"));
4338 response = rsadecrypt(challenge, &s->key);
4339 freebn(s->key.private_exponent);/* burn the evidence */
4341 for (i = 0; i < 32; i++) {
4342 buffer[i] = bignum_byte(response, 31 - i);
4346 MD5Update(&md5c, buffer, 32);
4347 MD5Update(&md5c, s->session_id, 16);
4348 MD5Final(buffer, &md5c);
4350 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4351 PKT_DATA, buffer, 16, PKT_END);
4358 if (pktin->type == SSH1_SMSG_FAILURE) {
4359 if (flags & FLAG_VERBOSE)
4360 c_write_str(ssh, "Failed to authenticate with"
4361 " our public key.\r\n");
4362 continue; /* go and try something else */
4363 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4364 bombout(("Bizarre response to RSA authentication response"));
4368 break; /* we're through! */
4374 * Otherwise, try various forms of password-like authentication.
4376 s->cur_prompt = new_prompts(ssh->frontend);
4378 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4379 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4380 !s->tis_auth_refused) {
4381 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4382 logevent("Requested TIS authentication");
4383 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4385 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4386 logevent("TIS authentication declined");
4387 if (flags & FLAG_INTERACTIVE)
4388 c_write_str(ssh, "TIS authentication refused.\r\n");
4389 s->tis_auth_refused = 1;
4394 char *instr_suf, *prompt;
4396 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4398 bombout(("TIS challenge packet was badly formed"));
4401 logevent("Received TIS challenge");
4402 s->cur_prompt->to_server = TRUE;
4403 s->cur_prompt->name = dupstr("SSH TIS authentication");
4404 /* Prompt heuristic comes from OpenSSH */
4405 if (memchr(challenge, '\n', challengelen)) {
4406 instr_suf = dupstr("");
4407 prompt = dupprintf("%.*s", challengelen, challenge);
4409 instr_suf = dupprintf("%.*s", challengelen, challenge);
4410 prompt = dupstr("Response: ");
4412 s->cur_prompt->instruction =
4413 dupprintf("Using TIS authentication.%s%s",
4414 (*instr_suf) ? "\n" : "",
4416 s->cur_prompt->instr_reqd = TRUE;
4417 add_prompt(s->cur_prompt, prompt, FALSE);
4421 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4422 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4423 !s->ccard_auth_refused) {
4424 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4425 logevent("Requested CryptoCard authentication");
4426 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4428 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4429 logevent("CryptoCard authentication declined");
4430 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4431 s->ccard_auth_refused = 1;
4436 char *instr_suf, *prompt;
4438 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4440 bombout(("CryptoCard challenge packet was badly formed"));
4443 logevent("Received CryptoCard challenge");
4444 s->cur_prompt->to_server = TRUE;
4445 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4446 s->cur_prompt->name_reqd = FALSE;
4447 /* Prompt heuristic comes from OpenSSH */
4448 if (memchr(challenge, '\n', challengelen)) {
4449 instr_suf = dupstr("");
4450 prompt = dupprintf("%.*s", challengelen, challenge);
4452 instr_suf = dupprintf("%.*s", challengelen, challenge);
4453 prompt = dupstr("Response: ");
4455 s->cur_prompt->instruction =
4456 dupprintf("Using CryptoCard authentication.%s%s",
4457 (*instr_suf) ? "\n" : "",
4459 s->cur_prompt->instr_reqd = TRUE;
4460 add_prompt(s->cur_prompt, prompt, FALSE);
4464 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4465 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4466 bombout(("No supported authentication methods available"));
4469 s->cur_prompt->to_server = TRUE;
4470 s->cur_prompt->name = dupstr("SSH password");
4471 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4472 ssh->username, ssh->savedhost),
4477 * Show password prompt, having first obtained it via a TIS
4478 * or CryptoCard exchange if we're doing TIS or CryptoCard
4482 int ret; /* need not be kept over crReturn */
4483 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4486 crWaitUntil(!pktin);
4487 ret = get_userpass_input(s->cur_prompt, in, inlen);
4492 * Failed to get a password (for example
4493 * because one was supplied on the command line
4494 * which has already failed to work). Terminate.
4496 free_prompts(s->cur_prompt);
4497 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4502 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4504 * Defence against traffic analysis: we send a
4505 * whole bunch of packets containing strings of
4506 * different lengths. One of these strings is the
4507 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4508 * The others are all random data in
4509 * SSH1_MSG_IGNORE packets. This way a passive
4510 * listener can't tell which is the password, and
4511 * hence can't deduce the password length.
4513 * Anybody with a password length greater than 16
4514 * bytes is going to have enough entropy in their
4515 * password that a listener won't find it _that_
4516 * much help to know how long it is. So what we'll
4519 * - if password length < 16, we send 15 packets
4520 * containing string lengths 1 through 15
4522 * - otherwise, we let N be the nearest multiple
4523 * of 8 below the password length, and send 8
4524 * packets containing string lengths N through
4525 * N+7. This won't obscure the order of
4526 * magnitude of the password length, but it will
4527 * introduce a bit of extra uncertainty.
4529 * A few servers can't deal with SSH1_MSG_IGNORE, at
4530 * least in this context. For these servers, we need
4531 * an alternative defence. We make use of the fact
4532 * that the password is interpreted as a C string:
4533 * so we can append a NUL, then some random data.
4535 * A few servers can deal with neither SSH1_MSG_IGNORE
4536 * here _nor_ a padded password string.
4537 * For these servers we are left with no defences
4538 * against password length sniffing.
4540 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4541 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4543 * The server can deal with SSH1_MSG_IGNORE, so
4544 * we can use the primary defence.
4546 int bottom, top, pwlen, i;
4549 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4551 bottom = 0; /* zero length passwords are OK! :-) */
4554 bottom = pwlen & ~7;
4558 assert(pwlen >= bottom && pwlen <= top);
4560 randomstr = snewn(top + 1, char);
4562 for (i = bottom; i <= top; i++) {
4564 defer_packet(ssh, s->pwpkt_type,
4565 PKT_STR,s->cur_prompt->prompts[0]->result,
4568 for (j = 0; j < i; j++) {
4570 randomstr[j] = random_byte();
4571 } while (randomstr[j] == '\0');
4573 randomstr[i] = '\0';
4574 defer_packet(ssh, SSH1_MSG_IGNORE,
4575 PKT_STR, randomstr, PKT_END);
4578 logevent("Sending password with camouflage packets");
4579 ssh_pkt_defersend(ssh);
4582 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4584 * The server can't deal with SSH1_MSG_IGNORE
4585 * but can deal with padded passwords, so we
4586 * can use the secondary defence.
4592 len = strlen(s->cur_prompt->prompts[0]->result);
4593 if (len < sizeof(string)) {
4595 strcpy(string, s->cur_prompt->prompts[0]->result);
4596 len++; /* cover the zero byte */
4597 while (len < sizeof(string)) {
4598 string[len++] = (char) random_byte();
4601 ss = s->cur_prompt->prompts[0]->result;
4603 logevent("Sending length-padded password");
4604 send_packet(ssh, s->pwpkt_type,
4605 PKT_INT, len, PKT_DATA, ss, len,
4609 * The server is believed unable to cope with
4610 * any of our password camouflage methods.
4613 len = strlen(s->cur_prompt->prompts[0]->result);
4614 logevent("Sending unpadded password");
4615 send_packet(ssh, s->pwpkt_type,
4617 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4621 send_packet(ssh, s->pwpkt_type,
4622 PKT_STR, s->cur_prompt->prompts[0]->result,
4625 logevent("Sent password");
4626 free_prompts(s->cur_prompt);
4628 if (pktin->type == SSH1_SMSG_FAILURE) {
4629 if (flags & FLAG_VERBOSE)
4630 c_write_str(ssh, "Access denied\r\n");
4631 logevent("Authentication refused");
4632 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4633 bombout(("Strange packet received, type %d", pktin->type));
4639 if (s->publickey_blob) {
4640 sfree(s->publickey_blob);
4641 sfree(s->publickey_comment);
4644 logevent("Authentication successful");
4649 static void ssh_channel_try_eof(struct ssh_channel *c)
4652 assert(c->pending_eof); /* precondition for calling us */
4654 return; /* can't close: not even opened yet */
4655 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4656 return; /* can't send EOF: pending outgoing data */
4658 c->pending_eof = FALSE; /* we're about to send it */
4659 if (ssh->version == 1) {
4660 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4662 c->closes |= CLOSES_SENT_EOF;
4664 struct Packet *pktout;
4665 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4666 ssh2_pkt_adduint32(pktout, c->remoteid);
4667 ssh2_pkt_send(ssh, pktout);
4668 c->closes |= CLOSES_SENT_EOF;
4669 ssh2_channel_check_close(c);
4673 Conf *sshfwd_get_conf(struct ssh_channel *c)
4679 void sshfwd_write_eof(struct ssh_channel *c)
4683 if (ssh->state == SSH_STATE_CLOSED)
4686 if (c->closes & CLOSES_SENT_EOF)
4689 c->pending_eof = TRUE;
4690 ssh_channel_try_eof(c);
4693 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4697 if (ssh->state == SSH_STATE_CLOSED)
4702 x11_close(c->u.x11.xconn);
4703 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4707 case CHAN_SOCKDATA_DORMANT:
4708 pfd_close(c->u.pfd.pf);
4709 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4712 c->type = CHAN_ZOMBIE;
4713 c->pending_eof = FALSE; /* this will confuse a zombie channel */
4715 ssh2_channel_check_close(c);
4718 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4722 if (ssh->state == SSH_STATE_CLOSED)
4725 if (ssh->version == 1) {
4726 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4727 PKT_INT, c->remoteid,
4728 PKT_INT, len, PKT_DATA, buf, len,
4731 * In SSH-1 we can return 0 here - implying that forwarded
4732 * connections are never individually throttled - because
4733 * the only circumstance that can cause throttling will be
4734 * the whole SSH connection backing up, in which case
4735 * _everything_ will be throttled as a whole.
4739 ssh2_add_channel_data(c, buf, len);
4740 return ssh2_try_send(c);
4744 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4749 if (ssh->state == SSH_STATE_CLOSED)
4752 if (ssh->version == 1) {
4753 buflimit = SSH1_BUFFER_LIMIT;
4755 buflimit = c->v.v2.locmaxwin;
4756 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4758 if (c->throttling_conn && bufsize <= buflimit) {
4759 c->throttling_conn = 0;
4760 ssh_throttle_conn(ssh, -1);
4764 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4766 struct queued_handler *qh = ssh->qhead;
4770 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4773 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4774 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4777 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4778 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4782 ssh->qhead = qh->next;
4784 if (ssh->qhead->msg1 > 0) {
4785 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4786 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4788 if (ssh->qhead->msg2 > 0) {
4789 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4790 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4793 ssh->qhead = ssh->qtail = NULL;
4796 qh->handler(ssh, pktin, qh->ctx);
4801 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4802 chandler_fn_t handler, void *ctx)
4804 struct queued_handler *qh;
4806 qh = snew(struct queued_handler);
4809 qh->handler = handler;
4813 if (ssh->qtail == NULL) {
4817 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4818 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4821 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4822 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4825 ssh->qtail->next = qh;
4830 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4832 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4834 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4835 SSH2_MSG_REQUEST_SUCCESS)) {
4836 logeventf(ssh, "Remote port forwarding from %s enabled",
4839 logeventf(ssh, "Remote port forwarding from %s refused",
4842 rpf = del234(ssh->rportfwds, pf);
4844 pf->pfrec->remote = NULL;
4849 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
4852 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
4855 pf->share_ctx = share_ctx;
4856 pf->shost = dupstr(shost);
4858 pf->sportdesc = NULL;
4859 if (!ssh->rportfwds) {
4860 assert(ssh->version == 2);
4861 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4863 if (add234(ssh->rportfwds, pf) != pf) {
4871 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
4874 share_got_pkt_from_server(ctx, pktin->type,
4875 pktin->body, pktin->length);
4878 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
4880 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
4881 ssh_sharing_global_request_response, share_ctx);
4884 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4886 struct ssh_portfwd *epf;
4890 if (!ssh->portfwds) {
4891 ssh->portfwds = newtree234(ssh_portcmp);
4894 * Go through the existing port forwardings and tag them
4895 * with status==DESTROY. Any that we want to keep will be
4896 * re-enabled (status==KEEP) as we go through the
4897 * configuration and find out which bits are the same as
4900 struct ssh_portfwd *epf;
4902 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4903 epf->status = DESTROY;
4906 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4908 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4909 char *kp, *kp2, *vp, *vp2;
4910 char address_family, type;
4911 int sport,dport,sserv,dserv;
4912 char *sports, *dports, *saddr, *host;
4916 address_family = 'A';
4918 if (*kp == 'A' || *kp == '4' || *kp == '6')
4919 address_family = *kp++;
4920 if (*kp == 'L' || *kp == 'R')
4923 if ((kp2 = host_strchr(kp, ':')) != NULL) {
4925 * There's a colon in the middle of the source port
4926 * string, which means that the part before it is
4927 * actually a source address.
4929 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
4930 saddr = host_strduptrim(saddr_tmp);
4937 sport = atoi(sports);
4941 sport = net_service_lookup(sports);
4943 logeventf(ssh, "Service lookup failed for source"
4944 " port \"%s\"", sports);
4948 if (type == 'L' && !strcmp(val, "D")) {
4949 /* dynamic forwarding */
4956 /* ordinary forwarding */
4958 vp2 = vp + host_strcspn(vp, ":");
4959 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
4963 dport = atoi(dports);
4967 dport = net_service_lookup(dports);
4969 logeventf(ssh, "Service lookup failed for destination"
4970 " port \"%s\"", dports);
4975 if (sport && dport) {
4976 /* Set up a description of the source port. */
4977 struct ssh_portfwd *pfrec, *epfrec;
4979 pfrec = snew(struct ssh_portfwd);
4981 pfrec->saddr = saddr;
4982 pfrec->sserv = sserv ? dupstr(sports) : NULL;
4983 pfrec->sport = sport;
4984 pfrec->daddr = host;
4985 pfrec->dserv = dserv ? dupstr(dports) : NULL;
4986 pfrec->dport = dport;
4987 pfrec->local = NULL;
4988 pfrec->remote = NULL;
4989 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4990 address_family == '6' ? ADDRTYPE_IPV6 :
4993 epfrec = add234(ssh->portfwds, pfrec);
4994 if (epfrec != pfrec) {
4995 if (epfrec->status == DESTROY) {
4997 * We already have a port forwarding up and running
4998 * with precisely these parameters. Hence, no need
4999 * to do anything; simply re-tag the existing one
5002 epfrec->status = KEEP;
5005 * Anything else indicates that there was a duplicate
5006 * in our input, which we'll silently ignore.
5008 free_portfwd(pfrec);
5010 pfrec->status = CREATE;
5019 * Now go through and destroy any port forwardings which were
5022 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5023 if (epf->status == DESTROY) {
5026 message = dupprintf("%s port forwarding from %s%s%d",
5027 epf->type == 'L' ? "local" :
5028 epf->type == 'R' ? "remote" : "dynamic",
5029 epf->saddr ? epf->saddr : "",
5030 epf->saddr ? ":" : "",
5033 if (epf->type != 'D') {
5034 char *msg2 = dupprintf("%s to %s:%d", message,
5035 epf->daddr, epf->dport);
5040 logeventf(ssh, "Cancelling %s", message);
5043 /* epf->remote or epf->local may be NULL if setting up a
5044 * forwarding failed. */
5046 struct ssh_rportfwd *rpf = epf->remote;
5047 struct Packet *pktout;
5050 * Cancel the port forwarding at the server
5053 if (ssh->version == 1) {
5055 * We cannot cancel listening ports on the
5056 * server side in SSH-1! There's no message
5057 * to support it. Instead, we simply remove
5058 * the rportfwd record from the local end
5059 * so that any connections the server tries
5060 * to make on it are rejected.
5063 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5064 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5065 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5067 ssh2_pkt_addstring(pktout, epf->saddr);
5068 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5069 /* XXX: rport_acceptall may not represent
5070 * what was used to open the original connection,
5071 * since it's reconfigurable. */
5072 ssh2_pkt_addstring(pktout, "");
5074 ssh2_pkt_addstring(pktout, "localhost");
5076 ssh2_pkt_adduint32(pktout, epf->sport);
5077 ssh2_pkt_send(ssh, pktout);
5080 del234(ssh->rportfwds, rpf);
5082 } else if (epf->local) {
5083 pfl_terminate(epf->local);
5086 delpos234(ssh->portfwds, i);
5088 i--; /* so we don't skip one in the list */
5092 * And finally, set up any new port forwardings (status==CREATE).
5094 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5095 if (epf->status == CREATE) {
5096 char *sportdesc, *dportdesc;
5097 sportdesc = dupprintf("%s%s%s%s%d%s",
5098 epf->saddr ? epf->saddr : "",
5099 epf->saddr ? ":" : "",
5100 epf->sserv ? epf->sserv : "",
5101 epf->sserv ? "(" : "",
5103 epf->sserv ? ")" : "");
5104 if (epf->type == 'D') {
5107 dportdesc = dupprintf("%s:%s%s%d%s",
5109 epf->dserv ? epf->dserv : "",
5110 epf->dserv ? "(" : "",
5112 epf->dserv ? ")" : "");
5115 if (epf->type == 'L') {
5116 char *err = pfl_listen(epf->daddr, epf->dport,
5117 epf->saddr, epf->sport,
5118 ssh, conf, &epf->local,
5119 epf->addressfamily);
5121 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5122 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5123 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5124 sportdesc, dportdesc,
5125 err ? " failed: " : "", err ? err : "");
5128 } else if (epf->type == 'D') {
5129 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5130 ssh, conf, &epf->local,
5131 epf->addressfamily);
5133 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5134 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5135 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5137 err ? " failed: " : "", err ? err : "");
5142 struct ssh_rportfwd *pf;
5145 * Ensure the remote port forwardings tree exists.
5147 if (!ssh->rportfwds) {
5148 if (ssh->version == 1)
5149 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5151 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5154 pf = snew(struct ssh_rportfwd);
5155 pf->share_ctx = NULL;
5156 pf->dhost = dupstr(epf->daddr);
5157 pf->dport = epf->dport;
5159 pf->shost = dupstr(epf->saddr);
5160 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5161 pf->shost = dupstr("");
5163 pf->shost = dupstr("localhost");
5165 pf->sport = epf->sport;
5166 if (add234(ssh->rportfwds, pf) != pf) {
5167 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5168 epf->daddr, epf->dport);
5171 logeventf(ssh, "Requesting remote port %s"
5172 " forward to %s", sportdesc, dportdesc);
5174 pf->sportdesc = sportdesc;
5179 if (ssh->version == 1) {
5180 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5181 PKT_INT, epf->sport,
5182 PKT_STR, epf->daddr,
5183 PKT_INT, epf->dport,
5185 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5187 ssh_rportfwd_succfail, pf);
5189 struct Packet *pktout;
5190 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5191 ssh2_pkt_addstring(pktout, "tcpip-forward");
5192 ssh2_pkt_addbool(pktout, 1);/* want reply */
5193 ssh2_pkt_addstring(pktout, pf->shost);
5194 ssh2_pkt_adduint32(pktout, pf->sport);
5195 ssh2_pkt_send(ssh, pktout);
5197 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5198 SSH2_MSG_REQUEST_FAILURE,
5199 ssh_rportfwd_succfail, pf);
5208 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5211 int stringlen, bufsize;
5213 ssh_pkt_getstring(pktin, &string, &stringlen);
5214 if (string == NULL) {
5215 bombout(("Incoming terminal data packet was badly formed"));
5219 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5221 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5222 ssh->v1_stdout_throttling = 1;
5223 ssh_throttle_conn(ssh, +1);
5227 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5229 /* Remote side is trying to open a channel to talk to our
5230 * X-Server. Give them back a local channel number. */
5231 struct ssh_channel *c;
5232 int remoteid = ssh_pkt_getuint32(pktin);
5234 logevent("Received X11 connect request");
5235 /* Refuse if X11 forwarding is disabled. */
5236 if (!ssh->X11_fwd_enabled) {
5237 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5238 PKT_INT, remoteid, PKT_END);
5239 logevent("Rejected X11 connect request");
5241 c = snew(struct ssh_channel);
5244 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5245 c->remoteid = remoteid;
5246 c->halfopen = FALSE;
5247 c->localid = alloc_channel_id(ssh);
5249 c->pending_eof = FALSE;
5250 c->throttling_conn = 0;
5251 c->type = CHAN_X11; /* identify channel type */
5252 add234(ssh->channels, c);
5253 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5254 PKT_INT, c->remoteid, PKT_INT,
5255 c->localid, PKT_END);
5256 logevent("Opened X11 forward channel");
5260 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5262 /* Remote side is trying to open a channel to talk to our
5263 * agent. Give them back a local channel number. */
5264 struct ssh_channel *c;
5265 int remoteid = ssh_pkt_getuint32(pktin);
5267 /* Refuse if agent forwarding is disabled. */
5268 if (!ssh->agentfwd_enabled) {
5269 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5270 PKT_INT, remoteid, PKT_END);
5272 c = snew(struct ssh_channel);
5274 c->remoteid = remoteid;
5275 c->halfopen = FALSE;
5276 c->localid = alloc_channel_id(ssh);
5278 c->pending_eof = FALSE;
5279 c->throttling_conn = 0;
5280 c->type = CHAN_AGENT; /* identify channel type */
5281 c->u.a.lensofar = 0;
5282 c->u.a.message = NULL;
5283 c->u.a.outstanding_requests = 0;
5284 add234(ssh->channels, c);
5285 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5286 PKT_INT, c->remoteid, PKT_INT, c->localid,
5291 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5293 /* Remote side is trying to open a channel to talk to a
5294 * forwarded port. Give them back a local channel number. */
5295 struct ssh_rportfwd pf, *pfp;
5301 remoteid = ssh_pkt_getuint32(pktin);
5302 ssh_pkt_getstring(pktin, &host, &hostsize);
5303 port = ssh_pkt_getuint32(pktin);
5305 pf.dhost = dupprintf("%.*s", hostsize, host);
5307 pfp = find234(ssh->rportfwds, &pf, NULL);
5310 logeventf(ssh, "Rejected remote port open request for %s:%d",
5312 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5313 PKT_INT, remoteid, PKT_END);
5315 struct ssh_channel *c = snew(struct ssh_channel);
5318 logeventf(ssh, "Received remote port open request for %s:%d",
5320 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5321 c, ssh->conf, pfp->pfrec->addressfamily);
5323 logeventf(ssh, "Port open failed: %s", err);
5326 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5327 PKT_INT, remoteid, PKT_END);
5329 c->remoteid = remoteid;
5330 c->halfopen = FALSE;
5331 c->localid = alloc_channel_id(ssh);
5333 c->pending_eof = FALSE;
5334 c->throttling_conn = 0;
5335 c->type = CHAN_SOCKDATA; /* identify channel type */
5336 add234(ssh->channels, c);
5337 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5338 PKT_INT, c->remoteid, PKT_INT,
5339 c->localid, PKT_END);
5340 logevent("Forwarded port opened successfully");
5347 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5349 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5350 unsigned int localid = ssh_pkt_getuint32(pktin);
5351 struct ssh_channel *c;
5353 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5354 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5355 c->remoteid = localid;
5356 c->halfopen = FALSE;
5357 c->type = CHAN_SOCKDATA;
5358 c->throttling_conn = 0;
5359 pfd_confirm(c->u.pfd.pf);
5362 if (c && c->pending_eof) {
5364 * We have a pending close on this channel,
5365 * which we decided on before the server acked
5366 * the channel open. So now we know the
5367 * remoteid, we can close it again.
5369 ssh_channel_try_eof(c);
5373 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5375 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5376 struct ssh_channel *c;
5378 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5379 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5380 logevent("Forwarded connection refused by server");
5381 pfd_close(c->u.pfd.pf);
5382 del234(ssh->channels, c);
5387 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5389 /* Remote side closes a channel. */
5390 unsigned i = ssh_pkt_getuint32(pktin);
5391 struct ssh_channel *c;
5392 c = find234(ssh->channels, &i, ssh_channelfind);
5393 if (c && !c->halfopen) {
5395 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5396 !(c->closes & CLOSES_RCVD_EOF)) {
5398 * Received CHANNEL_CLOSE, which we translate into
5401 int send_close = FALSE;
5403 c->closes |= CLOSES_RCVD_EOF;
5408 x11_send_eof(c->u.x11.xconn);
5414 pfd_send_eof(c->u.pfd.pf);
5423 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5424 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5426 c->closes |= CLOSES_SENT_EOF;
5430 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5431 !(c->closes & CLOSES_RCVD_CLOSE)) {
5433 if (!(c->closes & CLOSES_SENT_EOF)) {
5434 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5435 " for which we never sent CHANNEL_CLOSE\n", i));
5438 c->closes |= CLOSES_RCVD_CLOSE;
5441 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5442 !(c->closes & CLOSES_SENT_CLOSE)) {
5443 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5444 PKT_INT, c->remoteid, PKT_END);
5445 c->closes |= CLOSES_SENT_CLOSE;
5448 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5449 ssh_channel_destroy(c);
5451 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5452 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5453 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5458 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5460 /* Data sent down one of our channels. */
5461 int i = ssh_pkt_getuint32(pktin);
5464 struct ssh_channel *c;
5466 ssh_pkt_getstring(pktin, &p, &len);
5468 c = find234(ssh->channels, &i, ssh_channelfind);
5473 bufsize = x11_send(c->u.x11.xconn, p, len);
5476 bufsize = pfd_send(c->u.pfd.pf, p, len);
5479 /* Data for an agent message. Buffer it. */
5481 if (c->u.a.lensofar < 4) {
5482 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5483 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5487 c->u.a.lensofar += l;
5489 if (c->u.a.lensofar == 4) {
5491 4 + GET_32BIT(c->u.a.msglen);
5492 c->u.a.message = snewn(c->u.a.totallen,
5494 memcpy(c->u.a.message, c->u.a.msglen, 4);
5496 if (c->u.a.lensofar >= 4 && len > 0) {
5498 min(c->u.a.totallen - c->u.a.lensofar,
5500 memcpy(c->u.a.message + c->u.a.lensofar, p,
5504 c->u.a.lensofar += l;
5506 if (c->u.a.lensofar == c->u.a.totallen) {
5509 c->u.a.outstanding_requests++;
5510 if (agent_query(c->u.a.message,
5513 ssh_agentf_callback, c))
5514 ssh_agentf_callback(c, reply, replylen);
5515 sfree(c->u.a.message);
5516 c->u.a.lensofar = 0;
5519 bufsize = 0; /* agent channels never back up */
5522 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5523 c->throttling_conn = 1;
5524 ssh_throttle_conn(ssh, +1);
5529 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5531 ssh->exitcode = ssh_pkt_getuint32(pktin);
5532 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5533 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5535 * In case `helpful' firewalls or proxies tack
5536 * extra human-readable text on the end of the
5537 * session which we might mistake for another
5538 * encrypted packet, we close the session once
5539 * we've sent EXIT_CONFIRMATION.
5541 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5544 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5545 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5547 struct Packet *pktout = (struct Packet *)data;
5549 unsigned int arg = 0;
5550 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5551 if (i == lenof(ssh_ttymodes)) return;
5552 switch (ssh_ttymodes[i].type) {
5554 arg = ssh_tty_parse_specchar(val);
5557 arg = ssh_tty_parse_boolean(val);
5560 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5561 ssh2_pkt_addbyte(pktout, arg);
5564 int ssh_agent_forwarding_permitted(Ssh ssh)
5566 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5569 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5570 struct Packet *pktin)
5572 crBegin(ssh->do_ssh1_connection_crstate);
5574 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5575 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5576 ssh1_smsg_stdout_stderr_data;
5578 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5579 ssh1_msg_channel_open_confirmation;
5580 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5581 ssh1_msg_channel_open_failure;
5582 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5583 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5584 ssh1_msg_channel_close;
5585 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5586 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5588 if (ssh_agent_forwarding_permitted(ssh)) {
5589 logevent("Requesting agent forwarding");
5590 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5594 if (pktin->type != SSH1_SMSG_SUCCESS
5595 && pktin->type != SSH1_SMSG_FAILURE) {
5596 bombout(("Protocol confusion"));
5598 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5599 logevent("Agent forwarding refused");
5601 logevent("Agent forwarding enabled");
5602 ssh->agentfwd_enabled = TRUE;
5603 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5607 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5609 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5611 if (!ssh->x11disp) {
5612 /* FIXME: return an error message from x11_setup_display */
5613 logevent("X11 forwarding not enabled: unable to"
5614 " initialise X display");
5616 ssh->x11auth = x11_invent_fake_auth
5617 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5618 ssh->x11auth->disp = ssh->x11disp;
5620 logevent("Requesting X11 forwarding");
5621 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5622 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5623 PKT_STR, ssh->x11auth->protoname,
5624 PKT_STR, ssh->x11auth->datastring,
5625 PKT_INT, ssh->x11disp->screennum,
5628 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5629 PKT_STR, ssh->x11auth->protoname,
5630 PKT_STR, ssh->x11auth->datastring,
5636 if (pktin->type != SSH1_SMSG_SUCCESS
5637 && pktin->type != SSH1_SMSG_FAILURE) {
5638 bombout(("Protocol confusion"));
5640 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5641 logevent("X11 forwarding refused");
5643 logevent("X11 forwarding enabled");
5644 ssh->X11_fwd_enabled = TRUE;
5645 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5650 ssh_setup_portfwd(ssh, ssh->conf);
5651 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5653 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5655 /* Unpick the terminal-speed string. */
5656 /* XXX perhaps we should allow no speeds to be sent. */
5657 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5658 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5659 /* Send the pty request. */
5660 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5661 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5662 ssh_pkt_adduint32(pkt, ssh->term_height);
5663 ssh_pkt_adduint32(pkt, ssh->term_width);
5664 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5665 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5666 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5667 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5668 ssh_pkt_adduint32(pkt, ssh->ispeed);
5669 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5670 ssh_pkt_adduint32(pkt, ssh->ospeed);
5671 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5673 ssh->state = SSH_STATE_INTERMED;
5677 if (pktin->type != SSH1_SMSG_SUCCESS
5678 && pktin->type != SSH1_SMSG_FAILURE) {
5679 bombout(("Protocol confusion"));
5681 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5682 c_write_str(ssh, "Server refused to allocate pty\r\n");
5683 ssh->editing = ssh->echoing = 1;
5685 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5686 ssh->ospeed, ssh->ispeed);
5687 ssh->got_pty = TRUE;
5690 ssh->editing = ssh->echoing = 1;
5693 if (conf_get_int(ssh->conf, CONF_compression)) {
5694 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5698 if (pktin->type != SSH1_SMSG_SUCCESS
5699 && pktin->type != SSH1_SMSG_FAILURE) {
5700 bombout(("Protocol confusion"));
5702 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5703 c_write_str(ssh, "Server refused to compress\r\n");
5705 logevent("Started compression");
5706 ssh->v1_compressing = TRUE;
5707 ssh->cs_comp_ctx = zlib_compress_init();
5708 logevent("Initialised zlib (RFC1950) compression");
5709 ssh->sc_comp_ctx = zlib_decompress_init();
5710 logevent("Initialised zlib (RFC1950) decompression");
5714 * Start the shell or command.
5716 * Special case: if the first-choice command is an SSH-2
5717 * subsystem (hence not usable here) and the second choice
5718 * exists, we fall straight back to that.
5721 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5723 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5724 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5725 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5726 ssh->fallback_cmd = TRUE;
5729 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5731 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5732 logevent("Started session");
5735 ssh->state = SSH_STATE_SESSION;
5736 if (ssh->size_needed)
5737 ssh_size(ssh, ssh->term_width, ssh->term_height);
5738 if (ssh->eof_needed)
5739 ssh_special(ssh, TS_EOF);
5742 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5744 ssh->channels = newtree234(ssh_channelcmp);
5748 * By this point, most incoming packets are already being
5749 * handled by the dispatch table, and we need only pay
5750 * attention to the unusual ones.
5755 if (pktin->type == SSH1_SMSG_SUCCESS) {
5756 /* may be from EXEC_SHELL on some servers */
5757 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5758 /* may be from EXEC_SHELL on some servers
5759 * if no pty is available or in other odd cases. Ignore */
5761 bombout(("Strange packet received: type %d", pktin->type));
5766 int len = min(inlen, 512);
5767 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5768 PKT_INT, len, PKT_DATA, in, len,
5780 * Handle the top-level SSH-2 protocol.
5782 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5787 ssh_pkt_getstring(pktin, &msg, &msglen);
5788 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5791 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5793 /* log reason code in disconnect message */
5797 ssh_pkt_getstring(pktin, &msg, &msglen);
5798 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5801 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5803 /* Do nothing, because we're ignoring it! Duhh. */
5806 static void ssh1_protocol_setup(Ssh ssh)
5811 * Most messages are handled by the coroutines.
5813 for (i = 0; i < 256; i++)
5814 ssh->packet_dispatch[i] = NULL;
5817 * These special message types we install handlers for.
5819 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5820 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5821 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5824 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5825 struct Packet *pktin)
5827 unsigned char *in=(unsigned char*)vin;
5828 if (ssh->state == SSH_STATE_CLOSED)
5831 if (pktin && ssh->packet_dispatch[pktin->type]) {
5832 ssh->packet_dispatch[pktin->type](ssh, pktin);
5836 if (!ssh->protocol_initial_phase_done) {
5837 if (do_ssh1_login(ssh, in, inlen, pktin))
5838 ssh->protocol_initial_phase_done = TRUE;
5843 do_ssh1_connection(ssh, in, inlen, pktin);
5847 * Utility routine for decoding comma-separated strings in KEXINIT.
5849 static int in_commasep_string(char *needle, char *haystack, int haylen)
5852 if (!needle || !haystack) /* protect against null pointers */
5854 needlen = strlen(needle);
5857 * Is it at the start of the string?
5859 if (haylen >= needlen && /* haystack is long enough */
5860 !memcmp(needle, haystack, needlen) && /* initial match */
5861 (haylen == needlen || haystack[needlen] == ',')
5862 /* either , or EOS follows */
5866 * If not, search for the next comma and resume after that.
5867 * If no comma found, terminate.
5869 while (haylen > 0 && *haystack != ',')
5870 haylen--, haystack++;
5873 haylen--, haystack++; /* skip over comma itself */
5878 * Similar routine for checking whether we have the first string in a list.
5880 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5883 if (!needle || !haystack) /* protect against null pointers */
5885 needlen = strlen(needle);
5887 * Is it at the start of the string?
5889 if (haylen >= needlen && /* haystack is long enough */
5890 !memcmp(needle, haystack, needlen) && /* initial match */
5891 (haylen == needlen || haystack[needlen] == ',')
5892 /* either , or EOS follows */
5900 * SSH-2 key creation method.
5901 * (Currently assumes 2 lots of any hash are sufficient to generate
5902 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5904 #define SSH2_MKKEY_ITERS (2)
5905 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5906 unsigned char *keyspace)
5908 const struct ssh_hash *h = ssh->kex->hash;
5910 /* First hlen bytes. */
5912 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5913 hash_mpint(h, s, K);
5914 h->bytes(s, H, h->hlen);
5915 h->bytes(s, &chr, 1);
5916 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5917 h->final(s, keyspace);
5918 /* Next hlen bytes. */
5920 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5921 hash_mpint(h, s, K);
5922 h->bytes(s, H, h->hlen);
5923 h->bytes(s, keyspace, h->hlen);
5924 h->final(s, keyspace + h->hlen);
5928 * Handle the SSH-2 transport layer.
5930 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
5931 struct Packet *pktin)
5933 unsigned char *in = (unsigned char *)vin;
5934 struct do_ssh2_transport_state {
5936 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
5937 Bignum p, g, e, f, K;
5940 int kex_init_value, kex_reply_value;
5941 const struct ssh_mac **maclist;
5943 const struct ssh2_cipher *cscipher_tobe;
5944 const struct ssh2_cipher *sccipher_tobe;
5945 const struct ssh_mac *csmac_tobe;
5946 const struct ssh_mac *scmac_tobe;
5947 const struct ssh_compress *cscomp_tobe;
5948 const struct ssh_compress *sccomp_tobe;
5949 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5950 int hostkeylen, siglen, rsakeylen;
5951 void *hkey; /* actual host key */
5952 void *rsakey; /* for RSA kex */
5953 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
5954 int n_preferred_kex;
5955 const struct ssh_kexes *preferred_kex[KEX_MAX];
5956 int n_preferred_ciphers;
5957 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5958 const struct ssh_compress *preferred_comp;
5959 int userauth_succeeded; /* for delayed compression */
5960 int pending_compression;
5961 int got_session_id, activated_authconn;
5962 struct Packet *pktout;
5967 crState(do_ssh2_transport_state);
5969 assert(!ssh->bare_connection);
5973 s->cscipher_tobe = s->sccipher_tobe = NULL;
5974 s->csmac_tobe = s->scmac_tobe = NULL;
5975 s->cscomp_tobe = s->sccomp_tobe = NULL;
5977 s->got_session_id = s->activated_authconn = FALSE;
5978 s->userauth_succeeded = FALSE;
5979 s->pending_compression = FALSE;
5982 * Be prepared to work around the buggy MAC problem.
5984 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5985 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5987 s->maclist = macs, s->nmacs = lenof(macs);
5990 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
5992 int i, j, k, commalist_started;
5995 * Set up the preferred key exchange. (NULL => warn below here)
5997 s->n_preferred_kex = 0;
5998 for (i = 0; i < KEX_MAX; i++) {
5999 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6001 s->preferred_kex[s->n_preferred_kex++] =
6002 &ssh_diffiehellman_gex;
6005 s->preferred_kex[s->n_preferred_kex++] =
6006 &ssh_diffiehellman_group14;
6009 s->preferred_kex[s->n_preferred_kex++] =
6010 &ssh_diffiehellman_group1;
6013 s->preferred_kex[s->n_preferred_kex++] =
6017 /* Flag for later. Don't bother if it's the last in
6019 if (i < KEX_MAX - 1) {
6020 s->preferred_kex[s->n_preferred_kex++] = NULL;
6027 * Set up the preferred ciphers. (NULL => warn below here)
6029 s->n_preferred_ciphers = 0;
6030 for (i = 0; i < CIPHER_MAX; i++) {
6031 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6032 case CIPHER_BLOWFISH:
6033 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6036 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6037 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6041 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6044 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6046 case CIPHER_ARCFOUR:
6047 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6050 /* Flag for later. Don't bother if it's the last in
6052 if (i < CIPHER_MAX - 1) {
6053 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6060 * Set up preferred compression.
6062 if (conf_get_int(ssh->conf, CONF_compression))
6063 s->preferred_comp = &ssh_zlib;
6065 s->preferred_comp = &ssh_comp_none;
6068 * Enable queueing of outgoing auth- or connection-layer
6069 * packets while we are in the middle of a key exchange.
6071 ssh->queueing = TRUE;
6074 * Flag that KEX is in progress.
6076 ssh->kex_in_progress = TRUE;
6079 * Construct and send our key exchange packet.
6081 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6082 for (i = 0; i < 16; i++)
6083 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6084 /* List key exchange algorithms. */
6085 ssh2_pkt_addstring_start(s->pktout);
6086 commalist_started = 0;
6087 for (i = 0; i < s->n_preferred_kex; i++) {
6088 const struct ssh_kexes *k = s->preferred_kex[i];
6089 if (!k) continue; /* warning flag */
6090 for (j = 0; j < k->nkexes; j++) {
6091 if (commalist_started)
6092 ssh2_pkt_addstring_str(s->pktout, ",");
6093 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
6094 commalist_started = 1;
6097 /* List server host key algorithms. */
6098 if (!s->got_session_id) {
6100 * In the first key exchange, we list all the algorithms
6101 * we're prepared to cope with.
6103 ssh2_pkt_addstring_start(s->pktout);
6104 for (i = 0; i < lenof(hostkey_algs); i++) {
6105 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
6106 if (i < lenof(hostkey_algs) - 1)
6107 ssh2_pkt_addstring_str(s->pktout, ",");
6111 * In subsequent key exchanges, we list only the kex
6112 * algorithm that was selected in the first key exchange,
6113 * so that we keep getting the same host key and hence
6114 * don't have to interrupt the user's session to ask for
6118 ssh2_pkt_addstring(s->pktout, ssh->hostkey->name);
6120 /* List encryption algorithms (client->server then server->client). */
6121 for (k = 0; k < 2; k++) {
6122 ssh2_pkt_addstring_start(s->pktout);
6123 commalist_started = 0;
6124 for (i = 0; i < s->n_preferred_ciphers; i++) {
6125 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6126 if (!c) continue; /* warning flag */
6127 for (j = 0; j < c->nciphers; j++) {
6128 if (commalist_started)
6129 ssh2_pkt_addstring_str(s->pktout, ",");
6130 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
6131 commalist_started = 1;
6135 /* List MAC algorithms (client->server then server->client). */
6136 for (j = 0; j < 2; j++) {
6137 ssh2_pkt_addstring_start(s->pktout);
6138 for (i = 0; i < s->nmacs; i++) {
6139 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
6140 if (i < s->nmacs - 1)
6141 ssh2_pkt_addstring_str(s->pktout, ",");
6144 /* List client->server compression algorithms,
6145 * then server->client compression algorithms. (We use the
6146 * same set twice.) */
6147 for (j = 0; j < 2; j++) {
6148 ssh2_pkt_addstring_start(s->pktout);
6149 assert(lenof(compressions) > 1);
6150 /* Prefer non-delayed versions */
6151 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
6152 /* We don't even list delayed versions of algorithms until
6153 * they're allowed to be used, to avoid a race. See the end of
6155 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6156 ssh2_pkt_addstring_str(s->pktout, ",");
6157 ssh2_pkt_addstring_str(s->pktout,
6158 s->preferred_comp->delayed_name);
6160 for (i = 0; i < lenof(compressions); i++) {
6161 const struct ssh_compress *c = compressions[i];
6162 if (c != s->preferred_comp) {
6163 ssh2_pkt_addstring_str(s->pktout, ",");
6164 ssh2_pkt_addstring_str(s->pktout, c->name);
6165 if (s->userauth_succeeded && c->delayed_name) {
6166 ssh2_pkt_addstring_str(s->pktout, ",");
6167 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
6172 /* List client->server languages. Empty list. */
6173 ssh2_pkt_addstring_start(s->pktout);
6174 /* List server->client languages. Empty list. */
6175 ssh2_pkt_addstring_start(s->pktout);
6176 /* First KEX packet does _not_ follow, because we're not that brave. */
6177 ssh2_pkt_addbool(s->pktout, FALSE);
6179 ssh2_pkt_adduint32(s->pktout, 0);
6182 s->our_kexinitlen = s->pktout->length - 5;
6183 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6184 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6186 ssh2_pkt_send_noqueue(ssh, s->pktout);
6189 crWaitUntilV(pktin);
6192 * Now examine the other side's KEXINIT to see what we're up
6196 char *str, *preferred;
6199 if (pktin->type != SSH2_MSG_KEXINIT) {
6200 bombout(("expected key exchange packet from server"));
6204 ssh->hostkey = NULL;
6205 s->cscipher_tobe = NULL;
6206 s->sccipher_tobe = NULL;
6207 s->csmac_tobe = NULL;
6208 s->scmac_tobe = NULL;
6209 s->cscomp_tobe = NULL;
6210 s->sccomp_tobe = NULL;
6211 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
6213 pktin->savedpos += 16; /* skip garbage cookie */
6214 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
6217 for (i = 0; i < s->n_preferred_kex; i++) {
6218 const struct ssh_kexes *k = s->preferred_kex[i];
6222 for (j = 0; j < k->nkexes; j++) {
6223 if (!preferred) preferred = k->list[j]->name;
6224 if (in_commasep_string(k->list[j]->name, str, len)) {
6225 ssh->kex = k->list[j];
6234 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
6235 str ? str : "(null)"));
6239 * Note that the server's guess is considered wrong if it doesn't match
6240 * the first algorithm in our list, even if it's still the algorithm
6243 s->guessok = first_in_commasep_string(preferred, str, len);
6244 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
6245 for (i = 0; i < lenof(hostkey_algs); i++) {
6246 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
6247 ssh->hostkey = hostkey_algs[i];
6251 if (!ssh->hostkey) {
6252 bombout(("Couldn't agree a host key algorithm (available: %s)",
6253 str ? str : "(null)"));
6257 s->guessok = s->guessok &&
6258 first_in_commasep_string(hostkey_algs[0]->name, str, len);
6259 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
6260 for (i = 0; i < s->n_preferred_ciphers; i++) {
6261 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6263 s->warn_cscipher = TRUE;
6265 for (j = 0; j < c->nciphers; j++) {
6266 if (in_commasep_string(c->list[j]->name, str, len)) {
6267 s->cscipher_tobe = c->list[j];
6272 if (s->cscipher_tobe)
6275 if (!s->cscipher_tobe) {
6276 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
6277 str ? str : "(null)"));
6281 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
6282 for (i = 0; i < s->n_preferred_ciphers; i++) {
6283 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6285 s->warn_sccipher = TRUE;
6287 for (j = 0; j < c->nciphers; j++) {
6288 if (in_commasep_string(c->list[j]->name, str, len)) {
6289 s->sccipher_tobe = c->list[j];
6294 if (s->sccipher_tobe)
6297 if (!s->sccipher_tobe) {
6298 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
6299 str ? str : "(null)"));
6303 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
6304 for (i = 0; i < s->nmacs; i++) {
6305 if (in_commasep_string(s->maclist[i]->name, str, len)) {
6306 s->csmac_tobe = s->maclist[i];
6310 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
6311 for (i = 0; i < s->nmacs; i++) {
6312 if (in_commasep_string(s->maclist[i]->name, str, len)) {
6313 s->scmac_tobe = s->maclist[i];
6317 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
6318 for (i = 0; i < lenof(compressions) + 1; i++) {
6319 const struct ssh_compress *c =
6320 i == 0 ? s->preferred_comp : compressions[i - 1];
6321 if (in_commasep_string(c->name, str, len)) {
6324 } else if (in_commasep_string(c->delayed_name, str, len)) {
6325 if (s->userauth_succeeded) {
6329 s->pending_compression = TRUE; /* try this later */
6333 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
6334 for (i = 0; i < lenof(compressions) + 1; i++) {
6335 const struct ssh_compress *c =
6336 i == 0 ? s->preferred_comp : compressions[i - 1];
6337 if (in_commasep_string(c->name, str, len)) {
6340 } else if (in_commasep_string(c->delayed_name, str, len)) {
6341 if (s->userauth_succeeded) {
6345 s->pending_compression = TRUE; /* try this later */
6349 if (s->pending_compression) {
6350 logevent("Server supports delayed compression; "
6351 "will try this later");
6353 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6354 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6355 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6357 ssh->exhash = ssh->kex->hash->init();
6358 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6359 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6360 hash_string(ssh->kex->hash, ssh->exhash,
6361 s->our_kexinit, s->our_kexinitlen);
6362 sfree(s->our_kexinit);
6363 /* Include the type byte in the hash of server's KEXINIT */
6364 hash_string(ssh->kex->hash, ssh->exhash,
6365 pktin->body - 1, pktin->length + 1);
6368 ssh_set_frozen(ssh, 1);
6369 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6371 ssh_dialog_callback, ssh);
6372 if (s->dlgret < 0) {
6376 bombout(("Unexpected data from server while"
6377 " waiting for user response"));
6380 } while (pktin || inlen > 0);
6381 s->dlgret = ssh->user_response;
6383 ssh_set_frozen(ssh, 0);
6384 if (s->dlgret == 0) {
6385 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6391 if (s->warn_cscipher) {
6392 ssh_set_frozen(ssh, 1);
6393 s->dlgret = askalg(ssh->frontend,
6394 "client-to-server cipher",
6395 s->cscipher_tobe->name,
6396 ssh_dialog_callback, ssh);
6397 if (s->dlgret < 0) {
6401 bombout(("Unexpected data from server while"
6402 " waiting for user response"));
6405 } while (pktin || inlen > 0);
6406 s->dlgret = ssh->user_response;
6408 ssh_set_frozen(ssh, 0);
6409 if (s->dlgret == 0) {
6410 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6416 if (s->warn_sccipher) {
6417 ssh_set_frozen(ssh, 1);
6418 s->dlgret = askalg(ssh->frontend,
6419 "server-to-client cipher",
6420 s->sccipher_tobe->name,
6421 ssh_dialog_callback, ssh);
6422 if (s->dlgret < 0) {
6426 bombout(("Unexpected data from server while"
6427 " waiting for user response"));
6430 } while (pktin || inlen > 0);
6431 s->dlgret = ssh->user_response;
6433 ssh_set_frozen(ssh, 0);
6434 if (s->dlgret == 0) {
6435 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6441 if (s->ignorepkt) /* first_kex_packet_follows */
6442 crWaitUntilV(pktin); /* Ignore packet */
6445 if (ssh->kex->main_type == KEXTYPE_DH) {
6447 * Work out the number of bits of key we will need from the
6448 * key exchange. We start with the maximum key length of
6454 csbits = s->cscipher_tobe->keylen;
6455 scbits = s->sccipher_tobe->keylen;
6456 s->nbits = (csbits > scbits ? csbits : scbits);
6458 /* The keys only have hlen-bit entropy, since they're based on
6459 * a hash. So cap the key size at hlen bits. */
6460 if (s->nbits > ssh->kex->hash->hlen * 8)
6461 s->nbits = ssh->kex->hash->hlen * 8;
6464 * If we're doing Diffie-Hellman group exchange, start by
6465 * requesting a group.
6467 if (!ssh->kex->pdata) {
6468 logevent("Doing Diffie-Hellman group exchange");
6469 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6471 * Work out how big a DH group we will need to allow that
6474 s->pbits = 512 << ((s->nbits - 1) / 64);
6475 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6476 ssh2_pkt_adduint32(s->pktout, s->pbits);
6477 ssh2_pkt_send_noqueue(ssh, s->pktout);
6479 crWaitUntilV(pktin);
6480 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6481 bombout(("expected key exchange group packet from server"));
6484 s->p = ssh2_pkt_getmp(pktin);
6485 s->g = ssh2_pkt_getmp(pktin);
6486 if (!s->p || !s->g) {
6487 bombout(("unable to read mp-ints from incoming group packet"));
6490 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6491 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6492 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6494 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6495 ssh->kex_ctx = dh_setup_group(ssh->kex);
6496 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6497 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6498 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6499 ssh->kex->groupname);
6502 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6503 ssh->kex->hash->text_name);
6505 * Now generate and send e for Diffie-Hellman.
6507 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6508 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6509 s->pktout = ssh2_pkt_init(s->kex_init_value);
6510 ssh2_pkt_addmp(s->pktout, s->e);
6511 ssh2_pkt_send_noqueue(ssh, s->pktout);
6513 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6514 crWaitUntilV(pktin);
6515 if (pktin->type != s->kex_reply_value) {
6516 bombout(("expected key exchange reply packet from server"));
6519 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6520 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6521 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6522 s->f = ssh2_pkt_getmp(pktin);
6524 bombout(("unable to parse key exchange reply packet"));
6527 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6529 s->K = dh_find_K(ssh->kex_ctx, s->f);
6531 /* We assume everything from now on will be quick, and it might
6532 * involve user interaction. */
6533 set_busy_status(ssh->frontend, BUSY_NOT);
6535 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6536 if (!ssh->kex->pdata) {
6537 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6538 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6539 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6541 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6542 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6544 dh_cleanup(ssh->kex_ctx);
6546 if (!ssh->kex->pdata) {
6551 logeventf(ssh, "Doing RSA key exchange with hash %s",
6552 ssh->kex->hash->text_name);
6553 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6555 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6558 crWaitUntilV(pktin);
6559 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6560 bombout(("expected RSA public key packet from server"));
6564 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6565 hash_string(ssh->kex->hash, ssh->exhash,
6566 s->hostkeydata, s->hostkeylen);
6567 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6571 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6572 s->rsakeydata = snewn(s->rsakeylen, char);
6573 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6576 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6578 sfree(s->rsakeydata);
6579 bombout(("unable to parse RSA public key from server"));
6583 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6586 * Next, set up a shared secret K, of precisely KLEN -
6587 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6588 * RSA key modulus and HLEN is the bit length of the hash
6592 int klen = ssh_rsakex_klen(s->rsakey);
6593 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6595 unsigned char *kstr1, *kstr2, *outstr;
6596 int kstr1len, kstr2len, outstrlen;
6598 s->K = bn_power_2(nbits - 1);
6600 for (i = 0; i < nbits; i++) {
6602 byte = random_byte();
6604 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6608 * Encode this as an mpint.
6610 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6611 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6612 PUT_32BIT(kstr2, kstr1len);
6613 memcpy(kstr2 + 4, kstr1, kstr1len);
6616 * Encrypt it with the given RSA key.
6618 outstrlen = (klen + 7) / 8;
6619 outstr = snewn(outstrlen, unsigned char);
6620 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6621 outstr, outstrlen, s->rsakey);
6624 * And send it off in a return packet.
6626 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6627 ssh2_pkt_addstring_start(s->pktout);
6628 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6629 ssh2_pkt_send_noqueue(ssh, s->pktout);
6631 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6638 ssh_rsakex_freekey(s->rsakey);
6640 crWaitUntilV(pktin);
6641 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6642 sfree(s->rsakeydata);
6643 bombout(("expected signature packet from server"));
6647 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6649 sfree(s->rsakeydata);
6652 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6653 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6654 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6656 ssh->kex_ctx = NULL;
6659 debug(("Exchange hash is:\n"));
6660 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6664 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6665 (char *)s->exchange_hash,
6666 ssh->kex->hash->hlen)) {
6667 bombout(("Server's host key did not match the signature supplied"));
6671 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6672 if (!s->got_session_id) {
6674 * Authenticate remote host: verify host key. (We've already
6675 * checked the signature of the exchange hash.)
6677 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6678 ssh_set_frozen(ssh, 1);
6679 s->dlgret = verify_ssh_host_key(ssh->frontend,
6680 ssh->savedhost, ssh->savedport,
6681 ssh->hostkey->keytype, s->keystr,
6683 ssh_dialog_callback, ssh);
6684 if (s->dlgret < 0) {
6688 bombout(("Unexpected data from server while waiting"
6689 " for user host key response"));
6692 } while (pktin || inlen > 0);
6693 s->dlgret = ssh->user_response;
6695 ssh_set_frozen(ssh, 0);
6696 if (s->dlgret == 0) {
6697 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6701 logevent("Host key fingerprint is:");
6702 logevent(s->fingerprint);
6703 sfree(s->fingerprint);
6705 * Save this host key, to check against the one presented in
6706 * subsequent rekeys.
6708 ssh->hostkey_str = s->keystr;
6711 * In a rekey, we never present an interactive host key
6712 * verification request to the user. Instead, we simply
6713 * enforce that the key we're seeing this time is identical to
6714 * the one we saw before.
6716 if (strcmp(ssh->hostkey_str, s->keystr)) {
6717 bombout(("Host key was different in repeat key exchange"));
6722 ssh->hostkey->freekey(s->hkey);
6725 * The exchange hash from the very first key exchange is also
6726 * the session id, used in session key construction and
6729 if (!s->got_session_id) {
6730 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6731 memcpy(ssh->v2_session_id, s->exchange_hash,
6732 sizeof(s->exchange_hash));
6733 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6734 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6735 s->got_session_id = TRUE;
6739 * Send SSH2_MSG_NEWKEYS.
6741 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6742 ssh2_pkt_send_noqueue(ssh, s->pktout);
6743 ssh->outgoing_data_size = 0; /* start counting from here */
6746 * We've sent client NEWKEYS, so create and initialise
6747 * client-to-server session keys.
6749 if (ssh->cs_cipher_ctx)
6750 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6751 ssh->cscipher = s->cscipher_tobe;
6752 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6754 if (ssh->cs_mac_ctx)
6755 ssh->csmac->free_context(ssh->cs_mac_ctx);
6756 ssh->csmac = s->csmac_tobe;
6757 ssh->cs_mac_ctx = ssh->csmac->make_context();
6759 if (ssh->cs_comp_ctx)
6760 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6761 ssh->cscomp = s->cscomp_tobe;
6762 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6765 * Set IVs on client-to-server keys. Here we use the exchange
6766 * hash from the _first_ key exchange.
6769 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6770 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6771 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6772 assert((ssh->cscipher->keylen+7) / 8 <=
6773 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6774 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6775 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6776 assert(ssh->cscipher->blksize <=
6777 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6778 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6779 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6780 assert(ssh->csmac->len <=
6781 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6782 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6783 smemclr(keyspace, sizeof(keyspace));
6786 logeventf(ssh, "Initialised %.200s client->server encryption",
6787 ssh->cscipher->text_name);
6788 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6789 ssh->csmac->text_name);
6790 if (ssh->cscomp->text_name)
6791 logeventf(ssh, "Initialised %s compression",
6792 ssh->cscomp->text_name);
6795 * Now our end of the key exchange is complete, we can send all
6796 * our queued higher-layer packets.
6798 ssh->queueing = FALSE;
6799 ssh2_pkt_queuesend(ssh);
6802 * Expect SSH2_MSG_NEWKEYS from server.
6804 crWaitUntilV(pktin);
6805 if (pktin->type != SSH2_MSG_NEWKEYS) {
6806 bombout(("expected new-keys packet from server"));
6809 ssh->incoming_data_size = 0; /* start counting from here */
6812 * We've seen server NEWKEYS, so create and initialise
6813 * server-to-client session keys.
6815 if (ssh->sc_cipher_ctx)
6816 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6817 ssh->sccipher = s->sccipher_tobe;
6818 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6820 if (ssh->sc_mac_ctx)
6821 ssh->scmac->free_context(ssh->sc_mac_ctx);
6822 ssh->scmac = s->scmac_tobe;
6823 ssh->sc_mac_ctx = ssh->scmac->make_context();
6825 if (ssh->sc_comp_ctx)
6826 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6827 ssh->sccomp = s->sccomp_tobe;
6828 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6831 * Set IVs on server-to-client keys. Here we use the exchange
6832 * hash from the _first_ key exchange.
6835 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6836 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6837 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6838 assert((ssh->sccipher->keylen+7) / 8 <=
6839 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6840 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6841 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6842 assert(ssh->sccipher->blksize <=
6843 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6844 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6845 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6846 assert(ssh->scmac->len <=
6847 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6848 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6849 smemclr(keyspace, sizeof(keyspace));
6851 logeventf(ssh, "Initialised %.200s server->client encryption",
6852 ssh->sccipher->text_name);
6853 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6854 ssh->scmac->text_name);
6855 if (ssh->sccomp->text_name)
6856 logeventf(ssh, "Initialised %s decompression",
6857 ssh->sccomp->text_name);
6860 * Free shared secret.
6865 * Key exchange is over. Loop straight back round if we have a
6866 * deferred rekey reason.
6868 if (ssh->deferred_rekey_reason) {
6869 logevent(ssh->deferred_rekey_reason);
6871 ssh->deferred_rekey_reason = NULL;
6872 goto begin_key_exchange;
6876 * Otherwise, schedule a timer for our next rekey.
6878 ssh->kex_in_progress = FALSE;
6879 ssh->last_rekey = GETTICKCOUNT();
6880 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6881 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6885 * Now we're encrypting. Begin returning 1 to the protocol main
6886 * function so that other things can run on top of the
6887 * transport. If we ever see a KEXINIT, we must go back to the
6890 * We _also_ go back to the start if we see pktin==NULL and
6891 * inlen negative, because this is a special signal meaning
6892 * `initiate client-driven rekey', and `in' contains a message
6893 * giving the reason for the rekey.
6895 * inlen==-1 means always initiate a rekey;
6896 * inlen==-2 means that userauth has completed successfully and
6897 * we should consider rekeying (for delayed compression).
6899 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
6900 (!pktin && inlen < 0))) {
6902 if (!ssh->protocol_initial_phase_done) {
6903 ssh->protocol_initial_phase_done = TRUE;
6905 * Allow authconn to initialise itself.
6907 do_ssh2_authconn(ssh, NULL, 0, NULL);
6912 logevent("Server initiated key re-exchange");
6916 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6917 * delayed compression, if it's available.
6919 * draft-miller-secsh-compression-delayed-00 says that you
6920 * negotiate delayed compression in the first key exchange, and
6921 * both sides start compressing when the server has sent
6922 * USERAUTH_SUCCESS. This has a race condition -- the server
6923 * can't know when the client has seen it, and thus which incoming
6924 * packets it should treat as compressed.
6926 * Instead, we do the initial key exchange without offering the
6927 * delayed methods, but note if the server offers them; when we
6928 * get here, if a delayed method was available that was higher
6929 * on our list than what we got, we initiate a rekey in which we
6930 * _do_ list the delayed methods (and hopefully get it as a
6931 * result). Subsequent rekeys will do the same.
6933 assert(!s->userauth_succeeded); /* should only happen once */
6934 s->userauth_succeeded = TRUE;
6935 if (!s->pending_compression)
6936 /* Can't see any point rekeying. */
6937 goto wait_for_rekey; /* this is utterly horrid */
6938 /* else fall through to rekey... */
6939 s->pending_compression = FALSE;
6942 * Now we've decided to rekey.
6944 * Special case: if the server bug is set that doesn't
6945 * allow rekeying, we give a different log message and
6946 * continue waiting. (If such a server _initiates_ a rekey,
6947 * we process it anyway!)
6949 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6950 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6952 /* Reset the counters, so that at least this message doesn't
6953 * hit the event log _too_ often. */
6954 ssh->outgoing_data_size = 0;
6955 ssh->incoming_data_size = 0;
6956 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
6958 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
6961 goto wait_for_rekey; /* this is still utterly horrid */
6963 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
6966 goto begin_key_exchange;
6972 * Add data to an SSH-2 channel output buffer.
6974 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6977 bufchain_add(&c->v.v2.outbuffer, buf, len);
6981 * Attempt to send data on an SSH-2 channel.
6983 static int ssh2_try_send(struct ssh_channel *c)
6986 struct Packet *pktout;
6989 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6992 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6993 if ((unsigned)len > c->v.v2.remwindow)
6994 len = c->v.v2.remwindow;
6995 if ((unsigned)len > c->v.v2.remmaxpkt)
6996 len = c->v.v2.remmaxpkt;
6997 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6998 ssh2_pkt_adduint32(pktout, c->remoteid);
6999 ssh2_pkt_addstring_start(pktout);
7000 ssh2_pkt_addstring_data(pktout, data, len);
7001 ssh2_pkt_send(ssh, pktout);
7002 bufchain_consume(&c->v.v2.outbuffer, len);
7003 c->v.v2.remwindow -= len;
7007 * After having sent as much data as we can, return the amount
7010 ret = bufchain_size(&c->v.v2.outbuffer);
7013 * And if there's no data pending but we need to send an EOF, send
7016 if (!ret && c->pending_eof)
7017 ssh_channel_try_eof(c);
7022 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7025 if (c->closes & CLOSES_SENT_EOF)
7026 return; /* don't send on channels we've EOFed */
7027 bufsize = ssh2_try_send(c);
7030 case CHAN_MAINSESSION:
7031 /* stdin need not receive an unthrottle
7032 * notification since it will be polled */
7035 x11_unthrottle(c->u.x11.xconn);
7038 /* agent sockets are request/response and need no
7039 * buffer management */
7042 pfd_unthrottle(c->u.pfd.pf);
7048 static int ssh_is_simple(Ssh ssh)
7051 * We use the 'simple' variant of the SSH protocol if we're asked
7052 * to, except not if we're also doing connection-sharing (either
7053 * tunnelling our packets over an upstream or expecting to be
7054 * tunnelled over ourselves), since then the assumption that we
7055 * have only one channel to worry about is not true after all.
7057 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7058 !ssh->bare_connection && !ssh->connshare);
7062 * Set up most of a new ssh_channel for SSH-2.
7064 static void ssh2_channel_init(struct ssh_channel *c)
7067 c->localid = alloc_channel_id(ssh);
7069 c->pending_eof = FALSE;
7070 c->throttling_conn = FALSE;
7071 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7072 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7073 c->v.v2.chanreq_head = NULL;
7074 c->v.v2.throttle_state = UNTHROTTLED;
7075 bufchain_init(&c->v.v2.outbuffer);
7079 * Construct the common parts of a CHANNEL_OPEN.
7081 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c, char *type)
7083 struct Packet *pktout;
7085 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7086 ssh2_pkt_addstring(pktout, type);
7087 ssh2_pkt_adduint32(pktout, c->localid);
7088 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7089 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7094 * CHANNEL_FAILURE doesn't come with any indication of what message
7095 * caused it, so we have to keep track of the outstanding
7096 * CHANNEL_REQUESTs ourselves.
7098 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7099 cchandler_fn_t handler, void *ctx)
7101 struct outstanding_channel_request *ocr =
7102 snew(struct outstanding_channel_request);
7104 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7105 ocr->handler = handler;
7108 if (!c->v.v2.chanreq_head)
7109 c->v.v2.chanreq_head = ocr;
7111 c->v.v2.chanreq_tail->next = ocr;
7112 c->v.v2.chanreq_tail = ocr;
7116 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7117 * NULL then a reply will be requested and the handler will be called
7118 * when it arrives. The returned packet is ready to have any
7119 * request-specific data added and be sent. Note that if a handler is
7120 * provided, it's essential that the request actually be sent.
7122 * The handler will usually be passed the response packet in pktin.
7123 * If pktin is NULL, this means that no reply will ever be forthcoming
7124 * (e.g. because the entire connection is being destroyed) and the
7125 * handler should free any storage it's holding.
7127 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c, char *type,
7128 cchandler_fn_t handler, void *ctx)
7130 struct Packet *pktout;
7132 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7133 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7134 ssh2_pkt_adduint32(pktout, c->remoteid);
7135 ssh2_pkt_addstring(pktout, type);
7136 ssh2_pkt_addbool(pktout, handler != NULL);
7137 if (handler != NULL)
7138 ssh2_queue_chanreq_handler(c, handler, ctx);
7143 * Potentially enlarge the window on an SSH-2 channel.
7145 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7147 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7152 * Never send WINDOW_ADJUST for a channel that the remote side has
7153 * already sent EOF on; there's no point, since it won't be
7154 * sending any more data anyway. Ditto if _we've_ already sent
7157 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7161 * Also, never widen the window for an X11 channel when we're
7162 * still waiting to see its initial auth and may yet hand it off
7165 if (c->type == CHAN_X11 && c->u.x11.initial)
7169 * If the remote end has a habit of ignoring maxpkt, limit the
7170 * window so that it has no choice (assuming it doesn't ignore the
7173 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7174 newwin = OUR_V2_MAXPKT;
7177 * Only send a WINDOW_ADJUST if there's significantly more window
7178 * available than the other end thinks there is. This saves us
7179 * sending a WINDOW_ADJUST for every character in a shell session.
7181 * "Significant" is arbitrarily defined as half the window size.
7183 if (newwin / 2 >= c->v.v2.locwindow) {
7184 struct Packet *pktout;
7188 * In order to keep track of how much window the client
7189 * actually has available, we'd like it to acknowledge each
7190 * WINDOW_ADJUST. We can't do that directly, so we accompany
7191 * it with a CHANNEL_REQUEST that has to be acknowledged.
7193 * This is only necessary if we're opening the window wide.
7194 * If we're not, then throughput is being constrained by
7195 * something other than the maximum window size anyway.
7197 if (newwin == c->v.v2.locmaxwin &&
7198 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7199 up = snew(unsigned);
7200 *up = newwin - c->v.v2.locwindow;
7201 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7202 ssh2_handle_winadj_response, up);
7203 ssh2_pkt_send(ssh, pktout);
7205 if (c->v.v2.throttle_state != UNTHROTTLED)
7206 c->v.v2.throttle_state = UNTHROTTLING;
7208 /* Pretend the WINDOW_ADJUST was acked immediately. */
7209 c->v.v2.remlocwin = newwin;
7210 c->v.v2.throttle_state = THROTTLED;
7212 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7213 ssh2_pkt_adduint32(pktout, c->remoteid);
7214 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7215 ssh2_pkt_send(ssh, pktout);
7216 c->v.v2.locwindow = newwin;
7221 * Find the channel associated with a message. If there's no channel,
7222 * or it's not properly open, make a noise about it and return NULL.
7224 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7226 unsigned localid = ssh_pkt_getuint32(pktin);
7227 struct ssh_channel *c;
7229 c = find234(ssh->channels, &localid, ssh_channelfind);
7231 (c->type != CHAN_SHARING && c->halfopen &&
7232 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7233 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7234 char *buf = dupprintf("Received %s for %s channel %u",
7235 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7237 c ? "half-open" : "nonexistent", localid);
7238 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7245 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7246 struct Packet *pktin, void *ctx)
7248 unsigned *sizep = ctx;
7251 * Winadj responses should always be failures. However, at least
7252 * one server ("boks_sshd") is known to return SUCCESS for channel
7253 * requests it's never heard of, such as "winadj@putty". Raised
7254 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7255 * life, we don't worry about what kind of response we got.
7258 c->v.v2.remlocwin += *sizep;
7261 * winadj messages are only sent when the window is fully open, so
7262 * if we get an ack of one, we know any pending unthrottle is
7265 if (c->v.v2.throttle_state == UNTHROTTLING)
7266 c->v.v2.throttle_state = UNTHROTTLED;
7269 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
7271 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
7272 struct outstanding_channel_request *ocr;
7275 if (c->type == CHAN_SHARING) {
7276 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7277 pktin->body, pktin->length);
7280 ocr = c->v.v2.chanreq_head;
7282 ssh2_msg_unexpected(ssh, pktin);
7285 ocr->handler(c, pktin, ocr->ctx);
7286 c->v.v2.chanreq_head = ocr->next;
7289 * We may now initiate channel-closing procedures, if that
7290 * CHANNEL_REQUEST was the last thing outstanding before we send
7293 ssh2_channel_check_close(c);
7296 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
7298 struct ssh_channel *c;
7299 c = ssh2_channel_msg(ssh, pktin);
7302 if (c->type == CHAN_SHARING) {
7303 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7304 pktin->body, pktin->length);
7307 if (!(c->closes & CLOSES_SENT_EOF)) {
7308 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
7309 ssh2_try_send_and_unthrottle(ssh, c);
7313 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
7317 struct ssh_channel *c;
7318 c = ssh2_channel_msg(ssh, pktin);
7321 if (c->type == CHAN_SHARING) {
7322 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7323 pktin->body, pktin->length);
7326 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
7327 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
7328 return; /* extended but not stderr */
7329 ssh_pkt_getstring(pktin, &data, &length);
7332 c->v.v2.locwindow -= length;
7333 c->v.v2.remlocwin -= length;
7335 case CHAN_MAINSESSION:
7337 from_backend(ssh->frontend, pktin->type ==
7338 SSH2_MSG_CHANNEL_EXTENDED_DATA,
7342 bufsize = x11_send(c->u.x11.xconn, data, length);
7345 bufsize = pfd_send(c->u.pfd.pf, data, length);
7348 while (length > 0) {
7349 if (c->u.a.lensofar < 4) {
7350 unsigned int l = min(4 - c->u.a.lensofar,
7352 memcpy(c->u.a.msglen + c->u.a.lensofar,
7356 c->u.a.lensofar += l;
7358 if (c->u.a.lensofar == 4) {
7360 4 + GET_32BIT(c->u.a.msglen);
7361 c->u.a.message = snewn(c->u.a.totallen,
7363 memcpy(c->u.a.message, c->u.a.msglen, 4);
7365 if (c->u.a.lensofar >= 4 && length > 0) {
7367 min(c->u.a.totallen - c->u.a.lensofar,
7369 memcpy(c->u.a.message + c->u.a.lensofar,
7373 c->u.a.lensofar += l;
7375 if (c->u.a.lensofar == c->u.a.totallen) {
7378 c->u.a.outstanding_requests++;
7379 if (agent_query(c->u.a.message,
7382 ssh_agentf_callback, c))
7383 ssh_agentf_callback(c, reply, replylen);
7384 sfree(c->u.a.message);
7385 c->u.a.message = NULL;
7386 c->u.a.lensofar = 0;
7393 * If it looks like the remote end hit the end of its window,
7394 * and we didn't want it to do that, think about using a
7397 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
7398 c->v.v2.locmaxwin < 0x40000000)
7399 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
7401 * If we are not buffering too much data,
7402 * enlarge the window again at the remote side.
7403 * If we are buffering too much, we may still
7404 * need to adjust the window if the server's
7407 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7408 c->v.v2.locmaxwin - bufsize : 0);
7410 * If we're either buffering way too much data, or if we're
7411 * buffering anything at all and we're in "simple" mode,
7412 * throttle the whole channel.
7414 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
7415 && !c->throttling_conn) {
7416 c->throttling_conn = 1;
7417 ssh_throttle_conn(ssh, +1);
7422 static void ssh_check_termination(Ssh ssh)
7424 if (ssh->version == 2 &&
7425 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7426 count234(ssh->channels) == 0 &&
7427 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
7429 * We used to send SSH_MSG_DISCONNECT here, because I'd
7430 * believed that _every_ conforming SSH-2 connection had to
7431 * end with a disconnect being sent by at least one side;
7432 * apparently I was wrong and it's perfectly OK to
7433 * unceremoniously slam the connection shut when you're done,
7434 * and indeed OpenSSH feels this is more polite than sending a
7435 * DISCONNECT. So now we don't.
7437 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7441 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id)
7443 logeventf(ssh, "Connection sharing downstream #%u connected", id);
7446 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
7448 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
7449 ssh_check_termination(ssh);
7452 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
7457 va_start(ap, logfmt);
7458 buf = dupvprintf(logfmt, ap);
7461 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
7463 logeventf(ssh, "Connection sharing: %s", buf);
7467 static void ssh_channel_destroy(struct ssh_channel *c)
7472 case CHAN_MAINSESSION:
7473 ssh->mainchan = NULL;
7474 update_specials_menu(ssh->frontend);
7477 if (c->u.x11.xconn != NULL)
7478 x11_close(c->u.x11.xconn);
7479 logevent("Forwarded X11 connection terminated");
7482 sfree(c->u.a.message);
7485 if (c->u.pfd.pf != NULL)
7486 pfd_close(c->u.pfd.pf);
7487 logevent("Forwarded port closed");
7491 del234(ssh->channels, c);
7492 if (ssh->version == 2) {
7493 bufchain_clear(&c->v.v2.outbuffer);
7494 assert(c->v.v2.chanreq_head == NULL);
7499 * If that was the last channel left open, we might need to
7502 ssh_check_termination(ssh);
7505 static void ssh2_channel_check_close(struct ssh_channel *c)
7508 struct Packet *pktout;
7512 * If we've sent out our own CHANNEL_OPEN but not yet seen
7513 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
7514 * it's too early to be sending close messages of any kind.
7519 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
7520 c->type == CHAN_ZOMBIE) &&
7521 !c->v.v2.chanreq_head &&
7522 !(c->closes & CLOSES_SENT_CLOSE)) {
7524 * We have both sent and received EOF (or the channel is a
7525 * zombie), and we have no outstanding channel requests, which
7526 * means the channel is in final wind-up. But we haven't sent
7527 * CLOSE, so let's do so now.
7529 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
7530 ssh2_pkt_adduint32(pktout, c->remoteid);
7531 ssh2_pkt_send(ssh, pktout);
7532 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
7535 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
7536 assert(c->v.v2.chanreq_head == NULL);
7538 * We have both sent and received CLOSE, which means we're
7539 * completely done with the channel.
7541 ssh_channel_destroy(c);
7545 static void ssh2_channel_got_eof(struct ssh_channel *c)
7547 if (c->closes & CLOSES_RCVD_EOF)
7548 return; /* already seen EOF */
7549 c->closes |= CLOSES_RCVD_EOF;
7551 if (c->type == CHAN_X11) {
7552 x11_send_eof(c->u.x11.xconn);
7553 } else if (c->type == CHAN_AGENT) {
7554 if (c->u.a.outstanding_requests == 0) {
7555 /* Manufacture an outgoing EOF in response to the incoming one. */
7556 sshfwd_write_eof(c);
7558 } else if (c->type == CHAN_SOCKDATA) {
7559 pfd_send_eof(c->u.pfd.pf);
7560 } else if (c->type == CHAN_MAINSESSION) {
7563 if (!ssh->sent_console_eof &&
7564 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
7566 * Either from_backend_eof told us that the front end
7567 * wants us to close the outgoing side of the connection
7568 * as soon as we see EOF from the far end, or else we've
7569 * unilaterally decided to do that because we've allocated
7570 * a remote pty and hence EOF isn't a particularly
7571 * meaningful concept.
7573 sshfwd_write_eof(c);
7575 ssh->sent_console_eof = TRUE;
7578 ssh2_channel_check_close(c);
7581 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
7583 struct ssh_channel *c;
7585 c = ssh2_channel_msg(ssh, pktin);
7588 if (c->type == CHAN_SHARING) {
7589 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7590 pktin->body, pktin->length);
7593 ssh2_channel_got_eof(c);
7596 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7598 struct ssh_channel *c;
7600 c = ssh2_channel_msg(ssh, pktin);
7603 if (c->type == CHAN_SHARING) {
7604 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7605 pktin->body, pktin->length);
7610 * When we receive CLOSE on a channel, we assume it comes with an
7611 * implied EOF if we haven't seen EOF yet.
7613 ssh2_channel_got_eof(c);
7616 * And we also send an outgoing EOF, if we haven't already, on the
7617 * assumption that CLOSE is a pretty forceful announcement that
7618 * the remote side is doing away with the entire channel. (If it
7619 * had wanted to send us EOF and continue receiving data from us,
7620 * it would have just sent CHANNEL_EOF.)
7622 if (!(c->closes & CLOSES_SENT_EOF)) {
7624 * Make sure we don't read any more from whatever our local
7625 * data source is for this channel.
7628 case CHAN_MAINSESSION:
7629 ssh->send_ok = 0; /* stop trying to read from stdin */
7632 x11_override_throttle(c->u.x11.xconn, 1);
7635 pfd_override_throttle(c->u.pfd.pf, 1);
7640 * Abandon any buffered data we still wanted to send to this
7641 * channel. Receiving a CHANNEL_CLOSE is an indication that
7642 * the server really wants to get on and _destroy_ this
7643 * channel, and it isn't going to send us any further
7644 * WINDOW_ADJUSTs to permit us to send pending stuff.
7646 bufchain_clear(&c->v.v2.outbuffer);
7649 * Send outgoing EOF.
7651 sshfwd_write_eof(c);
7655 * Now process the actual close.
7657 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7658 c->closes |= CLOSES_RCVD_CLOSE;
7659 ssh2_channel_check_close(c);
7663 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7665 struct ssh_channel *c;
7667 c = ssh2_channel_msg(ssh, pktin);
7670 if (c->type == CHAN_SHARING) {
7671 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7672 pktin->body, pktin->length);
7675 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7676 c->remoteid = ssh_pkt_getuint32(pktin);
7677 c->halfopen = FALSE;
7678 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7679 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7681 if (c->type == CHAN_SOCKDATA_DORMANT) {
7682 c->type = CHAN_SOCKDATA;
7684 pfd_confirm(c->u.pfd.pf);
7685 } else if (c->type == CHAN_ZOMBIE) {
7687 * This case can occur if a local socket error occurred
7688 * between us sending out CHANNEL_OPEN and receiving
7689 * OPEN_CONFIRMATION. In this case, all we can do is
7690 * immediately initiate close proceedings now that we know the
7691 * server's id to put in the close message.
7693 ssh2_channel_check_close(c);
7696 * We never expect to receive OPEN_CONFIRMATION for any
7697 * *other* channel type (since only local-to-remote port
7698 * forwardings cause us to send CHANNEL_OPEN after the main
7699 * channel is live - all other auxiliary channel types are
7700 * initiated from the server end). It's safe to enforce this
7701 * by assertion rather than by ssh_disconnect, because the
7702 * real point is that we never constructed a half-open channel
7703 * structure in the first place with any type other than the
7706 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
7710 ssh_channel_try_eof(c); /* in case we had a pending EOF */
7713 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7715 static const char *const reasons[] = {
7716 "<unknown reason code>",
7717 "Administratively prohibited",
7719 "Unknown channel type",
7720 "Resource shortage",
7722 unsigned reason_code;
7723 char *reason_string;
7725 struct ssh_channel *c;
7727 c = ssh2_channel_msg(ssh, pktin);
7730 if (c->type == CHAN_SHARING) {
7731 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7732 pktin->body, pktin->length);
7735 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7737 if (c->type == CHAN_SOCKDATA_DORMANT) {
7738 reason_code = ssh_pkt_getuint32(pktin);
7739 if (reason_code >= lenof(reasons))
7740 reason_code = 0; /* ensure reasons[reason_code] in range */
7741 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7742 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7743 reasons[reason_code], reason_length, reason_string);
7745 pfd_close(c->u.pfd.pf);
7746 } else if (c->type == CHAN_ZOMBIE) {
7748 * This case can occur if a local socket error occurred
7749 * between us sending out CHANNEL_OPEN and receiving
7750 * OPEN_FAILURE. In this case, we need do nothing except allow
7751 * the code below to throw the half-open channel away.
7755 * We never expect to receive OPEN_FAILURE for any *other*
7756 * channel type (since only local-to-remote port forwardings
7757 * cause us to send CHANNEL_OPEN after the main channel is
7758 * live - all other auxiliary channel types are initiated from
7759 * the server end). It's safe to enforce this by assertion
7760 * rather than by ssh_disconnect, because the real point is
7761 * that we never constructed a half-open channel structure in
7762 * the first place with any type other than the above.
7764 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
7767 del234(ssh->channels, c);
7771 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7774 int typelen, want_reply;
7775 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7776 struct ssh_channel *c;
7777 struct Packet *pktout;
7779 c = ssh2_channel_msg(ssh, pktin);
7782 if (c->type == CHAN_SHARING) {
7783 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7784 pktin->body, pktin->length);
7787 ssh_pkt_getstring(pktin, &type, &typelen);
7788 want_reply = ssh2_pkt_getbool(pktin);
7791 * Having got the channel number, we now look at
7792 * the request type string to see if it's something
7795 if (c == ssh->mainchan) {
7797 * We recognise "exit-status" and "exit-signal" on
7798 * the primary channel.
7800 if (typelen == 11 &&
7801 !memcmp(type, "exit-status", 11)) {
7803 ssh->exitcode = ssh_pkt_getuint32(pktin);
7804 logeventf(ssh, "Server sent command exit status %d",
7806 reply = SSH2_MSG_CHANNEL_SUCCESS;
7808 } else if (typelen == 11 &&
7809 !memcmp(type, "exit-signal", 11)) {
7811 int is_plausible = TRUE, is_int = FALSE;
7812 char *fmt_sig = "", *fmt_msg = "";
7814 int msglen = 0, core = FALSE;
7815 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7816 * provide an `int' for the signal, despite its
7817 * having been a `string' in the drafts of RFC 4254 since at
7818 * least 2001. (Fixed in session.c 1.147.) Try to
7819 * infer which we can safely parse it as. */
7821 unsigned char *p = pktin->body +
7823 long len = pktin->length - pktin->savedpos;
7824 unsigned long num = GET_32BIT(p); /* what is it? */
7825 /* If it's 0, it hardly matters; assume string */
7829 int maybe_int = FALSE, maybe_str = FALSE;
7830 #define CHECK_HYPOTHESIS(offset, result) \
7833 int q = toint(offset); \
7834 if (q >= 0 && q+4 <= len) { \
7835 q = toint(q + 4 + GET_32BIT(p+q)); \
7836 if (q >= 0 && q+4 <= len && \
7837 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
7842 CHECK_HYPOTHESIS(4+1, maybe_int);
7843 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7844 #undef CHECK_HYPOTHESIS
7845 if (maybe_int && !maybe_str)
7847 else if (!maybe_int && maybe_str)
7850 /* Crikey. Either or neither. Panic. */
7851 is_plausible = FALSE;
7854 ssh->exitcode = 128; /* means `unknown signal' */
7857 /* Old non-standard OpenSSH. */
7858 int signum = ssh_pkt_getuint32(pktin);
7859 fmt_sig = dupprintf(" %d", signum);
7860 ssh->exitcode = 128 + signum;
7862 /* As per RFC 4254. */
7865 ssh_pkt_getstring(pktin, &sig, &siglen);
7866 /* Signal name isn't supposed to be blank, but
7867 * let's cope gracefully if it is. */
7869 fmt_sig = dupprintf(" \"%.*s\"",
7874 * Really hideous method of translating the
7875 * signal description back into a locally
7876 * meaningful number.
7881 #define TRANSLATE_SIGNAL(s) \
7882 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7883 ssh->exitcode = 128 + SIG ## s
7885 TRANSLATE_SIGNAL(ABRT);
7888 TRANSLATE_SIGNAL(ALRM);
7891 TRANSLATE_SIGNAL(FPE);
7894 TRANSLATE_SIGNAL(HUP);
7897 TRANSLATE_SIGNAL(ILL);
7900 TRANSLATE_SIGNAL(INT);
7903 TRANSLATE_SIGNAL(KILL);
7906 TRANSLATE_SIGNAL(PIPE);
7909 TRANSLATE_SIGNAL(QUIT);
7912 TRANSLATE_SIGNAL(SEGV);
7915 TRANSLATE_SIGNAL(TERM);
7918 TRANSLATE_SIGNAL(USR1);
7921 TRANSLATE_SIGNAL(USR2);
7923 #undef TRANSLATE_SIGNAL
7925 ssh->exitcode = 128;
7927 core = ssh2_pkt_getbool(pktin);
7928 ssh_pkt_getstring(pktin, &msg, &msglen);
7930 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7932 /* ignore lang tag */
7933 } /* else don't attempt to parse */
7934 logeventf(ssh, "Server exited on signal%s%s%s",
7935 fmt_sig, core ? " (core dumped)" : "",
7937 if (*fmt_sig) sfree(fmt_sig);
7938 if (*fmt_msg) sfree(fmt_msg);
7939 reply = SSH2_MSG_CHANNEL_SUCCESS;
7944 * This is a channel request we don't know
7945 * about, so we now either ignore the request
7946 * or respond with CHANNEL_FAILURE, depending
7949 reply = SSH2_MSG_CHANNEL_FAILURE;
7952 pktout = ssh2_pkt_init(reply);
7953 ssh2_pkt_adduint32(pktout, c->remoteid);
7954 ssh2_pkt_send(ssh, pktout);
7958 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7961 int typelen, want_reply;
7962 struct Packet *pktout;
7964 ssh_pkt_getstring(pktin, &type, &typelen);
7965 want_reply = ssh2_pkt_getbool(pktin);
7968 * We currently don't support any global requests
7969 * at all, so we either ignore the request or
7970 * respond with REQUEST_FAILURE, depending on
7974 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7975 ssh2_pkt_send(ssh, pktout);
7979 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
7983 struct X11FakeAuth *auth;
7986 * Make up a new set of fake X11 auth data, and add it to the tree
7987 * of currently valid ones with an indication of the sharing
7988 * context that it's relevant to.
7990 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
7991 auth->share_cs = share_cs;
7992 auth->share_chan = share_chan;
7997 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
7999 del234(ssh->x11authtree, auth);
8000 x11_free_fake_auth(auth);
8003 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8011 struct ssh_channel *c;
8012 unsigned remid, winsize, pktsize;
8013 unsigned our_winsize_override = 0;
8014 struct Packet *pktout;
8016 ssh_pkt_getstring(pktin, &type, &typelen);
8017 c = snew(struct ssh_channel);
8020 remid = ssh_pkt_getuint32(pktin);
8021 winsize = ssh_pkt_getuint32(pktin);
8022 pktsize = ssh_pkt_getuint32(pktin);
8024 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8027 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8028 addrstr = snewn(peeraddrlen+1, char);
8029 memcpy(addrstr, peeraddr, peeraddrlen);
8030 addrstr[peeraddrlen] = '\0';
8031 peerport = ssh_pkt_getuint32(pktin);
8033 logeventf(ssh, "Received X11 connect request from %s:%d",
8036 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8037 error = "X11 forwarding is not enabled";
8039 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8042 c->u.x11.initial = TRUE;
8045 * If we are a connection-sharing upstream, then we should
8046 * initially present a very small window, adequate to take
8047 * the X11 initial authorisation packet but not much more.
8048 * Downstream will then present us a larger window (by
8049 * fiat of the connection-sharing protocol) and we can
8050 * guarantee to send a positive-valued WINDOW_ADJUST.
8053 our_winsize_override = 128;
8055 logevent("Opened X11 forward channel");
8059 } else if (typelen == 15 &&
8060 !memcmp(type, "forwarded-tcpip", 15)) {
8061 struct ssh_rportfwd pf, *realpf;
8064 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8065 pf.shost = dupprintf("%.*s", shostlen, shost);
8066 pf.sport = ssh_pkt_getuint32(pktin);
8067 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8068 peerport = ssh_pkt_getuint32(pktin);
8069 realpf = find234(ssh->rportfwds, &pf, NULL);
8070 logeventf(ssh, "Received remote port %s:%d open request "
8071 "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
8074 if (realpf == NULL) {
8075 error = "Remote port is not recognised";
8079 if (realpf->share_ctx) {
8081 * This port forwarding is on behalf of a
8082 * connection-sharing downstream, so abandon our own
8083 * channel-open procedure and just pass the message on
8086 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8087 pktin->body, pktin->length);
8092 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8093 c, ssh->conf, realpf->pfrec->addressfamily);
8094 logeventf(ssh, "Attempting to forward remote port to "
8095 "%s:%d", realpf->dhost, realpf->dport);
8097 logeventf(ssh, "Port open failed: %s", err);
8099 error = "Port open failed";
8101 logevent("Forwarded port opened successfully");
8102 c->type = CHAN_SOCKDATA;
8105 } else if (typelen == 22 &&
8106 !memcmp(type, "auth-agent@openssh.com", 22)) {
8107 if (!ssh->agentfwd_enabled)
8108 error = "Agent forwarding is not enabled";
8110 c->type = CHAN_AGENT; /* identify channel type */
8111 c->u.a.lensofar = 0;
8112 c->u.a.message = NULL;
8113 c->u.a.outstanding_requests = 0;
8116 error = "Unsupported channel type requested";
8119 c->remoteid = remid;
8120 c->halfopen = FALSE;
8122 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8123 ssh2_pkt_adduint32(pktout, c->remoteid);
8124 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8125 ssh2_pkt_addstring(pktout, error);
8126 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8127 ssh2_pkt_send(ssh, pktout);
8128 logeventf(ssh, "Rejected channel open: %s", error);
8131 ssh2_channel_init(c);
8132 c->v.v2.remwindow = winsize;
8133 c->v.v2.remmaxpkt = pktsize;
8134 if (our_winsize_override) {
8135 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8136 our_winsize_override;
8138 add234(ssh->channels, c);
8139 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8140 ssh2_pkt_adduint32(pktout, c->remoteid);
8141 ssh2_pkt_adduint32(pktout, c->localid);
8142 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8143 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8144 ssh2_pkt_send(ssh, pktout);
8148 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8149 void *share_cs, void *share_chan,
8150 const char *peer_addr, int peer_port,
8151 int endian, int protomajor, int protominor,
8152 const void *initial_data, int initial_len)
8155 * This function is called when we've just discovered that an X
8156 * forwarding channel on which we'd been handling the initial auth
8157 * ourselves turns out to be destined for a connection-sharing
8158 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8159 * that we completely stop tracking windows and buffering data and
8160 * just pass more or less unmodified SSH messages back and forth.
8162 c->type = CHAN_SHARING;
8163 c->u.sharing.ctx = share_cs;
8164 share_setup_x11_channel(share_cs, share_chan,
8165 c->localid, c->remoteid, c->v.v2.remwindow,
8166 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8167 peer_addr, peer_port, endian,
8168 protomajor, protominor,
8169 initial_data, initial_len);
8172 void sshfwd_x11_is_local(struct ssh_channel *c)
8175 * This function is called when we've just discovered that an X
8176 * forwarding channel is _not_ destined for a connection-sharing
8177 * downstream but we're going to handle it ourselves. We stop
8178 * presenting a cautiously small window and go into ordinary data
8181 c->u.x11.initial = FALSE;
8182 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8186 * Buffer banner messages for later display at some convenient point,
8187 * if we're going to display them.
8189 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8191 /* Arbitrary limit to prevent unbounded inflation of buffer */
8192 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8193 bufchain_size(&ssh->banner) <= 131072) {
8194 char *banner = NULL;
8196 ssh_pkt_getstring(pktin, &banner, &size);
8198 bufchain_add(&ssh->banner, banner, size);
8202 /* Helper function to deal with sending tty modes for "pty-req" */
8203 static void ssh2_send_ttymode(void *data, char *mode, char *val)
8205 struct Packet *pktout = (struct Packet *)data;
8207 unsigned int arg = 0;
8208 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
8209 if (i == lenof(ssh_ttymodes)) return;
8210 switch (ssh_ttymodes[i].type) {
8212 arg = ssh_tty_parse_specchar(val);
8215 arg = ssh_tty_parse_boolean(val);
8218 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
8219 ssh2_pkt_adduint32(pktout, arg);
8222 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8225 struct ssh2_setup_x11_state {
8229 struct Packet *pktout;
8230 crStateP(ssh2_setup_x11_state, ctx);
8234 logevent("Requesting X11 forwarding");
8235 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8237 ssh2_pkt_addbool(pktout, 0); /* many connections */
8238 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8239 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8240 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8241 ssh2_pkt_send(ssh, pktout);
8243 /* Wait to be called back with either a response packet, or NULL
8244 * meaning clean up and free our data */
8248 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8249 logevent("X11 forwarding enabled");
8250 ssh->X11_fwd_enabled = TRUE;
8252 logevent("X11 forwarding refused");
8258 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8261 struct ssh2_setup_agent_state {
8265 struct Packet *pktout;
8266 crStateP(ssh2_setup_agent_state, ctx);
8270 logevent("Requesting OpenSSH-style agent forwarding");
8271 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8272 ssh2_setup_agent, s);
8273 ssh2_pkt_send(ssh, pktout);
8275 /* Wait to be called back with either a response packet, or NULL
8276 * meaning clean up and free our data */
8280 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8281 logevent("Agent forwarding enabled");
8282 ssh->agentfwd_enabled = TRUE;
8284 logevent("Agent forwarding refused");
8290 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8293 struct ssh2_setup_pty_state {
8297 struct Packet *pktout;
8298 crStateP(ssh2_setup_pty_state, ctx);
8302 /* Unpick the terminal-speed string. */
8303 /* XXX perhaps we should allow no speeds to be sent. */
8304 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8305 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8306 /* Build the pty request. */
8307 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
8309 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
8310 ssh2_pkt_adduint32(pktout, ssh->term_width);
8311 ssh2_pkt_adduint32(pktout, ssh->term_height);
8312 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
8313 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
8314 ssh2_pkt_addstring_start(pktout);
8315 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
8316 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
8317 ssh2_pkt_adduint32(pktout, ssh->ispeed);
8318 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
8319 ssh2_pkt_adduint32(pktout, ssh->ospeed);
8320 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
8321 ssh2_pkt_send(ssh, pktout);
8322 ssh->state = SSH_STATE_INTERMED;
8324 /* Wait to be called back with either a response packet, or NULL
8325 * meaning clean up and free our data */
8329 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8330 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8331 ssh->ospeed, ssh->ispeed);
8332 ssh->got_pty = TRUE;
8334 c_write_str(ssh, "Server refused to allocate pty\r\n");
8335 ssh->editing = ssh->echoing = 1;
8342 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
8345 struct ssh2_setup_env_state {
8347 int num_env, env_left, env_ok;
8350 struct Packet *pktout;
8351 crStateP(ssh2_setup_env_state, ctx);
8356 * Send environment variables.
8358 * Simplest thing here is to send all the requests at once, and
8359 * then wait for a whole bunch of successes or failures.
8365 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
8367 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
8368 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
8369 ssh2_pkt_addstring(pktout, key);
8370 ssh2_pkt_addstring(pktout, val);
8371 ssh2_pkt_send(ssh, pktout);
8376 logeventf(ssh, "Sent %d environment variables", s->num_env);
8381 s->env_left = s->num_env;
8383 while (s->env_left > 0) {
8384 /* Wait to be called back with either a response packet,
8385 * or NULL meaning clean up and free our data */
8387 if (!pktin) goto out;
8388 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
8393 if (s->env_ok == s->num_env) {
8394 logevent("All environment variables successfully set");
8395 } else if (s->env_ok == 0) {
8396 logevent("All environment variables refused");
8397 c_write_str(ssh, "Server refused to set environment variables\r\n");
8399 logeventf(ssh, "%d environment variables refused",
8400 s->num_env - s->env_ok);
8401 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8409 * Handle the SSH-2 userauth and connection layers.
8411 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
8413 do_ssh2_authconn(ssh, NULL, 0, pktin);
8416 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
8419 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
8422 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
8423 struct Packet *pktin)
8425 struct do_ssh2_authconn_state {
8429 AUTH_TYPE_PUBLICKEY,
8430 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
8431 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
8433 AUTH_TYPE_GSSAPI, /* always QUIET */
8434 AUTH_TYPE_KEYBOARD_INTERACTIVE,
8435 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
8437 int done_service_req;
8438 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
8439 int tried_pubkey_config, done_agent;
8444 int kbd_inter_refused;
8445 int we_are_in, userauth_success;
8446 prompts_t *cur_prompt;
8451 void *publickey_blob;
8452 int publickey_bloblen;
8453 int publickey_encrypted;
8454 char *publickey_algorithm;
8455 char *publickey_comment;
8456 unsigned char agent_request[5], *agent_response, *agentp;
8457 int agent_responselen;
8458 unsigned char *pkblob_in_agent;
8460 char *pkblob, *alg, *commentp;
8461 int pklen, alglen, commentlen;
8462 int siglen, retlen, len;
8463 char *q, *agentreq, *ret;
8465 struct Packet *pktout;
8468 struct ssh_gss_library *gsslib;
8469 Ssh_gss_ctx gss_ctx;
8470 Ssh_gss_buf gss_buf;
8471 Ssh_gss_buf gss_rcvtok, gss_sndtok;
8472 Ssh_gss_name gss_srv_name;
8473 Ssh_gss_stat gss_stat;
8476 crState(do_ssh2_authconn_state);
8480 /* Register as a handler for all the messages this coroutine handles. */
8481 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
8482 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
8483 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
8484 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
8485 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
8486 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
8487 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
8488 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
8489 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
8490 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
8491 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
8492 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
8493 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
8494 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
8495 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
8496 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
8497 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
8498 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
8499 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
8500 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
8502 s->done_service_req = FALSE;
8503 s->we_are_in = s->userauth_success = FALSE;
8504 s->agent_response = NULL;
8506 s->tried_gssapi = FALSE;
8509 if (!ssh->bare_connection) {
8510 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
8512 * Request userauth protocol, and await a response to it.
8514 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8515 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
8516 ssh2_pkt_send(ssh, s->pktout);
8517 crWaitUntilV(pktin);
8518 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
8519 s->done_service_req = TRUE;
8521 if (!s->done_service_req) {
8523 * Request connection protocol directly, without authentication.
8525 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8526 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8527 ssh2_pkt_send(ssh, s->pktout);
8528 crWaitUntilV(pktin);
8529 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
8530 s->we_are_in = TRUE; /* no auth required */
8532 bombout(("Server refused service request"));
8537 s->we_are_in = TRUE;
8540 /* Arrange to be able to deal with any BANNERs that come in.
8541 * (We do this now as packets may come in during the next bit.) */
8542 bufchain_init(&ssh->banner);
8543 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
8544 ssh2_msg_userauth_banner;
8547 * Misc one-time setup for authentication.
8549 s->publickey_blob = NULL;
8550 if (!s->we_are_in) {
8553 * Load the public half of any configured public key file
8556 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8557 if (!filename_is_null(s->keyfile)) {
8559 logeventf(ssh, "Reading private key file \"%.150s\"",
8560 filename_to_str(s->keyfile));
8561 keytype = key_type(s->keyfile);
8562 if (keytype == SSH_KEYTYPE_SSH2) {
8565 ssh2_userkey_loadpub(s->keyfile,
8566 &s->publickey_algorithm,
8567 &s->publickey_bloblen,
8568 &s->publickey_comment, &error);
8569 if (s->publickey_blob) {
8570 s->publickey_encrypted =
8571 ssh2_userkey_encrypted(s->keyfile, NULL);
8574 logeventf(ssh, "Unable to load private key (%s)",
8576 msgbuf = dupprintf("Unable to load private key file "
8577 "\"%.150s\" (%s)\r\n",
8578 filename_to_str(s->keyfile),
8580 c_write_str(ssh, msgbuf);
8585 logeventf(ssh, "Unable to use this key file (%s)",
8586 key_type_to_str(keytype));
8587 msgbuf = dupprintf("Unable to use key file \"%.150s\""
8589 filename_to_str(s->keyfile),
8590 key_type_to_str(keytype));
8591 c_write_str(ssh, msgbuf);
8593 s->publickey_blob = NULL;
8598 * Find out about any keys Pageant has (but if there's a
8599 * public key configured, filter out all others).
8602 s->agent_response = NULL;
8603 s->pkblob_in_agent = NULL;
8604 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
8608 logevent("Pageant is running. Requesting keys.");
8610 /* Request the keys held by the agent. */
8611 PUT_32BIT(s->agent_request, 1);
8612 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
8613 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
8614 ssh_agent_callback, ssh)) {
8618 bombout(("Unexpected data from server while"
8619 " waiting for agent response"));
8622 } while (pktin || inlen > 0);
8623 r = ssh->agent_response;
8624 s->agent_responselen = ssh->agent_response_len;
8626 s->agent_response = (unsigned char *) r;
8627 if (s->agent_response && s->agent_responselen >= 5 &&
8628 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
8631 p = s->agent_response + 5;
8632 s->nkeys = toint(GET_32BIT(p));
8635 * Vet the Pageant response to ensure that the key
8636 * count and blob lengths make sense.
8639 logeventf(ssh, "Pageant response contained a negative"
8640 " key count %d", s->nkeys);
8642 goto done_agent_query;
8644 unsigned char *q = p + 4;
8645 int lenleft = s->agent_responselen - 5 - 4;
8647 for (keyi = 0; keyi < s->nkeys; keyi++) {
8648 int bloblen, commentlen;
8650 logeventf(ssh, "Pageant response was truncated");
8652 goto done_agent_query;
8654 bloblen = toint(GET_32BIT(q));
8655 if (bloblen < 0 || bloblen > lenleft) {
8656 logeventf(ssh, "Pageant response was truncated");
8658 goto done_agent_query;
8660 lenleft -= 4 + bloblen;
8662 commentlen = toint(GET_32BIT(q));
8663 if (commentlen < 0 || commentlen > lenleft) {
8664 logeventf(ssh, "Pageant response was truncated");
8666 goto done_agent_query;
8668 lenleft -= 4 + commentlen;
8669 q += 4 + commentlen;
8674 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
8675 if (s->publickey_blob) {
8676 /* See if configured key is in agent. */
8677 for (keyi = 0; keyi < s->nkeys; keyi++) {
8678 s->pklen = toint(GET_32BIT(p));
8679 if (s->pklen == s->publickey_bloblen &&
8680 !memcmp(p+4, s->publickey_blob,
8681 s->publickey_bloblen)) {
8682 logeventf(ssh, "Pageant key #%d matches "
8683 "configured key file", keyi);
8685 s->pkblob_in_agent = p;
8689 p += toint(GET_32BIT(p)) + 4; /* comment */
8691 if (!s->pkblob_in_agent) {
8692 logevent("Configured key file not in Pageant");
8697 logevent("Failed to get reply from Pageant");
8705 * We repeat this whole loop, including the username prompt,
8706 * until we manage a successful authentication. If the user
8707 * types the wrong _password_, they can be sent back to the
8708 * beginning to try another username, if this is configured on.
8709 * (If they specify a username in the config, they are never
8710 * asked, even if they do give a wrong password.)
8712 * I think this best serves the needs of
8714 * - the people who have no configuration, no keys, and just
8715 * want to try repeated (username,password) pairs until they
8716 * type both correctly
8718 * - people who have keys and configuration but occasionally
8719 * need to fall back to passwords
8721 * - people with a key held in Pageant, who might not have
8722 * logged in to a particular machine before; so they want to
8723 * type a username, and then _either_ their key will be
8724 * accepted, _or_ they will type a password. If they mistype
8725 * the username they will want to be able to get back and
8728 s->got_username = FALSE;
8729 while (!s->we_are_in) {
8733 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
8735 * We got a username last time round this loop, and
8736 * with change_username turned off we don't try to get
8739 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
8740 int ret; /* need not be kept over crReturn */
8741 s->cur_prompt = new_prompts(ssh->frontend);
8742 s->cur_prompt->to_server = TRUE;
8743 s->cur_prompt->name = dupstr("SSH login name");
8744 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
8745 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8748 crWaitUntilV(!pktin);
8749 ret = get_userpass_input(s->cur_prompt, in, inlen);
8754 * get_userpass_input() failed to get a username.
8757 free_prompts(s->cur_prompt);
8758 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
8761 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
8762 free_prompts(s->cur_prompt);
8765 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
8766 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
8767 c_write_str(ssh, stuff);
8771 s->got_username = TRUE;
8774 * Send an authentication request using method "none": (a)
8775 * just in case it succeeds, and (b) so that we know what
8776 * authentication methods we can usefully try next.
8778 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8780 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8781 ssh2_pkt_addstring(s->pktout, ssh->username);
8782 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
8783 ssh2_pkt_addstring(s->pktout, "none"); /* method */
8784 ssh2_pkt_send(ssh, s->pktout);
8785 s->type = AUTH_TYPE_NONE;
8787 s->we_are_in = FALSE;
8789 s->tried_pubkey_config = FALSE;
8790 s->kbd_inter_refused = FALSE;
8792 /* Reset agent request state. */
8793 s->done_agent = FALSE;
8794 if (s->agent_response) {
8795 if (s->pkblob_in_agent) {
8796 s->agentp = s->pkblob_in_agent;
8798 s->agentp = s->agent_response + 5 + 4;
8804 char *methods = NULL;
8808 * Wait for the result of the last authentication request.
8811 crWaitUntilV(pktin);
8813 * Now is a convenient point to spew any banner material
8814 * that we've accumulated. (This should ensure that when
8815 * we exit the auth loop, we haven't any left to deal
8819 int size = bufchain_size(&ssh->banner);
8821 * Don't show the banner if we're operating in
8822 * non-verbose non-interactive mode. (It's probably
8823 * a script, which means nobody will read the
8824 * banner _anyway_, and moreover the printing of
8825 * the banner will screw up processing on the
8826 * output of (say) plink.)
8828 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
8829 char *banner = snewn(size, char);
8830 bufchain_fetch(&ssh->banner, banner, size);
8831 c_write_untrusted(ssh, banner, size);
8834 bufchain_clear(&ssh->banner);
8836 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
8837 logevent("Access granted");
8838 s->we_are_in = s->userauth_success = TRUE;
8842 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
8843 bombout(("Strange packet received during authentication: "
8844 "type %d", pktin->type));
8851 * OK, we're now sitting on a USERAUTH_FAILURE message, so
8852 * we can look at the string in it and know what we can
8853 * helpfully try next.
8855 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
8856 ssh_pkt_getstring(pktin, &methods, &methlen);
8857 if (!ssh2_pkt_getbool(pktin)) {
8859 * We have received an unequivocal Access
8860 * Denied. This can translate to a variety of
8861 * messages, or no message at all.
8863 * For forms of authentication which are attempted
8864 * implicitly, by which I mean without printing
8865 * anything in the window indicating that we're
8866 * trying them, we should never print 'Access
8869 * If we do print a message saying that we're
8870 * attempting some kind of authentication, it's OK
8871 * to print a followup message saying it failed -
8872 * but the message may sometimes be more specific
8873 * than simply 'Access denied'.
8875 * Additionally, if we'd just tried password
8876 * authentication, we should break out of this
8877 * whole loop so as to go back to the username
8878 * prompt (iff we're configured to allow
8879 * username change attempts).
8881 if (s->type == AUTH_TYPE_NONE) {
8883 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
8884 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
8885 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
8886 c_write_str(ssh, "Server refused our key\r\n");
8887 logevent("Server refused our key");
8888 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
8889 /* This _shouldn't_ happen except by a
8890 * protocol bug causing client and server to
8891 * disagree on what is a correct signature. */
8892 c_write_str(ssh, "Server refused public-key signature"
8893 " despite accepting key!\r\n");
8894 logevent("Server refused public-key signature"
8895 " despite accepting key!");
8896 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
8897 /* quiet, so no c_write */
8898 logevent("Server refused keyboard-interactive authentication");
8899 } else if (s->type==AUTH_TYPE_GSSAPI) {
8900 /* always quiet, so no c_write */
8901 /* also, the code down in the GSSAPI block has
8902 * already logged this in the Event Log */
8903 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
8904 logevent("Keyboard-interactive authentication failed");
8905 c_write_str(ssh, "Access denied\r\n");
8907 assert(s->type == AUTH_TYPE_PASSWORD);
8908 logevent("Password authentication failed");
8909 c_write_str(ssh, "Access denied\r\n");
8911 if (conf_get_int(ssh->conf, CONF_change_username)) {
8912 /* XXX perhaps we should allow
8913 * keyboard-interactive to do this too? */
8914 s->we_are_in = FALSE;
8919 c_write_str(ssh, "Further authentication required\r\n");
8920 logevent("Further authentication required");
8924 in_commasep_string("publickey", methods, methlen);
8926 in_commasep_string("password", methods, methlen);
8927 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
8928 in_commasep_string("keyboard-interactive", methods, methlen);
8931 ssh->gsslibs = ssh_gss_setup(ssh->conf);
8932 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
8933 in_commasep_string("gssapi-with-mic", methods, methlen) &&
8934 ssh->gsslibs->nlibraries > 0;
8938 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8940 if (s->can_pubkey && !s->done_agent && s->nkeys) {
8943 * Attempt public-key authentication using a key from Pageant.
8946 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
8948 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
8950 /* Unpack key from agent response */
8951 s->pklen = toint(GET_32BIT(s->agentp));
8953 s->pkblob = (char *)s->agentp;
8954 s->agentp += s->pklen;
8955 s->alglen = toint(GET_32BIT(s->pkblob));
8956 s->alg = s->pkblob + 4;
8957 s->commentlen = toint(GET_32BIT(s->agentp));
8959 s->commentp = (char *)s->agentp;
8960 s->agentp += s->commentlen;
8961 /* s->agentp now points at next key, if any */
8963 /* See if server will accept it */
8964 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8965 ssh2_pkt_addstring(s->pktout, ssh->username);
8966 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8967 /* service requested */
8968 ssh2_pkt_addstring(s->pktout, "publickey");
8970 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
8971 ssh2_pkt_addstring_start(s->pktout);
8972 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
8973 ssh2_pkt_addstring_start(s->pktout);
8974 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
8975 ssh2_pkt_send(ssh, s->pktout);
8976 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
8978 crWaitUntilV(pktin);
8979 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8981 /* Offer of key refused. */
8988 if (flags & FLAG_VERBOSE) {
8989 c_write_str(ssh, "Authenticating with "
8991 c_write(ssh, s->commentp, s->commentlen);
8992 c_write_str(ssh, "\" from agent\r\n");
8996 * Server is willing to accept the key.
8997 * Construct a SIGN_REQUEST.
8999 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9000 ssh2_pkt_addstring(s->pktout, ssh->username);
9001 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9002 /* service requested */
9003 ssh2_pkt_addstring(s->pktout, "publickey");
9005 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9006 ssh2_pkt_addstring_start(s->pktout);
9007 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9008 ssh2_pkt_addstring_start(s->pktout);
9009 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9011 /* Ask agent for signature. */
9012 s->siglen = s->pktout->length - 5 + 4 +
9013 ssh->v2_session_id_len;
9014 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9016 s->len = 1; /* message type */
9017 s->len += 4 + s->pklen; /* key blob */
9018 s->len += 4 + s->siglen; /* data to sign */
9019 s->len += 4; /* flags */
9020 s->agentreq = snewn(4 + s->len, char);
9021 PUT_32BIT(s->agentreq, s->len);
9022 s->q = s->agentreq + 4;
9023 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9024 PUT_32BIT(s->q, s->pklen);
9026 memcpy(s->q, s->pkblob, s->pklen);
9028 PUT_32BIT(s->q, s->siglen);
9030 /* Now the data to be signed... */
9031 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9032 PUT_32BIT(s->q, ssh->v2_session_id_len);
9035 memcpy(s->q, ssh->v2_session_id,
9036 ssh->v2_session_id_len);
9037 s->q += ssh->v2_session_id_len;
9038 memcpy(s->q, s->pktout->data + 5,
9039 s->pktout->length - 5);
9040 s->q += s->pktout->length - 5;
9041 /* And finally the (zero) flags word. */
9043 if (!agent_query(s->agentreq, s->len + 4,
9045 ssh_agent_callback, ssh)) {
9049 bombout(("Unexpected data from server"
9050 " while waiting for agent"
9054 } while (pktin || inlen > 0);
9055 vret = ssh->agent_response;
9056 s->retlen = ssh->agent_response_len;
9061 if (s->retlen >= 9 &&
9062 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9063 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9064 logevent("Sending Pageant's response");
9065 ssh2_add_sigblob(ssh, s->pktout,
9066 s->pkblob, s->pklen,
9068 GET_32BIT(s->ret + 5));
9069 ssh2_pkt_send(ssh, s->pktout);
9070 s->type = AUTH_TYPE_PUBLICKEY;
9072 /* FIXME: less drastic response */
9073 bombout(("Pageant failed to answer challenge"));
9079 /* Do we have any keys left to try? */
9080 if (s->pkblob_in_agent) {
9081 s->done_agent = TRUE;
9082 s->tried_pubkey_config = TRUE;
9085 if (s->keyi >= s->nkeys)
9086 s->done_agent = TRUE;
9089 } else if (s->can_pubkey && s->publickey_blob &&
9090 !s->tried_pubkey_config) {
9092 struct ssh2_userkey *key; /* not live over crReturn */
9093 char *passphrase; /* not live over crReturn */
9095 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9097 s->tried_pubkey_config = TRUE;
9100 * Try the public key supplied in the configuration.
9102 * First, offer the public blob to see if the server is
9103 * willing to accept it.
9105 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9106 ssh2_pkt_addstring(s->pktout, ssh->username);
9107 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9108 /* service requested */
9109 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9110 ssh2_pkt_addbool(s->pktout, FALSE);
9111 /* no signature included */
9112 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9113 ssh2_pkt_addstring_start(s->pktout);
9114 ssh2_pkt_addstring_data(s->pktout,
9115 (char *)s->publickey_blob,
9116 s->publickey_bloblen);
9117 ssh2_pkt_send(ssh, s->pktout);
9118 logevent("Offered public key");
9120 crWaitUntilV(pktin);
9121 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9122 /* Key refused. Give up. */
9123 s->gotit = TRUE; /* reconsider message next loop */
9124 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9125 continue; /* process this new message */
9127 logevent("Offer of public key accepted");
9130 * Actually attempt a serious authentication using
9133 if (flags & FLAG_VERBOSE) {
9134 c_write_str(ssh, "Authenticating with public key \"");
9135 c_write_str(ssh, s->publickey_comment);
9136 c_write_str(ssh, "\"\r\n");
9140 const char *error; /* not live over crReturn */
9141 if (s->publickey_encrypted) {
9143 * Get a passphrase from the user.
9145 int ret; /* need not be kept over crReturn */
9146 s->cur_prompt = new_prompts(ssh->frontend);
9147 s->cur_prompt->to_server = FALSE;
9148 s->cur_prompt->name = dupstr("SSH key passphrase");
9149 add_prompt(s->cur_prompt,
9150 dupprintf("Passphrase for key \"%.100s\": ",
9151 s->publickey_comment),
9153 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9156 crWaitUntilV(!pktin);
9157 ret = get_userpass_input(s->cur_prompt,
9162 /* Failed to get a passphrase. Terminate. */
9163 free_prompts(s->cur_prompt);
9164 ssh_disconnect(ssh, NULL,
9165 "Unable to authenticate",
9166 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9171 dupstr(s->cur_prompt->prompts[0]->result);
9172 free_prompts(s->cur_prompt);
9174 passphrase = NULL; /* no passphrase needed */
9178 * Try decrypting the key.
9180 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9181 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9183 /* burn the evidence */
9184 smemclr(passphrase, strlen(passphrase));
9187 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9189 (key == SSH2_WRONG_PASSPHRASE)) {
9190 c_write_str(ssh, "Wrong passphrase\r\n");
9192 /* and loop again */
9194 c_write_str(ssh, "Unable to load private key (");
9195 c_write_str(ssh, error);
9196 c_write_str(ssh, ")\r\n");
9198 break; /* try something else */
9204 unsigned char *pkblob, *sigblob, *sigdata;
9205 int pkblob_len, sigblob_len, sigdata_len;
9209 * We have loaded the private key and the server
9210 * has announced that it's willing to accept it.
9211 * Hallelujah. Generate a signature and send it.
9213 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9214 ssh2_pkt_addstring(s->pktout, ssh->username);
9215 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9216 /* service requested */
9217 ssh2_pkt_addstring(s->pktout, "publickey");
9219 ssh2_pkt_addbool(s->pktout, TRUE);
9220 /* signature follows */
9221 ssh2_pkt_addstring(s->pktout, key->alg->name);
9222 pkblob = key->alg->public_blob(key->data,
9224 ssh2_pkt_addstring_start(s->pktout);
9225 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9229 * The data to be signed is:
9233 * followed by everything so far placed in the
9236 sigdata_len = s->pktout->length - 5 + 4 +
9237 ssh->v2_session_id_len;
9238 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9240 sigdata = snewn(sigdata_len, unsigned char);
9242 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9243 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9246 memcpy(sigdata+p, ssh->v2_session_id,
9247 ssh->v2_session_id_len);
9248 p += ssh->v2_session_id_len;
9249 memcpy(sigdata+p, s->pktout->data + 5,
9250 s->pktout->length - 5);
9251 p += s->pktout->length - 5;
9252 assert(p == sigdata_len);
9253 sigblob = key->alg->sign(key->data, (char *)sigdata,
9254 sigdata_len, &sigblob_len);
9255 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9256 sigblob, sigblob_len);
9261 ssh2_pkt_send(ssh, s->pktout);
9262 logevent("Sent public key signature");
9263 s->type = AUTH_TYPE_PUBLICKEY;
9264 key->alg->freekey(key->data);
9268 } else if (s->can_gssapi && !s->tried_gssapi) {
9270 /* GSSAPI Authentication */
9275 s->type = AUTH_TYPE_GSSAPI;
9276 s->tried_gssapi = TRUE;
9278 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9281 * Pick the highest GSS library on the preference
9287 for (i = 0; i < ngsslibs; i++) {
9288 int want_id = conf_get_int_int(ssh->conf,
9289 CONF_ssh_gsslist, i);
9290 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
9291 if (ssh->gsslibs->libraries[j].id == want_id) {
9292 s->gsslib = &ssh->gsslibs->libraries[j];
9293 goto got_gsslib; /* double break */
9298 * We always expect to have found something in
9299 * the above loop: we only came here if there
9300 * was at least one viable GSS library, and the
9301 * preference list should always mention
9302 * everything and only change the order.
9307 if (s->gsslib->gsslogmsg)
9308 logevent(s->gsslib->gsslogmsg);
9310 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
9311 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9312 ssh2_pkt_addstring(s->pktout, ssh->username);
9313 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9314 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
9315 logevent("Attempting GSSAPI authentication");
9317 /* add mechanism info */
9318 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
9320 /* number of GSSAPI mechanisms */
9321 ssh2_pkt_adduint32(s->pktout,1);
9323 /* length of OID + 2 */
9324 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
9325 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
9328 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
9330 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
9332 ssh2_pkt_send(ssh, s->pktout);
9333 crWaitUntilV(pktin);
9334 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
9335 logevent("GSSAPI authentication request refused");
9339 /* check returned packet ... */
9341 ssh_pkt_getstring(pktin, &data, &len);
9342 s->gss_rcvtok.value = data;
9343 s->gss_rcvtok.length = len;
9344 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
9345 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
9346 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
9347 memcmp((char *)s->gss_rcvtok.value + 2,
9348 s->gss_buf.value,s->gss_buf.length) ) {
9349 logevent("GSSAPI authentication - wrong response from server");
9353 /* now start running */
9354 s->gss_stat = s->gsslib->import_name(s->gsslib,
9357 if (s->gss_stat != SSH_GSS_OK) {
9358 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
9359 logevent("GSSAPI import name failed - Bad service name");
9361 logevent("GSSAPI import name failed");
9365 /* fetch TGT into GSS engine */
9366 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
9368 if (s->gss_stat != SSH_GSS_OK) {
9369 logevent("GSSAPI authentication failed to get credentials");
9370 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9374 /* initial tokens are empty */
9375 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
9376 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
9378 /* now enter the loop */
9380 s->gss_stat = s->gsslib->init_sec_context
9384 conf_get_int(ssh->conf, CONF_gssapifwd),
9388 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
9389 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
9390 logevent("GSSAPI authentication initialisation failed");
9392 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
9393 &s->gss_buf) == SSH_GSS_OK) {
9394 logevent(s->gss_buf.value);
9395 sfree(s->gss_buf.value);
9400 logevent("GSSAPI authentication initialised");
9402 /* Client and server now exchange tokens until GSSAPI
9403 * no longer says CONTINUE_NEEDED */
9405 if (s->gss_sndtok.length != 0) {
9406 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
9407 ssh_pkt_addstring_start(s->pktout);
9408 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
9409 ssh2_pkt_send(ssh, s->pktout);
9410 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
9413 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
9414 crWaitUntilV(pktin);
9415 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
9416 logevent("GSSAPI authentication - bad server response");
9417 s->gss_stat = SSH_GSS_FAILURE;
9420 ssh_pkt_getstring(pktin, &data, &len);
9421 s->gss_rcvtok.value = data;
9422 s->gss_rcvtok.length = len;
9424 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
9426 if (s->gss_stat != SSH_GSS_OK) {
9427 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9428 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9431 logevent("GSSAPI authentication loop finished OK");
9433 /* Now send the MIC */
9435 s->pktout = ssh2_pkt_init(0);
9436 micoffset = s->pktout->length;
9437 ssh_pkt_addstring_start(s->pktout);
9438 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
9439 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
9440 ssh_pkt_addstring(s->pktout, ssh->username);
9441 ssh_pkt_addstring(s->pktout, "ssh-connection");
9442 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
9444 s->gss_buf.value = (char *)s->pktout->data + micoffset;
9445 s->gss_buf.length = s->pktout->length - micoffset;
9447 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
9448 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
9449 ssh_pkt_addstring_start(s->pktout);
9450 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
9451 ssh2_pkt_send(ssh, s->pktout);
9452 s->gsslib->free_mic(s->gsslib, &mic);
9456 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9457 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9460 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
9463 * Keyboard-interactive authentication.
9466 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
9468 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
9470 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9471 ssh2_pkt_addstring(s->pktout, ssh->username);
9472 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9473 /* service requested */
9474 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
9476 ssh2_pkt_addstring(s->pktout, ""); /* lang */
9477 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
9478 ssh2_pkt_send(ssh, s->pktout);
9480 logevent("Attempting keyboard-interactive authentication");
9482 crWaitUntilV(pktin);
9483 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
9484 /* Server is not willing to do keyboard-interactive
9485 * at all (or, bizarrely but legally, accepts the
9486 * user without actually issuing any prompts).
9487 * Give up on it entirely. */
9489 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
9490 s->kbd_inter_refused = TRUE; /* don't try it again */
9495 * Loop while the server continues to send INFO_REQUESTs.
9497 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
9499 char *name, *inst, *lang;
9500 int name_len, inst_len, lang_len;
9504 * We've got a fresh USERAUTH_INFO_REQUEST.
9505 * Get the preamble and start building a prompt.
9507 ssh_pkt_getstring(pktin, &name, &name_len);
9508 ssh_pkt_getstring(pktin, &inst, &inst_len);
9509 ssh_pkt_getstring(pktin, &lang, &lang_len);
9510 s->cur_prompt = new_prompts(ssh->frontend);
9511 s->cur_prompt->to_server = TRUE;
9514 * Get any prompt(s) from the packet.
9516 s->num_prompts = ssh_pkt_getuint32(pktin);
9517 for (i = 0; i < s->num_prompts; i++) {
9521 static char noprompt[] =
9522 "<server failed to send prompt>: ";
9524 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9525 echo = ssh2_pkt_getbool(pktin);
9528 prompt_len = lenof(noprompt)-1;
9530 add_prompt(s->cur_prompt,
9531 dupprintf("%.*s", prompt_len, prompt),
9536 /* FIXME: better prefix to distinguish from
9538 s->cur_prompt->name =
9539 dupprintf("SSH server: %.*s", name_len, name);
9540 s->cur_prompt->name_reqd = TRUE;
9542 s->cur_prompt->name =
9543 dupstr("SSH server authentication");
9544 s->cur_prompt->name_reqd = FALSE;
9546 /* We add a prefix to try to make it clear that a prompt
9547 * has come from the server.
9548 * FIXME: ugly to print "Using..." in prompt _every_
9549 * time round. Can this be done more subtly? */
9550 /* Special case: for reasons best known to themselves,
9551 * some servers send k-i requests with no prompts and
9552 * nothing to display. Keep quiet in this case. */
9553 if (s->num_prompts || name_len || inst_len) {
9554 s->cur_prompt->instruction =
9555 dupprintf("Using keyboard-interactive authentication.%s%.*s",
9556 inst_len ? "\n" : "", inst_len, inst);
9557 s->cur_prompt->instr_reqd = TRUE;
9559 s->cur_prompt->instr_reqd = FALSE;
9563 * Display any instructions, and get the user's
9567 int ret; /* not live over crReturn */
9568 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9571 crWaitUntilV(!pktin);
9572 ret = get_userpass_input(s->cur_prompt, in, inlen);
9577 * Failed to get responses. Terminate.
9579 free_prompts(s->cur_prompt);
9580 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9581 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9588 * Send the response(s) to the server.
9590 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
9591 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
9592 for (i=0; i < s->num_prompts; i++) {
9593 ssh2_pkt_addstring(s->pktout,
9594 s->cur_prompt->prompts[i]->result);
9596 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9599 * Free the prompts structure from this iteration.
9600 * If there's another, a new one will be allocated
9601 * when we return to the top of this while loop.
9603 free_prompts(s->cur_prompt);
9606 * Get the next packet in case it's another
9609 crWaitUntilV(pktin);
9614 * We should have SUCCESS or FAILURE now.
9618 } else if (s->can_passwd) {
9621 * Plain old password authentication.
9623 int ret; /* not live over crReturn */
9624 int changereq_first_time; /* not live over crReturn */
9626 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
9628 s->cur_prompt = new_prompts(ssh->frontend);
9629 s->cur_prompt->to_server = TRUE;
9630 s->cur_prompt->name = dupstr("SSH password");
9631 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
9636 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9639 crWaitUntilV(!pktin);
9640 ret = get_userpass_input(s->cur_prompt, in, inlen);
9645 * Failed to get responses. Terminate.
9647 free_prompts(s->cur_prompt);
9648 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9649 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9654 * Squirrel away the password. (We may need it later if
9655 * asked to change it.)
9657 s->password = dupstr(s->cur_prompt->prompts[0]->result);
9658 free_prompts(s->cur_prompt);
9661 * Send the password packet.
9663 * We pad out the password packet to 256 bytes to make
9664 * it harder for an attacker to find the length of the
9667 * Anyone using a password longer than 256 bytes
9668 * probably doesn't have much to worry about from
9669 * people who find out how long their password is!
9671 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9672 ssh2_pkt_addstring(s->pktout, ssh->username);
9673 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9674 /* service requested */
9675 ssh2_pkt_addstring(s->pktout, "password");
9676 ssh2_pkt_addbool(s->pktout, FALSE);
9677 ssh2_pkt_addstring(s->pktout, s->password);
9678 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9679 logevent("Sent password");
9680 s->type = AUTH_TYPE_PASSWORD;
9683 * Wait for next packet, in case it's a password change
9686 crWaitUntilV(pktin);
9687 changereq_first_time = TRUE;
9689 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
9692 * We're being asked for a new password
9693 * (perhaps not for the first time).
9694 * Loop until the server accepts it.
9697 int got_new = FALSE; /* not live over crReturn */
9698 char *prompt; /* not live over crReturn */
9699 int prompt_len; /* not live over crReturn */
9703 if (changereq_first_time)
9704 msg = "Server requested password change";
9706 msg = "Server rejected new password";
9708 c_write_str(ssh, msg);
9709 c_write_str(ssh, "\r\n");
9712 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9714 s->cur_prompt = new_prompts(ssh->frontend);
9715 s->cur_prompt->to_server = TRUE;
9716 s->cur_prompt->name = dupstr("New SSH password");
9717 s->cur_prompt->instruction =
9718 dupprintf("%.*s", prompt_len, prompt);
9719 s->cur_prompt->instr_reqd = TRUE;
9721 * There's no explicit requirement in the protocol
9722 * for the "old" passwords in the original and
9723 * password-change messages to be the same, and
9724 * apparently some Cisco kit supports password change
9725 * by the user entering a blank password originally
9726 * and the real password subsequently, so,
9727 * reluctantly, we prompt for the old password again.
9729 * (On the other hand, some servers don't even bother
9730 * to check this field.)
9732 add_prompt(s->cur_prompt,
9733 dupstr("Current password (blank for previously entered password): "),
9735 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
9737 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
9741 * Loop until the user manages to enter the same
9746 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9749 crWaitUntilV(!pktin);
9750 ret = get_userpass_input(s->cur_prompt, in, inlen);
9755 * Failed to get responses. Terminate.
9757 /* burn the evidence */
9758 free_prompts(s->cur_prompt);
9759 smemclr(s->password, strlen(s->password));
9761 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9762 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9768 * If the user specified a new original password
9769 * (IYSWIM), overwrite any previously specified
9771 * (A side effect is that the user doesn't have to
9772 * re-enter it if they louse up the new password.)
9774 if (s->cur_prompt->prompts[0]->result[0]) {
9775 smemclr(s->password, strlen(s->password));
9776 /* burn the evidence */
9779 dupstr(s->cur_prompt->prompts[0]->result);
9783 * Check the two new passwords match.
9785 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
9786 s->cur_prompt->prompts[2]->result)
9789 /* They don't. Silly user. */
9790 c_write_str(ssh, "Passwords do not match\r\n");
9795 * Send the new password (along with the old one).
9796 * (see above for padding rationale)
9798 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9799 ssh2_pkt_addstring(s->pktout, ssh->username);
9800 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9801 /* service requested */
9802 ssh2_pkt_addstring(s->pktout, "password");
9803 ssh2_pkt_addbool(s->pktout, TRUE);
9804 ssh2_pkt_addstring(s->pktout, s->password);
9805 ssh2_pkt_addstring(s->pktout,
9806 s->cur_prompt->prompts[1]->result);
9807 free_prompts(s->cur_prompt);
9808 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9809 logevent("Sent new password");
9812 * Now see what the server has to say about it.
9813 * (If it's CHANGEREQ again, it's not happy with the
9816 crWaitUntilV(pktin);
9817 changereq_first_time = FALSE;
9822 * We need to reexamine the current pktin at the top
9823 * of the loop. Either:
9824 * - we weren't asked to change password at all, in
9825 * which case it's a SUCCESS or FAILURE with the
9827 * - we sent a new password, and the server was
9828 * either OK with it (SUCCESS or FAILURE w/partial
9829 * success) or unhappy with the _old_ password
9830 * (FAILURE w/o partial success)
9831 * In any of these cases, we go back to the top of
9832 * the loop and start again.
9837 * We don't need the old password any more, in any
9838 * case. Burn the evidence.
9840 smemclr(s->password, strlen(s->password));
9844 char *str = dupprintf("No supported authentication methods available"
9845 " (server sent: %.*s)",
9848 ssh_disconnect(ssh, str,
9849 "No supported authentication methods available",
9850 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
9860 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9862 /* Clear up various bits and pieces from authentication. */
9863 if (s->publickey_blob) {
9864 sfree(s->publickey_blob);
9865 sfree(s->publickey_comment);
9867 if (s->agent_response)
9868 sfree(s->agent_response);
9870 if (s->userauth_success && !ssh->bare_connection) {
9872 * We've just received USERAUTH_SUCCESS, and we haven't sent any
9873 * packets since. Signal the transport layer to consider enacting
9874 * delayed compression.
9876 * (Relying on we_are_in is not sufficient, as
9877 * draft-miller-secsh-compression-delayed is quite clear that it
9878 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
9879 * become set for other reasons.)
9881 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
9884 ssh->channels = newtree234(ssh_channelcmp);
9887 * Set up handlers for some connection protocol messages, so we
9888 * don't have to handle them repeatedly in this coroutine.
9890 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
9891 ssh2_msg_channel_window_adjust;
9892 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
9893 ssh2_msg_global_request;
9896 * Create the main session channel.
9898 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
9899 ssh->mainchan = NULL;
9901 ssh->mainchan = snew(struct ssh_channel);
9902 ssh->mainchan->ssh = ssh;
9903 ssh2_channel_init(ssh->mainchan);
9905 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
9907 * Just start a direct-tcpip channel and use it as the main
9910 ssh_send_port_open(ssh->mainchan,
9911 conf_get_str(ssh->conf, CONF_ssh_nc_host),
9912 conf_get_int(ssh->conf, CONF_ssh_nc_port),
9916 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
9917 logevent("Opening session as main channel");
9918 ssh2_pkt_send(ssh, s->pktout);
9919 ssh->ncmode = FALSE;
9921 crWaitUntilV(pktin);
9922 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
9923 bombout(("Server refused to open channel"));
9925 /* FIXME: error data comes back in FAILURE packet */
9927 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
9928 bombout(("Server's channel confirmation cited wrong channel"));
9931 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
9932 ssh->mainchan->halfopen = FALSE;
9933 ssh->mainchan->type = CHAN_MAINSESSION;
9934 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
9935 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
9936 add234(ssh->channels, ssh->mainchan);
9937 update_specials_menu(ssh->frontend);
9938 logevent("Opened main channel");
9942 * Now we have a channel, make dispatch table entries for
9943 * general channel-based messages.
9945 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
9946 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
9947 ssh2_msg_channel_data;
9948 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
9949 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
9950 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
9951 ssh2_msg_channel_open_confirmation;
9952 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
9953 ssh2_msg_channel_open_failure;
9954 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
9955 ssh2_msg_channel_request;
9956 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
9957 ssh2_msg_channel_open;
9958 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
9959 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
9962 * Now the connection protocol is properly up and running, with
9963 * all those dispatch table entries, so it's safe to let
9964 * downstreams start trying to open extra channels through us.
9967 share_activate(ssh->connshare, ssh->v_s);
9969 if (ssh->mainchan && ssh_is_simple(ssh)) {
9971 * This message indicates to the server that we promise
9972 * not to try to run any other channel in parallel with
9973 * this one, so it's safe for it to advertise a very large
9974 * window and leave the flow control to TCP.
9976 s->pktout = ssh2_chanreq_init(ssh->mainchan,
9977 "simple@putty.projects.tartarus.org",
9979 ssh2_pkt_send(ssh, s->pktout);
9983 * Enable port forwardings.
9985 ssh_setup_portfwd(ssh, ssh->conf);
9987 if (ssh->mainchan && !ssh->ncmode) {
9989 * Send the CHANNEL_REQUESTS for the main session channel.
9990 * Each one is handled by its own little asynchronous
9994 /* Potentially enable X11 forwarding. */
9995 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
9997 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
9999 if (!ssh->x11disp) {
10000 /* FIXME: return an error message from x11_setup_display */
10001 logevent("X11 forwarding not enabled: unable to"
10002 " initialise X display");
10004 ssh->x11auth = x11_invent_fake_auth
10005 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10006 ssh->x11auth->disp = ssh->x11disp;
10008 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10012 /* Potentially enable agent forwarding. */
10013 if (ssh_agent_forwarding_permitted(ssh))
10014 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10016 /* Now allocate a pty for the session. */
10017 if (!conf_get_int(ssh->conf, CONF_nopty))
10018 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10020 /* Send environment variables. */
10021 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10024 * Start a shell or a remote command. We may have to attempt
10025 * this twice if the config data has provided a second choice
10032 if (ssh->fallback_cmd) {
10033 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10034 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10036 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10037 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10041 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10042 ssh2_response_authconn, NULL);
10043 ssh2_pkt_addstring(s->pktout, cmd);
10045 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10046 ssh2_response_authconn, NULL);
10047 ssh2_pkt_addstring(s->pktout, cmd);
10049 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10050 ssh2_response_authconn, NULL);
10052 ssh2_pkt_send(ssh, s->pktout);
10054 crWaitUntilV(pktin);
10056 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10057 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10058 bombout(("Unexpected response to shell/command request:"
10059 " packet type %d", pktin->type));
10063 * We failed to start the command. If this is the
10064 * fallback command, we really are finished; if it's
10065 * not, and if the fallback command exists, try falling
10066 * back to it before complaining.
10068 if (!ssh->fallback_cmd &&
10069 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10070 logevent("Primary command failed; attempting fallback");
10071 ssh->fallback_cmd = TRUE;
10074 bombout(("Server refused to start a shell/command"));
10077 logevent("Started a shell/command");
10082 ssh->editing = ssh->echoing = TRUE;
10085 ssh->state = SSH_STATE_SESSION;
10086 if (ssh->size_needed)
10087 ssh_size(ssh, ssh->term_width, ssh->term_height);
10088 if (ssh->eof_needed)
10089 ssh_special(ssh, TS_EOF);
10095 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
10100 s->try_send = FALSE;
10104 * _All_ the connection-layer packets we expect to
10105 * receive are now handled by the dispatch table.
10106 * Anything that reaches here must be bogus.
10109 bombout(("Strange packet received: type %d", pktin->type));
10111 } else if (ssh->mainchan) {
10113 * We have spare data. Add it to the channel buffer.
10115 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
10116 s->try_send = TRUE;
10120 struct ssh_channel *c;
10122 * Try to send data on all channels if we can.
10124 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
10125 ssh2_try_send_and_unthrottle(ssh, c);
10133 * Handlers for SSH-2 messages that might arrive at any moment.
10135 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10137 /* log reason code in disconnect message */
10139 int reason, msglen;
10141 reason = ssh_pkt_getuint32(pktin);
10142 ssh_pkt_getstring(pktin, &msg, &msglen);
10144 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10145 buf = dupprintf("Received disconnect message (%s)",
10146 ssh2_disconnect_reasons[reason]);
10148 buf = dupprintf("Received disconnect message (unknown"
10149 " type %d)", reason);
10153 buf = dupprintf("Disconnection message text: %.*s",
10156 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10158 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10159 ssh2_disconnect_reasons[reason] : "unknown",
10164 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10166 /* log the debug message */
10170 /* XXX maybe we should actually take notice of the return value */
10171 ssh2_pkt_getbool(pktin);
10172 ssh_pkt_getstring(pktin, &msg, &msglen);
10174 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
10177 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10179 do_ssh2_transport(ssh, NULL, 0, pktin);
10183 * Called if we receive a packet that isn't allowed by the protocol.
10184 * This only applies to packets whose meaning PuTTY understands.
10185 * Entirely unknown packets are handled below.
10187 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10189 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10190 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10192 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10196 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10198 struct Packet *pktout;
10199 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10200 ssh2_pkt_adduint32(pktout, pktin->sequence);
10202 * UNIMPLEMENTED messages MUST appear in the same order as the
10203 * messages they respond to. Hence, never queue them.
10205 ssh2_pkt_send_noqueue(ssh, pktout);
10209 * Handle the top-level SSH-2 protocol.
10211 static void ssh2_protocol_setup(Ssh ssh)
10216 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10218 for (i = 0; i < 256; i++)
10219 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10222 * Initially, we only accept transport messages (and a few generic
10223 * ones). do_ssh2_authconn will add more when it starts.
10224 * Messages that are understood but not currently acceptable go to
10225 * ssh2_msg_unexpected.
10227 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10228 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10229 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10230 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10231 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10232 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10233 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10234 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10235 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10236 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10237 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10238 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10239 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10240 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10241 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10242 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10243 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10244 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10245 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10246 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10247 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10248 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10249 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10250 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10251 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10252 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10253 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10254 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10255 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10256 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10257 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10258 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10259 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10262 * These messages have a special handler from the start.
10264 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10265 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10266 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10269 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10274 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10276 for (i = 0; i < 256; i++)
10277 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10280 * Initially, we set all ssh-connection messages to 'unexpected';
10281 * do_ssh2_authconn will fill things in properly. We also handle a
10282 * couple of messages from the transport protocol which aren't
10283 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10286 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10287 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10288 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10289 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10290 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10291 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10292 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10293 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10294 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10295 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10296 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10297 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10298 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10299 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10301 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10304 * These messages have a special handler from the start.
10306 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10307 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
10308 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10311 static void ssh2_timer(void *ctx, unsigned long now)
10313 Ssh ssh = (Ssh)ctx;
10315 if (ssh->state == SSH_STATE_CLOSED)
10318 if (!ssh->kex_in_progress && !ssh->bare_connection &&
10319 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
10320 now == ssh->next_rekey) {
10321 do_ssh2_transport(ssh, "timeout", -1, NULL);
10325 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
10326 struct Packet *pktin)
10328 unsigned char *in = (unsigned char *)vin;
10329 if (ssh->state == SSH_STATE_CLOSED)
10333 ssh->incoming_data_size += pktin->encrypted_len;
10334 if (!ssh->kex_in_progress &&
10335 ssh->max_data_size != 0 &&
10336 ssh->incoming_data_size > ssh->max_data_size)
10337 do_ssh2_transport(ssh, "too much data received", -1, NULL);
10341 ssh->packet_dispatch[pktin->type](ssh, pktin);
10342 else if (!ssh->protocol_initial_phase_done)
10343 do_ssh2_transport(ssh, in, inlen, pktin);
10345 do_ssh2_authconn(ssh, in, inlen, pktin);
10348 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
10349 struct Packet *pktin)
10351 unsigned char *in = (unsigned char *)vin;
10352 if (ssh->state == SSH_STATE_CLOSED)
10356 ssh->packet_dispatch[pktin->type](ssh, pktin);
10358 do_ssh2_authconn(ssh, in, inlen, pktin);
10361 static void ssh_cache_conf_values(Ssh ssh)
10363 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
10367 * Called to set up the connection.
10369 * Returns an error message, or NULL on success.
10371 static const char *ssh_init(void *frontend_handle, void **backend_handle,
10372 Conf *conf, char *host, int port, char **realhost,
10373 int nodelay, int keepalive)
10378 ssh = snew(struct ssh_tag);
10379 ssh->conf = conf_copy(conf);
10380 ssh_cache_conf_values(ssh);
10381 ssh->version = 0; /* when not ready yet */
10383 ssh->cipher = NULL;
10384 ssh->v1_cipher_ctx = NULL;
10385 ssh->crcda_ctx = NULL;
10386 ssh->cscipher = NULL;
10387 ssh->cs_cipher_ctx = NULL;
10388 ssh->sccipher = NULL;
10389 ssh->sc_cipher_ctx = NULL;
10391 ssh->cs_mac_ctx = NULL;
10393 ssh->sc_mac_ctx = NULL;
10394 ssh->cscomp = NULL;
10395 ssh->cs_comp_ctx = NULL;
10396 ssh->sccomp = NULL;
10397 ssh->sc_comp_ctx = NULL;
10399 ssh->kex_ctx = NULL;
10400 ssh->hostkey = NULL;
10401 ssh->hostkey_str = NULL;
10402 ssh->exitcode = -1;
10403 ssh->close_expected = FALSE;
10404 ssh->clean_exit = FALSE;
10405 ssh->state = SSH_STATE_PREPACKET;
10406 ssh->size_needed = FALSE;
10407 ssh->eof_needed = FALSE;
10409 ssh->logctx = NULL;
10410 ssh->deferred_send_data = NULL;
10411 ssh->deferred_len = 0;
10412 ssh->deferred_size = 0;
10413 ssh->fallback_cmd = 0;
10414 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
10415 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
10416 ssh->x11disp = NULL;
10417 ssh->x11auth = NULL;
10418 ssh->x11authtree = newtree234(x11_authcmp);
10419 ssh->v1_compressing = FALSE;
10420 ssh->v2_outgoing_sequence = 0;
10421 ssh->ssh1_rdpkt_crstate = 0;
10422 ssh->ssh2_rdpkt_crstate = 0;
10423 ssh->ssh2_bare_rdpkt_crstate = 0;
10424 ssh->ssh_gotdata_crstate = 0;
10425 ssh->do_ssh1_connection_crstate = 0;
10426 ssh->do_ssh_init_state = NULL;
10427 ssh->do_ssh_connection_init_state = NULL;
10428 ssh->do_ssh1_login_state = NULL;
10429 ssh->do_ssh2_transport_state = NULL;
10430 ssh->do_ssh2_authconn_state = NULL;
10433 ssh->mainchan = NULL;
10434 ssh->throttled_all = 0;
10435 ssh->v1_stdout_throttling = 0;
10437 ssh->queuelen = ssh->queuesize = 0;
10438 ssh->queueing = FALSE;
10439 ssh->qhead = ssh->qtail = NULL;
10440 ssh->deferred_rekey_reason = NULL;
10441 bufchain_init(&ssh->queued_incoming_data);
10442 ssh->frozen = FALSE;
10443 ssh->username = NULL;
10444 ssh->sent_console_eof = FALSE;
10445 ssh->got_pty = FALSE;
10446 ssh->bare_connection = FALSE;
10447 ssh->attempting_connshare = FALSE;
10449 *backend_handle = ssh;
10452 if (crypto_startup() == 0)
10453 return "Microsoft high encryption pack not installed!";
10456 ssh->frontend = frontend_handle;
10457 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
10458 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
10460 ssh->channels = NULL;
10461 ssh->rportfwds = NULL;
10462 ssh->portfwds = NULL;
10467 ssh->conn_throttle_count = 0;
10468 ssh->overall_bufsize = 0;
10469 ssh->fallback_cmd = 0;
10471 ssh->protocol = NULL;
10473 ssh->protocol_initial_phase_done = FALSE;
10475 ssh->pinger = NULL;
10477 ssh->incoming_data_size = ssh->outgoing_data_size =
10478 ssh->deferred_data_size = 0L;
10479 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10480 CONF_ssh_rekey_data));
10481 ssh->kex_in_progress = FALSE;
10484 ssh->gsslibs = NULL;
10487 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
10496 static void ssh_free(void *handle)
10498 Ssh ssh = (Ssh) handle;
10499 struct ssh_channel *c;
10500 struct ssh_rportfwd *pf;
10501 struct X11FakeAuth *auth;
10503 if (ssh->v1_cipher_ctx)
10504 ssh->cipher->free_context(ssh->v1_cipher_ctx);
10505 if (ssh->cs_cipher_ctx)
10506 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
10507 if (ssh->sc_cipher_ctx)
10508 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
10509 if (ssh->cs_mac_ctx)
10510 ssh->csmac->free_context(ssh->cs_mac_ctx);
10511 if (ssh->sc_mac_ctx)
10512 ssh->scmac->free_context(ssh->sc_mac_ctx);
10513 if (ssh->cs_comp_ctx) {
10515 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
10517 zlib_compress_cleanup(ssh->cs_comp_ctx);
10519 if (ssh->sc_comp_ctx) {
10521 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
10523 zlib_decompress_cleanup(ssh->sc_comp_ctx);
10526 dh_cleanup(ssh->kex_ctx);
10527 sfree(ssh->savedhost);
10529 while (ssh->queuelen-- > 0)
10530 ssh_free_packet(ssh->queue[ssh->queuelen]);
10533 while (ssh->qhead) {
10534 struct queued_handler *qh = ssh->qhead;
10535 ssh->qhead = qh->next;
10538 ssh->qhead = ssh->qtail = NULL;
10540 if (ssh->channels) {
10541 while ((c = delpos234(ssh->channels, 0)) != NULL) {
10544 if (c->u.x11.xconn != NULL)
10545 x11_close(c->u.x11.xconn);
10547 case CHAN_SOCKDATA:
10548 case CHAN_SOCKDATA_DORMANT:
10549 if (c->u.pfd.pf != NULL)
10550 pfd_close(c->u.pfd.pf);
10553 if (ssh->version == 2) {
10554 struct outstanding_channel_request *ocr, *nocr;
10555 ocr = c->v.v2.chanreq_head;
10557 ocr->handler(c, NULL, ocr->ctx);
10562 bufchain_clear(&c->v.v2.outbuffer);
10566 freetree234(ssh->channels);
10567 ssh->channels = NULL;
10570 if (ssh->connshare)
10571 sharestate_free(ssh->connshare);
10573 if (ssh->rportfwds) {
10574 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
10576 freetree234(ssh->rportfwds);
10577 ssh->rportfwds = NULL;
10579 sfree(ssh->deferred_send_data);
10581 x11_free_display(ssh->x11disp);
10582 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
10583 x11_free_fake_auth(auth);
10584 freetree234(ssh->x11authtree);
10585 sfree(ssh->do_ssh_init_state);
10586 sfree(ssh->do_ssh1_login_state);
10587 sfree(ssh->do_ssh2_transport_state);
10588 sfree(ssh->do_ssh2_authconn_state);
10591 sfree(ssh->fullhostname);
10592 sfree(ssh->hostkey_str);
10593 if (ssh->crcda_ctx) {
10594 crcda_free_context(ssh->crcda_ctx);
10595 ssh->crcda_ctx = NULL;
10598 ssh_do_close(ssh, TRUE);
10599 expire_timer_context(ssh);
10601 pinger_free(ssh->pinger);
10602 bufchain_clear(&ssh->queued_incoming_data);
10603 sfree(ssh->username);
10604 conf_free(ssh->conf);
10607 ssh_gss_cleanup(ssh->gsslibs);
10615 * Reconfigure the SSH backend.
10617 static void ssh_reconfig(void *handle, Conf *conf)
10619 Ssh ssh = (Ssh) handle;
10620 char *rekeying = NULL, rekey_mandatory = FALSE;
10621 unsigned long old_max_data_size;
10624 pinger_reconfig(ssh->pinger, ssh->conf, conf);
10626 ssh_setup_portfwd(ssh, conf);
10628 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
10629 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
10631 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
10632 unsigned long now = GETTICKCOUNT();
10634 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
10635 rekeying = "timeout shortened";
10637 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
10641 old_max_data_size = ssh->max_data_size;
10642 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10643 CONF_ssh_rekey_data));
10644 if (old_max_data_size != ssh->max_data_size &&
10645 ssh->max_data_size != 0) {
10646 if (ssh->outgoing_data_size > ssh->max_data_size ||
10647 ssh->incoming_data_size > ssh->max_data_size)
10648 rekeying = "data limit lowered";
10651 if (conf_get_int(ssh->conf, CONF_compression) !=
10652 conf_get_int(conf, CONF_compression)) {
10653 rekeying = "compression setting changed";
10654 rekey_mandatory = TRUE;
10657 for (i = 0; i < CIPHER_MAX; i++)
10658 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
10659 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
10660 rekeying = "cipher settings changed";
10661 rekey_mandatory = TRUE;
10663 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
10664 conf_get_int(conf, CONF_ssh2_des_cbc)) {
10665 rekeying = "cipher settings changed";
10666 rekey_mandatory = TRUE;
10669 conf_free(ssh->conf);
10670 ssh->conf = conf_copy(conf);
10671 ssh_cache_conf_values(ssh);
10673 if (!ssh->bare_connection && rekeying) {
10674 if (!ssh->kex_in_progress) {
10675 do_ssh2_transport(ssh, rekeying, -1, NULL);
10676 } else if (rekey_mandatory) {
10677 ssh->deferred_rekey_reason = rekeying;
10683 * Called to send data down the SSH connection.
10685 static int ssh_send(void *handle, char *buf, int len)
10687 Ssh ssh = (Ssh) handle;
10689 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10692 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
10694 return ssh_sendbuffer(ssh);
10698 * Called to query the current amount of buffered stdin data.
10700 static int ssh_sendbuffer(void *handle)
10702 Ssh ssh = (Ssh) handle;
10703 int override_value;
10705 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10709 * If the SSH socket itself has backed up, add the total backup
10710 * size on that to any individual buffer on the stdin channel.
10712 override_value = 0;
10713 if (ssh->throttled_all)
10714 override_value = ssh->overall_bufsize;
10716 if (ssh->version == 1) {
10717 return override_value;
10718 } else if (ssh->version == 2) {
10719 if (!ssh->mainchan)
10720 return override_value;
10722 return (override_value +
10723 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
10730 * Called to set the size of the window from SSH's POV.
10732 static void ssh_size(void *handle, int width, int height)
10734 Ssh ssh = (Ssh) handle;
10735 struct Packet *pktout;
10737 ssh->term_width = width;
10738 ssh->term_height = height;
10740 switch (ssh->state) {
10741 case SSH_STATE_BEFORE_SIZE:
10742 case SSH_STATE_PREPACKET:
10743 case SSH_STATE_CLOSED:
10744 break; /* do nothing */
10745 case SSH_STATE_INTERMED:
10746 ssh->size_needed = TRUE; /* buffer for later */
10748 case SSH_STATE_SESSION:
10749 if (!conf_get_int(ssh->conf, CONF_nopty)) {
10750 if (ssh->version == 1) {
10751 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
10752 PKT_INT, ssh->term_height,
10753 PKT_INT, ssh->term_width,
10754 PKT_INT, 0, PKT_INT, 0, PKT_END);
10755 } else if (ssh->mainchan) {
10756 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
10758 ssh2_pkt_adduint32(pktout, ssh->term_width);
10759 ssh2_pkt_adduint32(pktout, ssh->term_height);
10760 ssh2_pkt_adduint32(pktout, 0);
10761 ssh2_pkt_adduint32(pktout, 0);
10762 ssh2_pkt_send(ssh, pktout);
10770 * Return a list of the special codes that make sense in this
10773 static const struct telnet_special *ssh_get_specials(void *handle)
10775 static const struct telnet_special ssh1_ignore_special[] = {
10776 {"IGNORE message", TS_NOP}
10778 static const struct telnet_special ssh2_ignore_special[] = {
10779 {"IGNORE message", TS_NOP},
10781 static const struct telnet_special ssh2_rekey_special[] = {
10782 {"Repeat key exchange", TS_REKEY},
10784 static const struct telnet_special ssh2_session_specials[] = {
10787 /* These are the signal names defined by RFC 4254.
10788 * They include all the ISO C signals, but are a subset of the POSIX
10789 * required signals. */
10790 {"SIGINT (Interrupt)", TS_SIGINT},
10791 {"SIGTERM (Terminate)", TS_SIGTERM},
10792 {"SIGKILL (Kill)", TS_SIGKILL},
10793 {"SIGQUIT (Quit)", TS_SIGQUIT},
10794 {"SIGHUP (Hangup)", TS_SIGHUP},
10795 {"More signals", TS_SUBMENU},
10796 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
10797 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
10798 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
10799 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
10800 {NULL, TS_EXITMENU}
10802 static const struct telnet_special specials_end[] = {
10803 {NULL, TS_EXITMENU}
10805 /* XXX review this length for any changes: */
10806 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
10807 lenof(ssh2_rekey_special) +
10808 lenof(ssh2_session_specials) +
10809 lenof(specials_end)];
10810 Ssh ssh = (Ssh) handle;
10812 #define ADD_SPECIALS(name) \
10814 assert((i + lenof(name)) <= lenof(ssh_specials)); \
10815 memcpy(&ssh_specials[i], name, sizeof name); \
10816 i += lenof(name); \
10819 if (ssh->version == 1) {
10820 /* Don't bother offering IGNORE if we've decided the remote
10821 * won't cope with it, since we wouldn't bother sending it if
10823 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10824 ADD_SPECIALS(ssh1_ignore_special);
10825 } else if (ssh->version == 2) {
10826 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
10827 ADD_SPECIALS(ssh2_ignore_special);
10828 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
10829 ADD_SPECIALS(ssh2_rekey_special);
10831 ADD_SPECIALS(ssh2_session_specials);
10832 } /* else we're not ready yet */
10835 ADD_SPECIALS(specials_end);
10836 return ssh_specials;
10840 #undef ADD_SPECIALS
10844 * Send special codes. TS_EOF is useful for `plink', so you
10845 * can send an EOF and collect resulting output (e.g. `plink
10848 static void ssh_special(void *handle, Telnet_Special code)
10850 Ssh ssh = (Ssh) handle;
10851 struct Packet *pktout;
10853 if (code == TS_EOF) {
10854 if (ssh->state != SSH_STATE_SESSION) {
10856 * Buffer the EOF in case we are pre-SESSION, so we can
10857 * send it as soon as we reach SESSION.
10859 if (code == TS_EOF)
10860 ssh->eof_needed = TRUE;
10863 if (ssh->version == 1) {
10864 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
10865 } else if (ssh->mainchan) {
10866 sshfwd_write_eof(ssh->mainchan);
10867 ssh->send_ok = 0; /* now stop trying to read from stdin */
10869 logevent("Sent EOF message");
10870 } else if (code == TS_PING || code == TS_NOP) {
10871 if (ssh->state == SSH_STATE_CLOSED
10872 || ssh->state == SSH_STATE_PREPACKET) return;
10873 if (ssh->version == 1) {
10874 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10875 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
10877 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
10878 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
10879 ssh2_pkt_addstring_start(pktout);
10880 ssh2_pkt_send_noqueue(ssh, pktout);
10883 } else if (code == TS_REKEY) {
10884 if (!ssh->kex_in_progress && !ssh->bare_connection &&
10885 ssh->version == 2) {
10886 do_ssh2_transport(ssh, "at user request", -1, NULL);
10888 } else if (code == TS_BRK) {
10889 if (ssh->state == SSH_STATE_CLOSED
10890 || ssh->state == SSH_STATE_PREPACKET) return;
10891 if (ssh->version == 1) {
10892 logevent("Unable to send BREAK signal in SSH-1");
10893 } else if (ssh->mainchan) {
10894 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
10895 ssh2_pkt_adduint32(pktout, 0); /* default break length */
10896 ssh2_pkt_send(ssh, pktout);
10899 /* Is is a POSIX signal? */
10900 char *signame = NULL;
10901 if (code == TS_SIGABRT) signame = "ABRT";
10902 if (code == TS_SIGALRM) signame = "ALRM";
10903 if (code == TS_SIGFPE) signame = "FPE";
10904 if (code == TS_SIGHUP) signame = "HUP";
10905 if (code == TS_SIGILL) signame = "ILL";
10906 if (code == TS_SIGINT) signame = "INT";
10907 if (code == TS_SIGKILL) signame = "KILL";
10908 if (code == TS_SIGPIPE) signame = "PIPE";
10909 if (code == TS_SIGQUIT) signame = "QUIT";
10910 if (code == TS_SIGSEGV) signame = "SEGV";
10911 if (code == TS_SIGTERM) signame = "TERM";
10912 if (code == TS_SIGUSR1) signame = "USR1";
10913 if (code == TS_SIGUSR2) signame = "USR2";
10914 /* The SSH-2 protocol does in principle support arbitrary named
10915 * signals, including signame@domain, but we don't support those. */
10917 /* It's a signal. */
10918 if (ssh->version == 2 && ssh->mainchan) {
10919 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
10920 ssh2_pkt_addstring(pktout, signame);
10921 ssh2_pkt_send(ssh, pktout);
10922 logeventf(ssh, "Sent signal SIG%s", signame);
10925 /* Never heard of it. Do nothing */
10930 void *new_sock_channel(void *handle, struct PortForwarding *pf)
10932 Ssh ssh = (Ssh) handle;
10933 struct ssh_channel *c;
10934 c = snew(struct ssh_channel);
10937 ssh2_channel_init(c);
10938 c->halfopen = TRUE;
10939 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
10941 add234(ssh->channels, c);
10945 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
10947 struct ssh_channel *c;
10948 c = snew(struct ssh_channel);
10951 ssh2_channel_init(c);
10952 c->type = CHAN_SHARING;
10953 c->u.sharing.ctx = sharing_ctx;
10954 add234(ssh->channels, c);
10958 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
10960 struct ssh_channel *c;
10962 c = find234(ssh->channels, &localid, ssh_channelfind);
10964 ssh_channel_destroy(c);
10967 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
10968 const void *data, int datalen,
10969 const char *additional_log_text)
10971 struct Packet *pkt;
10973 pkt = ssh2_pkt_init(type);
10974 pkt->downstream_id = id;
10975 pkt->additional_log_text = additional_log_text;
10976 ssh2_pkt_adddata(pkt, data, datalen);
10977 ssh2_pkt_send(ssh, pkt);
10981 * This is called when stdout/stderr (the entity to which
10982 * from_backend sends data) manages to clear some backlog.
10984 static void ssh_unthrottle(void *handle, int bufsize)
10986 Ssh ssh = (Ssh) handle;
10989 if (ssh->version == 1) {
10990 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
10991 ssh->v1_stdout_throttling = 0;
10992 ssh_throttle_conn(ssh, -1);
10995 if (ssh->mainchan) {
10996 ssh2_set_window(ssh->mainchan,
10997 bufsize < ssh->mainchan->v.v2.locmaxwin ?
10998 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
10999 if (ssh_is_simple(ssh))
11002 buflimit = ssh->mainchan->v.v2.locmaxwin;
11003 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11004 ssh->mainchan->throttling_conn = 0;
11005 ssh_throttle_conn(ssh, -1);
11011 * Now process any SSH connection data that was stashed in our
11012 * queue while we were frozen.
11014 ssh_process_queued_incoming_data(ssh);
11017 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
11019 struct ssh_channel *c = (struct ssh_channel *)channel;
11021 struct Packet *pktout;
11023 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11025 if (ssh->version == 1) {
11026 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11027 PKT_INT, c->localid,
11030 /* PKT_STR, <org:orgport>, */
11033 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11035 char *trimmed_host = host_strduptrim(hostname);
11036 ssh2_pkt_addstring(pktout, trimmed_host);
11037 sfree(trimmed_host);
11039 ssh2_pkt_adduint32(pktout, port);
11041 * We make up values for the originator data; partly it's
11042 * too much hassle to keep track, and partly I'm not
11043 * convinced the server should be told details like that
11044 * about my local network configuration.
11045 * The "originator IP address" is syntactically a numeric
11046 * IP address, and some servers (e.g., Tectia) get upset
11047 * if it doesn't match this syntax.
11049 ssh2_pkt_addstring(pktout, "0.0.0.0");
11050 ssh2_pkt_adduint32(pktout, 0);
11051 ssh2_pkt_send(ssh, pktout);
11055 static int ssh_connected(void *handle)
11057 Ssh ssh = (Ssh) handle;
11058 return ssh->s != NULL;
11061 static int ssh_sendok(void *handle)
11063 Ssh ssh = (Ssh) handle;
11064 return ssh->send_ok;
11067 static int ssh_ldisc(void *handle, int option)
11069 Ssh ssh = (Ssh) handle;
11070 if (option == LD_ECHO)
11071 return ssh->echoing;
11072 if (option == LD_EDIT)
11073 return ssh->editing;
11077 static void ssh_provide_ldisc(void *handle, void *ldisc)
11079 Ssh ssh = (Ssh) handle;
11080 ssh->ldisc = ldisc;
11083 static void ssh_provide_logctx(void *handle, void *logctx)
11085 Ssh ssh = (Ssh) handle;
11086 ssh->logctx = logctx;
11089 static int ssh_return_exitcode(void *handle)
11091 Ssh ssh = (Ssh) handle;
11092 if (ssh->s != NULL)
11095 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11099 * cfg_info for SSH is the currently running version of the
11100 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
11102 static int ssh_cfg_info(void *handle)
11104 Ssh ssh = (Ssh) handle;
11105 return ssh->version;
11109 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11110 * that fails. This variable is the means by which scp.c can reach
11111 * into the SSH code and find out which one it got.
11113 extern int ssh_fallback_cmd(void *handle)
11115 Ssh ssh = (Ssh) handle;
11116 return ssh->fallback_cmd;
11119 Backend ssh_backend = {
11129 ssh_return_exitcode,
11133 ssh_provide_logctx,