28 * Packet type contexts, so that ssh2_pkt_type can correctly decode
29 * the ambiguous type numbers back into the correct type strings.
39 SSH2_PKTCTX_PUBLICKEY,
45 static const char *const ssh2_disconnect_reasons[] = {
47 "host not allowed to connect",
49 "key exchange failed",
50 "host authentication failed",
53 "service not available",
54 "protocol version not supported",
55 "host key not verifiable",
58 "too many connections",
59 "auth cancelled by user",
60 "no more auth methods available",
65 * Various remote-bug flags.
67 #define BUG_CHOKES_ON_SSH1_IGNORE 1
68 #define BUG_SSH2_HMAC 2
69 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
70 #define BUG_CHOKES_ON_RSA 8
71 #define BUG_SSH2_RSA_PADDING 16
72 #define BUG_SSH2_DERIVEKEY 32
73 #define BUG_SSH2_REKEY 64
74 #define BUG_SSH2_PK_SESSIONID 128
75 #define BUG_SSH2_MAXPKT 256
76 #define BUG_CHOKES_ON_SSH2_IGNORE 512
77 #define BUG_CHOKES_ON_WINADJ 1024
78 #define BUG_SENDS_LATE_REQUEST_REPLY 2048
81 * Codes for terminal modes.
82 * Most of these are the same in SSH-1 and SSH-2.
83 * This list is derived from RFC 4254 and
87 const char* const mode;
89 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
91 /* "V" prefix discarded for special characters relative to SSH specs */
92 { "INTR", 1, TTY_OP_CHAR },
93 { "QUIT", 2, TTY_OP_CHAR },
94 { "ERASE", 3, TTY_OP_CHAR },
95 { "KILL", 4, TTY_OP_CHAR },
96 { "EOF", 5, TTY_OP_CHAR },
97 { "EOL", 6, TTY_OP_CHAR },
98 { "EOL2", 7, TTY_OP_CHAR },
99 { "START", 8, TTY_OP_CHAR },
100 { "STOP", 9, TTY_OP_CHAR },
101 { "SUSP", 10, TTY_OP_CHAR },
102 { "DSUSP", 11, TTY_OP_CHAR },
103 { "REPRINT", 12, TTY_OP_CHAR },
104 { "WERASE", 13, TTY_OP_CHAR },
105 { "LNEXT", 14, TTY_OP_CHAR },
106 { "FLUSH", 15, TTY_OP_CHAR },
107 { "SWTCH", 16, TTY_OP_CHAR },
108 { "STATUS", 17, TTY_OP_CHAR },
109 { "DISCARD", 18, TTY_OP_CHAR },
110 { "IGNPAR", 30, TTY_OP_BOOL },
111 { "PARMRK", 31, TTY_OP_BOOL },
112 { "INPCK", 32, TTY_OP_BOOL },
113 { "ISTRIP", 33, TTY_OP_BOOL },
114 { "INLCR", 34, TTY_OP_BOOL },
115 { "IGNCR", 35, TTY_OP_BOOL },
116 { "ICRNL", 36, TTY_OP_BOOL },
117 { "IUCLC", 37, TTY_OP_BOOL },
118 { "IXON", 38, TTY_OP_BOOL },
119 { "IXANY", 39, TTY_OP_BOOL },
120 { "IXOFF", 40, TTY_OP_BOOL },
121 { "IMAXBEL", 41, TTY_OP_BOOL },
122 { "ISIG", 50, TTY_OP_BOOL },
123 { "ICANON", 51, TTY_OP_BOOL },
124 { "XCASE", 52, TTY_OP_BOOL },
125 { "ECHO", 53, TTY_OP_BOOL },
126 { "ECHOE", 54, TTY_OP_BOOL },
127 { "ECHOK", 55, TTY_OP_BOOL },
128 { "ECHONL", 56, TTY_OP_BOOL },
129 { "NOFLSH", 57, TTY_OP_BOOL },
130 { "TOSTOP", 58, TTY_OP_BOOL },
131 { "IEXTEN", 59, TTY_OP_BOOL },
132 { "ECHOCTL", 60, TTY_OP_BOOL },
133 { "ECHOKE", 61, TTY_OP_BOOL },
134 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
135 { "OPOST", 70, TTY_OP_BOOL },
136 { "OLCUC", 71, TTY_OP_BOOL },
137 { "ONLCR", 72, TTY_OP_BOOL },
138 { "OCRNL", 73, TTY_OP_BOOL },
139 { "ONOCR", 74, TTY_OP_BOOL },
140 { "ONLRET", 75, TTY_OP_BOOL },
141 { "CS7", 90, TTY_OP_BOOL },
142 { "CS8", 91, TTY_OP_BOOL },
143 { "PARENB", 92, TTY_OP_BOOL },
144 { "PARODD", 93, TTY_OP_BOOL }
147 /* Miscellaneous other tty-related constants. */
148 #define SSH_TTY_OP_END 0
149 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
150 #define SSH1_TTY_OP_ISPEED 192
151 #define SSH1_TTY_OP_OSPEED 193
152 #define SSH2_TTY_OP_ISPEED 128
153 #define SSH2_TTY_OP_OSPEED 129
155 /* Helper functions for parsing tty-related config. */
156 static unsigned int ssh_tty_parse_specchar(char *s)
161 ret = ctrlparse(s, &next);
162 if (!next) ret = s[0];
164 ret = 255; /* special value meaning "don't set" */
168 static unsigned int ssh_tty_parse_boolean(char *s)
170 if (stricmp(s, "yes") == 0 ||
171 stricmp(s, "on") == 0 ||
172 stricmp(s, "true") == 0 ||
173 stricmp(s, "+") == 0)
175 else if (stricmp(s, "no") == 0 ||
176 stricmp(s, "off") == 0 ||
177 stricmp(s, "false") == 0 ||
178 stricmp(s, "-") == 0)
179 return 0; /* false */
181 return (atoi(s) != 0);
184 #define translate(x) if (type == x) return #x
185 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
186 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
187 static char *ssh1_pkt_type(int type)
189 translate(SSH1_MSG_DISCONNECT);
190 translate(SSH1_SMSG_PUBLIC_KEY);
191 translate(SSH1_CMSG_SESSION_KEY);
192 translate(SSH1_CMSG_USER);
193 translate(SSH1_CMSG_AUTH_RSA);
194 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
195 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
196 translate(SSH1_CMSG_AUTH_PASSWORD);
197 translate(SSH1_CMSG_REQUEST_PTY);
198 translate(SSH1_CMSG_WINDOW_SIZE);
199 translate(SSH1_CMSG_EXEC_SHELL);
200 translate(SSH1_CMSG_EXEC_CMD);
201 translate(SSH1_SMSG_SUCCESS);
202 translate(SSH1_SMSG_FAILURE);
203 translate(SSH1_CMSG_STDIN_DATA);
204 translate(SSH1_SMSG_STDOUT_DATA);
205 translate(SSH1_SMSG_STDERR_DATA);
206 translate(SSH1_CMSG_EOF);
207 translate(SSH1_SMSG_EXIT_STATUS);
208 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
209 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
210 translate(SSH1_MSG_CHANNEL_DATA);
211 translate(SSH1_MSG_CHANNEL_CLOSE);
212 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
213 translate(SSH1_SMSG_X11_OPEN);
214 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
215 translate(SSH1_MSG_PORT_OPEN);
216 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
217 translate(SSH1_SMSG_AGENT_OPEN);
218 translate(SSH1_MSG_IGNORE);
219 translate(SSH1_CMSG_EXIT_CONFIRMATION);
220 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
221 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
222 translate(SSH1_MSG_DEBUG);
223 translate(SSH1_CMSG_REQUEST_COMPRESSION);
224 translate(SSH1_CMSG_AUTH_TIS);
225 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
226 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
227 translate(SSH1_CMSG_AUTH_CCARD);
228 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
229 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
232 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
234 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
235 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
236 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
237 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
238 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
239 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
240 translate(SSH2_MSG_DISCONNECT);
241 translate(SSH2_MSG_IGNORE);
242 translate(SSH2_MSG_UNIMPLEMENTED);
243 translate(SSH2_MSG_DEBUG);
244 translate(SSH2_MSG_SERVICE_REQUEST);
245 translate(SSH2_MSG_SERVICE_ACCEPT);
246 translate(SSH2_MSG_KEXINIT);
247 translate(SSH2_MSG_NEWKEYS);
248 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
249 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
250 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
251 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
252 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
253 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
254 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
255 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
256 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
257 translate(SSH2_MSG_USERAUTH_REQUEST);
258 translate(SSH2_MSG_USERAUTH_FAILURE);
259 translate(SSH2_MSG_USERAUTH_SUCCESS);
260 translate(SSH2_MSG_USERAUTH_BANNER);
261 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
262 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
263 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
264 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
265 translate(SSH2_MSG_GLOBAL_REQUEST);
266 translate(SSH2_MSG_REQUEST_SUCCESS);
267 translate(SSH2_MSG_REQUEST_FAILURE);
268 translate(SSH2_MSG_CHANNEL_OPEN);
269 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
270 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
271 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
272 translate(SSH2_MSG_CHANNEL_DATA);
273 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
274 translate(SSH2_MSG_CHANNEL_EOF);
275 translate(SSH2_MSG_CHANNEL_CLOSE);
276 translate(SSH2_MSG_CHANNEL_REQUEST);
277 translate(SSH2_MSG_CHANNEL_SUCCESS);
278 translate(SSH2_MSG_CHANNEL_FAILURE);
284 /* Enumeration values for fields in SSH-1 packets */
286 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
290 * Coroutine mechanics for the sillier bits of the code. If these
291 * macros look impenetrable to you, you might find it helpful to
294 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
296 * which explains the theory behind these macros.
298 * In particular, if you are getting `case expression not constant'
299 * errors when building with MS Visual Studio, this is because MS's
300 * Edit and Continue debugging feature causes their compiler to
301 * violate ANSI C. To disable Edit and Continue debugging:
303 * - right-click ssh.c in the FileView
305 * - select the C/C++ tab and the General category
306 * - under `Debug info:', select anything _other_ than `Program
307 * Database for Edit and Continue'.
309 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
310 #define crBeginState crBegin(s->crLine)
311 #define crStateP(t, v) \
313 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
315 #define crState(t) crStateP(t, ssh->t)
316 #define crFinish(z) } *crLine = 0; return (z); }
317 #define crFinishV } *crLine = 0; return; }
318 #define crFinishFree(z) } sfree(s); return (z); }
319 #define crFinishFreeV } sfree(s); return; }
320 #define crReturn(z) \
322 *crLine =__LINE__; return (z); case __LINE__:;\
326 *crLine=__LINE__; return; case __LINE__:;\
328 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
329 #define crStopV do{ *crLine = 0; return; }while(0)
330 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
331 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
335 static struct Packet *ssh1_pkt_init(int pkt_type);
336 static struct Packet *ssh2_pkt_init(int pkt_type);
337 static void ssh_pkt_ensure(struct Packet *, int length);
338 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
339 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
340 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
341 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
342 static void ssh_pkt_addstring_start(struct Packet *);
343 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
344 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
345 static void ssh_pkt_addstring(struct Packet *, const char *data);
346 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
347 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
348 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
349 static int ssh2_pkt_construct(Ssh, struct Packet *);
350 static void ssh2_pkt_send(Ssh, struct Packet *);
351 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
352 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
353 struct Packet *pktin);
354 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
355 struct Packet *pktin);
356 static void ssh2_channel_check_close(struct ssh_channel *c);
357 static void ssh_channel_destroy(struct ssh_channel *c);
360 * Buffer management constants. There are several of these for
361 * various different purposes:
363 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
364 * on a local data stream before we throttle the whole SSH
365 * connection (in SSH-1 only). Throttling the whole connection is
366 * pretty drastic so we set this high in the hope it won't
369 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
370 * on the SSH connection itself before we defensively throttle
371 * _all_ local data streams. This is pretty drastic too (though
372 * thankfully unlikely in SSH-2 since the window mechanism should
373 * ensure that the server never has any need to throttle its end
374 * of the connection), so we set this high as well.
376 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
379 * - OUR_V2_BIGWIN is the window size we advertise for the only
380 * channel in a simple connection. It must be <= INT_MAX.
382 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
383 * to the remote side. This actually has nothing to do with the
384 * size of the _packet_, but is instead a limit on the amount
385 * of data we're willing to receive in a single SSH2 channel
388 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
389 * _packet_ we're prepared to cope with. It must be a multiple
390 * of the cipher block size, and must be at least 35000.
393 #define SSH1_BUFFER_LIMIT 32768
394 #define SSH_MAX_BACKLOG 32768
395 #define OUR_V2_WINSIZE 16384
396 #define OUR_V2_BIGWIN 0x7fffffff
397 #define OUR_V2_MAXPKT 0x4000UL
398 #define OUR_V2_PACKETLIMIT 0x9000UL
400 const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
402 const static struct ssh_mac *macs[] = {
403 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
405 const static struct ssh_mac *buggymacs[] = {
406 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
409 static void *ssh_comp_none_init(void)
413 static void ssh_comp_none_cleanup(void *handle)
416 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
417 unsigned char **outblock, int *outlen)
421 static int ssh_comp_none_disable(void *handle)
425 const static struct ssh_compress ssh_comp_none = {
427 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
428 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
429 ssh_comp_none_disable, NULL
431 extern const struct ssh_compress ssh_zlib;
432 const static struct ssh_compress *compressions[] = {
433 &ssh_zlib, &ssh_comp_none
436 enum { /* channel types */
441 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
443 * CHAN_SHARING indicates a channel which is tracked here on
444 * behalf of a connection-sharing downstream. We do almost nothing
445 * with these channels ourselves: all messages relating to them
446 * get thrown straight to sshshare.c and passed on almost
447 * unmodified to downstream.
451 * CHAN_ZOMBIE is used to indicate a channel for which we've
452 * already destroyed the local data source: for instance, if a
453 * forwarded port experiences a socket error on the local side, we
454 * immediately destroy its local socket and turn the SSH channel
460 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
461 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
462 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
465 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
468 struct outstanding_channel_request {
469 cchandler_fn_t handler;
471 struct outstanding_channel_request *next;
475 * 2-3-4 tree storing channels.
478 Ssh ssh; /* pointer back to main context */
479 unsigned remoteid, localid;
481 /* True if we opened this channel but server hasn't confirmed. */
484 * In SSH-1, this value contains four bits:
486 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
487 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
488 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
489 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
491 * A channel is completely finished with when all four bits are set.
493 * In SSH-2, the four bits mean:
495 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
496 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
497 * 4 We have received SSH2_MSG_CHANNEL_EOF.
498 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
500 * A channel is completely finished with when we have both sent
501 * and received CLOSE.
503 * The symbolic constants below use the SSH-2 terminology, which
504 * is a bit confusing in SSH-1, but we have to use _something_.
506 #define CLOSES_SENT_EOF 1
507 #define CLOSES_SENT_CLOSE 2
508 #define CLOSES_RCVD_EOF 4
509 #define CLOSES_RCVD_CLOSE 8
513 * This flag indicates that an EOF is pending on the outgoing side
514 * of the channel: that is, wherever we're getting the data for
515 * this channel has sent us some data followed by EOF. We can't
516 * actually send the EOF until we've finished sending the data, so
517 * we set this flag instead to remind us to do so once our buffer
523 * True if this channel is causing the underlying connection to be
528 struct ssh2_data_channel {
530 unsigned remwindow, remmaxpkt;
531 /* locwindow is signed so we can cope with excess data. */
532 int locwindow, locmaxwin;
534 * remlocwin is the amount of local window that we think
535 * the remote end had available to it after it sent the
536 * last data packet or window adjust ack.
540 * These store the list of channel requests that haven't
543 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
544 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
548 struct ssh_agent_channel {
549 unsigned char *message;
550 unsigned char msglen[4];
551 unsigned lensofar, totallen;
552 int outstanding_requests;
554 struct ssh_x11_channel {
555 struct X11Connection *xconn;
558 struct ssh_pfd_channel {
559 struct PortForwarding *pf;
561 struct ssh_sharing_channel {
568 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
569 * use this structure in different ways, reflecting SSH-2's
570 * altogether saner approach to port forwarding.
572 * In SSH-1, you arrange a remote forwarding by sending the server
573 * the remote port number, and the local destination host:port.
574 * When a connection comes in, the server sends you back that
575 * host:port pair, and you connect to it. This is a ready-made
576 * security hole if you're not on the ball: a malicious server
577 * could send you back _any_ host:port pair, so if you trustingly
578 * connect to the address it gives you then you've just opened the
579 * entire inside of your corporate network just by connecting
580 * through it to a dodgy SSH server. Hence, we must store a list of
581 * host:port pairs we _are_ trying to forward to, and reject a
582 * connection request from the server if it's not in the list.
584 * In SSH-2, each side of the connection minds its own business and
585 * doesn't send unnecessary information to the other. You arrange a
586 * remote forwarding by sending the server just the remote port
587 * number. When a connection comes in, the server tells you which
588 * of its ports was connected to; and _you_ have to remember what
589 * local host:port pair went with that port number.
591 * Hence, in SSH-1 this structure is indexed by destination
592 * host:port pair, whereas in SSH-2 it is indexed by source port.
594 struct ssh_portfwd; /* forward declaration */
596 struct ssh_rportfwd {
597 unsigned sport, dport;
601 struct ssh_portfwd *pfrec;
604 static void free_rportfwd(struct ssh_rportfwd *pf)
607 sfree(pf->sportdesc);
615 * Separately to the rportfwd tree (which is for looking up port
616 * open requests from the server), a tree of _these_ structures is
617 * used to keep track of all the currently open port forwardings,
618 * so that we can reconfigure in mid-session if the user requests
622 enum { DESTROY, KEEP, CREATE } status;
624 unsigned sport, dport;
627 struct ssh_rportfwd *remote;
629 struct PortListener *local;
631 #define free_portfwd(pf) ( \
632 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
633 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
636 long length; /* length of packet: see below */
637 long forcepad; /* SSH-2: force padding to at least this length */
638 int type; /* only used for incoming packets */
639 unsigned long sequence; /* SSH-2 incoming sequence number */
640 unsigned char *data; /* allocated storage */
641 unsigned char *body; /* offset of payload within `data' */
642 long savedpos; /* dual-purpose saved packet position: see below */
643 long maxlen; /* amount of storage allocated for `data' */
644 long encrypted_len; /* for SSH-2 total-size counting */
647 * A note on the 'length' and 'savedpos' fields above.
649 * Incoming packets are set up so that pkt->length is measured
650 * relative to pkt->body, which itself points to a few bytes after
651 * pkt->data (skipping some uninteresting header fields including
652 * the packet type code). The ssh_pkt_get* functions all expect
653 * this setup, and they also use pkt->savedpos to indicate how far
654 * through the packet being decoded they've got - and that, too,
655 * is an offset from pkt->body rather than pkt->data.
657 * During construction of an outgoing packet, however, pkt->length
658 * is measured relative to the base pointer pkt->data, and
659 * pkt->body is not really used for anything until the packet is
660 * ready for sending. In this mode, pkt->savedpos is reused as a
661 * temporary variable by the addstring functions, which write out
662 * a string length field and then keep going back and updating it
663 * as more data is appended to the subsequent string data field;
664 * pkt->savedpos stores the offset (again relative to pkt->data)
665 * of the start of the string data field.
668 /* Extra metadata used in SSH packet logging mode, allowing us to
669 * log in the packet header line that the packet came from a
670 * connection-sharing downstream and what if anything unusual was
671 * done to it. The additional_log_text field is expected to be a
672 * static string - it will not be freed. */
673 unsigned downstream_id;
674 const char *additional_log_text;
677 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
678 struct Packet *pktin);
679 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
680 struct Packet *pktin);
681 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
682 struct Packet *pktin);
683 static void ssh1_protocol_setup(Ssh ssh);
684 static void ssh2_protocol_setup(Ssh ssh);
685 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
686 static void ssh_size(void *handle, int width, int height);
687 static void ssh_special(void *handle, Telnet_Special);
688 static int ssh2_try_send(struct ssh_channel *c);
689 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
690 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
691 static void ssh2_set_window(struct ssh_channel *c, int newwin);
692 static int ssh_sendbuffer(void *handle);
693 static int ssh_do_close(Ssh ssh, int notify_exit);
694 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
695 static int ssh2_pkt_getbool(struct Packet *pkt);
696 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
697 static void ssh2_timer(void *ctx, unsigned long now);
698 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
699 struct Packet *pktin);
700 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
702 struct rdpkt1_state_tag {
703 long len, pad, biglen, to_read;
704 unsigned long realcrc, gotcrc;
708 struct Packet *pktin;
711 struct rdpkt2_state_tag {
712 long len, pad, payload, packetlen, maclen;
715 unsigned long incoming_sequence;
716 struct Packet *pktin;
719 struct rdpkt2_bare_state_tag {
723 unsigned long incoming_sequence;
724 struct Packet *pktin;
727 struct queued_handler;
728 struct queued_handler {
730 chandler_fn_t handler;
732 struct queued_handler *next;
736 const struct plug_function_table *fn;
737 /* the above field _must_ be first in the structure */
747 unsigned char session_key[32];
749 int v1_remote_protoflags;
750 int v1_local_protoflags;
751 int agentfwd_enabled;
754 const struct ssh_cipher *cipher;
757 const struct ssh2_cipher *cscipher, *sccipher;
758 void *cs_cipher_ctx, *sc_cipher_ctx;
759 const struct ssh_mac *csmac, *scmac;
760 void *cs_mac_ctx, *sc_mac_ctx;
761 const struct ssh_compress *cscomp, *sccomp;
762 void *cs_comp_ctx, *sc_comp_ctx;
763 const struct ssh_kex *kex;
764 const struct ssh_signkey *hostkey;
765 char *hostkey_str; /* string representation, for easy checking in rekeys */
766 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
767 int v2_session_id_len;
771 int attempting_connshare;
777 int echoing, editing;
781 int ospeed, ispeed; /* temporaries */
782 int term_width, term_height;
784 tree234 *channels; /* indexed by local id */
785 struct ssh_channel *mainchan; /* primary session channel */
786 int ncmode; /* is primary channel direct-tcpip? */
791 tree234 *rportfwds, *portfwds;
795 SSH_STATE_BEFORE_SIZE,
801 int size_needed, eof_needed;
802 int sent_console_eof;
803 int got_pty; /* affects EOF behaviour on main channel */
805 struct Packet **queue;
806 int queuelen, queuesize;
808 unsigned char *deferred_send_data;
809 int deferred_len, deferred_size;
812 * Gross hack: pscp will try to start SFTP but fall back to
813 * scp1 if that fails. This variable is the means by which
814 * scp.c can reach into the SSH code and find out which one it
819 bufchain banner; /* accumulates banners during do_ssh2_authconn */
824 struct X11Display *x11disp;
825 struct X11FakeAuth *x11auth;
826 tree234 *x11authtree;
829 int conn_throttle_count;
832 int v1_stdout_throttling;
833 unsigned long v2_outgoing_sequence;
835 int ssh1_rdpkt_crstate;
836 int ssh2_rdpkt_crstate;
837 int ssh2_bare_rdpkt_crstate;
838 int ssh_gotdata_crstate;
839 int do_ssh1_connection_crstate;
841 void *do_ssh_init_state;
842 void *do_ssh1_login_state;
843 void *do_ssh2_transport_state;
844 void *do_ssh2_authconn_state;
845 void *do_ssh_connection_init_state;
847 struct rdpkt1_state_tag rdpkt1_state;
848 struct rdpkt2_state_tag rdpkt2_state;
849 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
851 /* SSH-1 and SSH-2 use this for different things, but both use it */
852 int protocol_initial_phase_done;
854 void (*protocol) (Ssh ssh, void *vin, int inlen,
856 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
857 int (*do_ssh_init)(Ssh ssh, unsigned char c);
860 * We maintain our own copy of a Conf structure here. That way,
861 * when we're passed a new one for reconfiguration, we can check
862 * the differences and potentially reconfigure port forwardings
863 * etc in mid-session.
868 * Values cached out of conf so as to avoid the tree234 lookup
869 * cost every time they're used.
874 * Dynamically allocated username string created during SSH
875 * login. Stored in here rather than in the coroutine state so
876 * that it'll be reliably freed if we shut down the SSH session
877 * at some unexpected moment.
882 * Used to transfer data back from async callbacks.
884 void *agent_response;
885 int agent_response_len;
889 * The SSH connection can be set as `frozen', meaning we are
890 * not currently accepting incoming data from the network. This
891 * is slightly more serious than setting the _socket_ as
892 * frozen, because we may already have had data passed to us
893 * from the network which we need to delay processing until
894 * after the freeze is lifted, so we also need a bufchain to
898 bufchain queued_incoming_data;
901 * Dispatch table for packet types that we may have to deal
904 handler_fn_t packet_dispatch[256];
907 * Queues of one-off handler functions for success/failure
908 * indications from a request.
910 struct queued_handler *qhead, *qtail;
911 handler_fn_t q_saved_handler1, q_saved_handler2;
914 * This module deals with sending keepalives.
919 * Track incoming and outgoing data sizes and time, for
922 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
923 unsigned long max_data_size;
925 unsigned long next_rekey, last_rekey;
926 char *deferred_rekey_reason; /* points to STATIC string; don't free */
929 * Fully qualified host name, which we need if doing GSSAPI.
935 * GSSAPI libraries for this session.
937 struct ssh_gss_liblist *gsslibs;
941 #define logevent(s) logevent(ssh->frontend, s)
943 /* logevent, only printf-formatted. */
944 static void logeventf(Ssh ssh, const char *fmt, ...)
950 buf = dupvprintf(fmt, ap);
956 static void bomb_out(Ssh ssh, char *text)
958 ssh_do_close(ssh, FALSE);
960 connection_fatal(ssh->frontend, "%s", text);
964 #define bombout(msg) bomb_out(ssh, dupprintf msg)
966 /* Helper function for common bits of parsing ttymodes. */
967 static void parse_ttymodes(Ssh ssh,
968 void (*do_mode)(void *data, char *mode, char *val),
973 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
975 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
977 * val[0] is either 'V', indicating that an explicit value
978 * follows it, or 'A' indicating that we should pass the
979 * value through from the local environment via get_ttymode.
982 val = get_ttymode(ssh->frontend, key);
984 do_mode(data, key, val);
988 do_mode(data, key, val + 1); /* skip the 'V' */
992 static int ssh_channelcmp(void *av, void *bv)
994 struct ssh_channel *a = (struct ssh_channel *) av;
995 struct ssh_channel *b = (struct ssh_channel *) bv;
996 if (a->localid < b->localid)
998 if (a->localid > b->localid)
1002 static int ssh_channelfind(void *av, void *bv)
1004 unsigned *a = (unsigned *) av;
1005 struct ssh_channel *b = (struct ssh_channel *) bv;
1006 if (*a < b->localid)
1008 if (*a > b->localid)
1013 static int ssh_rportcmp_ssh1(void *av, void *bv)
1015 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1016 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1018 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1019 return i < 0 ? -1 : +1;
1020 if (a->dport > b->dport)
1022 if (a->dport < b->dport)
1027 static int ssh_rportcmp_ssh2(void *av, void *bv)
1029 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1030 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1032 if ( (i = strcmp(a->shost, b->shost)) != 0)
1033 return i < 0 ? -1 : +1;
1034 if (a->sport > b->sport)
1036 if (a->sport < b->sport)
1042 * Special form of strcmp which can cope with NULL inputs. NULL is
1043 * defined to sort before even the empty string.
1045 static int nullstrcmp(const char *a, const char *b)
1047 if (a == NULL && b == NULL)
1053 return strcmp(a, b);
1056 static int ssh_portcmp(void *av, void *bv)
1058 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1059 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1061 if (a->type > b->type)
1063 if (a->type < b->type)
1065 if (a->addressfamily > b->addressfamily)
1067 if (a->addressfamily < b->addressfamily)
1069 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1070 return i < 0 ? -1 : +1;
1071 if (a->sport > b->sport)
1073 if (a->sport < b->sport)
1075 if (a->type != 'D') {
1076 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1077 return i < 0 ? -1 : +1;
1078 if (a->dport > b->dport)
1080 if (a->dport < b->dport)
1086 static int alloc_channel_id(Ssh ssh)
1088 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1089 unsigned low, high, mid;
1091 struct ssh_channel *c;
1094 * First-fit allocation of channel numbers: always pick the
1095 * lowest unused one. To do this, binary-search using the
1096 * counted B-tree to find the largest channel ID which is in a
1097 * contiguous sequence from the beginning. (Precisely
1098 * everything in that sequence must have ID equal to its tree
1099 * index plus CHANNEL_NUMBER_OFFSET.)
1101 tsize = count234(ssh->channels);
1105 while (high - low > 1) {
1106 mid = (high + low) / 2;
1107 c = index234(ssh->channels, mid);
1108 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1109 low = mid; /* this one is fine */
1111 high = mid; /* this one is past it */
1114 * Now low points to either -1, or the tree index of the
1115 * largest ID in the initial sequence.
1118 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1119 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1121 return low + 1 + CHANNEL_NUMBER_OFFSET;
1124 static void c_write_stderr(int trusted, const char *buf, int len)
1127 for (i = 0; i < len; i++)
1128 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1129 fputc(buf[i], stderr);
1132 static void c_write(Ssh ssh, const char *buf, int len)
1134 if (flags & FLAG_STDERR)
1135 c_write_stderr(1, buf, len);
1137 from_backend(ssh->frontend, 1, buf, len);
1140 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1142 if (flags & FLAG_STDERR)
1143 c_write_stderr(0, buf, len);
1145 from_backend_untrusted(ssh->frontend, buf, len);
1148 static void c_write_str(Ssh ssh, const char *buf)
1150 c_write(ssh, buf, strlen(buf));
1153 static void ssh_free_packet(struct Packet *pkt)
1158 static struct Packet *ssh_new_packet(void)
1160 struct Packet *pkt = snew(struct Packet);
1162 pkt->body = pkt->data = NULL;
1168 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1171 struct logblank_t blanks[4];
1177 if (ssh->logomitdata &&
1178 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1179 pkt->type == SSH1_SMSG_STDERR_DATA ||
1180 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1181 /* "Session data" packets - omit the data string. */
1182 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1183 ssh_pkt_getuint32(pkt); /* skip channel id */
1184 blanks[nblanks].offset = pkt->savedpos + 4;
1185 blanks[nblanks].type = PKTLOG_OMIT;
1186 ssh_pkt_getstring(pkt, &str, &slen);
1188 blanks[nblanks].len = slen;
1192 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1193 ssh1_pkt_type(pkt->type),
1194 pkt->body, pkt->length, nblanks, blanks, NULL,
1198 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1201 struct logblank_t blanks[4];
1206 * For outgoing packets, pkt->length represents the length of the
1207 * whole packet starting at pkt->data (including some header), and
1208 * pkt->body refers to the point within that where the log-worthy
1209 * payload begins. However, incoming packets expect pkt->length to
1210 * represent only the payload length (that is, it's measured from
1211 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1212 * packet to conform to the incoming-packet semantics, so that we
1213 * can analyse it with the ssh_pkt_get functions.
1215 pkt->length -= (pkt->body - pkt->data);
1218 if (ssh->logomitdata &&
1219 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1220 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1221 /* "Session data" packets - omit the data string. */
1222 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1223 ssh_pkt_getuint32(pkt); /* skip channel id */
1224 blanks[nblanks].offset = pkt->savedpos + 4;
1225 blanks[nblanks].type = PKTLOG_OMIT;
1226 ssh_pkt_getstring(pkt, &str, &slen);
1228 blanks[nblanks].len = slen;
1233 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1234 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1235 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1236 conf_get_int(ssh->conf, CONF_logomitpass)) {
1237 /* If this is a password or similar packet, blank the password(s). */
1238 blanks[nblanks].offset = 0;
1239 blanks[nblanks].len = pkt->length;
1240 blanks[nblanks].type = PKTLOG_BLANK;
1242 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1243 conf_get_int(ssh->conf, CONF_logomitpass)) {
1245 * If this is an X forwarding request packet, blank the fake
1248 * Note that while we blank the X authentication data here, we
1249 * don't take any special action to blank the start of an X11
1250 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1251 * an X connection without having session blanking enabled is
1252 * likely to leak your cookie into the log.
1255 ssh_pkt_getstring(pkt, &str, &slen);
1256 blanks[nblanks].offset = pkt->savedpos;
1257 blanks[nblanks].type = PKTLOG_BLANK;
1258 ssh_pkt_getstring(pkt, &str, &slen);
1260 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1265 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1266 ssh1_pkt_type(pkt->data[12]),
1267 pkt->body, pkt->length,
1268 nblanks, blanks, NULL, 0, NULL);
1271 * Undo the above adjustment of pkt->length, to put the packet
1272 * back in the state we found it.
1274 pkt->length += (pkt->body - pkt->data);
1278 * Collect incoming data in the incoming packet buffer.
1279 * Decipher and verify the packet when it is completely read.
1280 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1281 * Update the *data and *datalen variables.
1282 * Return a Packet structure when a packet is completed.
1284 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1286 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1288 crBegin(ssh->ssh1_rdpkt_crstate);
1290 st->pktin = ssh_new_packet();
1292 st->pktin->type = 0;
1293 st->pktin->length = 0;
1295 for (st->i = st->len = 0; st->i < 4; st->i++) {
1296 while ((*datalen) == 0)
1298 st->len = (st->len << 8) + **data;
1299 (*data)++, (*datalen)--;
1302 st->pad = 8 - (st->len % 8);
1303 st->biglen = st->len + st->pad;
1304 st->pktin->length = st->len - 5;
1306 if (st->biglen < 0) {
1307 bombout(("Extremely large packet length from server suggests"
1308 " data stream corruption"));
1309 ssh_free_packet(st->pktin);
1313 st->pktin->maxlen = st->biglen;
1314 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1316 st->to_read = st->biglen;
1317 st->p = st->pktin->data;
1318 while (st->to_read > 0) {
1319 st->chunk = st->to_read;
1320 while ((*datalen) == 0)
1322 if (st->chunk > (*datalen))
1323 st->chunk = (*datalen);
1324 memcpy(st->p, *data, st->chunk);
1326 *datalen -= st->chunk;
1328 st->to_read -= st->chunk;
1331 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1332 st->biglen, NULL)) {
1333 bombout(("Network attack (CRC compensation) detected!"));
1334 ssh_free_packet(st->pktin);
1339 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1341 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1342 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1343 if (st->gotcrc != st->realcrc) {
1344 bombout(("Incorrect CRC received on packet"));
1345 ssh_free_packet(st->pktin);
1349 st->pktin->body = st->pktin->data + st->pad + 1;
1351 if (ssh->v1_compressing) {
1352 unsigned char *decompblk;
1354 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1355 st->pktin->body - 1, st->pktin->length + 1,
1356 &decompblk, &decomplen)) {
1357 bombout(("Zlib decompression encountered invalid data"));
1358 ssh_free_packet(st->pktin);
1362 if (st->pktin->maxlen < st->pad + decomplen) {
1363 st->pktin->maxlen = st->pad + decomplen;
1364 st->pktin->data = sresize(st->pktin->data,
1365 st->pktin->maxlen + APIEXTRA,
1367 st->pktin->body = st->pktin->data + st->pad + 1;
1370 memcpy(st->pktin->body - 1, decompblk, decomplen);
1372 st->pktin->length = decomplen - 1;
1375 st->pktin->type = st->pktin->body[-1];
1378 * Now pktin->body and pktin->length identify the semantic content
1379 * of the packet, excluding the initial type byte.
1383 ssh1_log_incoming_packet(ssh, st->pktin);
1385 st->pktin->savedpos = 0;
1387 crFinish(st->pktin);
1390 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1393 struct logblank_t blanks[4];
1399 if (ssh->logomitdata &&
1400 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1401 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1402 /* "Session data" packets - omit the data string. */
1403 ssh_pkt_getuint32(pkt); /* skip channel id */
1404 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1405 ssh_pkt_getuint32(pkt); /* skip extended data type */
1406 blanks[nblanks].offset = pkt->savedpos + 4;
1407 blanks[nblanks].type = PKTLOG_OMIT;
1408 ssh_pkt_getstring(pkt, &str, &slen);
1410 blanks[nblanks].len = slen;
1415 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1416 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1417 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1421 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1424 struct logblank_t blanks[4];
1429 * For outgoing packets, pkt->length represents the length of the
1430 * whole packet starting at pkt->data (including some header), and
1431 * pkt->body refers to the point within that where the log-worthy
1432 * payload begins. However, incoming packets expect pkt->length to
1433 * represent only the payload length (that is, it's measured from
1434 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1435 * packet to conform to the incoming-packet semantics, so that we
1436 * can analyse it with the ssh_pkt_get functions.
1438 pkt->length -= (pkt->body - pkt->data);
1441 if (ssh->logomitdata &&
1442 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1443 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1444 /* "Session data" packets - omit the data string. */
1445 ssh_pkt_getuint32(pkt); /* skip channel id */
1446 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1447 ssh_pkt_getuint32(pkt); /* skip extended data type */
1448 blanks[nblanks].offset = pkt->savedpos + 4;
1449 blanks[nblanks].type = PKTLOG_OMIT;
1450 ssh_pkt_getstring(pkt, &str, &slen);
1452 blanks[nblanks].len = slen;
1457 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1458 conf_get_int(ssh->conf, CONF_logomitpass)) {
1459 /* If this is a password packet, blank the password(s). */
1461 ssh_pkt_getstring(pkt, &str, &slen);
1462 ssh_pkt_getstring(pkt, &str, &slen);
1463 ssh_pkt_getstring(pkt, &str, &slen);
1464 if (slen == 8 && !memcmp(str, "password", 8)) {
1465 ssh2_pkt_getbool(pkt);
1466 /* Blank the password field. */
1467 blanks[nblanks].offset = pkt->savedpos;
1468 blanks[nblanks].type = PKTLOG_BLANK;
1469 ssh_pkt_getstring(pkt, &str, &slen);
1471 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1473 /* If there's another password field beyond it (change of
1474 * password), blank that too. */
1475 ssh_pkt_getstring(pkt, &str, &slen);
1477 blanks[nblanks-1].len =
1478 pkt->savedpos - blanks[nblanks].offset;
1481 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1482 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1483 conf_get_int(ssh->conf, CONF_logomitpass)) {
1484 /* If this is a keyboard-interactive response packet, blank
1487 ssh_pkt_getuint32(pkt);
1488 blanks[nblanks].offset = pkt->savedpos;
1489 blanks[nblanks].type = PKTLOG_BLANK;
1491 ssh_pkt_getstring(pkt, &str, &slen);
1495 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1497 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1498 conf_get_int(ssh->conf, CONF_logomitpass)) {
1500 * If this is an X forwarding request packet, blank the fake
1503 * Note that while we blank the X authentication data here, we
1504 * don't take any special action to blank the start of an X11
1505 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1506 * an X connection without having session blanking enabled is
1507 * likely to leak your cookie into the log.
1510 ssh_pkt_getuint32(pkt);
1511 ssh_pkt_getstring(pkt, &str, &slen);
1512 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1513 ssh2_pkt_getbool(pkt);
1514 ssh2_pkt_getbool(pkt);
1515 ssh_pkt_getstring(pkt, &str, &slen);
1516 blanks[nblanks].offset = pkt->savedpos;
1517 blanks[nblanks].type = PKTLOG_BLANK;
1518 ssh_pkt_getstring(pkt, &str, &slen);
1520 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1526 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1527 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1528 pkt->body, pkt->length, nblanks, blanks,
1529 &ssh->v2_outgoing_sequence,
1530 pkt->downstream_id, pkt->additional_log_text);
1533 * Undo the above adjustment of pkt->length, to put the packet
1534 * back in the state we found it.
1536 pkt->length += (pkt->body - pkt->data);
1539 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1541 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1543 crBegin(ssh->ssh2_rdpkt_crstate);
1545 st->pktin = ssh_new_packet();
1547 st->pktin->type = 0;
1548 st->pktin->length = 0;
1550 st->cipherblk = ssh->sccipher->blksize;
1553 if (st->cipherblk < 8)
1555 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1557 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1560 * When dealing with a CBC-mode cipher, we want to avoid the
1561 * possibility of an attacker's tweaking the ciphertext stream
1562 * so as to cause us to feed the same block to the block
1563 * cipher more than once and thus leak information
1564 * (VU#958563). The way we do this is not to take any
1565 * decisions on the basis of anything we've decrypted until
1566 * we've verified it with a MAC. That includes the packet
1567 * length, so we just read data and check the MAC repeatedly,
1568 * and when the MAC passes, see if the length we've got is
1572 /* May as well allocate the whole lot now. */
1573 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1576 /* Read an amount corresponding to the MAC. */
1577 for (st->i = 0; st->i < st->maclen; st->i++) {
1578 while ((*datalen) == 0)
1580 st->pktin->data[st->i] = *(*data)++;
1586 unsigned char seq[4];
1587 ssh->scmac->start(ssh->sc_mac_ctx);
1588 PUT_32BIT(seq, st->incoming_sequence);
1589 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1592 for (;;) { /* Once around this loop per cipher block. */
1593 /* Read another cipher-block's worth, and tack it onto the end. */
1594 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1595 while ((*datalen) == 0)
1597 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1600 /* Decrypt one more block (a little further back in the stream). */
1601 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1602 st->pktin->data + st->packetlen,
1604 /* Feed that block to the MAC. */
1605 ssh->scmac->bytes(ssh->sc_mac_ctx,
1606 st->pktin->data + st->packetlen, st->cipherblk);
1607 st->packetlen += st->cipherblk;
1608 /* See if that gives us a valid packet. */
1609 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1610 st->pktin->data + st->packetlen) &&
1611 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1614 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1615 bombout(("No valid incoming packet found"));
1616 ssh_free_packet(st->pktin);
1620 st->pktin->maxlen = st->packetlen + st->maclen;
1621 st->pktin->data = sresize(st->pktin->data,
1622 st->pktin->maxlen + APIEXTRA,
1625 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1628 * Acquire and decrypt the first block of the packet. This will
1629 * contain the length and padding details.
1631 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1632 while ((*datalen) == 0)
1634 st->pktin->data[st->i] = *(*data)++;
1639 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1640 st->pktin->data, st->cipherblk);
1643 * Now get the length figure.
1645 st->len = toint(GET_32BIT(st->pktin->data));
1648 * _Completely_ silly lengths should be stomped on before they
1649 * do us any more damage.
1651 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1652 (st->len + 4) % st->cipherblk != 0) {
1653 bombout(("Incoming packet was garbled on decryption"));
1654 ssh_free_packet(st->pktin);
1659 * So now we can work out the total packet length.
1661 st->packetlen = st->len + 4;
1664 * Allocate memory for the rest of the packet.
1666 st->pktin->maxlen = st->packetlen + st->maclen;
1667 st->pktin->data = sresize(st->pktin->data,
1668 st->pktin->maxlen + APIEXTRA,
1672 * Read and decrypt the remainder of the packet.
1674 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1676 while ((*datalen) == 0)
1678 st->pktin->data[st->i] = *(*data)++;
1681 /* Decrypt everything _except_ the MAC. */
1683 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1684 st->pktin->data + st->cipherblk,
1685 st->packetlen - st->cipherblk);
1691 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1692 st->len + 4, st->incoming_sequence)) {
1693 bombout(("Incorrect MAC received on packet"));
1694 ssh_free_packet(st->pktin);
1698 /* Get and sanity-check the amount of random padding. */
1699 st->pad = st->pktin->data[4];
1700 if (st->pad < 4 || st->len - st->pad < 1) {
1701 bombout(("Invalid padding length on received packet"));
1702 ssh_free_packet(st->pktin);
1706 * This enables us to deduce the payload length.
1708 st->payload = st->len - st->pad - 1;
1710 st->pktin->length = st->payload + 5;
1711 st->pktin->encrypted_len = st->packetlen;
1713 st->pktin->sequence = st->incoming_sequence++;
1715 st->pktin->length = st->packetlen - st->pad;
1716 assert(st->pktin->length >= 0);
1719 * Decompress packet payload.
1722 unsigned char *newpayload;
1725 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1726 st->pktin->data + 5, st->pktin->length - 5,
1727 &newpayload, &newlen)) {
1728 if (st->pktin->maxlen < newlen + 5) {
1729 st->pktin->maxlen = newlen + 5;
1730 st->pktin->data = sresize(st->pktin->data,
1731 st->pktin->maxlen + APIEXTRA,
1734 st->pktin->length = 5 + newlen;
1735 memcpy(st->pktin->data + 5, newpayload, newlen);
1741 * pktin->body and pktin->length should identify the semantic
1742 * content of the packet, excluding the initial type byte.
1744 st->pktin->type = st->pktin->data[5];
1745 st->pktin->body = st->pktin->data + 6;
1746 st->pktin->length -= 6;
1747 assert(st->pktin->length >= 0); /* one last double-check */
1750 ssh2_log_incoming_packet(ssh, st->pktin);
1752 st->pktin->savedpos = 0;
1754 crFinish(st->pktin);
1757 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh, unsigned char **data,
1760 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1762 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1765 * Read the packet length field.
1767 for (st->i = 0; st->i < 4; st->i++) {
1768 while ((*datalen) == 0)
1770 st->length[st->i] = *(*data)++;
1774 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1775 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1776 bombout(("Invalid packet length received"));
1780 st->pktin = ssh_new_packet();
1781 st->pktin->data = snewn(st->packetlen, unsigned char);
1783 st->pktin->encrypted_len = st->packetlen;
1785 st->pktin->sequence = st->incoming_sequence++;
1788 * Read the remainder of the packet.
1790 for (st->i = 0; st->i < st->packetlen; st->i++) {
1791 while ((*datalen) == 0)
1793 st->pktin->data[st->i] = *(*data)++;
1798 * pktin->body and pktin->length should identify the semantic
1799 * content of the packet, excluding the initial type byte.
1801 st->pktin->type = st->pktin->data[0];
1802 st->pktin->body = st->pktin->data + 1;
1803 st->pktin->length = st->packetlen - 1;
1806 * Log incoming packet, possibly omitting sensitive fields.
1809 ssh2_log_incoming_packet(ssh, st->pktin);
1811 st->pktin->savedpos = 0;
1813 crFinish(st->pktin);
1816 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1818 int pad, biglen, i, pktoffs;
1822 * XXX various versions of SC (including 8.8.4) screw up the
1823 * register allocation in this function and use the same register
1824 * (D6) for len and as a temporary, with predictable results. The
1825 * following sledgehammer prevents this.
1832 ssh1_log_outgoing_packet(ssh, pkt);
1834 if (ssh->v1_compressing) {
1835 unsigned char *compblk;
1837 zlib_compress_block(ssh->cs_comp_ctx,
1838 pkt->data + 12, pkt->length - 12,
1839 &compblk, &complen);
1840 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1841 memcpy(pkt->data + 12, compblk, complen);
1843 pkt->length = complen + 12;
1846 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1848 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1849 pad = 8 - (len % 8);
1851 biglen = len + pad; /* len(padding+type+data+CRC) */
1853 for (i = pktoffs; i < 4+8; i++)
1854 pkt->data[i] = random_byte();
1855 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1856 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1857 PUT_32BIT(pkt->data + pktoffs, len);
1860 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1861 pkt->data + pktoffs + 4, biglen);
1863 if (offset_p) *offset_p = pktoffs;
1864 return biglen + 4; /* len(length+padding+type+data+CRC) */
1867 static int s_write(Ssh ssh, void *data, int len)
1870 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1871 0, NULL, NULL, 0, NULL);
1874 return sk_write(ssh->s, (char *)data, len);
1877 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1879 int len, backlog, offset;
1880 len = s_wrpkt_prepare(ssh, pkt, &offset);
1881 backlog = s_write(ssh, pkt->data + offset, len);
1882 if (backlog > SSH_MAX_BACKLOG)
1883 ssh_throttle_all(ssh, 1, backlog);
1884 ssh_free_packet(pkt);
1887 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1890 len = s_wrpkt_prepare(ssh, pkt, &offset);
1891 if (ssh->deferred_len + len > ssh->deferred_size) {
1892 ssh->deferred_size = ssh->deferred_len + len + 128;
1893 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1897 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1898 pkt->data + offset, len);
1899 ssh->deferred_len += len;
1900 ssh_free_packet(pkt);
1904 * Construct a SSH-1 packet with the specified contents.
1905 * (This all-at-once interface used to be the only one, but now SSH-1
1906 * packets can also be constructed incrementally.)
1908 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1914 pkt = ssh1_pkt_init(pkttype);
1916 while ((argtype = va_arg(ap, int)) != PKT_END) {
1917 unsigned char *argp, argchar;
1919 unsigned long argint;
1922 /* Actual fields in the packet */
1924 argint = va_arg(ap, int);
1925 ssh_pkt_adduint32(pkt, argint);
1928 argchar = (unsigned char) va_arg(ap, int);
1929 ssh_pkt_addbyte(pkt, argchar);
1932 argp = va_arg(ap, unsigned char *);
1933 arglen = va_arg(ap, int);
1934 ssh_pkt_adddata(pkt, argp, arglen);
1937 sargp = va_arg(ap, char *);
1938 ssh_pkt_addstring(pkt, sargp);
1941 bn = va_arg(ap, Bignum);
1942 ssh1_pkt_addmp(pkt, bn);
1950 static void send_packet(Ssh ssh, int pkttype, ...)
1954 va_start(ap, pkttype);
1955 pkt = construct_packet(ssh, pkttype, ap);
1960 static void defer_packet(Ssh ssh, int pkttype, ...)
1964 va_start(ap, pkttype);
1965 pkt = construct_packet(ssh, pkttype, ap);
1967 s_wrpkt_defer(ssh, pkt);
1970 static int ssh_versioncmp(char *a, char *b)
1973 unsigned long av, bv;
1975 av = strtoul(a, &ae, 10);
1976 bv = strtoul(b, &be, 10);
1978 return (av < bv ? -1 : +1);
1983 av = strtoul(ae, &ae, 10);
1984 bv = strtoul(be, &be, 10);
1986 return (av < bv ? -1 : +1);
1991 * Utility routines for putting an SSH-protocol `string' and
1992 * `uint32' into a hash state.
1994 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
1996 unsigned char lenblk[4];
1997 PUT_32BIT(lenblk, len);
1998 h->bytes(s, lenblk, 4);
1999 h->bytes(s, str, len);
2002 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2004 unsigned char intblk[4];
2005 PUT_32BIT(intblk, i);
2006 h->bytes(s, intblk, 4);
2010 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2012 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2014 if (pkt->maxlen < length) {
2015 unsigned char *body = pkt->body;
2016 int offset = body ? body - pkt->data : 0;
2017 pkt->maxlen = length + 256;
2018 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2019 if (body) pkt->body = pkt->data + offset;
2022 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2025 ssh_pkt_ensure(pkt, pkt->length);
2026 memcpy(pkt->data + pkt->length - len, data, len);
2028 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2030 ssh_pkt_adddata(pkt, &byte, 1);
2032 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2034 ssh_pkt_adddata(pkt, &value, 1);
2036 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2039 PUT_32BIT(x, value);
2040 ssh_pkt_adddata(pkt, x, 4);
2042 static void ssh_pkt_addstring_start(struct Packet *pkt)
2044 ssh_pkt_adduint32(pkt, 0);
2045 pkt->savedpos = pkt->length;
2047 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2049 ssh_pkt_adddata(pkt, data, strlen(data));
2050 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2052 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2055 ssh_pkt_adddata(pkt, data, len);
2056 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2058 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2060 ssh_pkt_addstring_start(pkt);
2061 ssh_pkt_addstring_str(pkt, data);
2063 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2065 int len = ssh1_bignum_length(b);
2066 unsigned char *data = snewn(len, unsigned char);
2067 (void) ssh1_write_bignum(data, b);
2068 ssh_pkt_adddata(pkt, data, len);
2071 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2074 int i, n = (bignum_bitcount(b) + 7) / 8;
2075 p = snewn(n + 1, unsigned char);
2077 for (i = 1; i <= n; i++)
2078 p[i] = bignum_byte(b, n - i);
2080 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2082 memmove(p, p + i, n + 1 - i);
2086 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2090 p = ssh2_mpint_fmt(b, &len);
2091 ssh_pkt_addstring_start(pkt);
2092 ssh_pkt_addstring_data(pkt, (char *)p, len);
2096 static struct Packet *ssh1_pkt_init(int pkt_type)
2098 struct Packet *pkt = ssh_new_packet();
2099 pkt->length = 4 + 8; /* space for length + max padding */
2100 ssh_pkt_addbyte(pkt, pkt_type);
2101 pkt->body = pkt->data + pkt->length;
2102 pkt->type = pkt_type;
2103 pkt->downstream_id = 0;
2104 pkt->additional_log_text = NULL;
2108 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2109 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2110 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2111 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2112 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2113 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2114 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2115 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2116 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2118 static struct Packet *ssh2_pkt_init(int pkt_type)
2120 struct Packet *pkt = ssh_new_packet();
2121 pkt->length = 5; /* space for packet length + padding length */
2123 pkt->type = pkt_type;
2124 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2125 pkt->body = pkt->data + pkt->length; /* after packet type */
2126 pkt->downstream_id = 0;
2127 pkt->additional_log_text = NULL;
2132 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2133 * put the MAC on it. Final packet, ready to be sent, is stored in
2134 * pkt->data. Total length is returned.
2136 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2138 int cipherblk, maclen, padding, i;
2141 ssh2_log_outgoing_packet(ssh, pkt);
2143 if (ssh->bare_connection) {
2145 * Trivial packet construction for the bare connection
2148 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2149 pkt->body = pkt->data + 1;
2150 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2151 return pkt->length - 1;
2155 * Compress packet payload.
2158 unsigned char *newpayload;
2161 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2163 &newpayload, &newlen)) {
2165 ssh2_pkt_adddata(pkt, newpayload, newlen);
2171 * Add padding. At least four bytes, and must also bring total
2172 * length (minus MAC) up to a multiple of the block size.
2173 * If pkt->forcepad is set, make sure the packet is at least that size
2176 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2177 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2179 if (pkt->length + padding < pkt->forcepad)
2180 padding = pkt->forcepad - pkt->length;
2182 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
2183 assert(padding <= 255);
2184 maclen = ssh->csmac ? ssh->csmac->len : 0;
2185 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2186 pkt->data[4] = padding;
2187 for (i = 0; i < padding; i++)
2188 pkt->data[pkt->length + i] = random_byte();
2189 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2191 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2192 pkt->length + padding,
2193 ssh->v2_outgoing_sequence);
2194 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2197 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2198 pkt->data, pkt->length + padding);
2200 pkt->encrypted_len = pkt->length + padding;
2202 /* Ready-to-send packet starts at pkt->data. We return length. */
2203 pkt->body = pkt->data;
2204 return pkt->length + padding + maclen;
2208 * Routines called from the main SSH code to send packets. There
2209 * are quite a few of these, because we have two separate
2210 * mechanisms for delaying the sending of packets:
2212 * - In order to send an IGNORE message and a password message in
2213 * a single fixed-length blob, we require the ability to
2214 * concatenate the encrypted forms of those two packets _into_ a
2215 * single blob and then pass it to our <network.h> transport
2216 * layer in one go. Hence, there's a deferment mechanism which
2217 * works after packet encryption.
2219 * - In order to avoid sending any connection-layer messages
2220 * during repeat key exchange, we have to queue up any such
2221 * outgoing messages _before_ they are encrypted (and in
2222 * particular before they're allocated sequence numbers), and
2223 * then send them once we've finished.
2225 * I call these mechanisms `defer' and `queue' respectively, so as
2226 * to distinguish them reasonably easily.
2228 * The functions send_noqueue() and defer_noqueue() free the packet
2229 * structure they are passed. Every outgoing packet goes through
2230 * precisely one of these functions in its life; packets passed to
2231 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2232 * these or get queued, and then when the queue is later emptied
2233 * the packets are all passed to defer_noqueue().
2235 * When using a CBC-mode cipher, it's necessary to ensure that an
2236 * attacker can't provide data to be encrypted using an IV that they
2237 * know. We ensure this by prefixing each packet that might contain
2238 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2239 * mechanism, so in this case send_noqueue() ends up redirecting to
2240 * defer_noqueue(). If you don't like this inefficiency, don't use
2244 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2245 static void ssh_pkt_defersend(Ssh);
2248 * Send an SSH-2 packet immediately, without queuing or deferring.
2250 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2254 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2255 /* We need to send two packets, so use the deferral mechanism. */
2256 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2257 ssh_pkt_defersend(ssh);
2260 len = ssh2_pkt_construct(ssh, pkt);
2261 backlog = s_write(ssh, pkt->body, len);
2262 if (backlog > SSH_MAX_BACKLOG)
2263 ssh_throttle_all(ssh, 1, backlog);
2265 ssh->outgoing_data_size += pkt->encrypted_len;
2266 if (!ssh->kex_in_progress &&
2267 !ssh->bare_connection &&
2268 ssh->max_data_size != 0 &&
2269 ssh->outgoing_data_size > ssh->max_data_size)
2270 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2272 ssh_free_packet(pkt);
2276 * Defer an SSH-2 packet.
2278 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2281 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2282 ssh->deferred_len == 0 && !noignore &&
2283 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2285 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2286 * get encrypted with a known IV.
2288 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2289 ssh2_pkt_addstring_start(ipkt);
2290 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2292 len = ssh2_pkt_construct(ssh, pkt);
2293 if (ssh->deferred_len + len > ssh->deferred_size) {
2294 ssh->deferred_size = ssh->deferred_len + len + 128;
2295 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2299 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2300 ssh->deferred_len += len;
2301 ssh->deferred_data_size += pkt->encrypted_len;
2302 ssh_free_packet(pkt);
2306 * Queue an SSH-2 packet.
2308 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2310 assert(ssh->queueing);
2312 if (ssh->queuelen >= ssh->queuesize) {
2313 ssh->queuesize = ssh->queuelen + 32;
2314 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2317 ssh->queue[ssh->queuelen++] = pkt;
2321 * Either queue or send a packet, depending on whether queueing is
2324 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2327 ssh2_pkt_queue(ssh, pkt);
2329 ssh2_pkt_send_noqueue(ssh, pkt);
2333 * Either queue or defer a packet, depending on whether queueing is
2336 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2339 ssh2_pkt_queue(ssh, pkt);
2341 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2345 * Send the whole deferred data block constructed by
2346 * ssh2_pkt_defer() or SSH-1's defer_packet().
2348 * The expected use of the defer mechanism is that you call
2349 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2350 * not currently queueing, this simply sets up deferred_send_data
2351 * and then sends it. If we _are_ currently queueing, the calls to
2352 * ssh2_pkt_defer() put the deferred packets on to the queue
2353 * instead, and therefore ssh_pkt_defersend() has no deferred data
2354 * to send. Hence, there's no need to make it conditional on
2357 static void ssh_pkt_defersend(Ssh ssh)
2360 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2361 ssh->deferred_len = ssh->deferred_size = 0;
2362 sfree(ssh->deferred_send_data);
2363 ssh->deferred_send_data = NULL;
2364 if (backlog > SSH_MAX_BACKLOG)
2365 ssh_throttle_all(ssh, 1, backlog);
2367 ssh->outgoing_data_size += ssh->deferred_data_size;
2368 if (!ssh->kex_in_progress &&
2369 !ssh->bare_connection &&
2370 ssh->max_data_size != 0 &&
2371 ssh->outgoing_data_size > ssh->max_data_size)
2372 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2373 ssh->deferred_data_size = 0;
2377 * Send a packet whose length needs to be disguised (typically
2378 * passwords or keyboard-interactive responses).
2380 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2386 * The simplest way to do this is to adjust the
2387 * variable-length padding field in the outgoing packet.
2389 * Currently compiled out, because some Cisco SSH servers
2390 * don't like excessively padded packets (bah, why's it
2393 pkt->forcepad = padsize;
2394 ssh2_pkt_send(ssh, pkt);
2399 * If we can't do that, however, an alternative approach is
2400 * to use the pkt_defer mechanism to bundle the packet
2401 * tightly together with an SSH_MSG_IGNORE such that their
2402 * combined length is a constant. So first we construct the
2403 * final form of this packet and defer its sending.
2405 ssh2_pkt_defer(ssh, pkt);
2408 * Now construct an SSH_MSG_IGNORE which includes a string
2409 * that's an exact multiple of the cipher block size. (If
2410 * the cipher is NULL so that the block size is
2411 * unavailable, we don't do this trick at all, because we
2412 * gain nothing by it.)
2414 if (ssh->cscipher &&
2415 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2418 stringlen = (256 - ssh->deferred_len);
2419 stringlen += ssh->cscipher->blksize - 1;
2420 stringlen -= (stringlen % ssh->cscipher->blksize);
2423 * Temporarily disable actual compression, so we
2424 * can guarantee to get this string exactly the
2425 * length we want it. The compression-disabling
2426 * routine should return an integer indicating how
2427 * many bytes we should adjust our string length
2431 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2433 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2434 ssh2_pkt_addstring_start(pkt);
2435 for (i = 0; i < stringlen; i++) {
2436 char c = (char) random_byte();
2437 ssh2_pkt_addstring_data(pkt, &c, 1);
2439 ssh2_pkt_defer(ssh, pkt);
2441 ssh_pkt_defersend(ssh);
2446 * Send all queued SSH-2 packets. We send them by means of
2447 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2448 * packets that needed to be lumped together.
2450 static void ssh2_pkt_queuesend(Ssh ssh)
2454 assert(!ssh->queueing);
2456 for (i = 0; i < ssh->queuelen; i++)
2457 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2460 ssh_pkt_defersend(ssh);
2464 void bndebug(char *string, Bignum b)
2468 p = ssh2_mpint_fmt(b, &len);
2469 debug(("%s", string));
2470 for (i = 0; i < len; i++)
2471 debug((" %02x", p[i]));
2477 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2481 p = ssh2_mpint_fmt(b, &len);
2482 hash_string(h, s, p, len);
2487 * Packet decode functions for both SSH-1 and SSH-2.
2489 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2491 unsigned long value;
2492 if (pkt->length - pkt->savedpos < 4)
2493 return 0; /* arrgh, no way to decline (FIXME?) */
2494 value = GET_32BIT(pkt->body + pkt->savedpos);
2498 static int ssh2_pkt_getbool(struct Packet *pkt)
2500 unsigned long value;
2501 if (pkt->length - pkt->savedpos < 1)
2502 return 0; /* arrgh, no way to decline (FIXME?) */
2503 value = pkt->body[pkt->savedpos] != 0;
2507 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2512 if (pkt->length - pkt->savedpos < 4)
2514 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2519 if (pkt->length - pkt->savedpos < *length)
2521 *p = (char *)(pkt->body + pkt->savedpos);
2522 pkt->savedpos += *length;
2524 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2526 if (pkt->length - pkt->savedpos < length)
2528 pkt->savedpos += length;
2529 return pkt->body + (pkt->savedpos - length);
2531 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2532 unsigned char **keystr)
2536 j = makekey(pkt->body + pkt->savedpos,
2537 pkt->length - pkt->savedpos,
2544 assert(pkt->savedpos < pkt->length);
2548 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2553 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2554 pkt->length - pkt->savedpos, &b);
2562 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2568 ssh_pkt_getstring(pkt, &p, &length);
2573 b = bignum_from_bytes((unsigned char *)p, length);
2578 * Helper function to add an SSH-2 signature blob to a packet.
2579 * Expects to be shown the public key blob as well as the signature
2580 * blob. Normally works just like ssh2_pkt_addstring, but will
2581 * fiddle with the signature packet if necessary for
2582 * BUG_SSH2_RSA_PADDING.
2584 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2585 void *pkblob_v, int pkblob_len,
2586 void *sigblob_v, int sigblob_len)
2588 unsigned char *pkblob = (unsigned char *)pkblob_v;
2589 unsigned char *sigblob = (unsigned char *)sigblob_v;
2591 /* dmemdump(pkblob, pkblob_len); */
2592 /* dmemdump(sigblob, sigblob_len); */
2595 * See if this is in fact an ssh-rsa signature and a buggy
2596 * server; otherwise we can just do this the easy way.
2598 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2599 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2600 int pos, len, siglen;
2603 * Find the byte length of the modulus.
2606 pos = 4+7; /* skip over "ssh-rsa" */
2607 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2608 if (len < 0 || len > pkblob_len - pos - 4)
2610 pos += 4 + len; /* skip over exponent */
2611 if (pkblob_len - pos < 4)
2613 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2614 if (len < 0 || len > pkblob_len - pos - 4)
2616 pos += 4; /* find modulus itself */
2617 while (len > 0 && pkblob[pos] == 0)
2619 /* debug(("modulus length is %d\n", len)); */
2622 * Now find the signature integer.
2624 pos = 4+7; /* skip over "ssh-rsa" */
2625 if (sigblob_len < pos+4)
2627 siglen = toint(GET_32BIT(sigblob+pos));
2628 if (siglen != sigblob_len - pos - 4)
2630 /* debug(("signature length is %d\n", siglen)); */
2632 if (len != siglen) {
2633 unsigned char newlen[4];
2634 ssh2_pkt_addstring_start(pkt);
2635 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2636 /* dmemdump(sigblob, pos); */
2637 pos += 4; /* point to start of actual sig */
2638 PUT_32BIT(newlen, len);
2639 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2640 /* dmemdump(newlen, 4); */
2642 while (len-- > siglen) {
2643 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2644 /* dmemdump(newlen, 1); */
2646 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2647 /* dmemdump(sigblob+pos, siglen); */
2651 /* Otherwise fall through and do it the easy way. We also come
2652 * here as a fallback if we discover above that the key blob
2653 * is misformatted in some way. */
2657 ssh2_pkt_addstring_start(pkt);
2658 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2662 * Examine the remote side's version string and compare it against
2663 * a list of known buggy implementations.
2665 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2667 char *imp; /* pointer to implementation part */
2669 imp += strcspn(imp, "-");
2671 imp += strcspn(imp, "-");
2674 ssh->remote_bugs = 0;
2677 * General notes on server version strings:
2678 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2679 * here -- in particular, we've heard of one that's perfectly happy
2680 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2681 * so we can't distinguish them.
2683 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2684 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2685 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2686 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2687 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2688 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2690 * These versions don't support SSH1_MSG_IGNORE, so we have
2691 * to use a different defence against password length
2694 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2695 logevent("We believe remote version has SSH-1 ignore bug");
2698 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2699 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2700 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2702 * These versions need a plain password sent; they can't
2703 * handle having a null and a random length of data after
2706 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2707 logevent("We believe remote version needs a plain SSH-1 password");
2710 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2711 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2712 (!strcmp(imp, "Cisco-1.25")))) {
2714 * These versions apparently have no clue whatever about
2715 * RSA authentication and will panic and die if they see
2716 * an AUTH_RSA message.
2718 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2719 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2722 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2723 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2724 !wc_match("* VShell", imp) &&
2725 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2726 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2727 wc_match("2.1 *", imp)))) {
2729 * These versions have the HMAC bug.
2731 ssh->remote_bugs |= BUG_SSH2_HMAC;
2732 logevent("We believe remote version has SSH-2 HMAC bug");
2735 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2736 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2737 !wc_match("* VShell", imp) &&
2738 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2740 * These versions have the key-derivation bug (failing to
2741 * include the literal shared secret in the hashes that
2742 * generate the keys).
2744 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2745 logevent("We believe remote version has SSH-2 key-derivation bug");
2748 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2749 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2750 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2751 wc_match("OpenSSH_3.[0-2]*", imp) ||
2752 wc_match("mod_sftp/0.[0-8]*", imp) ||
2753 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2755 * These versions have the SSH-2 RSA padding bug.
2757 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2758 logevent("We believe remote version has SSH-2 RSA padding bug");
2761 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2762 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2763 wc_match("OpenSSH_2.[0-2]*", imp))) {
2765 * These versions have the SSH-2 session-ID bug in
2766 * public-key authentication.
2768 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2769 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2772 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2773 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2774 (wc_match("DigiSSH_2.0", imp) ||
2775 wc_match("OpenSSH_2.[0-4]*", imp) ||
2776 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2777 wc_match("Sun_SSH_1.0", imp) ||
2778 wc_match("Sun_SSH_1.0.1", imp) ||
2779 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2780 wc_match("WeOnlyDo-*", imp)))) {
2782 * These versions have the SSH-2 rekey bug.
2784 ssh->remote_bugs |= BUG_SSH2_REKEY;
2785 logevent("We believe remote version has SSH-2 rekey bug");
2788 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2789 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2790 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2791 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2793 * This version ignores our makpkt and needs to be throttled.
2795 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2796 logevent("We believe remote version ignores SSH-2 maximum packet size");
2799 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2801 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2802 * none detected automatically.
2804 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2805 logevent("We believe remote version has SSH-2 ignore bug");
2808 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2810 * Servers that don't support our winadj request for one
2811 * reason or another. Currently, none detected automatically.
2813 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2814 logevent("We believe remote version has winadj bug");
2817 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
2818 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
2819 (wc_match("OpenSSH_[2-5].*", imp) ||
2820 wc_match("OpenSSH_6.[0-6]*", imp)))) {
2822 * These versions have the SSH-2 channel request bug. 6.7 and
2824 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
2826 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
2827 logevent("We believe remote version has SSH-2 channel request bug");
2832 * The `software version' part of an SSH version string is required
2833 * to contain no spaces or minus signs.
2835 static void ssh_fix_verstring(char *str)
2837 /* Eat "<protoversion>-". */
2838 while (*str && *str != '-') str++;
2839 assert(*str == '-'); str++;
2841 /* Convert minus signs and spaces in the remaining string into
2844 if (*str == '-' || *str == ' ')
2851 * Send an appropriate SSH version string.
2853 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
2857 if (ssh->version == 2) {
2859 * Construct a v2 version string.
2861 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
2864 * Construct a v1 version string.
2866 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
2867 verstring = dupprintf("SSH-%s-%s\012",
2868 (ssh_versioncmp(svers, "1.5") <= 0 ?
2873 ssh_fix_verstring(verstring + strlen(protoname));
2875 if (ssh->version == 2) {
2878 * Record our version string.
2880 len = strcspn(verstring, "\015\012");
2881 ssh->v_c = snewn(len + 1, char);
2882 memcpy(ssh->v_c, verstring, len);
2886 logeventf(ssh, "We claim version: %.*s",
2887 strcspn(verstring, "\015\012"), verstring);
2888 s_write(ssh, verstring, strlen(verstring));
2892 static int do_ssh_init(Ssh ssh, unsigned char c)
2894 static const char protoname[] = "SSH-";
2896 struct do_ssh_init_state {
2905 crState(do_ssh_init_state);
2909 /* Search for a line beginning with the protocol name prefix in
2912 for (s->i = 0; protoname[s->i]; s->i++) {
2913 if ((char)c != protoname[s->i]) goto no;
2923 s->vstrsize = sizeof(protoname) + 16;
2924 s->vstring = snewn(s->vstrsize, char);
2925 strcpy(s->vstring, protoname);
2926 s->vslen = strlen(protoname);
2929 if (s->vslen >= s->vstrsize - 1) {
2931 s->vstring = sresize(s->vstring, s->vstrsize, char);
2933 s->vstring[s->vslen++] = c;
2936 s->version[s->i] = '\0';
2938 } else if (s->i < sizeof(s->version) - 1)
2939 s->version[s->i++] = c;
2940 } else if (c == '\012')
2942 crReturn(1); /* get another char */
2945 ssh->agentfwd_enabled = FALSE;
2946 ssh->rdpkt2_state.incoming_sequence = 0;
2948 s->vstring[s->vslen] = 0;
2949 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2950 logeventf(ssh, "Server version: %s", s->vstring);
2951 ssh_detect_bugs(ssh, s->vstring);
2954 * Decide which SSH protocol version to support.
2957 /* Anything strictly below "2.0" means protocol 1 is supported. */
2958 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2959 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2960 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2962 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2963 bombout(("SSH protocol version 1 required by configuration but "
2964 "not provided by server"));
2967 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2968 bombout(("SSH protocol version 2 required by configuration but "
2969 "not provided by server"));
2973 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2978 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2980 /* Send the version string, if we haven't already */
2981 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2982 ssh_send_verstring(ssh, protoname, s->version);
2984 if (ssh->version == 2) {
2987 * Record their version string.
2989 len = strcspn(s->vstring, "\015\012");
2990 ssh->v_s = snewn(len + 1, char);
2991 memcpy(ssh->v_s, s->vstring, len);
2995 * Initialise SSH-2 protocol.
2997 ssh->protocol = ssh2_protocol;
2998 ssh2_protocol_setup(ssh);
2999 ssh->s_rdpkt = ssh2_rdpkt;
3002 * Initialise SSH-1 protocol.
3004 ssh->protocol = ssh1_protocol;
3005 ssh1_protocol_setup(ssh);
3006 ssh->s_rdpkt = ssh1_rdpkt;
3008 if (ssh->version == 2)
3009 do_ssh2_transport(ssh, NULL, -1, NULL);
3011 update_specials_menu(ssh->frontend);
3012 ssh->state = SSH_STATE_BEFORE_SIZE;
3013 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3020 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3023 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3024 * the ssh-connection part, extracted and given a trivial binary
3025 * packet protocol, so we replace 'SSH-' at the start with a new
3026 * name. In proper SSH style (though of course this part of the
3027 * proper SSH protocol _isn't_ subject to this kind of
3028 * DNS-domain-based extension), we define the new name in our
3031 static const char protoname[] =
3032 "SSHCONNECTION@putty.projects.tartarus.org-";
3034 struct do_ssh_connection_init_state {
3042 crState(do_ssh_connection_init_state);
3046 /* Search for a line beginning with the protocol name prefix in
3049 for (s->i = 0; protoname[s->i]; s->i++) {
3050 if ((char)c != protoname[s->i]) goto no;
3060 s->vstrsize = sizeof(protoname) + 16;
3061 s->vstring = snewn(s->vstrsize, char);
3062 strcpy(s->vstring, protoname);
3063 s->vslen = strlen(protoname);
3066 if (s->vslen >= s->vstrsize - 1) {
3068 s->vstring = sresize(s->vstring, s->vstrsize, char);
3070 s->vstring[s->vslen++] = c;
3073 s->version[s->i] = '\0';
3075 } else if (s->i < sizeof(s->version) - 1)
3076 s->version[s->i++] = c;
3077 } else if (c == '\012')
3079 crReturn(1); /* get another char */
3082 ssh->agentfwd_enabled = FALSE;
3083 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3085 s->vstring[s->vslen] = 0;
3086 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3087 logeventf(ssh, "Server version: %s", s->vstring);
3088 ssh_detect_bugs(ssh, s->vstring);
3091 * Decide which SSH protocol version to support. This is easy in
3092 * bare ssh-connection mode: only 2.0 is legal.
3094 if (ssh_versioncmp(s->version, "2.0") < 0) {
3095 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3098 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3099 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3105 logeventf(ssh, "Using bare ssh-connection protocol");
3107 /* Send the version string, if we haven't already */
3108 ssh_send_verstring(ssh, protoname, s->version);
3111 * Initialise bare connection protocol.
3113 ssh->protocol = ssh2_bare_connection_protocol;
3114 ssh2_bare_connection_protocol_setup(ssh);
3115 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3117 update_specials_menu(ssh->frontend);
3118 ssh->state = SSH_STATE_BEFORE_SIZE;
3119 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3122 * Get authconn (really just conn) under way.
3124 do_ssh2_authconn(ssh, NULL, 0, NULL);
3131 static void ssh_process_incoming_data(Ssh ssh,
3132 unsigned char **data, int *datalen)
3134 struct Packet *pktin;
3136 pktin = ssh->s_rdpkt(ssh, data, datalen);
3138 ssh->protocol(ssh, NULL, 0, pktin);
3139 ssh_free_packet(pktin);
3143 static void ssh_queue_incoming_data(Ssh ssh,
3144 unsigned char **data, int *datalen)
3146 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3151 static void ssh_process_queued_incoming_data(Ssh ssh)
3154 unsigned char *data;
3157 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3158 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3162 while (!ssh->frozen && len > 0)
3163 ssh_process_incoming_data(ssh, &data, &len);
3166 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3170 static void ssh_set_frozen(Ssh ssh, int frozen)
3173 sk_set_frozen(ssh->s, frozen);
3174 ssh->frozen = frozen;
3177 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
3179 /* Log raw data, if we're in that mode. */
3181 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3182 0, NULL, NULL, 0, NULL);
3184 crBegin(ssh->ssh_gotdata_crstate);
3187 * To begin with, feed the characters one by one to the
3188 * protocol initialisation / selection function do_ssh_init().
3189 * When that returns 0, we're done with the initial greeting
3190 * exchange and can move on to packet discipline.
3193 int ret; /* need not be kept across crReturn */
3195 crReturnV; /* more data please */
3196 ret = ssh->do_ssh_init(ssh, *data);
3204 * We emerge from that loop when the initial negotiation is
3205 * over and we have selected an s_rdpkt function. Now pass
3206 * everything to s_rdpkt, and then pass the resulting packets
3207 * to the proper protocol handler.
3211 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3213 ssh_queue_incoming_data(ssh, &data, &datalen);
3214 /* This uses up all data and cannot cause anything interesting
3215 * to happen; indeed, for anything to happen at all, we must
3216 * return, so break out. */
3218 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3219 /* This uses up some or all data, and may freeze the
3221 ssh_process_queued_incoming_data(ssh);
3223 /* This uses up some or all data, and may freeze the
3225 ssh_process_incoming_data(ssh, &data, &datalen);
3227 /* FIXME this is probably EBW. */
3228 if (ssh->state == SSH_STATE_CLOSED)
3231 /* We're out of data. Go and get some more. */
3237 static int ssh_do_close(Ssh ssh, int notify_exit)
3240 struct ssh_channel *c;
3242 ssh->state = SSH_STATE_CLOSED;
3243 expire_timer_context(ssh);
3248 notify_remote_exit(ssh->frontend);
3253 * Now we must shut down any port- and X-forwarded channels going
3254 * through this connection.
3256 if (ssh->channels) {
3257 while (NULL != (c = index234(ssh->channels, 0))) {
3260 x11_close(c->u.x11.xconn);
3263 case CHAN_SOCKDATA_DORMANT:
3264 pfd_close(c->u.pfd.pf);
3267 del234(ssh->channels, c); /* moving next one to index 0 */
3268 if (ssh->version == 2)
3269 bufchain_clear(&c->v.v2.outbuffer);
3274 * Go through port-forwardings, and close any associated
3275 * listening sockets.
3277 if (ssh->portfwds) {
3278 struct ssh_portfwd *pf;
3279 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3280 /* Dispose of any listening socket. */
3282 pfl_terminate(pf->local);
3283 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3286 freetree234(ssh->portfwds);
3287 ssh->portfwds = NULL;
3293 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3294 const char *error_msg, int error_code)
3296 Ssh ssh = (Ssh) plug;
3297 char addrbuf[256], *msg;
3299 if (ssh->attempting_connshare) {
3301 * While we're attempting connection sharing, don't loudly log
3302 * everything that happens. Real TCP connections need to be
3303 * logged when we _start_ trying to connect, because it might
3304 * be ages before they respond if something goes wrong; but
3305 * connection sharing is local and quick to respond, and it's
3306 * sufficient to simply wait and see whether it worked
3310 sk_getaddr(addr, addrbuf, lenof(addrbuf));
3313 if (sk_addr_needs_port(addr)) {
3314 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
3316 msg = dupprintf("Connecting to %s", addrbuf);
3319 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
3327 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3328 const char *ds_err, const char *us_err)
3330 if (event == SHARE_NONE) {
3331 /* In this case, 'logtext' is an error message indicating a
3332 * reason why connection sharing couldn't be set up _at all_.
3333 * Failing that, ds_err and us_err indicate why we couldn't be
3334 * a downstream and an upstream respectively. */
3336 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3339 logeventf(ssh, "Could not set up connection sharing"
3340 " as downstream: %s", ds_err);
3342 logeventf(ssh, "Could not set up connection sharing"
3343 " as upstream: %s", us_err);
3345 } else if (event == SHARE_DOWNSTREAM) {
3346 /* In this case, 'logtext' is a local endpoint address */
3347 logeventf(ssh, "Using existing shared connection at %s", logtext);
3348 /* Also we should mention this in the console window to avoid
3349 * confusing users as to why this window doesn't behave the
3351 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3352 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3354 } else if (event == SHARE_UPSTREAM) {
3355 /* In this case, 'logtext' is a local endpoint address too */
3356 logeventf(ssh, "Sharing this connection at %s", logtext);
3360 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3363 Ssh ssh = (Ssh) plug;
3364 int need_notify = ssh_do_close(ssh, FALSE);
3367 if (!ssh->close_expected)
3368 error_msg = "Server unexpectedly closed network connection";
3370 error_msg = "Server closed network connection";
3373 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3377 notify_remote_exit(ssh->frontend);
3380 logevent(error_msg);
3381 if (!ssh->close_expected || !ssh->clean_exit)
3382 connection_fatal(ssh->frontend, "%s", error_msg);
3386 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3388 Ssh ssh = (Ssh) plug;
3389 ssh_gotdata(ssh, (unsigned char *)data, len);
3390 if (ssh->state == SSH_STATE_CLOSED) {
3391 ssh_do_close(ssh, TRUE);
3397 static void ssh_sent(Plug plug, int bufsize)
3399 Ssh ssh = (Ssh) plug;
3401 * If the send backlog on the SSH socket itself clears, we
3402 * should unthrottle the whole world if it was throttled.
3404 if (bufsize < SSH_MAX_BACKLOG)
3405 ssh_throttle_all(ssh, 0, bufsize);
3409 * Connect to specified host and port.
3410 * Returns an error message, or NULL on success.
3411 * Also places the canonical host name into `realhost'. It must be
3412 * freed by the caller.
3414 static const char *connect_to_host(Ssh ssh, char *host, int port,
3415 char **realhost, int nodelay, int keepalive)
3417 static const struct plug_function_table fn_table = {
3428 int addressfamily, sshprot;
3430 loghost = conf_get_str(ssh->conf, CONF_loghost);
3435 tmphost = dupstr(loghost);
3436 ssh->savedport = 22; /* default ssh port */
3439 * A colon suffix on the hostname string also lets us affect
3440 * savedport. (Unless there are multiple colons, in which case
3441 * we assume this is an unbracketed IPv6 literal.)
3443 colon = host_strrchr(tmphost, ':');
3444 if (colon && colon == host_strchr(tmphost, ':')) {
3447 ssh->savedport = atoi(colon);
3450 ssh->savedhost = host_strduptrim(tmphost);
3453 ssh->savedhost = host_strduptrim(host);
3455 port = 22; /* default ssh port */
3456 ssh->savedport = port;
3459 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3462 * Try connection-sharing, in case that means we don't open a
3463 * socket after all. ssh_connection_sharing_init will connect to a
3464 * previously established upstream if it can, and failing that,
3465 * establish a listening socket for _us_ to be the upstream. In
3466 * the latter case it will return NULL just as if it had done
3467 * nothing, because here we only need to care if we're a
3468 * downstream and need to do our connection setup differently.
3470 ssh->connshare = NULL;
3471 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3472 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3473 ssh->conf, ssh, &ssh->connshare);
3474 ssh->attempting_connshare = FALSE;
3475 if (ssh->s != NULL) {
3477 * We are a downstream.
3479 ssh->bare_connection = TRUE;
3480 ssh->do_ssh_init = do_ssh_connection_init;
3481 ssh->fullhostname = NULL;
3482 *realhost = dupstr(host); /* best we can do */
3485 * We're not a downstream, so open a normal socket.
3487 ssh->do_ssh_init = do_ssh_init;
3492 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3493 logeventf(ssh, "Looking up host \"%s\"%s", host,
3494 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3495 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3496 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3497 if ((err = sk_addr_error(addr)) != NULL) {
3501 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3503 ssh->s = new_connection(addr, *realhost, port,
3504 0, 1, nodelay, keepalive,
3505 (Plug) ssh, ssh->conf);
3506 if ((err = sk_socket_error(ssh->s)) != NULL) {
3508 notify_remote_exit(ssh->frontend);
3514 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3515 * send the version string too.
3517 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3520 if (sshprot == 3 && !ssh->bare_connection) {
3522 ssh_send_verstring(ssh, "SSH-", NULL);
3526 * loghost, if configured, overrides realhost.
3530 *realhost = dupstr(loghost);
3537 * Throttle or unthrottle the SSH connection.
3539 static void ssh_throttle_conn(Ssh ssh, int adjust)
3541 int old_count = ssh->conn_throttle_count;
3542 ssh->conn_throttle_count += adjust;
3543 assert(ssh->conn_throttle_count >= 0);
3544 if (ssh->conn_throttle_count && !old_count) {
3545 ssh_set_frozen(ssh, 1);
3546 } else if (!ssh->conn_throttle_count && old_count) {
3547 ssh_set_frozen(ssh, 0);
3552 * Throttle or unthrottle _all_ local data streams (for when sends
3553 * on the SSH connection itself back up).
3555 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3558 struct ssh_channel *c;
3560 if (enable == ssh->throttled_all)
3562 ssh->throttled_all = enable;
3563 ssh->overall_bufsize = bufsize;
3566 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3568 case CHAN_MAINSESSION:
3570 * This is treated separately, outside the switch.
3574 x11_override_throttle(c->u.x11.xconn, enable);
3577 /* Agent channels require no buffer management. */
3580 pfd_override_throttle(c->u.pfd.pf, enable);
3586 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3588 Ssh ssh = (Ssh) sshv;
3590 ssh->agent_response = reply;
3591 ssh->agent_response_len = replylen;
3593 if (ssh->version == 1)
3594 do_ssh1_login(ssh, NULL, -1, NULL);
3596 do_ssh2_authconn(ssh, NULL, -1, NULL);
3599 static void ssh_dialog_callback(void *sshv, int ret)
3601 Ssh ssh = (Ssh) sshv;
3603 ssh->user_response = ret;
3605 if (ssh->version == 1)
3606 do_ssh1_login(ssh, NULL, -1, NULL);
3608 do_ssh2_transport(ssh, NULL, -1, NULL);
3611 * This may have unfrozen the SSH connection, so do a
3614 ssh_process_queued_incoming_data(ssh);
3617 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3619 struct ssh_channel *c = (struct ssh_channel *)cv;
3621 void *sentreply = reply;
3623 c->u.a.outstanding_requests--;
3625 /* Fake SSH_AGENT_FAILURE. */
3626 sentreply = "\0\0\0\1\5";
3629 if (ssh->version == 2) {
3630 ssh2_add_channel_data(c, sentreply, replylen);
3633 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3634 PKT_INT, c->remoteid,
3636 PKT_DATA, sentreply, replylen,
3642 * If we've already seen an incoming EOF but haven't sent an
3643 * outgoing one, this may be the moment to send it.
3645 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3646 sshfwd_write_eof(c);
3650 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3651 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3652 * => log `wire_reason'.
3654 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3655 int code, int clean_exit)
3659 client_reason = wire_reason;
3661 error = dupprintf("Disconnected: %s", client_reason);
3663 error = dupstr("Disconnected");
3665 if (ssh->version == 1) {
3666 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3668 } else if (ssh->version == 2) {
3669 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3670 ssh2_pkt_adduint32(pktout, code);
3671 ssh2_pkt_addstring(pktout, wire_reason);
3672 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3673 ssh2_pkt_send_noqueue(ssh, pktout);
3676 ssh->close_expected = TRUE;
3677 ssh->clean_exit = clean_exit;
3678 ssh_closing((Plug)ssh, error, 0, 0);
3682 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3683 const struct ssh_signkey *ssh2keytype,
3686 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3687 return -1; /* no manual keys configured */
3692 * The fingerprint string we've been given will have things
3693 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3694 * narrow down to just the colon-separated hex block at the
3695 * end of the string.
3697 const char *p = strrchr(fingerprint, ' ');
3698 fingerprint = p ? p+1 : fingerprint;
3699 /* Quick sanity checks, including making sure it's in lowercase */
3700 assert(strlen(fingerprint) == 16*3 - 1);
3701 assert(fingerprint[2] == ':');
3702 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3704 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3706 return 1; /* success */
3711 * Construct the base64-encoded public key blob and see if
3714 unsigned char *binblob;
3716 int binlen, atoms, i;
3717 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3718 atoms = (binlen + 2) / 3;
3719 base64blob = snewn(atoms * 4 + 1, char);
3720 for (i = 0; i < atoms; i++)
3721 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3722 base64blob[atoms * 4] = '\0';
3724 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3727 return 1; /* success */
3736 * Handle the key exchange and user authentication phases.
3738 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3739 struct Packet *pktin)
3742 unsigned char cookie[8], *ptr;
3743 struct MD5Context md5c;
3744 struct do_ssh1_login_state {
3747 unsigned char *rsabuf, *keystr1, *keystr2;
3748 unsigned long supported_ciphers_mask, supported_auths_mask;
3749 int tried_publickey, tried_agent;
3750 int tis_auth_refused, ccard_auth_refused;
3751 unsigned char session_id[16];
3753 void *publickey_blob;
3754 int publickey_bloblen;
3755 char *publickey_comment;
3756 int publickey_encrypted;
3757 prompts_t *cur_prompt;
3760 unsigned char request[5], *response, *p;
3770 struct RSAKey servkey, hostkey;
3772 crState(do_ssh1_login_state);
3779 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3780 bombout(("Public key packet not received"));
3784 logevent("Received public keys");
3786 ptr = ssh_pkt_getdata(pktin, 8);
3788 bombout(("SSH-1 public key packet stopped before random cookie"));
3791 memcpy(cookie, ptr, 8);
3793 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3794 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3795 bombout(("Failed to read SSH-1 public keys from public key packet"));
3800 * Log the host key fingerprint.
3804 logevent("Host key fingerprint is:");
3805 strcpy(logmsg, " ");
3806 s->hostkey.comment = NULL;
3807 rsa_fingerprint(logmsg + strlen(logmsg),
3808 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3812 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3813 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3814 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3815 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3816 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3818 ssh->v1_local_protoflags =
3819 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3820 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3823 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3824 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3825 MD5Update(&md5c, cookie, 8);
3826 MD5Final(s->session_id, &md5c);
3828 for (i = 0; i < 32; i++)
3829 ssh->session_key[i] = random_byte();
3832 * Verify that the `bits' and `bytes' parameters match.
3834 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3835 s->servkey.bits > s->servkey.bytes * 8) {
3836 bombout(("SSH-1 public keys were badly formatted"));
3840 s->len = (s->hostkey.bytes > s->servkey.bytes ?
3841 s->hostkey.bytes : s->servkey.bytes);
3843 s->rsabuf = snewn(s->len, unsigned char);
3846 * Verify the host key.
3850 * First format the key into a string.
3852 int len = rsastr_len(&s->hostkey);
3853 char fingerprint[100];
3854 char *keystr = snewn(len, char);
3855 rsastr_fmt(keystr, &s->hostkey);
3856 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
3858 /* First check against manually configured host keys. */
3859 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
3860 if (s->dlgret == 0) { /* did not match */
3861 bombout(("Host key did not appear in manually configured list"));
3863 } else if (s->dlgret < 0) { /* none configured; use standard handling */
3864 ssh_set_frozen(ssh, 1);
3865 s->dlgret = verify_ssh_host_key(ssh->frontend,
3866 ssh->savedhost, ssh->savedport,
3867 "rsa", keystr, fingerprint,
3868 ssh_dialog_callback, ssh);
3870 if (s->dlgret < 0) {
3874 bombout(("Unexpected data from server while waiting"
3875 " for user host key response"));
3878 } while (pktin || inlen > 0);
3879 s->dlgret = ssh->user_response;
3881 ssh_set_frozen(ssh, 0);
3883 if (s->dlgret == 0) {
3884 ssh_disconnect(ssh, "User aborted at host key verification",
3891 for (i = 0; i < 32; i++) {
3892 s->rsabuf[i] = ssh->session_key[i];
3894 s->rsabuf[i] ^= s->session_id[i];
3897 if (s->hostkey.bytes > s->servkey.bytes) {
3898 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
3900 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
3902 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
3904 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
3907 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3911 logevent("Encrypted session key");
3914 int cipher_chosen = 0, warn = 0;
3915 char *cipher_string = NULL;
3917 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3918 int next_cipher = conf_get_int_int(ssh->conf,
3919 CONF_ssh_cipherlist, i);
3920 if (next_cipher == CIPHER_WARN) {
3921 /* If/when we choose a cipher, warn about it */
3923 } else if (next_cipher == CIPHER_AES) {
3924 /* XXX Probably don't need to mention this. */
3925 logevent("AES not supported in SSH-1, skipping");
3927 switch (next_cipher) {
3928 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3929 cipher_string = "3DES"; break;
3930 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3931 cipher_string = "Blowfish"; break;
3932 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3933 cipher_string = "single-DES"; break;
3935 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3939 if (!cipher_chosen) {
3940 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3941 bombout(("Server violates SSH-1 protocol by not "
3942 "supporting 3DES encryption"));
3944 /* shouldn't happen */
3945 bombout(("No supported ciphers found"));
3949 /* Warn about chosen cipher if necessary. */
3951 ssh_set_frozen(ssh, 1);
3952 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3953 ssh_dialog_callback, ssh);
3954 if (s->dlgret < 0) {
3958 bombout(("Unexpected data from server while waiting"
3959 " for user response"));
3962 } while (pktin || inlen > 0);
3963 s->dlgret = ssh->user_response;
3965 ssh_set_frozen(ssh, 0);
3966 if (s->dlgret == 0) {
3967 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3974 switch (s->cipher_type) {
3975 case SSH_CIPHER_3DES:
3976 logevent("Using 3DES encryption");
3978 case SSH_CIPHER_DES:
3979 logevent("Using single-DES encryption");
3981 case SSH_CIPHER_BLOWFISH:
3982 logevent("Using Blowfish encryption");
3986 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3987 PKT_CHAR, s->cipher_type,
3988 PKT_DATA, cookie, 8,
3989 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3990 PKT_DATA, s->rsabuf, s->len,
3991 PKT_INT, ssh->v1_local_protoflags, PKT_END);
3993 logevent("Trying to enable encryption...");
3997 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3998 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4000 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4001 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4002 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4004 ssh->crcda_ctx = crcda_make_context();
4005 logevent("Installing CRC compensation attack detector");
4007 if (s->servkey.modulus) {
4008 sfree(s->servkey.modulus);
4009 s->servkey.modulus = NULL;
4011 if (s->servkey.exponent) {
4012 sfree(s->servkey.exponent);
4013 s->servkey.exponent = NULL;
4015 if (s->hostkey.modulus) {
4016 sfree(s->hostkey.modulus);
4017 s->hostkey.modulus = NULL;
4019 if (s->hostkey.exponent) {
4020 sfree(s->hostkey.exponent);
4021 s->hostkey.exponent = NULL;
4025 if (pktin->type != SSH1_SMSG_SUCCESS) {
4026 bombout(("Encryption not successfully enabled"));
4030 logevent("Successfully started encryption");
4032 fflush(stdout); /* FIXME eh? */
4034 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4035 int ret; /* need not be kept over crReturn */
4036 s->cur_prompt = new_prompts(ssh->frontend);
4037 s->cur_prompt->to_server = TRUE;
4038 s->cur_prompt->name = dupstr("SSH login name");
4039 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4040 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4043 crWaitUntil(!pktin);
4044 ret = get_userpass_input(s->cur_prompt, in, inlen);
4049 * Failed to get a username. Terminate.
4051 free_prompts(s->cur_prompt);
4052 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4055 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4056 free_prompts(s->cur_prompt);
4059 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4061 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4063 if (flags & FLAG_INTERACTIVE &&
4064 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4065 c_write_str(ssh, userlog);
4066 c_write_str(ssh, "\r\n");
4074 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4075 /* We must not attempt PK auth. Pretend we've already tried it. */
4076 s->tried_publickey = s->tried_agent = 1;
4078 s->tried_publickey = s->tried_agent = 0;
4080 s->tis_auth_refused = s->ccard_auth_refused = 0;
4082 * Load the public half of any configured keyfile for later use.
4084 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4085 if (!filename_is_null(s->keyfile)) {
4087 logeventf(ssh, "Reading private key file \"%.150s\"",
4088 filename_to_str(s->keyfile));
4089 keytype = key_type(s->keyfile);
4090 if (keytype == SSH_KEYTYPE_SSH1) {
4092 if (rsakey_pubblob(s->keyfile,
4093 &s->publickey_blob, &s->publickey_bloblen,
4094 &s->publickey_comment, &error)) {
4095 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
4099 logeventf(ssh, "Unable to load private key (%s)", error);
4100 msgbuf = dupprintf("Unable to load private key file "
4101 "\"%.150s\" (%s)\r\n",
4102 filename_to_str(s->keyfile),
4104 c_write_str(ssh, msgbuf);
4106 s->publickey_blob = NULL;
4110 logeventf(ssh, "Unable to use this key file (%s)",
4111 key_type_to_str(keytype));
4112 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4114 filename_to_str(s->keyfile),
4115 key_type_to_str(keytype));
4116 c_write_str(ssh, msgbuf);
4118 s->publickey_blob = NULL;
4121 s->publickey_blob = NULL;
4123 while (pktin->type == SSH1_SMSG_FAILURE) {
4124 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4126 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4128 * Attempt RSA authentication using Pageant.
4134 logevent("Pageant is running. Requesting keys.");
4136 /* Request the keys held by the agent. */
4137 PUT_32BIT(s->request, 1);
4138 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4139 if (!agent_query(s->request, 5, &r, &s->responselen,
4140 ssh_agent_callback, ssh)) {
4144 bombout(("Unexpected data from server while waiting"
4145 " for agent response"));
4148 } while (pktin || inlen > 0);
4149 r = ssh->agent_response;
4150 s->responselen = ssh->agent_response_len;
4152 s->response = (unsigned char *) r;
4153 if (s->response && s->responselen >= 5 &&
4154 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4155 s->p = s->response + 5;
4156 s->nkeys = toint(GET_32BIT(s->p));
4158 logeventf(ssh, "Pageant reported negative key count %d",
4163 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4164 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4165 unsigned char *pkblob = s->p;
4169 do { /* do while (0) to make breaking easy */
4170 n = ssh1_read_bignum
4171 (s->p, toint(s->responselen-(s->p-s->response)),
4176 n = ssh1_read_bignum
4177 (s->p, toint(s->responselen-(s->p-s->response)),
4182 if (s->responselen - (s->p-s->response) < 4)
4184 s->commentlen = toint(GET_32BIT(s->p));
4186 if (s->commentlen < 0 ||
4187 toint(s->responselen - (s->p-s->response)) <
4190 s->commentp = (char *)s->p;
4191 s->p += s->commentlen;
4195 logevent("Pageant key list packet was truncated");
4199 if (s->publickey_blob) {
4200 if (!memcmp(pkblob, s->publickey_blob,
4201 s->publickey_bloblen)) {
4202 logeventf(ssh, "Pageant key #%d matches "
4203 "configured key file", s->keyi);
4204 s->tried_publickey = 1;
4206 /* Skip non-configured key */
4209 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4210 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4211 PKT_BIGNUM, s->key.modulus, PKT_END);
4213 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4214 logevent("Key refused");
4217 logevent("Received RSA challenge");
4218 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4219 bombout(("Server's RSA challenge was badly formatted"));
4224 char *agentreq, *q, *ret;
4227 len = 1 + 4; /* message type, bit count */
4228 len += ssh1_bignum_length(s->key.exponent);
4229 len += ssh1_bignum_length(s->key.modulus);
4230 len += ssh1_bignum_length(s->challenge);
4231 len += 16; /* session id */
4232 len += 4; /* response format */
4233 agentreq = snewn(4 + len, char);
4234 PUT_32BIT(agentreq, len);
4236 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4237 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4239 q += ssh1_write_bignum(q, s->key.exponent);
4240 q += ssh1_write_bignum(q, s->key.modulus);
4241 q += ssh1_write_bignum(q, s->challenge);
4242 memcpy(q, s->session_id, 16);
4244 PUT_32BIT(q, 1); /* response format */
4245 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4246 ssh_agent_callback, ssh)) {
4251 bombout(("Unexpected data from server"
4252 " while waiting for agent"
4256 } while (pktin || inlen > 0);
4257 vret = ssh->agent_response;
4258 retlen = ssh->agent_response_len;
4263 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4264 logevent("Sending Pageant's response");
4265 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4266 PKT_DATA, ret + 5, 16,
4270 if (pktin->type == SSH1_SMSG_SUCCESS) {
4272 ("Pageant's response accepted");
4273 if (flags & FLAG_VERBOSE) {
4274 c_write_str(ssh, "Authenticated using"
4276 c_write(ssh, s->commentp,
4278 c_write_str(ssh, "\" from agent\r\n");
4283 ("Pageant's response not accepted");
4286 ("Pageant failed to answer challenge");
4290 logevent("No reply received from Pageant");
4293 freebn(s->key.exponent);
4294 freebn(s->key.modulus);
4295 freebn(s->challenge);
4300 if (s->publickey_blob && !s->tried_publickey)
4301 logevent("Configured key file not in Pageant");
4303 logevent("Failed to get reply from Pageant");
4308 if (s->publickey_blob && !s->tried_publickey) {
4310 * Try public key authentication with the specified
4313 int got_passphrase; /* need not be kept over crReturn */
4314 if (flags & FLAG_VERBOSE)
4315 c_write_str(ssh, "Trying public key authentication.\r\n");
4316 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4317 logeventf(ssh, "Trying public key \"%s\"",
4318 filename_to_str(s->keyfile));
4319 s->tried_publickey = 1;
4320 got_passphrase = FALSE;
4321 while (!got_passphrase) {
4323 * Get a passphrase, if necessary.
4325 char *passphrase = NULL; /* only written after crReturn */
4327 if (!s->publickey_encrypted) {
4328 if (flags & FLAG_VERBOSE)
4329 c_write_str(ssh, "No passphrase required.\r\n");
4332 int ret; /* need not be kept over crReturn */
4333 s->cur_prompt = new_prompts(ssh->frontend);
4334 s->cur_prompt->to_server = FALSE;
4335 s->cur_prompt->name = dupstr("SSH key passphrase");
4336 add_prompt(s->cur_prompt,
4337 dupprintf("Passphrase for key \"%.100s\": ",
4338 s->publickey_comment), FALSE);
4339 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4342 crWaitUntil(!pktin);
4343 ret = get_userpass_input(s->cur_prompt, in, inlen);
4347 /* Failed to get a passphrase. Terminate. */
4348 free_prompts(s->cur_prompt);
4349 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4353 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4354 free_prompts(s->cur_prompt);
4357 * Try decrypting key with passphrase.
4359 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4360 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4363 smemclr(passphrase, strlen(passphrase));
4367 /* Correct passphrase. */
4368 got_passphrase = TRUE;
4369 } else if (ret == 0) {
4370 c_write_str(ssh, "Couldn't load private key from ");
4371 c_write_str(ssh, filename_to_str(s->keyfile));
4372 c_write_str(ssh, " (");
4373 c_write_str(ssh, error);
4374 c_write_str(ssh, ").\r\n");
4375 got_passphrase = FALSE;
4376 break; /* go and try something else */
4377 } else if (ret == -1) {
4378 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4379 got_passphrase = FALSE;
4382 assert(0 && "unexpected return from loadrsakey()");
4383 got_passphrase = FALSE; /* placate optimisers */
4387 if (got_passphrase) {
4390 * Send a public key attempt.
4392 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4393 PKT_BIGNUM, s->key.modulus, PKT_END);
4396 if (pktin->type == SSH1_SMSG_FAILURE) {
4397 c_write_str(ssh, "Server refused our public key.\r\n");
4398 continue; /* go and try something else */
4400 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4401 bombout(("Bizarre response to offer of public key"));
4407 unsigned char buffer[32];
4408 Bignum challenge, response;
4410 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4411 bombout(("Server's RSA challenge was badly formatted"));
4414 response = rsadecrypt(challenge, &s->key);
4415 freebn(s->key.private_exponent);/* burn the evidence */
4417 for (i = 0; i < 32; i++) {
4418 buffer[i] = bignum_byte(response, 31 - i);
4422 MD5Update(&md5c, buffer, 32);
4423 MD5Update(&md5c, s->session_id, 16);
4424 MD5Final(buffer, &md5c);
4426 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4427 PKT_DATA, buffer, 16, PKT_END);
4434 if (pktin->type == SSH1_SMSG_FAILURE) {
4435 if (flags & FLAG_VERBOSE)
4436 c_write_str(ssh, "Failed to authenticate with"
4437 " our public key.\r\n");
4438 continue; /* go and try something else */
4439 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4440 bombout(("Bizarre response to RSA authentication response"));
4444 break; /* we're through! */
4450 * Otherwise, try various forms of password-like authentication.
4452 s->cur_prompt = new_prompts(ssh->frontend);
4454 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4455 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4456 !s->tis_auth_refused) {
4457 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4458 logevent("Requested TIS authentication");
4459 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4461 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4462 logevent("TIS authentication declined");
4463 if (flags & FLAG_INTERACTIVE)
4464 c_write_str(ssh, "TIS authentication refused.\r\n");
4465 s->tis_auth_refused = 1;
4470 char *instr_suf, *prompt;
4472 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4474 bombout(("TIS challenge packet was badly formed"));
4477 logevent("Received TIS challenge");
4478 s->cur_prompt->to_server = TRUE;
4479 s->cur_prompt->name = dupstr("SSH TIS authentication");
4480 /* Prompt heuristic comes from OpenSSH */
4481 if (memchr(challenge, '\n', challengelen)) {
4482 instr_suf = dupstr("");
4483 prompt = dupprintf("%.*s", challengelen, challenge);
4485 instr_suf = dupprintf("%.*s", challengelen, challenge);
4486 prompt = dupstr("Response: ");
4488 s->cur_prompt->instruction =
4489 dupprintf("Using TIS authentication.%s%s",
4490 (*instr_suf) ? "\n" : "",
4492 s->cur_prompt->instr_reqd = TRUE;
4493 add_prompt(s->cur_prompt, prompt, FALSE);
4497 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4498 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4499 !s->ccard_auth_refused) {
4500 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4501 logevent("Requested CryptoCard authentication");
4502 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4504 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4505 logevent("CryptoCard authentication declined");
4506 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4507 s->ccard_auth_refused = 1;
4512 char *instr_suf, *prompt;
4514 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4516 bombout(("CryptoCard challenge packet was badly formed"));
4519 logevent("Received CryptoCard challenge");
4520 s->cur_prompt->to_server = TRUE;
4521 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4522 s->cur_prompt->name_reqd = FALSE;
4523 /* Prompt heuristic comes from OpenSSH */
4524 if (memchr(challenge, '\n', challengelen)) {
4525 instr_suf = dupstr("");
4526 prompt = dupprintf("%.*s", challengelen, challenge);
4528 instr_suf = dupprintf("%.*s", challengelen, challenge);
4529 prompt = dupstr("Response: ");
4531 s->cur_prompt->instruction =
4532 dupprintf("Using CryptoCard authentication.%s%s",
4533 (*instr_suf) ? "\n" : "",
4535 s->cur_prompt->instr_reqd = TRUE;
4536 add_prompt(s->cur_prompt, prompt, FALSE);
4540 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4541 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4542 bombout(("No supported authentication methods available"));
4545 s->cur_prompt->to_server = TRUE;
4546 s->cur_prompt->name = dupstr("SSH password");
4547 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4548 ssh->username, ssh->savedhost),
4553 * Show password prompt, having first obtained it via a TIS
4554 * or CryptoCard exchange if we're doing TIS or CryptoCard
4558 int ret; /* need not be kept over crReturn */
4559 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4562 crWaitUntil(!pktin);
4563 ret = get_userpass_input(s->cur_prompt, in, inlen);
4568 * Failed to get a password (for example
4569 * because one was supplied on the command line
4570 * which has already failed to work). Terminate.
4572 free_prompts(s->cur_prompt);
4573 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4578 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4580 * Defence against traffic analysis: we send a
4581 * whole bunch of packets containing strings of
4582 * different lengths. One of these strings is the
4583 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4584 * The others are all random data in
4585 * SSH1_MSG_IGNORE packets. This way a passive
4586 * listener can't tell which is the password, and
4587 * hence can't deduce the password length.
4589 * Anybody with a password length greater than 16
4590 * bytes is going to have enough entropy in their
4591 * password that a listener won't find it _that_
4592 * much help to know how long it is. So what we'll
4595 * - if password length < 16, we send 15 packets
4596 * containing string lengths 1 through 15
4598 * - otherwise, we let N be the nearest multiple
4599 * of 8 below the password length, and send 8
4600 * packets containing string lengths N through
4601 * N+7. This won't obscure the order of
4602 * magnitude of the password length, but it will
4603 * introduce a bit of extra uncertainty.
4605 * A few servers can't deal with SSH1_MSG_IGNORE, at
4606 * least in this context. For these servers, we need
4607 * an alternative defence. We make use of the fact
4608 * that the password is interpreted as a C string:
4609 * so we can append a NUL, then some random data.
4611 * A few servers can deal with neither SSH1_MSG_IGNORE
4612 * here _nor_ a padded password string.
4613 * For these servers we are left with no defences
4614 * against password length sniffing.
4616 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4617 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4619 * The server can deal with SSH1_MSG_IGNORE, so
4620 * we can use the primary defence.
4622 int bottom, top, pwlen, i;
4625 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4627 bottom = 0; /* zero length passwords are OK! :-) */
4630 bottom = pwlen & ~7;
4634 assert(pwlen >= bottom && pwlen <= top);
4636 randomstr = snewn(top + 1, char);
4638 for (i = bottom; i <= top; i++) {
4640 defer_packet(ssh, s->pwpkt_type,
4641 PKT_STR,s->cur_prompt->prompts[0]->result,
4644 for (j = 0; j < i; j++) {
4646 randomstr[j] = random_byte();
4647 } while (randomstr[j] == '\0');
4649 randomstr[i] = '\0';
4650 defer_packet(ssh, SSH1_MSG_IGNORE,
4651 PKT_STR, randomstr, PKT_END);
4654 logevent("Sending password with camouflage packets");
4655 ssh_pkt_defersend(ssh);
4658 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4660 * The server can't deal with SSH1_MSG_IGNORE
4661 * but can deal with padded passwords, so we
4662 * can use the secondary defence.
4668 len = strlen(s->cur_prompt->prompts[0]->result);
4669 if (len < sizeof(string)) {
4671 strcpy(string, s->cur_prompt->prompts[0]->result);
4672 len++; /* cover the zero byte */
4673 while (len < sizeof(string)) {
4674 string[len++] = (char) random_byte();
4677 ss = s->cur_prompt->prompts[0]->result;
4679 logevent("Sending length-padded password");
4680 send_packet(ssh, s->pwpkt_type,
4681 PKT_INT, len, PKT_DATA, ss, len,
4685 * The server is believed unable to cope with
4686 * any of our password camouflage methods.
4689 len = strlen(s->cur_prompt->prompts[0]->result);
4690 logevent("Sending unpadded password");
4691 send_packet(ssh, s->pwpkt_type,
4693 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4697 send_packet(ssh, s->pwpkt_type,
4698 PKT_STR, s->cur_prompt->prompts[0]->result,
4701 logevent("Sent password");
4702 free_prompts(s->cur_prompt);
4704 if (pktin->type == SSH1_SMSG_FAILURE) {
4705 if (flags & FLAG_VERBOSE)
4706 c_write_str(ssh, "Access denied\r\n");
4707 logevent("Authentication refused");
4708 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4709 bombout(("Strange packet received, type %d", pktin->type));
4715 if (s->publickey_blob) {
4716 sfree(s->publickey_blob);
4717 sfree(s->publickey_comment);
4720 logevent("Authentication successful");
4725 static void ssh_channel_try_eof(struct ssh_channel *c)
4728 assert(c->pending_eof); /* precondition for calling us */
4730 return; /* can't close: not even opened yet */
4731 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4732 return; /* can't send EOF: pending outgoing data */
4734 c->pending_eof = FALSE; /* we're about to send it */
4735 if (ssh->version == 1) {
4736 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4738 c->closes |= CLOSES_SENT_EOF;
4740 struct Packet *pktout;
4741 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4742 ssh2_pkt_adduint32(pktout, c->remoteid);
4743 ssh2_pkt_send(ssh, pktout);
4744 c->closes |= CLOSES_SENT_EOF;
4745 ssh2_channel_check_close(c);
4749 Conf *sshfwd_get_conf(struct ssh_channel *c)
4755 void sshfwd_write_eof(struct ssh_channel *c)
4759 if (ssh->state == SSH_STATE_CLOSED)
4762 if (c->closes & CLOSES_SENT_EOF)
4765 c->pending_eof = TRUE;
4766 ssh_channel_try_eof(c);
4769 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4773 if (ssh->state == SSH_STATE_CLOSED)
4778 x11_close(c->u.x11.xconn);
4779 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4783 case CHAN_SOCKDATA_DORMANT:
4784 pfd_close(c->u.pfd.pf);
4785 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4788 c->type = CHAN_ZOMBIE;
4789 c->pending_eof = FALSE; /* this will confuse a zombie channel */
4791 ssh2_channel_check_close(c);
4794 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4798 if (ssh->state == SSH_STATE_CLOSED)
4801 if (ssh->version == 1) {
4802 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4803 PKT_INT, c->remoteid,
4804 PKT_INT, len, PKT_DATA, buf, len,
4807 * In SSH-1 we can return 0 here - implying that forwarded
4808 * connections are never individually throttled - because
4809 * the only circumstance that can cause throttling will be
4810 * the whole SSH connection backing up, in which case
4811 * _everything_ will be throttled as a whole.
4815 ssh2_add_channel_data(c, buf, len);
4816 return ssh2_try_send(c);
4820 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4825 if (ssh->state == SSH_STATE_CLOSED)
4828 if (ssh->version == 1) {
4829 buflimit = SSH1_BUFFER_LIMIT;
4831 buflimit = c->v.v2.locmaxwin;
4832 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4834 if (c->throttling_conn && bufsize <= buflimit) {
4835 c->throttling_conn = 0;
4836 ssh_throttle_conn(ssh, -1);
4840 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4842 struct queued_handler *qh = ssh->qhead;
4846 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4849 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4850 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4853 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4854 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4858 ssh->qhead = qh->next;
4860 if (ssh->qhead->msg1 > 0) {
4861 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4862 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4864 if (ssh->qhead->msg2 > 0) {
4865 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4866 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4869 ssh->qhead = ssh->qtail = NULL;
4872 qh->handler(ssh, pktin, qh->ctx);
4877 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4878 chandler_fn_t handler, void *ctx)
4880 struct queued_handler *qh;
4882 qh = snew(struct queued_handler);
4885 qh->handler = handler;
4889 if (ssh->qtail == NULL) {
4893 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4894 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4897 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4898 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4901 ssh->qtail->next = qh;
4906 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4908 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4910 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4911 SSH2_MSG_REQUEST_SUCCESS)) {
4912 logeventf(ssh, "Remote port forwarding from %s enabled",
4915 logeventf(ssh, "Remote port forwarding from %s refused",
4918 rpf = del234(ssh->rportfwds, pf);
4920 pf->pfrec->remote = NULL;
4925 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
4928 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
4931 pf->share_ctx = share_ctx;
4932 pf->shost = dupstr(shost);
4934 pf->sportdesc = NULL;
4935 if (!ssh->rportfwds) {
4936 assert(ssh->version == 2);
4937 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4939 if (add234(ssh->rportfwds, pf) != pf) {
4947 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
4950 share_got_pkt_from_server(ctx, pktin->type,
4951 pktin->body, pktin->length);
4954 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
4956 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
4957 ssh_sharing_global_request_response, share_ctx);
4960 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4962 struct ssh_portfwd *epf;
4966 if (!ssh->portfwds) {
4967 ssh->portfwds = newtree234(ssh_portcmp);
4970 * Go through the existing port forwardings and tag them
4971 * with status==DESTROY. Any that we want to keep will be
4972 * re-enabled (status==KEEP) as we go through the
4973 * configuration and find out which bits are the same as
4976 struct ssh_portfwd *epf;
4978 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4979 epf->status = DESTROY;
4982 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4984 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4985 char *kp, *kp2, *vp, *vp2;
4986 char address_family, type;
4987 int sport,dport,sserv,dserv;
4988 char *sports, *dports, *saddr, *host;
4992 address_family = 'A';
4994 if (*kp == 'A' || *kp == '4' || *kp == '6')
4995 address_family = *kp++;
4996 if (*kp == 'L' || *kp == 'R')
4999 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5001 * There's a colon in the middle of the source port
5002 * string, which means that the part before it is
5003 * actually a source address.
5005 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5006 saddr = host_strduptrim(saddr_tmp);
5013 sport = atoi(sports);
5017 sport = net_service_lookup(sports);
5019 logeventf(ssh, "Service lookup failed for source"
5020 " port \"%s\"", sports);
5024 if (type == 'L' && !strcmp(val, "D")) {
5025 /* dynamic forwarding */
5032 /* ordinary forwarding */
5034 vp2 = vp + host_strcspn(vp, ":");
5035 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5039 dport = atoi(dports);
5043 dport = net_service_lookup(dports);
5045 logeventf(ssh, "Service lookup failed for destination"
5046 " port \"%s\"", dports);
5051 if (sport && dport) {
5052 /* Set up a description of the source port. */
5053 struct ssh_portfwd *pfrec, *epfrec;
5055 pfrec = snew(struct ssh_portfwd);
5057 pfrec->saddr = saddr;
5058 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5059 pfrec->sport = sport;
5060 pfrec->daddr = host;
5061 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5062 pfrec->dport = dport;
5063 pfrec->local = NULL;
5064 pfrec->remote = NULL;
5065 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5066 address_family == '6' ? ADDRTYPE_IPV6 :
5069 epfrec = add234(ssh->portfwds, pfrec);
5070 if (epfrec != pfrec) {
5071 if (epfrec->status == DESTROY) {
5073 * We already have a port forwarding up and running
5074 * with precisely these parameters. Hence, no need
5075 * to do anything; simply re-tag the existing one
5078 epfrec->status = KEEP;
5081 * Anything else indicates that there was a duplicate
5082 * in our input, which we'll silently ignore.
5084 free_portfwd(pfrec);
5086 pfrec->status = CREATE;
5095 * Now go through and destroy any port forwardings which were
5098 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5099 if (epf->status == DESTROY) {
5102 message = dupprintf("%s port forwarding from %s%s%d",
5103 epf->type == 'L' ? "local" :
5104 epf->type == 'R' ? "remote" : "dynamic",
5105 epf->saddr ? epf->saddr : "",
5106 epf->saddr ? ":" : "",
5109 if (epf->type != 'D') {
5110 char *msg2 = dupprintf("%s to %s:%d", message,
5111 epf->daddr, epf->dport);
5116 logeventf(ssh, "Cancelling %s", message);
5119 /* epf->remote or epf->local may be NULL if setting up a
5120 * forwarding failed. */
5122 struct ssh_rportfwd *rpf = epf->remote;
5123 struct Packet *pktout;
5126 * Cancel the port forwarding at the server
5129 if (ssh->version == 1) {
5131 * We cannot cancel listening ports on the
5132 * server side in SSH-1! There's no message
5133 * to support it. Instead, we simply remove
5134 * the rportfwd record from the local end
5135 * so that any connections the server tries
5136 * to make on it are rejected.
5139 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5140 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5141 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5143 ssh2_pkt_addstring(pktout, epf->saddr);
5144 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5145 /* XXX: rport_acceptall may not represent
5146 * what was used to open the original connection,
5147 * since it's reconfigurable. */
5148 ssh2_pkt_addstring(pktout, "");
5150 ssh2_pkt_addstring(pktout, "localhost");
5152 ssh2_pkt_adduint32(pktout, epf->sport);
5153 ssh2_pkt_send(ssh, pktout);
5156 del234(ssh->rportfwds, rpf);
5158 } else if (epf->local) {
5159 pfl_terminate(epf->local);
5162 delpos234(ssh->portfwds, i);
5164 i--; /* so we don't skip one in the list */
5168 * And finally, set up any new port forwardings (status==CREATE).
5170 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5171 if (epf->status == CREATE) {
5172 char *sportdesc, *dportdesc;
5173 sportdesc = dupprintf("%s%s%s%s%d%s",
5174 epf->saddr ? epf->saddr : "",
5175 epf->saddr ? ":" : "",
5176 epf->sserv ? epf->sserv : "",
5177 epf->sserv ? "(" : "",
5179 epf->sserv ? ")" : "");
5180 if (epf->type == 'D') {
5183 dportdesc = dupprintf("%s:%s%s%d%s",
5185 epf->dserv ? epf->dserv : "",
5186 epf->dserv ? "(" : "",
5188 epf->dserv ? ")" : "");
5191 if (epf->type == 'L') {
5192 char *err = pfl_listen(epf->daddr, epf->dport,
5193 epf->saddr, epf->sport,
5194 ssh, conf, &epf->local,
5195 epf->addressfamily);
5197 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5198 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5199 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5200 sportdesc, dportdesc,
5201 err ? " failed: " : "", err ? err : "");
5204 } else if (epf->type == 'D') {
5205 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5206 ssh, conf, &epf->local,
5207 epf->addressfamily);
5209 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5210 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5211 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5213 err ? " failed: " : "", err ? err : "");
5218 struct ssh_rportfwd *pf;
5221 * Ensure the remote port forwardings tree exists.
5223 if (!ssh->rportfwds) {
5224 if (ssh->version == 1)
5225 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5227 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5230 pf = snew(struct ssh_rportfwd);
5231 pf->share_ctx = NULL;
5232 pf->dhost = dupstr(epf->daddr);
5233 pf->dport = epf->dport;
5235 pf->shost = dupstr(epf->saddr);
5236 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5237 pf->shost = dupstr("");
5239 pf->shost = dupstr("localhost");
5241 pf->sport = epf->sport;
5242 if (add234(ssh->rportfwds, pf) != pf) {
5243 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5244 epf->daddr, epf->dport);
5247 logeventf(ssh, "Requesting remote port %s"
5248 " forward to %s", sportdesc, dportdesc);
5250 pf->sportdesc = sportdesc;
5255 if (ssh->version == 1) {
5256 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5257 PKT_INT, epf->sport,
5258 PKT_STR, epf->daddr,
5259 PKT_INT, epf->dport,
5261 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5263 ssh_rportfwd_succfail, pf);
5265 struct Packet *pktout;
5266 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5267 ssh2_pkt_addstring(pktout, "tcpip-forward");
5268 ssh2_pkt_addbool(pktout, 1);/* want reply */
5269 ssh2_pkt_addstring(pktout, pf->shost);
5270 ssh2_pkt_adduint32(pktout, pf->sport);
5271 ssh2_pkt_send(ssh, pktout);
5273 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5274 SSH2_MSG_REQUEST_FAILURE,
5275 ssh_rportfwd_succfail, pf);
5284 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5287 int stringlen, bufsize;
5289 ssh_pkt_getstring(pktin, &string, &stringlen);
5290 if (string == NULL) {
5291 bombout(("Incoming terminal data packet was badly formed"));
5295 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5297 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5298 ssh->v1_stdout_throttling = 1;
5299 ssh_throttle_conn(ssh, +1);
5303 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5305 /* Remote side is trying to open a channel to talk to our
5306 * X-Server. Give them back a local channel number. */
5307 struct ssh_channel *c;
5308 int remoteid = ssh_pkt_getuint32(pktin);
5310 logevent("Received X11 connect request");
5311 /* Refuse if X11 forwarding is disabled. */
5312 if (!ssh->X11_fwd_enabled) {
5313 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5314 PKT_INT, remoteid, PKT_END);
5315 logevent("Rejected X11 connect request");
5317 c = snew(struct ssh_channel);
5320 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5321 c->remoteid = remoteid;
5322 c->halfopen = FALSE;
5323 c->localid = alloc_channel_id(ssh);
5325 c->pending_eof = FALSE;
5326 c->throttling_conn = 0;
5327 c->type = CHAN_X11; /* identify channel type */
5328 add234(ssh->channels, c);
5329 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5330 PKT_INT, c->remoteid, PKT_INT,
5331 c->localid, PKT_END);
5332 logevent("Opened X11 forward channel");
5336 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5338 /* Remote side is trying to open a channel to talk to our
5339 * agent. Give them back a local channel number. */
5340 struct ssh_channel *c;
5341 int remoteid = ssh_pkt_getuint32(pktin);
5343 /* Refuse if agent forwarding is disabled. */
5344 if (!ssh->agentfwd_enabled) {
5345 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5346 PKT_INT, remoteid, PKT_END);
5348 c = snew(struct ssh_channel);
5350 c->remoteid = remoteid;
5351 c->halfopen = FALSE;
5352 c->localid = alloc_channel_id(ssh);
5354 c->pending_eof = FALSE;
5355 c->throttling_conn = 0;
5356 c->type = CHAN_AGENT; /* identify channel type */
5357 c->u.a.lensofar = 0;
5358 c->u.a.message = NULL;
5359 c->u.a.outstanding_requests = 0;
5360 add234(ssh->channels, c);
5361 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5362 PKT_INT, c->remoteid, PKT_INT, c->localid,
5367 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5369 /* Remote side is trying to open a channel to talk to a
5370 * forwarded port. Give them back a local channel number. */
5371 struct ssh_rportfwd pf, *pfp;
5377 remoteid = ssh_pkt_getuint32(pktin);
5378 ssh_pkt_getstring(pktin, &host, &hostsize);
5379 port = ssh_pkt_getuint32(pktin);
5381 pf.dhost = dupprintf("%.*s", hostsize, host);
5383 pfp = find234(ssh->rportfwds, &pf, NULL);
5386 logeventf(ssh, "Rejected remote port open request for %s:%d",
5388 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5389 PKT_INT, remoteid, PKT_END);
5391 struct ssh_channel *c = snew(struct ssh_channel);
5394 logeventf(ssh, "Received remote port open request for %s:%d",
5396 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5397 c, ssh->conf, pfp->pfrec->addressfamily);
5399 logeventf(ssh, "Port open failed: %s", err);
5402 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5403 PKT_INT, remoteid, PKT_END);
5405 c->remoteid = remoteid;
5406 c->halfopen = FALSE;
5407 c->localid = alloc_channel_id(ssh);
5409 c->pending_eof = FALSE;
5410 c->throttling_conn = 0;
5411 c->type = CHAN_SOCKDATA; /* identify channel type */
5412 add234(ssh->channels, c);
5413 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5414 PKT_INT, c->remoteid, PKT_INT,
5415 c->localid, PKT_END);
5416 logevent("Forwarded port opened successfully");
5423 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5425 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5426 unsigned int localid = ssh_pkt_getuint32(pktin);
5427 struct ssh_channel *c;
5429 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5430 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5431 c->remoteid = localid;
5432 c->halfopen = FALSE;
5433 c->type = CHAN_SOCKDATA;
5434 c->throttling_conn = 0;
5435 pfd_confirm(c->u.pfd.pf);
5438 if (c && c->pending_eof) {
5440 * We have a pending close on this channel,
5441 * which we decided on before the server acked
5442 * the channel open. So now we know the
5443 * remoteid, we can close it again.
5445 ssh_channel_try_eof(c);
5449 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5451 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5452 struct ssh_channel *c;
5454 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5455 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5456 logevent("Forwarded connection refused by server");
5457 pfd_close(c->u.pfd.pf);
5458 del234(ssh->channels, c);
5463 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5465 /* Remote side closes a channel. */
5466 unsigned i = ssh_pkt_getuint32(pktin);
5467 struct ssh_channel *c;
5468 c = find234(ssh->channels, &i, ssh_channelfind);
5469 if (c && !c->halfopen) {
5471 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5472 !(c->closes & CLOSES_RCVD_EOF)) {
5474 * Received CHANNEL_CLOSE, which we translate into
5477 int send_close = FALSE;
5479 c->closes |= CLOSES_RCVD_EOF;
5484 x11_send_eof(c->u.x11.xconn);
5490 pfd_send_eof(c->u.pfd.pf);
5499 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5500 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5502 c->closes |= CLOSES_SENT_EOF;
5506 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5507 !(c->closes & CLOSES_RCVD_CLOSE)) {
5509 if (!(c->closes & CLOSES_SENT_EOF)) {
5510 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5511 " for which we never sent CHANNEL_CLOSE\n", i));
5514 c->closes |= CLOSES_RCVD_CLOSE;
5517 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5518 !(c->closes & CLOSES_SENT_CLOSE)) {
5519 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5520 PKT_INT, c->remoteid, PKT_END);
5521 c->closes |= CLOSES_SENT_CLOSE;
5524 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5525 ssh_channel_destroy(c);
5527 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5528 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5529 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5534 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5536 /* Data sent down one of our channels. */
5537 int i = ssh_pkt_getuint32(pktin);
5540 struct ssh_channel *c;
5542 ssh_pkt_getstring(pktin, &p, &len);
5544 c = find234(ssh->channels, &i, ssh_channelfind);
5549 bufsize = x11_send(c->u.x11.xconn, p, len);
5552 bufsize = pfd_send(c->u.pfd.pf, p, len);
5555 /* Data for an agent message. Buffer it. */
5557 if (c->u.a.lensofar < 4) {
5558 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5559 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5563 c->u.a.lensofar += l;
5565 if (c->u.a.lensofar == 4) {
5567 4 + GET_32BIT(c->u.a.msglen);
5568 c->u.a.message = snewn(c->u.a.totallen,
5570 memcpy(c->u.a.message, c->u.a.msglen, 4);
5572 if (c->u.a.lensofar >= 4 && len > 0) {
5574 min(c->u.a.totallen - c->u.a.lensofar,
5576 memcpy(c->u.a.message + c->u.a.lensofar, p,
5580 c->u.a.lensofar += l;
5582 if (c->u.a.lensofar == c->u.a.totallen) {
5585 c->u.a.outstanding_requests++;
5586 if (agent_query(c->u.a.message,
5589 ssh_agentf_callback, c))
5590 ssh_agentf_callback(c, reply, replylen);
5591 sfree(c->u.a.message);
5592 c->u.a.lensofar = 0;
5595 bufsize = 0; /* agent channels never back up */
5598 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5599 c->throttling_conn = 1;
5600 ssh_throttle_conn(ssh, +1);
5605 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5607 ssh->exitcode = ssh_pkt_getuint32(pktin);
5608 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5609 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5611 * In case `helpful' firewalls or proxies tack
5612 * extra human-readable text on the end of the
5613 * session which we might mistake for another
5614 * encrypted packet, we close the session once
5615 * we've sent EXIT_CONFIRMATION.
5617 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5620 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5621 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5623 struct Packet *pktout = (struct Packet *)data;
5625 unsigned int arg = 0;
5626 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5627 if (i == lenof(ssh_ttymodes)) return;
5628 switch (ssh_ttymodes[i].type) {
5630 arg = ssh_tty_parse_specchar(val);
5633 arg = ssh_tty_parse_boolean(val);
5636 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5637 ssh2_pkt_addbyte(pktout, arg);
5640 int ssh_agent_forwarding_permitted(Ssh ssh)
5642 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5645 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5646 struct Packet *pktin)
5648 crBegin(ssh->do_ssh1_connection_crstate);
5650 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5651 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5652 ssh1_smsg_stdout_stderr_data;
5654 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5655 ssh1_msg_channel_open_confirmation;
5656 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5657 ssh1_msg_channel_open_failure;
5658 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5659 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5660 ssh1_msg_channel_close;
5661 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5662 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5664 if (ssh_agent_forwarding_permitted(ssh)) {
5665 logevent("Requesting agent forwarding");
5666 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5670 if (pktin->type != SSH1_SMSG_SUCCESS
5671 && pktin->type != SSH1_SMSG_FAILURE) {
5672 bombout(("Protocol confusion"));
5674 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5675 logevent("Agent forwarding refused");
5677 logevent("Agent forwarding enabled");
5678 ssh->agentfwd_enabled = TRUE;
5679 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5683 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5685 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5687 if (!ssh->x11disp) {
5688 /* FIXME: return an error message from x11_setup_display */
5689 logevent("X11 forwarding not enabled: unable to"
5690 " initialise X display");
5692 ssh->x11auth = x11_invent_fake_auth
5693 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5694 ssh->x11auth->disp = ssh->x11disp;
5696 logevent("Requesting X11 forwarding");
5697 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5698 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5699 PKT_STR, ssh->x11auth->protoname,
5700 PKT_STR, ssh->x11auth->datastring,
5701 PKT_INT, ssh->x11disp->screennum,
5704 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5705 PKT_STR, ssh->x11auth->protoname,
5706 PKT_STR, ssh->x11auth->datastring,
5712 if (pktin->type != SSH1_SMSG_SUCCESS
5713 && pktin->type != SSH1_SMSG_FAILURE) {
5714 bombout(("Protocol confusion"));
5716 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5717 logevent("X11 forwarding refused");
5719 logevent("X11 forwarding enabled");
5720 ssh->X11_fwd_enabled = TRUE;
5721 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5726 ssh_setup_portfwd(ssh, ssh->conf);
5727 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5729 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5731 /* Unpick the terminal-speed string. */
5732 /* XXX perhaps we should allow no speeds to be sent. */
5733 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5734 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5735 /* Send the pty request. */
5736 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5737 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5738 ssh_pkt_adduint32(pkt, ssh->term_height);
5739 ssh_pkt_adduint32(pkt, ssh->term_width);
5740 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5741 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5742 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5743 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5744 ssh_pkt_adduint32(pkt, ssh->ispeed);
5745 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5746 ssh_pkt_adduint32(pkt, ssh->ospeed);
5747 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5749 ssh->state = SSH_STATE_INTERMED;
5753 if (pktin->type != SSH1_SMSG_SUCCESS
5754 && pktin->type != SSH1_SMSG_FAILURE) {
5755 bombout(("Protocol confusion"));
5757 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5758 c_write_str(ssh, "Server refused to allocate pty\r\n");
5759 ssh->editing = ssh->echoing = 1;
5761 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5762 ssh->ospeed, ssh->ispeed);
5763 ssh->got_pty = TRUE;
5766 ssh->editing = ssh->echoing = 1;
5769 if (conf_get_int(ssh->conf, CONF_compression)) {
5770 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5774 if (pktin->type != SSH1_SMSG_SUCCESS
5775 && pktin->type != SSH1_SMSG_FAILURE) {
5776 bombout(("Protocol confusion"));
5778 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5779 c_write_str(ssh, "Server refused to compress\r\n");
5781 logevent("Started compression");
5782 ssh->v1_compressing = TRUE;
5783 ssh->cs_comp_ctx = zlib_compress_init();
5784 logevent("Initialised zlib (RFC1950) compression");
5785 ssh->sc_comp_ctx = zlib_decompress_init();
5786 logevent("Initialised zlib (RFC1950) decompression");
5790 * Start the shell or command.
5792 * Special case: if the first-choice command is an SSH-2
5793 * subsystem (hence not usable here) and the second choice
5794 * exists, we fall straight back to that.
5797 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5799 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5800 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5801 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5802 ssh->fallback_cmd = TRUE;
5805 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5807 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5808 logevent("Started session");
5811 ssh->state = SSH_STATE_SESSION;
5812 if (ssh->size_needed)
5813 ssh_size(ssh, ssh->term_width, ssh->term_height);
5814 if (ssh->eof_needed)
5815 ssh_special(ssh, TS_EOF);
5818 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
5820 ssh->channels = newtree234(ssh_channelcmp);
5824 * By this point, most incoming packets are already being
5825 * handled by the dispatch table, and we need only pay
5826 * attention to the unusual ones.
5831 if (pktin->type == SSH1_SMSG_SUCCESS) {
5832 /* may be from EXEC_SHELL on some servers */
5833 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5834 /* may be from EXEC_SHELL on some servers
5835 * if no pty is available or in other odd cases. Ignore */
5837 bombout(("Strange packet received: type %d", pktin->type));
5842 int len = min(inlen, 512);
5843 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5844 PKT_INT, len, PKT_DATA, in, len,
5856 * Handle the top-level SSH-2 protocol.
5858 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5863 ssh_pkt_getstring(pktin, &msg, &msglen);
5864 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5867 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5869 /* log reason code in disconnect message */
5873 ssh_pkt_getstring(pktin, &msg, &msglen);
5874 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5877 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5879 /* Do nothing, because we're ignoring it! Duhh. */
5882 static void ssh1_protocol_setup(Ssh ssh)
5887 * Most messages are handled by the coroutines.
5889 for (i = 0; i < 256; i++)
5890 ssh->packet_dispatch[i] = NULL;
5893 * These special message types we install handlers for.
5895 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5896 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5897 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5900 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5901 struct Packet *pktin)
5903 unsigned char *in=(unsigned char*)vin;
5904 if (ssh->state == SSH_STATE_CLOSED)
5907 if (pktin && ssh->packet_dispatch[pktin->type]) {
5908 ssh->packet_dispatch[pktin->type](ssh, pktin);
5912 if (!ssh->protocol_initial_phase_done) {
5913 if (do_ssh1_login(ssh, in, inlen, pktin))
5914 ssh->protocol_initial_phase_done = TRUE;
5919 do_ssh1_connection(ssh, in, inlen, pktin);
5923 * Utility routine for decoding comma-separated strings in KEXINIT.
5925 static int in_commasep_string(char *needle, char *haystack, int haylen)
5928 if (!needle || !haystack) /* protect against null pointers */
5930 needlen = strlen(needle);
5933 * Is it at the start of the string?
5935 if (haylen >= needlen && /* haystack is long enough */
5936 !memcmp(needle, haystack, needlen) && /* initial match */
5937 (haylen == needlen || haystack[needlen] == ',')
5938 /* either , or EOS follows */
5942 * If not, search for the next comma and resume after that.
5943 * If no comma found, terminate.
5945 while (haylen > 0 && *haystack != ',')
5946 haylen--, haystack++;
5949 haylen--, haystack++; /* skip over comma itself */
5954 * Similar routine for checking whether we have the first string in a list.
5956 static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5959 if (!needle || !haystack) /* protect against null pointers */
5961 needlen = strlen(needle);
5963 * Is it at the start of the string?
5965 if (haylen >= needlen && /* haystack is long enough */
5966 !memcmp(needle, haystack, needlen) && /* initial match */
5967 (haylen == needlen || haystack[needlen] == ',')
5968 /* either , or EOS follows */
5976 * SSH-2 key creation method.
5977 * (Currently assumes 2 lots of any hash are sufficient to generate
5978 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
5980 #define SSH2_MKKEY_ITERS (2)
5981 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
5982 unsigned char *keyspace)
5984 const struct ssh_hash *h = ssh->kex->hash;
5986 /* First hlen bytes. */
5988 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5989 hash_mpint(h, s, K);
5990 h->bytes(s, H, h->hlen);
5991 h->bytes(s, &chr, 1);
5992 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5993 h->final(s, keyspace);
5994 /* Next hlen bytes. */
5996 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
5997 hash_mpint(h, s, K);
5998 h->bytes(s, H, h->hlen);
5999 h->bytes(s, keyspace, h->hlen);
6000 h->final(s, keyspace + h->hlen);
6004 * Handle the SSH-2 transport layer.
6006 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
6007 struct Packet *pktin)
6009 unsigned char *in = (unsigned char *)vin;
6010 struct do_ssh2_transport_state {
6012 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
6013 Bignum p, g, e, f, K;
6016 int kex_init_value, kex_reply_value;
6017 const struct ssh_mac **maclist;
6019 const struct ssh2_cipher *cscipher_tobe;
6020 const struct ssh2_cipher *sccipher_tobe;
6021 const struct ssh_mac *csmac_tobe;
6022 const struct ssh_mac *scmac_tobe;
6023 const struct ssh_compress *cscomp_tobe;
6024 const struct ssh_compress *sccomp_tobe;
6025 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6026 int hostkeylen, siglen, rsakeylen;
6027 void *hkey; /* actual host key */
6028 void *rsakey; /* for RSA kex */
6029 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6030 int n_preferred_kex;
6031 const struct ssh_kexes *preferred_kex[KEX_MAX];
6032 int n_preferred_ciphers;
6033 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6034 const struct ssh_compress *preferred_comp;
6035 int userauth_succeeded; /* for delayed compression */
6036 int pending_compression;
6037 int got_session_id, activated_authconn;
6038 struct Packet *pktout;
6043 crState(do_ssh2_transport_state);
6045 assert(!ssh->bare_connection);
6049 s->cscipher_tobe = s->sccipher_tobe = NULL;
6050 s->csmac_tobe = s->scmac_tobe = NULL;
6051 s->cscomp_tobe = s->sccomp_tobe = NULL;
6053 s->got_session_id = s->activated_authconn = FALSE;
6054 s->userauth_succeeded = FALSE;
6055 s->pending_compression = FALSE;
6058 * Be prepared to work around the buggy MAC problem.
6060 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6061 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6063 s->maclist = macs, s->nmacs = lenof(macs);
6066 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6068 int i, j, k, commalist_started;
6071 * Set up the preferred key exchange. (NULL => warn below here)
6073 s->n_preferred_kex = 0;
6074 for (i = 0; i < KEX_MAX; i++) {
6075 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6077 s->preferred_kex[s->n_preferred_kex++] =
6078 &ssh_diffiehellman_gex;
6081 s->preferred_kex[s->n_preferred_kex++] =
6082 &ssh_diffiehellman_group14;
6085 s->preferred_kex[s->n_preferred_kex++] =
6086 &ssh_diffiehellman_group1;
6089 s->preferred_kex[s->n_preferred_kex++] =
6093 /* Flag for later. Don't bother if it's the last in
6095 if (i < KEX_MAX - 1) {
6096 s->preferred_kex[s->n_preferred_kex++] = NULL;
6103 * Set up the preferred ciphers. (NULL => warn below here)
6105 s->n_preferred_ciphers = 0;
6106 for (i = 0; i < CIPHER_MAX; i++) {
6107 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6108 case CIPHER_BLOWFISH:
6109 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6112 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6113 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6117 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6120 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6122 case CIPHER_ARCFOUR:
6123 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6126 /* Flag for later. Don't bother if it's the last in
6128 if (i < CIPHER_MAX - 1) {
6129 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6136 * Set up preferred compression.
6138 if (conf_get_int(ssh->conf, CONF_compression))
6139 s->preferred_comp = &ssh_zlib;
6141 s->preferred_comp = &ssh_comp_none;
6144 * Enable queueing of outgoing auth- or connection-layer
6145 * packets while we are in the middle of a key exchange.
6147 ssh->queueing = TRUE;
6150 * Flag that KEX is in progress.
6152 ssh->kex_in_progress = TRUE;
6155 * Construct and send our key exchange packet.
6157 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6158 for (i = 0; i < 16; i++)
6159 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6160 /* List key exchange algorithms. */
6161 ssh2_pkt_addstring_start(s->pktout);
6162 commalist_started = 0;
6163 for (i = 0; i < s->n_preferred_kex; i++) {
6164 const struct ssh_kexes *k = s->preferred_kex[i];
6165 if (!k) continue; /* warning flag */
6166 for (j = 0; j < k->nkexes; j++) {
6167 if (commalist_started)
6168 ssh2_pkt_addstring_str(s->pktout, ",");
6169 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
6170 commalist_started = 1;
6173 /* List server host key algorithms. */
6174 if (!s->got_session_id) {
6176 * In the first key exchange, we list all the algorithms
6177 * we're prepared to cope with.
6179 ssh2_pkt_addstring_start(s->pktout);
6180 for (i = 0; i < lenof(hostkey_algs); i++) {
6181 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
6182 if (i < lenof(hostkey_algs) - 1)
6183 ssh2_pkt_addstring_str(s->pktout, ",");
6187 * In subsequent key exchanges, we list only the kex
6188 * algorithm that was selected in the first key exchange,
6189 * so that we keep getting the same host key and hence
6190 * don't have to interrupt the user's session to ask for
6194 ssh2_pkt_addstring(s->pktout, ssh->hostkey->name);
6196 /* List encryption algorithms (client->server then server->client). */
6197 for (k = 0; k < 2; k++) {
6198 ssh2_pkt_addstring_start(s->pktout);
6199 commalist_started = 0;
6200 for (i = 0; i < s->n_preferred_ciphers; i++) {
6201 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6202 if (!c) continue; /* warning flag */
6203 for (j = 0; j < c->nciphers; j++) {
6204 if (commalist_started)
6205 ssh2_pkt_addstring_str(s->pktout, ",");
6206 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
6207 commalist_started = 1;
6211 /* List MAC algorithms (client->server then server->client). */
6212 for (j = 0; j < 2; j++) {
6213 ssh2_pkt_addstring_start(s->pktout);
6214 for (i = 0; i < s->nmacs; i++) {
6215 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
6216 if (i < s->nmacs - 1)
6217 ssh2_pkt_addstring_str(s->pktout, ",");
6220 /* List client->server compression algorithms,
6221 * then server->client compression algorithms. (We use the
6222 * same set twice.) */
6223 for (j = 0; j < 2; j++) {
6224 ssh2_pkt_addstring_start(s->pktout);
6225 assert(lenof(compressions) > 1);
6226 /* Prefer non-delayed versions */
6227 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
6228 /* We don't even list delayed versions of algorithms until
6229 * they're allowed to be used, to avoid a race. See the end of
6231 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6232 ssh2_pkt_addstring_str(s->pktout, ",");
6233 ssh2_pkt_addstring_str(s->pktout,
6234 s->preferred_comp->delayed_name);
6236 for (i = 0; i < lenof(compressions); i++) {
6237 const struct ssh_compress *c = compressions[i];
6238 if (c != s->preferred_comp) {
6239 ssh2_pkt_addstring_str(s->pktout, ",");
6240 ssh2_pkt_addstring_str(s->pktout, c->name);
6241 if (s->userauth_succeeded && c->delayed_name) {
6242 ssh2_pkt_addstring_str(s->pktout, ",");
6243 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
6248 /* List client->server languages. Empty list. */
6249 ssh2_pkt_addstring_start(s->pktout);
6250 /* List server->client languages. Empty list. */
6251 ssh2_pkt_addstring_start(s->pktout);
6252 /* First KEX packet does _not_ follow, because we're not that brave. */
6253 ssh2_pkt_addbool(s->pktout, FALSE);
6255 ssh2_pkt_adduint32(s->pktout, 0);
6258 s->our_kexinitlen = s->pktout->length - 5;
6259 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6260 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6262 ssh2_pkt_send_noqueue(ssh, s->pktout);
6265 crWaitUntilV(pktin);
6268 * Now examine the other side's KEXINIT to see what we're up
6272 char *str, *preferred;
6275 if (pktin->type != SSH2_MSG_KEXINIT) {
6276 bombout(("expected key exchange packet from server"));
6280 ssh->hostkey = NULL;
6281 s->cscipher_tobe = NULL;
6282 s->sccipher_tobe = NULL;
6283 s->csmac_tobe = NULL;
6284 s->scmac_tobe = NULL;
6285 s->cscomp_tobe = NULL;
6286 s->sccomp_tobe = NULL;
6287 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
6289 pktin->savedpos += 16; /* skip garbage cookie */
6290 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
6292 bombout(("KEXINIT packet was incomplete"));
6297 for (i = 0; i < s->n_preferred_kex; i++) {
6298 const struct ssh_kexes *k = s->preferred_kex[i];
6302 for (j = 0; j < k->nkexes; j++) {
6303 if (!preferred) preferred = k->list[j]->name;
6304 if (in_commasep_string(k->list[j]->name, str, len)) {
6305 ssh->kex = k->list[j];
6314 bombout(("Couldn't agree a key exchange algorithm"
6315 " (available: %.*s)", len, str));
6319 * Note that the server's guess is considered wrong if it doesn't match
6320 * the first algorithm in our list, even if it's still the algorithm
6323 s->guessok = first_in_commasep_string(preferred, str, len);
6324 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
6326 bombout(("KEXINIT packet was incomplete"));
6329 for (i = 0; i < lenof(hostkey_algs); i++) {
6330 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
6331 ssh->hostkey = hostkey_algs[i];
6335 if (!ssh->hostkey) {
6336 bombout(("Couldn't agree a host key algorithm"
6337 " (available: %.*s)", len, str));
6341 s->guessok = s->guessok &&
6342 first_in_commasep_string(hostkey_algs[0]->name, str, len);
6343 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
6345 bombout(("KEXINIT packet was incomplete"));
6348 for (i = 0; i < s->n_preferred_ciphers; i++) {
6349 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6351 s->warn_cscipher = TRUE;
6353 for (j = 0; j < c->nciphers; j++) {
6354 if (in_commasep_string(c->list[j]->name, str, len)) {
6355 s->cscipher_tobe = c->list[j];
6360 if (s->cscipher_tobe)
6363 if (!s->cscipher_tobe) {
6364 bombout(("Couldn't agree a client-to-server cipher"
6365 " (available: %.*s)", len, str));
6369 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
6371 bombout(("KEXINIT packet was incomplete"));
6374 for (i = 0; i < s->n_preferred_ciphers; i++) {
6375 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6377 s->warn_sccipher = TRUE;
6379 for (j = 0; j < c->nciphers; j++) {
6380 if (in_commasep_string(c->list[j]->name, str, len)) {
6381 s->sccipher_tobe = c->list[j];
6386 if (s->sccipher_tobe)
6389 if (!s->sccipher_tobe) {
6390 bombout(("Couldn't agree a server-to-client cipher"
6391 " (available: %.*s)", len, str));
6395 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
6397 bombout(("KEXINIT packet was incomplete"));
6400 for (i = 0; i < s->nmacs; i++) {
6401 if (in_commasep_string(s->maclist[i]->name, str, len)) {
6402 s->csmac_tobe = s->maclist[i];
6406 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
6408 bombout(("KEXINIT packet was incomplete"));
6411 for (i = 0; i < s->nmacs; i++) {
6412 if (in_commasep_string(s->maclist[i]->name, str, len)) {
6413 s->scmac_tobe = s->maclist[i];
6417 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
6419 bombout(("KEXINIT packet was incomplete"));
6422 for (i = 0; i < lenof(compressions) + 1; i++) {
6423 const struct ssh_compress *c =
6424 i == 0 ? s->preferred_comp : compressions[i - 1];
6425 if (in_commasep_string(c->name, str, len)) {
6428 } else if (in_commasep_string(c->delayed_name, str, len)) {
6429 if (s->userauth_succeeded) {
6433 s->pending_compression = TRUE; /* try this later */
6437 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
6439 bombout(("KEXINIT packet was incomplete"));
6442 for (i = 0; i < lenof(compressions) + 1; i++) {
6443 const struct ssh_compress *c =
6444 i == 0 ? s->preferred_comp : compressions[i - 1];
6445 if (in_commasep_string(c->name, str, len)) {
6448 } else if (in_commasep_string(c->delayed_name, str, len)) {
6449 if (s->userauth_succeeded) {
6453 s->pending_compression = TRUE; /* try this later */
6457 if (s->pending_compression) {
6458 logevent("Server supports delayed compression; "
6459 "will try this later");
6461 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6462 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6463 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6465 ssh->exhash = ssh->kex->hash->init();
6466 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6467 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6468 hash_string(ssh->kex->hash, ssh->exhash,
6469 s->our_kexinit, s->our_kexinitlen);
6470 sfree(s->our_kexinit);
6471 /* Include the type byte in the hash of server's KEXINIT */
6472 hash_string(ssh->kex->hash, ssh->exhash,
6473 pktin->body - 1, pktin->length + 1);
6476 ssh_set_frozen(ssh, 1);
6477 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6479 ssh_dialog_callback, ssh);
6480 if (s->dlgret < 0) {
6484 bombout(("Unexpected data from server while"
6485 " waiting for user response"));
6488 } while (pktin || inlen > 0);
6489 s->dlgret = ssh->user_response;
6491 ssh_set_frozen(ssh, 0);
6492 if (s->dlgret == 0) {
6493 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6499 if (s->warn_cscipher) {
6500 ssh_set_frozen(ssh, 1);
6501 s->dlgret = askalg(ssh->frontend,
6502 "client-to-server cipher",
6503 s->cscipher_tobe->name,
6504 ssh_dialog_callback, ssh);
6505 if (s->dlgret < 0) {
6509 bombout(("Unexpected data from server while"
6510 " waiting for user response"));
6513 } while (pktin || inlen > 0);
6514 s->dlgret = ssh->user_response;
6516 ssh_set_frozen(ssh, 0);
6517 if (s->dlgret == 0) {
6518 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6524 if (s->warn_sccipher) {
6525 ssh_set_frozen(ssh, 1);
6526 s->dlgret = askalg(ssh->frontend,
6527 "server-to-client cipher",
6528 s->sccipher_tobe->name,
6529 ssh_dialog_callback, ssh);
6530 if (s->dlgret < 0) {
6534 bombout(("Unexpected data from server while"
6535 " waiting for user response"));
6538 } while (pktin || inlen > 0);
6539 s->dlgret = ssh->user_response;
6541 ssh_set_frozen(ssh, 0);
6542 if (s->dlgret == 0) {
6543 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6549 if (s->ignorepkt) /* first_kex_packet_follows */
6550 crWaitUntilV(pktin); /* Ignore packet */
6553 if (ssh->kex->main_type == KEXTYPE_DH) {
6555 * Work out the number of bits of key we will need from the
6556 * key exchange. We start with the maximum key length of
6562 csbits = s->cscipher_tobe->keylen;
6563 scbits = s->sccipher_tobe->keylen;
6564 s->nbits = (csbits > scbits ? csbits : scbits);
6566 /* The keys only have hlen-bit entropy, since they're based on
6567 * a hash. So cap the key size at hlen bits. */
6568 if (s->nbits > ssh->kex->hash->hlen * 8)
6569 s->nbits = ssh->kex->hash->hlen * 8;
6572 * If we're doing Diffie-Hellman group exchange, start by
6573 * requesting a group.
6575 if (!ssh->kex->pdata) {
6576 logevent("Doing Diffie-Hellman group exchange");
6577 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6579 * Work out how big a DH group we will need to allow that
6582 s->pbits = 512 << ((s->nbits - 1) / 64);
6583 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6584 ssh2_pkt_adduint32(s->pktout, s->pbits);
6585 ssh2_pkt_send_noqueue(ssh, s->pktout);
6587 crWaitUntilV(pktin);
6588 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6589 bombout(("expected key exchange group packet from server"));
6592 s->p = ssh2_pkt_getmp(pktin);
6593 s->g = ssh2_pkt_getmp(pktin);
6594 if (!s->p || !s->g) {
6595 bombout(("unable to read mp-ints from incoming group packet"));
6598 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6599 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6600 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6602 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6603 ssh->kex_ctx = dh_setup_group(ssh->kex);
6604 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6605 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6606 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6607 ssh->kex->groupname);
6610 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6611 ssh->kex->hash->text_name);
6613 * Now generate and send e for Diffie-Hellman.
6615 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6616 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6617 s->pktout = ssh2_pkt_init(s->kex_init_value);
6618 ssh2_pkt_addmp(s->pktout, s->e);
6619 ssh2_pkt_send_noqueue(ssh, s->pktout);
6621 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6622 crWaitUntilV(pktin);
6623 if (pktin->type != s->kex_reply_value) {
6624 bombout(("expected key exchange reply packet from server"));
6627 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6628 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6629 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6630 s->f = ssh2_pkt_getmp(pktin);
6632 bombout(("unable to parse key exchange reply packet"));
6635 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6637 s->K = dh_find_K(ssh->kex_ctx, s->f);
6639 /* We assume everything from now on will be quick, and it might
6640 * involve user interaction. */
6641 set_busy_status(ssh->frontend, BUSY_NOT);
6643 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6644 if (!ssh->kex->pdata) {
6645 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6646 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6647 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6649 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6650 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6652 dh_cleanup(ssh->kex_ctx);
6654 if (!ssh->kex->pdata) {
6659 logeventf(ssh, "Doing RSA key exchange with hash %s",
6660 ssh->kex->hash->text_name);
6661 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6663 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6666 crWaitUntilV(pktin);
6667 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6668 bombout(("expected RSA public key packet from server"));
6672 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6673 hash_string(ssh->kex->hash, ssh->exhash,
6674 s->hostkeydata, s->hostkeylen);
6675 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6679 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6680 s->rsakeydata = snewn(s->rsakeylen, char);
6681 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6684 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6686 sfree(s->rsakeydata);
6687 bombout(("unable to parse RSA public key from server"));
6691 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6694 * Next, set up a shared secret K, of precisely KLEN -
6695 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6696 * RSA key modulus and HLEN is the bit length of the hash
6700 int klen = ssh_rsakex_klen(s->rsakey);
6701 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6703 unsigned char *kstr1, *kstr2, *outstr;
6704 int kstr1len, kstr2len, outstrlen;
6706 s->K = bn_power_2(nbits - 1);
6708 for (i = 0; i < nbits; i++) {
6710 byte = random_byte();
6712 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6716 * Encode this as an mpint.
6718 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6719 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6720 PUT_32BIT(kstr2, kstr1len);
6721 memcpy(kstr2 + 4, kstr1, kstr1len);
6724 * Encrypt it with the given RSA key.
6726 outstrlen = (klen + 7) / 8;
6727 outstr = snewn(outstrlen, unsigned char);
6728 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6729 outstr, outstrlen, s->rsakey);
6732 * And send it off in a return packet.
6734 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6735 ssh2_pkt_addstring_start(s->pktout);
6736 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6737 ssh2_pkt_send_noqueue(ssh, s->pktout);
6739 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6746 ssh_rsakex_freekey(s->rsakey);
6748 crWaitUntilV(pktin);
6749 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6750 sfree(s->rsakeydata);
6751 bombout(("expected signature packet from server"));
6755 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6757 sfree(s->rsakeydata);
6760 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6761 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6762 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6764 ssh->kex_ctx = NULL;
6767 debug(("Exchange hash is:\n"));
6768 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6772 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6773 (char *)s->exchange_hash,
6774 ssh->kex->hash->hlen)) {
6775 bombout(("Server's host key did not match the signature supplied"));
6779 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6780 if (!s->got_session_id) {
6782 * Authenticate remote host: verify host key. (We've already
6783 * checked the signature of the exchange hash.)
6785 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6786 logevent("Host key fingerprint is:");
6787 logevent(s->fingerprint);
6788 /* First check against manually configured host keys. */
6789 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
6790 ssh->hostkey, s->hkey);
6791 if (s->dlgret == 0) { /* did not match */
6792 bombout(("Host key did not appear in manually configured list"));
6794 } else if (s->dlgret < 0) { /* none configured; use standard handling */
6795 ssh_set_frozen(ssh, 1);
6796 s->dlgret = verify_ssh_host_key(ssh->frontend,
6797 ssh->savedhost, ssh->savedport,
6798 ssh->hostkey->keytype, s->keystr,
6800 ssh_dialog_callback, ssh);
6801 if (s->dlgret < 0) {
6805 bombout(("Unexpected data from server while waiting"
6806 " for user host key response"));
6809 } while (pktin || inlen > 0);
6810 s->dlgret = ssh->user_response;
6812 ssh_set_frozen(ssh, 0);
6813 if (s->dlgret == 0) {
6814 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
6819 sfree(s->fingerprint);
6821 * Save this host key, to check against the one presented in
6822 * subsequent rekeys.
6824 ssh->hostkey_str = s->keystr;
6827 * In a rekey, we never present an interactive host key
6828 * verification request to the user. Instead, we simply
6829 * enforce that the key we're seeing this time is identical to
6830 * the one we saw before.
6832 if (strcmp(ssh->hostkey_str, s->keystr)) {
6833 bombout(("Host key was different in repeat key exchange"));
6838 ssh->hostkey->freekey(s->hkey);
6841 * The exchange hash from the very first key exchange is also
6842 * the session id, used in session key construction and
6845 if (!s->got_session_id) {
6846 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6847 memcpy(ssh->v2_session_id, s->exchange_hash,
6848 sizeof(s->exchange_hash));
6849 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6850 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6851 s->got_session_id = TRUE;
6855 * Send SSH2_MSG_NEWKEYS.
6857 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6858 ssh2_pkt_send_noqueue(ssh, s->pktout);
6859 ssh->outgoing_data_size = 0; /* start counting from here */
6862 * We've sent client NEWKEYS, so create and initialise
6863 * client-to-server session keys.
6865 if (ssh->cs_cipher_ctx)
6866 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6867 ssh->cscipher = s->cscipher_tobe;
6868 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6870 if (ssh->cs_mac_ctx)
6871 ssh->csmac->free_context(ssh->cs_mac_ctx);
6872 ssh->csmac = s->csmac_tobe;
6873 ssh->cs_mac_ctx = ssh->csmac->make_context();
6875 if (ssh->cs_comp_ctx)
6876 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6877 ssh->cscomp = s->cscomp_tobe;
6878 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6881 * Set IVs on client-to-server keys. Here we use the exchange
6882 * hash from the _first_ key exchange.
6885 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6886 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6887 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6888 assert((ssh->cscipher->keylen+7) / 8 <=
6889 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6890 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6891 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6892 assert(ssh->cscipher->blksize <=
6893 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6894 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6895 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6896 assert(ssh->csmac->len <=
6897 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6898 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6899 smemclr(keyspace, sizeof(keyspace));
6902 logeventf(ssh, "Initialised %.200s client->server encryption",
6903 ssh->cscipher->text_name);
6904 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6905 ssh->csmac->text_name);
6906 if (ssh->cscomp->text_name)
6907 logeventf(ssh, "Initialised %s compression",
6908 ssh->cscomp->text_name);
6911 * Now our end of the key exchange is complete, we can send all
6912 * our queued higher-layer packets.
6914 ssh->queueing = FALSE;
6915 ssh2_pkt_queuesend(ssh);
6918 * Expect SSH2_MSG_NEWKEYS from server.
6920 crWaitUntilV(pktin);
6921 if (pktin->type != SSH2_MSG_NEWKEYS) {
6922 bombout(("expected new-keys packet from server"));
6925 ssh->incoming_data_size = 0; /* start counting from here */
6928 * We've seen server NEWKEYS, so create and initialise
6929 * server-to-client session keys.
6931 if (ssh->sc_cipher_ctx)
6932 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6933 ssh->sccipher = s->sccipher_tobe;
6934 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
6936 if (ssh->sc_mac_ctx)
6937 ssh->scmac->free_context(ssh->sc_mac_ctx);
6938 ssh->scmac = s->scmac_tobe;
6939 ssh->sc_mac_ctx = ssh->scmac->make_context();
6941 if (ssh->sc_comp_ctx)
6942 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
6943 ssh->sccomp = s->sccomp_tobe;
6944 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6947 * Set IVs on server-to-client keys. Here we use the exchange
6948 * hash from the _first_ key exchange.
6951 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6952 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6953 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
6954 assert((ssh->sccipher->keylen+7) / 8 <=
6955 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6956 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
6957 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
6958 assert(ssh->sccipher->blksize <=
6959 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6960 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
6961 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
6962 assert(ssh->scmac->len <=
6963 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6964 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
6965 smemclr(keyspace, sizeof(keyspace));
6967 logeventf(ssh, "Initialised %.200s server->client encryption",
6968 ssh->sccipher->text_name);
6969 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6970 ssh->scmac->text_name);
6971 if (ssh->sccomp->text_name)
6972 logeventf(ssh, "Initialised %s decompression",
6973 ssh->sccomp->text_name);
6976 * Free shared secret.
6981 * Key exchange is over. Loop straight back round if we have a
6982 * deferred rekey reason.
6984 if (ssh->deferred_rekey_reason) {
6985 logevent(ssh->deferred_rekey_reason);
6987 ssh->deferred_rekey_reason = NULL;
6988 goto begin_key_exchange;
6992 * Otherwise, schedule a timer for our next rekey.
6994 ssh->kex_in_progress = FALSE;
6995 ssh->last_rekey = GETTICKCOUNT();
6996 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6997 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7001 * Now we're encrypting. Begin returning 1 to the protocol main
7002 * function so that other things can run on top of the
7003 * transport. If we ever see a KEXINIT, we must go back to the
7006 * We _also_ go back to the start if we see pktin==NULL and
7007 * inlen negative, because this is a special signal meaning
7008 * `initiate client-driven rekey', and `in' contains a message
7009 * giving the reason for the rekey.
7011 * inlen==-1 means always initiate a rekey;
7012 * inlen==-2 means that userauth has completed successfully and
7013 * we should consider rekeying (for delayed compression).
7015 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7016 (!pktin && inlen < 0))) {
7018 if (!ssh->protocol_initial_phase_done) {
7019 ssh->protocol_initial_phase_done = TRUE;
7021 * Allow authconn to initialise itself.
7023 do_ssh2_authconn(ssh, NULL, 0, NULL);
7028 logevent("Server initiated key re-exchange");
7032 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7033 * delayed compression, if it's available.
7035 * draft-miller-secsh-compression-delayed-00 says that you
7036 * negotiate delayed compression in the first key exchange, and
7037 * both sides start compressing when the server has sent
7038 * USERAUTH_SUCCESS. This has a race condition -- the server
7039 * can't know when the client has seen it, and thus which incoming
7040 * packets it should treat as compressed.
7042 * Instead, we do the initial key exchange without offering the
7043 * delayed methods, but note if the server offers them; when we
7044 * get here, if a delayed method was available that was higher
7045 * on our list than what we got, we initiate a rekey in which we
7046 * _do_ list the delayed methods (and hopefully get it as a
7047 * result). Subsequent rekeys will do the same.
7049 assert(!s->userauth_succeeded); /* should only happen once */
7050 s->userauth_succeeded = TRUE;
7051 if (!s->pending_compression)
7052 /* Can't see any point rekeying. */
7053 goto wait_for_rekey; /* this is utterly horrid */
7054 /* else fall through to rekey... */
7055 s->pending_compression = FALSE;
7058 * Now we've decided to rekey.
7060 * Special case: if the server bug is set that doesn't
7061 * allow rekeying, we give a different log message and
7062 * continue waiting. (If such a server _initiates_ a rekey,
7063 * we process it anyway!)
7065 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7066 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7068 /* Reset the counters, so that at least this message doesn't
7069 * hit the event log _too_ often. */
7070 ssh->outgoing_data_size = 0;
7071 ssh->incoming_data_size = 0;
7072 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7074 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7077 goto wait_for_rekey; /* this is still utterly horrid */
7079 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7082 goto begin_key_exchange;
7088 * Add data to an SSH-2 channel output buffer.
7090 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
7093 bufchain_add(&c->v.v2.outbuffer, buf, len);
7097 * Attempt to send data on an SSH-2 channel.
7099 static int ssh2_try_send(struct ssh_channel *c)
7102 struct Packet *pktout;
7105 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7108 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7109 if ((unsigned)len > c->v.v2.remwindow)
7110 len = c->v.v2.remwindow;
7111 if ((unsigned)len > c->v.v2.remmaxpkt)
7112 len = c->v.v2.remmaxpkt;
7113 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7114 ssh2_pkt_adduint32(pktout, c->remoteid);
7115 ssh2_pkt_addstring_start(pktout);
7116 ssh2_pkt_addstring_data(pktout, data, len);
7117 ssh2_pkt_send(ssh, pktout);
7118 bufchain_consume(&c->v.v2.outbuffer, len);
7119 c->v.v2.remwindow -= len;
7123 * After having sent as much data as we can, return the amount
7126 ret = bufchain_size(&c->v.v2.outbuffer);
7129 * And if there's no data pending but we need to send an EOF, send
7132 if (!ret && c->pending_eof)
7133 ssh_channel_try_eof(c);
7138 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7141 if (c->closes & CLOSES_SENT_EOF)
7142 return; /* don't send on channels we've EOFed */
7143 bufsize = ssh2_try_send(c);
7146 case CHAN_MAINSESSION:
7147 /* stdin need not receive an unthrottle
7148 * notification since it will be polled */
7151 x11_unthrottle(c->u.x11.xconn);
7154 /* agent sockets are request/response and need no
7155 * buffer management */
7158 pfd_unthrottle(c->u.pfd.pf);
7164 static int ssh_is_simple(Ssh ssh)
7167 * We use the 'simple' variant of the SSH protocol if we're asked
7168 * to, except not if we're also doing connection-sharing (either
7169 * tunnelling our packets over an upstream or expecting to be
7170 * tunnelled over ourselves), since then the assumption that we
7171 * have only one channel to worry about is not true after all.
7173 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7174 !ssh->bare_connection && !ssh->connshare);
7178 * Set up most of a new ssh_channel for SSH-2.
7180 static void ssh2_channel_init(struct ssh_channel *c)
7183 c->localid = alloc_channel_id(ssh);
7185 c->pending_eof = FALSE;
7186 c->throttling_conn = FALSE;
7187 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7188 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7189 c->v.v2.chanreq_head = NULL;
7190 c->v.v2.throttle_state = UNTHROTTLED;
7191 bufchain_init(&c->v.v2.outbuffer);
7195 * Construct the common parts of a CHANNEL_OPEN.
7197 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c, char *type)
7199 struct Packet *pktout;
7201 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7202 ssh2_pkt_addstring(pktout, type);
7203 ssh2_pkt_adduint32(pktout, c->localid);
7204 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7205 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7210 * CHANNEL_FAILURE doesn't come with any indication of what message
7211 * caused it, so we have to keep track of the outstanding
7212 * CHANNEL_REQUESTs ourselves.
7214 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7215 cchandler_fn_t handler, void *ctx)
7217 struct outstanding_channel_request *ocr =
7218 snew(struct outstanding_channel_request);
7220 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7221 ocr->handler = handler;
7224 if (!c->v.v2.chanreq_head)
7225 c->v.v2.chanreq_head = ocr;
7227 c->v.v2.chanreq_tail->next = ocr;
7228 c->v.v2.chanreq_tail = ocr;
7232 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7233 * NULL then a reply will be requested and the handler will be called
7234 * when it arrives. The returned packet is ready to have any
7235 * request-specific data added and be sent. Note that if a handler is
7236 * provided, it's essential that the request actually be sent.
7238 * The handler will usually be passed the response packet in pktin. If
7239 * pktin is NULL, this means that no reply will ever be forthcoming
7240 * (e.g. because the entire connection is being destroyed, or because
7241 * the server initiated channel closure before we saw the response)
7242 * and the handler should free any storage it's holding.
7244 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c, char *type,
7245 cchandler_fn_t handler, void *ctx)
7247 struct Packet *pktout;
7249 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7250 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7251 ssh2_pkt_adduint32(pktout, c->remoteid);
7252 ssh2_pkt_addstring(pktout, type);
7253 ssh2_pkt_addbool(pktout, handler != NULL);
7254 if (handler != NULL)
7255 ssh2_queue_chanreq_handler(c, handler, ctx);
7260 * Potentially enlarge the window on an SSH-2 channel.
7262 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7264 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7269 * Never send WINDOW_ADJUST for a channel that the remote side has
7270 * already sent EOF on; there's no point, since it won't be
7271 * sending any more data anyway. Ditto if _we've_ already sent
7274 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7278 * Also, never widen the window for an X11 channel when we're
7279 * still waiting to see its initial auth and may yet hand it off
7282 if (c->type == CHAN_X11 && c->u.x11.initial)
7286 * If the remote end has a habit of ignoring maxpkt, limit the
7287 * window so that it has no choice (assuming it doesn't ignore the
7290 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7291 newwin = OUR_V2_MAXPKT;
7294 * Only send a WINDOW_ADJUST if there's significantly more window
7295 * available than the other end thinks there is. This saves us
7296 * sending a WINDOW_ADJUST for every character in a shell session.
7298 * "Significant" is arbitrarily defined as half the window size.
7300 if (newwin / 2 >= c->v.v2.locwindow) {
7301 struct Packet *pktout;
7305 * In order to keep track of how much window the client
7306 * actually has available, we'd like it to acknowledge each
7307 * WINDOW_ADJUST. We can't do that directly, so we accompany
7308 * it with a CHANNEL_REQUEST that has to be acknowledged.
7310 * This is only necessary if we're opening the window wide.
7311 * If we're not, then throughput is being constrained by
7312 * something other than the maximum window size anyway.
7314 if (newwin == c->v.v2.locmaxwin &&
7315 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7316 up = snew(unsigned);
7317 *up = newwin - c->v.v2.locwindow;
7318 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7319 ssh2_handle_winadj_response, up);
7320 ssh2_pkt_send(ssh, pktout);
7322 if (c->v.v2.throttle_state != UNTHROTTLED)
7323 c->v.v2.throttle_state = UNTHROTTLING;
7325 /* Pretend the WINDOW_ADJUST was acked immediately. */
7326 c->v.v2.remlocwin = newwin;
7327 c->v.v2.throttle_state = THROTTLED;
7329 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7330 ssh2_pkt_adduint32(pktout, c->remoteid);
7331 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7332 ssh2_pkt_send(ssh, pktout);
7333 c->v.v2.locwindow = newwin;
7338 * Find the channel associated with a message. If there's no channel,
7339 * or it's not properly open, make a noise about it and return NULL.
7341 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7343 unsigned localid = ssh_pkt_getuint32(pktin);
7344 struct ssh_channel *c;
7346 c = find234(ssh->channels, &localid, ssh_channelfind);
7348 (c->type != CHAN_SHARING && c->halfopen &&
7349 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7350 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7351 char *buf = dupprintf("Received %s for %s channel %u",
7352 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7354 c ? "half-open" : "nonexistent", localid);
7355 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7362 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7363 struct Packet *pktin, void *ctx)
7365 unsigned *sizep = ctx;
7368 * Winadj responses should always be failures. However, at least
7369 * one server ("boks_sshd") is known to return SUCCESS for channel
7370 * requests it's never heard of, such as "winadj@putty". Raised
7371 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7372 * life, we don't worry about what kind of response we got.
7375 c->v.v2.remlocwin += *sizep;
7378 * winadj messages are only sent when the window is fully open, so
7379 * if we get an ack of one, we know any pending unthrottle is
7382 if (c->v.v2.throttle_state == UNTHROTTLING)
7383 c->v.v2.throttle_state = UNTHROTTLED;
7386 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
7388 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
7389 struct outstanding_channel_request *ocr;
7392 if (c->type == CHAN_SHARING) {
7393 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7394 pktin->body, pktin->length);
7397 ocr = c->v.v2.chanreq_head;
7399 ssh2_msg_unexpected(ssh, pktin);
7402 ocr->handler(c, pktin, ocr->ctx);
7403 c->v.v2.chanreq_head = ocr->next;
7406 * We may now initiate channel-closing procedures, if that
7407 * CHANNEL_REQUEST was the last thing outstanding before we send
7410 ssh2_channel_check_close(c);
7413 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
7415 struct ssh_channel *c;
7416 c = ssh2_channel_msg(ssh, pktin);
7419 if (c->type == CHAN_SHARING) {
7420 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7421 pktin->body, pktin->length);
7424 if (!(c->closes & CLOSES_SENT_EOF)) {
7425 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
7426 ssh2_try_send_and_unthrottle(ssh, c);
7430 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
7434 struct ssh_channel *c;
7435 c = ssh2_channel_msg(ssh, pktin);
7438 if (c->type == CHAN_SHARING) {
7439 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7440 pktin->body, pktin->length);
7443 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
7444 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
7445 return; /* extended but not stderr */
7446 ssh_pkt_getstring(pktin, &data, &length);
7449 c->v.v2.locwindow -= length;
7450 c->v.v2.remlocwin -= length;
7452 case CHAN_MAINSESSION:
7454 from_backend(ssh->frontend, pktin->type ==
7455 SSH2_MSG_CHANNEL_EXTENDED_DATA,
7459 bufsize = x11_send(c->u.x11.xconn, data, length);
7462 bufsize = pfd_send(c->u.pfd.pf, data, length);
7465 while (length > 0) {
7466 if (c->u.a.lensofar < 4) {
7467 unsigned int l = min(4 - c->u.a.lensofar,
7469 memcpy(c->u.a.msglen + c->u.a.lensofar,
7473 c->u.a.lensofar += l;
7475 if (c->u.a.lensofar == 4) {
7477 4 + GET_32BIT(c->u.a.msglen);
7478 c->u.a.message = snewn(c->u.a.totallen,
7480 memcpy(c->u.a.message, c->u.a.msglen, 4);
7482 if (c->u.a.lensofar >= 4 && length > 0) {
7484 min(c->u.a.totallen - c->u.a.lensofar,
7486 memcpy(c->u.a.message + c->u.a.lensofar,
7490 c->u.a.lensofar += l;
7492 if (c->u.a.lensofar == c->u.a.totallen) {
7495 c->u.a.outstanding_requests++;
7496 if (agent_query(c->u.a.message,
7499 ssh_agentf_callback, c))
7500 ssh_agentf_callback(c, reply, replylen);
7501 sfree(c->u.a.message);
7502 c->u.a.message = NULL;
7503 c->u.a.lensofar = 0;
7510 * If it looks like the remote end hit the end of its window,
7511 * and we didn't want it to do that, think about using a
7514 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
7515 c->v.v2.locmaxwin < 0x40000000)
7516 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
7518 * If we are not buffering too much data,
7519 * enlarge the window again at the remote side.
7520 * If we are buffering too much, we may still
7521 * need to adjust the window if the server's
7524 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7525 c->v.v2.locmaxwin - bufsize : 0);
7527 * If we're either buffering way too much data, or if we're
7528 * buffering anything at all and we're in "simple" mode,
7529 * throttle the whole channel.
7531 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
7532 && !c->throttling_conn) {
7533 c->throttling_conn = 1;
7534 ssh_throttle_conn(ssh, +1);
7539 static void ssh_check_termination(Ssh ssh)
7541 if (ssh->version == 2 &&
7542 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7543 count234(ssh->channels) == 0 &&
7544 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
7546 * We used to send SSH_MSG_DISCONNECT here, because I'd
7547 * believed that _every_ conforming SSH-2 connection had to
7548 * end with a disconnect being sent by at least one side;
7549 * apparently I was wrong and it's perfectly OK to
7550 * unceremoniously slam the connection shut when you're done,
7551 * and indeed OpenSSH feels this is more polite than sending a
7552 * DISCONNECT. So now we don't.
7554 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7558 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id)
7560 logeventf(ssh, "Connection sharing downstream #%u connected", id);
7563 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
7565 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
7566 ssh_check_termination(ssh);
7569 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
7574 va_start(ap, logfmt);
7575 buf = dupvprintf(logfmt, ap);
7578 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
7580 logeventf(ssh, "Connection sharing: %s", buf);
7584 static void ssh_channel_destroy(struct ssh_channel *c)
7589 case CHAN_MAINSESSION:
7590 ssh->mainchan = NULL;
7591 update_specials_menu(ssh->frontend);
7594 if (c->u.x11.xconn != NULL)
7595 x11_close(c->u.x11.xconn);
7596 logevent("Forwarded X11 connection terminated");
7599 sfree(c->u.a.message);
7602 if (c->u.pfd.pf != NULL)
7603 pfd_close(c->u.pfd.pf);
7604 logevent("Forwarded port closed");
7608 del234(ssh->channels, c);
7609 if (ssh->version == 2) {
7610 bufchain_clear(&c->v.v2.outbuffer);
7611 assert(c->v.v2.chanreq_head == NULL);
7616 * If that was the last channel left open, we might need to
7619 ssh_check_termination(ssh);
7622 static void ssh2_channel_check_close(struct ssh_channel *c)
7625 struct Packet *pktout;
7629 * If we've sent out our own CHANNEL_OPEN but not yet seen
7630 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
7631 * it's too early to be sending close messages of any kind.
7636 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
7637 c->type == CHAN_ZOMBIE) &&
7638 !c->v.v2.chanreq_head &&
7639 !(c->closes & CLOSES_SENT_CLOSE)) {
7641 * We have both sent and received EOF (or the channel is a
7642 * zombie), and we have no outstanding channel requests, which
7643 * means the channel is in final wind-up. But we haven't sent
7644 * CLOSE, so let's do so now.
7646 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
7647 ssh2_pkt_adduint32(pktout, c->remoteid);
7648 ssh2_pkt_send(ssh, pktout);
7649 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
7652 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
7653 assert(c->v.v2.chanreq_head == NULL);
7655 * We have both sent and received CLOSE, which means we're
7656 * completely done with the channel.
7658 ssh_channel_destroy(c);
7662 static void ssh2_channel_got_eof(struct ssh_channel *c)
7664 if (c->closes & CLOSES_RCVD_EOF)
7665 return; /* already seen EOF */
7666 c->closes |= CLOSES_RCVD_EOF;
7668 if (c->type == CHAN_X11) {
7669 x11_send_eof(c->u.x11.xconn);
7670 } else if (c->type == CHAN_AGENT) {
7671 if (c->u.a.outstanding_requests == 0) {
7672 /* Manufacture an outgoing EOF in response to the incoming one. */
7673 sshfwd_write_eof(c);
7675 } else if (c->type == CHAN_SOCKDATA) {
7676 pfd_send_eof(c->u.pfd.pf);
7677 } else if (c->type == CHAN_MAINSESSION) {
7680 if (!ssh->sent_console_eof &&
7681 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
7683 * Either from_backend_eof told us that the front end
7684 * wants us to close the outgoing side of the connection
7685 * as soon as we see EOF from the far end, or else we've
7686 * unilaterally decided to do that because we've allocated
7687 * a remote pty and hence EOF isn't a particularly
7688 * meaningful concept.
7690 sshfwd_write_eof(c);
7692 ssh->sent_console_eof = TRUE;
7695 ssh2_channel_check_close(c);
7698 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
7700 struct ssh_channel *c;
7702 c = ssh2_channel_msg(ssh, pktin);
7705 if (c->type == CHAN_SHARING) {
7706 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7707 pktin->body, pktin->length);
7710 ssh2_channel_got_eof(c);
7713 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7715 struct ssh_channel *c;
7717 c = ssh2_channel_msg(ssh, pktin);
7720 if (c->type == CHAN_SHARING) {
7721 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7722 pktin->body, pktin->length);
7727 * When we receive CLOSE on a channel, we assume it comes with an
7728 * implied EOF if we haven't seen EOF yet.
7730 ssh2_channel_got_eof(c);
7732 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
7734 * It also means we stop expecting to see replies to any
7735 * outstanding channel requests, so clean those up too.
7736 * (ssh_chanreq_init will enforce by assertion that we don't
7737 * subsequently put anything back on this list.)
7739 while (c->v.v2.chanreq_head) {
7740 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
7741 ocr->handler(c, NULL, ocr->ctx);
7742 c->v.v2.chanreq_head = ocr->next;
7748 * And we also send an outgoing EOF, if we haven't already, on the
7749 * assumption that CLOSE is a pretty forceful announcement that
7750 * the remote side is doing away with the entire channel. (If it
7751 * had wanted to send us EOF and continue receiving data from us,
7752 * it would have just sent CHANNEL_EOF.)
7754 if (!(c->closes & CLOSES_SENT_EOF)) {
7756 * Make sure we don't read any more from whatever our local
7757 * data source is for this channel.
7760 case CHAN_MAINSESSION:
7761 ssh->send_ok = 0; /* stop trying to read from stdin */
7764 x11_override_throttle(c->u.x11.xconn, 1);
7767 pfd_override_throttle(c->u.pfd.pf, 1);
7772 * Abandon any buffered data we still wanted to send to this
7773 * channel. Receiving a CHANNEL_CLOSE is an indication that
7774 * the server really wants to get on and _destroy_ this
7775 * channel, and it isn't going to send us any further
7776 * WINDOW_ADJUSTs to permit us to send pending stuff.
7778 bufchain_clear(&c->v.v2.outbuffer);
7781 * Send outgoing EOF.
7783 sshfwd_write_eof(c);
7787 * Now process the actual close.
7789 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7790 c->closes |= CLOSES_RCVD_CLOSE;
7791 ssh2_channel_check_close(c);
7795 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7797 struct ssh_channel *c;
7799 c = ssh2_channel_msg(ssh, pktin);
7802 if (c->type == CHAN_SHARING) {
7803 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7804 pktin->body, pktin->length);
7807 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7808 c->remoteid = ssh_pkt_getuint32(pktin);
7809 c->halfopen = FALSE;
7810 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7811 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7813 if (c->type == CHAN_SOCKDATA_DORMANT) {
7814 c->type = CHAN_SOCKDATA;
7816 pfd_confirm(c->u.pfd.pf);
7817 } else if (c->type == CHAN_ZOMBIE) {
7819 * This case can occur if a local socket error occurred
7820 * between us sending out CHANNEL_OPEN and receiving
7821 * OPEN_CONFIRMATION. In this case, all we can do is
7822 * immediately initiate close proceedings now that we know the
7823 * server's id to put in the close message.
7825 ssh2_channel_check_close(c);
7828 * We never expect to receive OPEN_CONFIRMATION for any
7829 * *other* channel type (since only local-to-remote port
7830 * forwardings cause us to send CHANNEL_OPEN after the main
7831 * channel is live - all other auxiliary channel types are
7832 * initiated from the server end). It's safe to enforce this
7833 * by assertion rather than by ssh_disconnect, because the
7834 * real point is that we never constructed a half-open channel
7835 * structure in the first place with any type other than the
7838 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
7842 ssh_channel_try_eof(c); /* in case we had a pending EOF */
7845 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7847 static const char *const reasons[] = {
7848 "<unknown reason code>",
7849 "Administratively prohibited",
7851 "Unknown channel type",
7852 "Resource shortage",
7854 unsigned reason_code;
7855 char *reason_string;
7857 struct ssh_channel *c;
7859 c = ssh2_channel_msg(ssh, pktin);
7862 if (c->type == CHAN_SHARING) {
7863 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7864 pktin->body, pktin->length);
7867 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7869 if (c->type == CHAN_SOCKDATA_DORMANT) {
7870 reason_code = ssh_pkt_getuint32(pktin);
7871 if (reason_code >= lenof(reasons))
7872 reason_code = 0; /* ensure reasons[reason_code] in range */
7873 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7874 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7875 reasons[reason_code], reason_length, reason_string);
7877 pfd_close(c->u.pfd.pf);
7878 } else if (c->type == CHAN_ZOMBIE) {
7880 * This case can occur if a local socket error occurred
7881 * between us sending out CHANNEL_OPEN and receiving
7882 * OPEN_FAILURE. In this case, we need do nothing except allow
7883 * the code below to throw the half-open channel away.
7887 * We never expect to receive OPEN_FAILURE for any *other*
7888 * channel type (since only local-to-remote port forwardings
7889 * cause us to send CHANNEL_OPEN after the main channel is
7890 * live - all other auxiliary channel types are initiated from
7891 * the server end). It's safe to enforce this by assertion
7892 * rather than by ssh_disconnect, because the real point is
7893 * that we never constructed a half-open channel structure in
7894 * the first place with any type other than the above.
7896 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
7899 del234(ssh->channels, c);
7903 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7906 int typelen, want_reply;
7907 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7908 struct ssh_channel *c;
7909 struct Packet *pktout;
7911 c = ssh2_channel_msg(ssh, pktin);
7914 if (c->type == CHAN_SHARING) {
7915 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7916 pktin->body, pktin->length);
7919 ssh_pkt_getstring(pktin, &type, &typelen);
7920 want_reply = ssh2_pkt_getbool(pktin);
7922 if (c->closes & CLOSES_SENT_CLOSE) {
7924 * We don't reply to channel requests after we've sent
7925 * CHANNEL_CLOSE for the channel, because our reply might
7926 * cross in the network with the other side's CHANNEL_CLOSE
7927 * and arrive after they have wound the channel up completely.
7933 * Having got the channel number, we now look at
7934 * the request type string to see if it's something
7937 if (c == ssh->mainchan) {
7939 * We recognise "exit-status" and "exit-signal" on
7940 * the primary channel.
7942 if (typelen == 11 &&
7943 !memcmp(type, "exit-status", 11)) {
7945 ssh->exitcode = ssh_pkt_getuint32(pktin);
7946 logeventf(ssh, "Server sent command exit status %d",
7948 reply = SSH2_MSG_CHANNEL_SUCCESS;
7950 } else if (typelen == 11 &&
7951 !memcmp(type, "exit-signal", 11)) {
7953 int is_plausible = TRUE, is_int = FALSE;
7954 char *fmt_sig = "", *fmt_msg = "";
7956 int msglen = 0, core = FALSE;
7957 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7958 * provide an `int' for the signal, despite its
7959 * having been a `string' in the drafts of RFC 4254 since at
7960 * least 2001. (Fixed in session.c 1.147.) Try to
7961 * infer which we can safely parse it as. */
7963 unsigned char *p = pktin->body +
7965 long len = pktin->length - pktin->savedpos;
7966 unsigned long num = GET_32BIT(p); /* what is it? */
7967 /* If it's 0, it hardly matters; assume string */
7971 int maybe_int = FALSE, maybe_str = FALSE;
7972 #define CHECK_HYPOTHESIS(offset, result) \
7975 int q = toint(offset); \
7976 if (q >= 0 && q+4 <= len) { \
7977 q = toint(q + 4 + GET_32BIT(p+q)); \
7978 if (q >= 0 && q+4 <= len && \
7979 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
7984 CHECK_HYPOTHESIS(4+1, maybe_int);
7985 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7986 #undef CHECK_HYPOTHESIS
7987 if (maybe_int && !maybe_str)
7989 else if (!maybe_int && maybe_str)
7992 /* Crikey. Either or neither. Panic. */
7993 is_plausible = FALSE;
7996 ssh->exitcode = 128; /* means `unknown signal' */
7999 /* Old non-standard OpenSSH. */
8000 int signum = ssh_pkt_getuint32(pktin);
8001 fmt_sig = dupprintf(" %d", signum);
8002 ssh->exitcode = 128 + signum;
8004 /* As per RFC 4254. */
8007 ssh_pkt_getstring(pktin, &sig, &siglen);
8008 /* Signal name isn't supposed to be blank, but
8009 * let's cope gracefully if it is. */
8011 fmt_sig = dupprintf(" \"%.*s\"",
8016 * Really hideous method of translating the
8017 * signal description back into a locally
8018 * meaningful number.
8023 #define TRANSLATE_SIGNAL(s) \
8024 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8025 ssh->exitcode = 128 + SIG ## s
8027 TRANSLATE_SIGNAL(ABRT);
8030 TRANSLATE_SIGNAL(ALRM);
8033 TRANSLATE_SIGNAL(FPE);
8036 TRANSLATE_SIGNAL(HUP);
8039 TRANSLATE_SIGNAL(ILL);
8042 TRANSLATE_SIGNAL(INT);
8045 TRANSLATE_SIGNAL(KILL);
8048 TRANSLATE_SIGNAL(PIPE);
8051 TRANSLATE_SIGNAL(QUIT);
8054 TRANSLATE_SIGNAL(SEGV);
8057 TRANSLATE_SIGNAL(TERM);
8060 TRANSLATE_SIGNAL(USR1);
8063 TRANSLATE_SIGNAL(USR2);
8065 #undef TRANSLATE_SIGNAL
8067 ssh->exitcode = 128;
8069 core = ssh2_pkt_getbool(pktin);
8070 ssh_pkt_getstring(pktin, &msg, &msglen);
8072 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8074 /* ignore lang tag */
8075 } /* else don't attempt to parse */
8076 logeventf(ssh, "Server exited on signal%s%s%s",
8077 fmt_sig, core ? " (core dumped)" : "",
8079 if (*fmt_sig) sfree(fmt_sig);
8080 if (*fmt_msg) sfree(fmt_msg);
8081 reply = SSH2_MSG_CHANNEL_SUCCESS;
8086 * This is a channel request we don't know
8087 * about, so we now either ignore the request
8088 * or respond with CHANNEL_FAILURE, depending
8091 reply = SSH2_MSG_CHANNEL_FAILURE;
8094 pktout = ssh2_pkt_init(reply);
8095 ssh2_pkt_adduint32(pktout, c->remoteid);
8096 ssh2_pkt_send(ssh, pktout);
8100 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8103 int typelen, want_reply;
8104 struct Packet *pktout;
8106 ssh_pkt_getstring(pktin, &type, &typelen);
8107 want_reply = ssh2_pkt_getbool(pktin);
8110 * We currently don't support any global requests
8111 * at all, so we either ignore the request or
8112 * respond with REQUEST_FAILURE, depending on
8116 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8117 ssh2_pkt_send(ssh, pktout);
8121 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8125 struct X11FakeAuth *auth;
8128 * Make up a new set of fake X11 auth data, and add it to the tree
8129 * of currently valid ones with an indication of the sharing
8130 * context that it's relevant to.
8132 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8133 auth->share_cs = share_cs;
8134 auth->share_chan = share_chan;
8139 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8141 del234(ssh->x11authtree, auth);
8142 x11_free_fake_auth(auth);
8145 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8153 struct ssh_channel *c;
8154 unsigned remid, winsize, pktsize;
8155 unsigned our_winsize_override = 0;
8156 struct Packet *pktout;
8158 ssh_pkt_getstring(pktin, &type, &typelen);
8159 c = snew(struct ssh_channel);
8162 remid = ssh_pkt_getuint32(pktin);
8163 winsize = ssh_pkt_getuint32(pktin);
8164 pktsize = ssh_pkt_getuint32(pktin);
8166 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8169 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8170 addrstr = snewn(peeraddrlen+1, char);
8171 memcpy(addrstr, peeraddr, peeraddrlen);
8172 addrstr[peeraddrlen] = '\0';
8173 peerport = ssh_pkt_getuint32(pktin);
8175 logeventf(ssh, "Received X11 connect request from %s:%d",
8178 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8179 error = "X11 forwarding is not enabled";
8181 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8184 c->u.x11.initial = TRUE;
8187 * If we are a connection-sharing upstream, then we should
8188 * initially present a very small window, adequate to take
8189 * the X11 initial authorisation packet but not much more.
8190 * Downstream will then present us a larger window (by
8191 * fiat of the connection-sharing protocol) and we can
8192 * guarantee to send a positive-valued WINDOW_ADJUST.
8195 our_winsize_override = 128;
8197 logevent("Opened X11 forward channel");
8201 } else if (typelen == 15 &&
8202 !memcmp(type, "forwarded-tcpip", 15)) {
8203 struct ssh_rportfwd pf, *realpf;
8206 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8207 pf.shost = dupprintf("%.*s", shostlen, shost);
8208 pf.sport = ssh_pkt_getuint32(pktin);
8209 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8210 peerport = ssh_pkt_getuint32(pktin);
8211 realpf = find234(ssh->rportfwds, &pf, NULL);
8212 logeventf(ssh, "Received remote port %s:%d open request "
8213 "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
8216 if (realpf == NULL) {
8217 error = "Remote port is not recognised";
8221 if (realpf->share_ctx) {
8223 * This port forwarding is on behalf of a
8224 * connection-sharing downstream, so abandon our own
8225 * channel-open procedure and just pass the message on
8228 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8229 pktin->body, pktin->length);
8234 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8235 c, ssh->conf, realpf->pfrec->addressfamily);
8236 logeventf(ssh, "Attempting to forward remote port to "
8237 "%s:%d", realpf->dhost, realpf->dport);
8239 logeventf(ssh, "Port open failed: %s", err);
8241 error = "Port open failed";
8243 logevent("Forwarded port opened successfully");
8244 c->type = CHAN_SOCKDATA;
8247 } else if (typelen == 22 &&
8248 !memcmp(type, "auth-agent@openssh.com", 22)) {
8249 if (!ssh->agentfwd_enabled)
8250 error = "Agent forwarding is not enabled";
8252 c->type = CHAN_AGENT; /* identify channel type */
8253 c->u.a.lensofar = 0;
8254 c->u.a.message = NULL;
8255 c->u.a.outstanding_requests = 0;
8258 error = "Unsupported channel type requested";
8261 c->remoteid = remid;
8262 c->halfopen = FALSE;
8264 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8265 ssh2_pkt_adduint32(pktout, c->remoteid);
8266 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8267 ssh2_pkt_addstring(pktout, error);
8268 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8269 ssh2_pkt_send(ssh, pktout);
8270 logeventf(ssh, "Rejected channel open: %s", error);
8273 ssh2_channel_init(c);
8274 c->v.v2.remwindow = winsize;
8275 c->v.v2.remmaxpkt = pktsize;
8276 if (our_winsize_override) {
8277 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8278 our_winsize_override;
8280 add234(ssh->channels, c);
8281 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8282 ssh2_pkt_adduint32(pktout, c->remoteid);
8283 ssh2_pkt_adduint32(pktout, c->localid);
8284 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8285 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8286 ssh2_pkt_send(ssh, pktout);
8290 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8291 void *share_cs, void *share_chan,
8292 const char *peer_addr, int peer_port,
8293 int endian, int protomajor, int protominor,
8294 const void *initial_data, int initial_len)
8297 * This function is called when we've just discovered that an X
8298 * forwarding channel on which we'd been handling the initial auth
8299 * ourselves turns out to be destined for a connection-sharing
8300 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8301 * that we completely stop tracking windows and buffering data and
8302 * just pass more or less unmodified SSH messages back and forth.
8304 c->type = CHAN_SHARING;
8305 c->u.sharing.ctx = share_cs;
8306 share_setup_x11_channel(share_cs, share_chan,
8307 c->localid, c->remoteid, c->v.v2.remwindow,
8308 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8309 peer_addr, peer_port, endian,
8310 protomajor, protominor,
8311 initial_data, initial_len);
8314 void sshfwd_x11_is_local(struct ssh_channel *c)
8317 * This function is called when we've just discovered that an X
8318 * forwarding channel is _not_ destined for a connection-sharing
8319 * downstream but we're going to handle it ourselves. We stop
8320 * presenting a cautiously small window and go into ordinary data
8323 c->u.x11.initial = FALSE;
8324 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8328 * Buffer banner messages for later display at some convenient point,
8329 * if we're going to display them.
8331 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8333 /* Arbitrary limit to prevent unbounded inflation of buffer */
8334 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8335 bufchain_size(&ssh->banner) <= 131072) {
8336 char *banner = NULL;
8338 ssh_pkt_getstring(pktin, &banner, &size);
8340 bufchain_add(&ssh->banner, banner, size);
8344 /* Helper function to deal with sending tty modes for "pty-req" */
8345 static void ssh2_send_ttymode(void *data, char *mode, char *val)
8347 struct Packet *pktout = (struct Packet *)data;
8349 unsigned int arg = 0;
8350 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
8351 if (i == lenof(ssh_ttymodes)) return;
8352 switch (ssh_ttymodes[i].type) {
8354 arg = ssh_tty_parse_specchar(val);
8357 arg = ssh_tty_parse_boolean(val);
8360 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
8361 ssh2_pkt_adduint32(pktout, arg);
8364 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8367 struct ssh2_setup_x11_state {
8371 struct Packet *pktout;
8372 crStateP(ssh2_setup_x11_state, ctx);
8376 logevent("Requesting X11 forwarding");
8377 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8379 ssh2_pkt_addbool(pktout, 0); /* many connections */
8380 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8381 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8382 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8383 ssh2_pkt_send(ssh, pktout);
8385 /* Wait to be called back with either a response packet, or NULL
8386 * meaning clean up and free our data */
8390 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8391 logevent("X11 forwarding enabled");
8392 ssh->X11_fwd_enabled = TRUE;
8394 logevent("X11 forwarding refused");
8400 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8403 struct ssh2_setup_agent_state {
8407 struct Packet *pktout;
8408 crStateP(ssh2_setup_agent_state, ctx);
8412 logevent("Requesting OpenSSH-style agent forwarding");
8413 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8414 ssh2_setup_agent, s);
8415 ssh2_pkt_send(ssh, pktout);
8417 /* Wait to be called back with either a response packet, or NULL
8418 * meaning clean up and free our data */
8422 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8423 logevent("Agent forwarding enabled");
8424 ssh->agentfwd_enabled = TRUE;
8426 logevent("Agent forwarding refused");
8432 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8435 struct ssh2_setup_pty_state {
8439 struct Packet *pktout;
8440 crStateP(ssh2_setup_pty_state, ctx);
8444 /* Unpick the terminal-speed string. */
8445 /* XXX perhaps we should allow no speeds to be sent. */
8446 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8447 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8448 /* Build the pty request. */
8449 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
8451 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
8452 ssh2_pkt_adduint32(pktout, ssh->term_width);
8453 ssh2_pkt_adduint32(pktout, ssh->term_height);
8454 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
8455 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
8456 ssh2_pkt_addstring_start(pktout);
8457 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
8458 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
8459 ssh2_pkt_adduint32(pktout, ssh->ispeed);
8460 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
8461 ssh2_pkt_adduint32(pktout, ssh->ospeed);
8462 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
8463 ssh2_pkt_send(ssh, pktout);
8464 ssh->state = SSH_STATE_INTERMED;
8466 /* Wait to be called back with either a response packet, or NULL
8467 * meaning clean up and free our data */
8471 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8472 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8473 ssh->ospeed, ssh->ispeed);
8474 ssh->got_pty = TRUE;
8476 c_write_str(ssh, "Server refused to allocate pty\r\n");
8477 ssh->editing = ssh->echoing = 1;
8484 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
8487 struct ssh2_setup_env_state {
8489 int num_env, env_left, env_ok;
8492 struct Packet *pktout;
8493 crStateP(ssh2_setup_env_state, ctx);
8498 * Send environment variables.
8500 * Simplest thing here is to send all the requests at once, and
8501 * then wait for a whole bunch of successes or failures.
8507 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
8509 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
8510 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
8511 ssh2_pkt_addstring(pktout, key);
8512 ssh2_pkt_addstring(pktout, val);
8513 ssh2_pkt_send(ssh, pktout);
8518 logeventf(ssh, "Sent %d environment variables", s->num_env);
8523 s->env_left = s->num_env;
8525 while (s->env_left > 0) {
8526 /* Wait to be called back with either a response packet,
8527 * or NULL meaning clean up and free our data */
8529 if (!pktin) goto out;
8530 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
8535 if (s->env_ok == s->num_env) {
8536 logevent("All environment variables successfully set");
8537 } else if (s->env_ok == 0) {
8538 logevent("All environment variables refused");
8539 c_write_str(ssh, "Server refused to set environment variables\r\n");
8541 logeventf(ssh, "%d environment variables refused",
8542 s->num_env - s->env_ok);
8543 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8551 * Handle the SSH-2 userauth and connection layers.
8553 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
8555 do_ssh2_authconn(ssh, NULL, 0, pktin);
8558 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
8562 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
8565 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
8566 struct Packet *pktin)
8568 struct do_ssh2_authconn_state {
8572 AUTH_TYPE_PUBLICKEY,
8573 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
8574 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
8576 AUTH_TYPE_GSSAPI, /* always QUIET */
8577 AUTH_TYPE_KEYBOARD_INTERACTIVE,
8578 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
8580 int done_service_req;
8581 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
8582 int tried_pubkey_config, done_agent;
8587 int kbd_inter_refused;
8588 int we_are_in, userauth_success;
8589 prompts_t *cur_prompt;
8594 void *publickey_blob;
8595 int publickey_bloblen;
8596 int publickey_encrypted;
8597 char *publickey_algorithm;
8598 char *publickey_comment;
8599 unsigned char agent_request[5], *agent_response, *agentp;
8600 int agent_responselen;
8601 unsigned char *pkblob_in_agent;
8603 char *pkblob, *alg, *commentp;
8604 int pklen, alglen, commentlen;
8605 int siglen, retlen, len;
8606 char *q, *agentreq, *ret;
8608 struct Packet *pktout;
8611 struct ssh_gss_library *gsslib;
8612 Ssh_gss_ctx gss_ctx;
8613 Ssh_gss_buf gss_buf;
8614 Ssh_gss_buf gss_rcvtok, gss_sndtok;
8615 Ssh_gss_name gss_srv_name;
8616 Ssh_gss_stat gss_stat;
8619 crState(do_ssh2_authconn_state);
8623 /* Register as a handler for all the messages this coroutine handles. */
8624 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
8625 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
8626 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
8627 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
8628 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
8629 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
8630 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
8631 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
8632 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
8633 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
8634 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
8635 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
8636 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
8637 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
8638 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
8639 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
8640 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
8641 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
8642 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
8643 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
8645 s->done_service_req = FALSE;
8646 s->we_are_in = s->userauth_success = FALSE;
8647 s->agent_response = NULL;
8649 s->tried_gssapi = FALSE;
8652 if (!ssh->bare_connection) {
8653 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
8655 * Request userauth protocol, and await a response to it.
8657 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8658 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
8659 ssh2_pkt_send(ssh, s->pktout);
8660 crWaitUntilV(pktin);
8661 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
8662 s->done_service_req = TRUE;
8664 if (!s->done_service_req) {
8666 * Request connection protocol directly, without authentication.
8668 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8669 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8670 ssh2_pkt_send(ssh, s->pktout);
8671 crWaitUntilV(pktin);
8672 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
8673 s->we_are_in = TRUE; /* no auth required */
8675 bombout(("Server refused service request"));
8680 s->we_are_in = TRUE;
8683 /* Arrange to be able to deal with any BANNERs that come in.
8684 * (We do this now as packets may come in during the next bit.) */
8685 bufchain_init(&ssh->banner);
8686 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
8687 ssh2_msg_userauth_banner;
8690 * Misc one-time setup for authentication.
8692 s->publickey_blob = NULL;
8693 if (!s->we_are_in) {
8696 * Load the public half of any configured public key file
8699 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8700 if (!filename_is_null(s->keyfile)) {
8702 logeventf(ssh, "Reading private key file \"%.150s\"",
8703 filename_to_str(s->keyfile));
8704 keytype = key_type(s->keyfile);
8705 if (keytype == SSH_KEYTYPE_SSH2) {
8708 ssh2_userkey_loadpub(s->keyfile,
8709 &s->publickey_algorithm,
8710 &s->publickey_bloblen,
8711 &s->publickey_comment, &error);
8712 if (s->publickey_blob) {
8713 s->publickey_encrypted =
8714 ssh2_userkey_encrypted(s->keyfile, NULL);
8717 logeventf(ssh, "Unable to load private key (%s)",
8719 msgbuf = dupprintf("Unable to load private key file "
8720 "\"%.150s\" (%s)\r\n",
8721 filename_to_str(s->keyfile),
8723 c_write_str(ssh, msgbuf);
8728 logeventf(ssh, "Unable to use this key file (%s)",
8729 key_type_to_str(keytype));
8730 msgbuf = dupprintf("Unable to use key file \"%.150s\""
8732 filename_to_str(s->keyfile),
8733 key_type_to_str(keytype));
8734 c_write_str(ssh, msgbuf);
8736 s->publickey_blob = NULL;
8741 * Find out about any keys Pageant has (but if there's a
8742 * public key configured, filter out all others).
8745 s->agent_response = NULL;
8746 s->pkblob_in_agent = NULL;
8747 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
8751 logevent("Pageant is running. Requesting keys.");
8753 /* Request the keys held by the agent. */
8754 PUT_32BIT(s->agent_request, 1);
8755 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
8756 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
8757 ssh_agent_callback, ssh)) {
8761 bombout(("Unexpected data from server while"
8762 " waiting for agent response"));
8765 } while (pktin || inlen > 0);
8766 r = ssh->agent_response;
8767 s->agent_responselen = ssh->agent_response_len;
8769 s->agent_response = (unsigned char *) r;
8770 if (s->agent_response && s->agent_responselen >= 5 &&
8771 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
8774 p = s->agent_response + 5;
8775 s->nkeys = toint(GET_32BIT(p));
8778 * Vet the Pageant response to ensure that the key
8779 * count and blob lengths make sense.
8782 logeventf(ssh, "Pageant response contained a negative"
8783 " key count %d", s->nkeys);
8785 goto done_agent_query;
8787 unsigned char *q = p + 4;
8788 int lenleft = s->agent_responselen - 5 - 4;
8790 for (keyi = 0; keyi < s->nkeys; keyi++) {
8791 int bloblen, commentlen;
8793 logeventf(ssh, "Pageant response was truncated");
8795 goto done_agent_query;
8797 bloblen = toint(GET_32BIT(q));
8798 if (bloblen < 0 || bloblen > lenleft) {
8799 logeventf(ssh, "Pageant response was truncated");
8801 goto done_agent_query;
8803 lenleft -= 4 + bloblen;
8805 commentlen = toint(GET_32BIT(q));
8806 if (commentlen < 0 || commentlen > lenleft) {
8807 logeventf(ssh, "Pageant response was truncated");
8809 goto done_agent_query;
8811 lenleft -= 4 + commentlen;
8812 q += 4 + commentlen;
8817 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
8818 if (s->publickey_blob) {
8819 /* See if configured key is in agent. */
8820 for (keyi = 0; keyi < s->nkeys; keyi++) {
8821 s->pklen = toint(GET_32BIT(p));
8822 if (s->pklen == s->publickey_bloblen &&
8823 !memcmp(p+4, s->publickey_blob,
8824 s->publickey_bloblen)) {
8825 logeventf(ssh, "Pageant key #%d matches "
8826 "configured key file", keyi);
8828 s->pkblob_in_agent = p;
8832 p += toint(GET_32BIT(p)) + 4; /* comment */
8834 if (!s->pkblob_in_agent) {
8835 logevent("Configured key file not in Pageant");
8840 logevent("Failed to get reply from Pageant");
8848 * We repeat this whole loop, including the username prompt,
8849 * until we manage a successful authentication. If the user
8850 * types the wrong _password_, they can be sent back to the
8851 * beginning to try another username, if this is configured on.
8852 * (If they specify a username in the config, they are never
8853 * asked, even if they do give a wrong password.)
8855 * I think this best serves the needs of
8857 * - the people who have no configuration, no keys, and just
8858 * want to try repeated (username,password) pairs until they
8859 * type both correctly
8861 * - people who have keys and configuration but occasionally
8862 * need to fall back to passwords
8864 * - people with a key held in Pageant, who might not have
8865 * logged in to a particular machine before; so they want to
8866 * type a username, and then _either_ their key will be
8867 * accepted, _or_ they will type a password. If they mistype
8868 * the username they will want to be able to get back and
8871 s->got_username = FALSE;
8872 while (!s->we_are_in) {
8876 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
8878 * We got a username last time round this loop, and
8879 * with change_username turned off we don't try to get
8882 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
8883 int ret; /* need not be kept over crReturn */
8884 s->cur_prompt = new_prompts(ssh->frontend);
8885 s->cur_prompt->to_server = TRUE;
8886 s->cur_prompt->name = dupstr("SSH login name");
8887 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
8888 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8891 crWaitUntilV(!pktin);
8892 ret = get_userpass_input(s->cur_prompt, in, inlen);
8897 * get_userpass_input() failed to get a username.
8900 free_prompts(s->cur_prompt);
8901 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
8904 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
8905 free_prompts(s->cur_prompt);
8908 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
8909 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
8910 c_write_str(ssh, stuff);
8914 s->got_username = TRUE;
8917 * Send an authentication request using method "none": (a)
8918 * just in case it succeeds, and (b) so that we know what
8919 * authentication methods we can usefully try next.
8921 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8923 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
8924 ssh2_pkt_addstring(s->pktout, ssh->username);
8925 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
8926 ssh2_pkt_addstring(s->pktout, "none"); /* method */
8927 ssh2_pkt_send(ssh, s->pktout);
8928 s->type = AUTH_TYPE_NONE;
8930 s->we_are_in = FALSE;
8932 s->tried_pubkey_config = FALSE;
8933 s->kbd_inter_refused = FALSE;
8935 /* Reset agent request state. */
8936 s->done_agent = FALSE;
8937 if (s->agent_response) {
8938 if (s->pkblob_in_agent) {
8939 s->agentp = s->pkblob_in_agent;
8941 s->agentp = s->agent_response + 5 + 4;
8947 char *methods = NULL;
8951 * Wait for the result of the last authentication request.
8954 crWaitUntilV(pktin);
8956 * Now is a convenient point to spew any banner material
8957 * that we've accumulated. (This should ensure that when
8958 * we exit the auth loop, we haven't any left to deal
8962 int size = bufchain_size(&ssh->banner);
8964 * Don't show the banner if we're operating in
8965 * non-verbose non-interactive mode. (It's probably
8966 * a script, which means nobody will read the
8967 * banner _anyway_, and moreover the printing of
8968 * the banner will screw up processing on the
8969 * output of (say) plink.)
8971 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
8972 char *banner = snewn(size, char);
8973 bufchain_fetch(&ssh->banner, banner, size);
8974 c_write_untrusted(ssh, banner, size);
8977 bufchain_clear(&ssh->banner);
8979 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
8980 logevent("Access granted");
8981 s->we_are_in = s->userauth_success = TRUE;
8985 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
8986 bombout(("Strange packet received during authentication: "
8987 "type %d", pktin->type));
8994 * OK, we're now sitting on a USERAUTH_FAILURE message, so
8995 * we can look at the string in it and know what we can
8996 * helpfully try next.
8998 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
8999 ssh_pkt_getstring(pktin, &methods, &methlen);
9000 if (!ssh2_pkt_getbool(pktin)) {
9002 * We have received an unequivocal Access
9003 * Denied. This can translate to a variety of
9004 * messages, or no message at all.
9006 * For forms of authentication which are attempted
9007 * implicitly, by which I mean without printing
9008 * anything in the window indicating that we're
9009 * trying them, we should never print 'Access
9012 * If we do print a message saying that we're
9013 * attempting some kind of authentication, it's OK
9014 * to print a followup message saying it failed -
9015 * but the message may sometimes be more specific
9016 * than simply 'Access denied'.
9018 * Additionally, if we'd just tried password
9019 * authentication, we should break out of this
9020 * whole loop so as to go back to the username
9021 * prompt (iff we're configured to allow
9022 * username change attempts).
9024 if (s->type == AUTH_TYPE_NONE) {
9026 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9027 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9028 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9029 c_write_str(ssh, "Server refused our key\r\n");
9030 logevent("Server refused our key");
9031 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9032 /* This _shouldn't_ happen except by a
9033 * protocol bug causing client and server to
9034 * disagree on what is a correct signature. */
9035 c_write_str(ssh, "Server refused public-key signature"
9036 " despite accepting key!\r\n");
9037 logevent("Server refused public-key signature"
9038 " despite accepting key!");
9039 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9040 /* quiet, so no c_write */
9041 logevent("Server refused keyboard-interactive authentication");
9042 } else if (s->type==AUTH_TYPE_GSSAPI) {
9043 /* always quiet, so no c_write */
9044 /* also, the code down in the GSSAPI block has
9045 * already logged this in the Event Log */
9046 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9047 logevent("Keyboard-interactive authentication failed");
9048 c_write_str(ssh, "Access denied\r\n");
9050 assert(s->type == AUTH_TYPE_PASSWORD);
9051 logevent("Password authentication failed");
9052 c_write_str(ssh, "Access denied\r\n");
9054 if (conf_get_int(ssh->conf, CONF_change_username)) {
9055 /* XXX perhaps we should allow
9056 * keyboard-interactive to do this too? */
9057 s->we_are_in = FALSE;
9062 c_write_str(ssh, "Further authentication required\r\n");
9063 logevent("Further authentication required");
9067 in_commasep_string("publickey", methods, methlen);
9069 in_commasep_string("password", methods, methlen);
9070 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9071 in_commasep_string("keyboard-interactive", methods, methlen);
9074 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9075 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9076 in_commasep_string("gssapi-with-mic", methods, methlen) &&
9077 ssh->gsslibs->nlibraries > 0;
9081 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9083 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9086 * Attempt public-key authentication using a key from Pageant.
9089 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9091 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9093 /* Unpack key from agent response */
9094 s->pklen = toint(GET_32BIT(s->agentp));
9096 s->pkblob = (char *)s->agentp;
9097 s->agentp += s->pklen;
9098 s->alglen = toint(GET_32BIT(s->pkblob));
9099 s->alg = s->pkblob + 4;
9100 s->commentlen = toint(GET_32BIT(s->agentp));
9102 s->commentp = (char *)s->agentp;
9103 s->agentp += s->commentlen;
9104 /* s->agentp now points at next key, if any */
9106 /* See if server will accept it */
9107 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9108 ssh2_pkt_addstring(s->pktout, ssh->username);
9109 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9110 /* service requested */
9111 ssh2_pkt_addstring(s->pktout, "publickey");
9113 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9114 ssh2_pkt_addstring_start(s->pktout);
9115 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9116 ssh2_pkt_addstring_start(s->pktout);
9117 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9118 ssh2_pkt_send(ssh, s->pktout);
9119 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9121 crWaitUntilV(pktin);
9122 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9124 /* Offer of key refused. */
9131 if (flags & FLAG_VERBOSE) {
9132 c_write_str(ssh, "Authenticating with "
9134 c_write(ssh, s->commentp, s->commentlen);
9135 c_write_str(ssh, "\" from agent\r\n");
9139 * Server is willing to accept the key.
9140 * Construct a SIGN_REQUEST.
9142 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9143 ssh2_pkt_addstring(s->pktout, ssh->username);
9144 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9145 /* service requested */
9146 ssh2_pkt_addstring(s->pktout, "publickey");
9148 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9149 ssh2_pkt_addstring_start(s->pktout);
9150 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9151 ssh2_pkt_addstring_start(s->pktout);
9152 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9154 /* Ask agent for signature. */
9155 s->siglen = s->pktout->length - 5 + 4 +
9156 ssh->v2_session_id_len;
9157 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9159 s->len = 1; /* message type */
9160 s->len += 4 + s->pklen; /* key blob */
9161 s->len += 4 + s->siglen; /* data to sign */
9162 s->len += 4; /* flags */
9163 s->agentreq = snewn(4 + s->len, char);
9164 PUT_32BIT(s->agentreq, s->len);
9165 s->q = s->agentreq + 4;
9166 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9167 PUT_32BIT(s->q, s->pklen);
9169 memcpy(s->q, s->pkblob, s->pklen);
9171 PUT_32BIT(s->q, s->siglen);
9173 /* Now the data to be signed... */
9174 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9175 PUT_32BIT(s->q, ssh->v2_session_id_len);
9178 memcpy(s->q, ssh->v2_session_id,
9179 ssh->v2_session_id_len);
9180 s->q += ssh->v2_session_id_len;
9181 memcpy(s->q, s->pktout->data + 5,
9182 s->pktout->length - 5);
9183 s->q += s->pktout->length - 5;
9184 /* And finally the (zero) flags word. */
9186 if (!agent_query(s->agentreq, s->len + 4,
9188 ssh_agent_callback, ssh)) {
9192 bombout(("Unexpected data from server"
9193 " while waiting for agent"
9197 } while (pktin || inlen > 0);
9198 vret = ssh->agent_response;
9199 s->retlen = ssh->agent_response_len;
9204 if (s->retlen >= 9 &&
9205 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9206 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9207 logevent("Sending Pageant's response");
9208 ssh2_add_sigblob(ssh, s->pktout,
9209 s->pkblob, s->pklen,
9211 GET_32BIT(s->ret + 5));
9212 ssh2_pkt_send(ssh, s->pktout);
9213 s->type = AUTH_TYPE_PUBLICKEY;
9215 /* FIXME: less drastic response */
9216 bombout(("Pageant failed to answer challenge"));
9222 /* Do we have any keys left to try? */
9223 if (s->pkblob_in_agent) {
9224 s->done_agent = TRUE;
9225 s->tried_pubkey_config = TRUE;
9228 if (s->keyi >= s->nkeys)
9229 s->done_agent = TRUE;
9232 } else if (s->can_pubkey && s->publickey_blob &&
9233 !s->tried_pubkey_config) {
9235 struct ssh2_userkey *key; /* not live over crReturn */
9236 char *passphrase; /* not live over crReturn */
9238 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9240 s->tried_pubkey_config = TRUE;
9243 * Try the public key supplied in the configuration.
9245 * First, offer the public blob to see if the server is
9246 * willing to accept it.
9248 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9249 ssh2_pkt_addstring(s->pktout, ssh->username);
9250 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9251 /* service requested */
9252 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9253 ssh2_pkt_addbool(s->pktout, FALSE);
9254 /* no signature included */
9255 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9256 ssh2_pkt_addstring_start(s->pktout);
9257 ssh2_pkt_addstring_data(s->pktout,
9258 (char *)s->publickey_blob,
9259 s->publickey_bloblen);
9260 ssh2_pkt_send(ssh, s->pktout);
9261 logevent("Offered public key");
9263 crWaitUntilV(pktin);
9264 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9265 /* Key refused. Give up. */
9266 s->gotit = TRUE; /* reconsider message next loop */
9267 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9268 continue; /* process this new message */
9270 logevent("Offer of public key accepted");
9273 * Actually attempt a serious authentication using
9276 if (flags & FLAG_VERBOSE) {
9277 c_write_str(ssh, "Authenticating with public key \"");
9278 c_write_str(ssh, s->publickey_comment);
9279 c_write_str(ssh, "\"\r\n");
9283 const char *error; /* not live over crReturn */
9284 if (s->publickey_encrypted) {
9286 * Get a passphrase from the user.
9288 int ret; /* need not be kept over crReturn */
9289 s->cur_prompt = new_prompts(ssh->frontend);
9290 s->cur_prompt->to_server = FALSE;
9291 s->cur_prompt->name = dupstr("SSH key passphrase");
9292 add_prompt(s->cur_prompt,
9293 dupprintf("Passphrase for key \"%.100s\": ",
9294 s->publickey_comment),
9296 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9299 crWaitUntilV(!pktin);
9300 ret = get_userpass_input(s->cur_prompt,
9305 /* Failed to get a passphrase. Terminate. */
9306 free_prompts(s->cur_prompt);
9307 ssh_disconnect(ssh, NULL,
9308 "Unable to authenticate",
9309 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9314 dupstr(s->cur_prompt->prompts[0]->result);
9315 free_prompts(s->cur_prompt);
9317 passphrase = NULL; /* no passphrase needed */
9321 * Try decrypting the key.
9323 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9324 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9326 /* burn the evidence */
9327 smemclr(passphrase, strlen(passphrase));
9330 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9332 (key == SSH2_WRONG_PASSPHRASE)) {
9333 c_write_str(ssh, "Wrong passphrase\r\n");
9335 /* and loop again */
9337 c_write_str(ssh, "Unable to load private key (");
9338 c_write_str(ssh, error);
9339 c_write_str(ssh, ")\r\n");
9341 break; /* try something else */
9347 unsigned char *pkblob, *sigblob, *sigdata;
9348 int pkblob_len, sigblob_len, sigdata_len;
9352 * We have loaded the private key and the server
9353 * has announced that it's willing to accept it.
9354 * Hallelujah. Generate a signature and send it.
9356 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9357 ssh2_pkt_addstring(s->pktout, ssh->username);
9358 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9359 /* service requested */
9360 ssh2_pkt_addstring(s->pktout, "publickey");
9362 ssh2_pkt_addbool(s->pktout, TRUE);
9363 /* signature follows */
9364 ssh2_pkt_addstring(s->pktout, key->alg->name);
9365 pkblob = key->alg->public_blob(key->data,
9367 ssh2_pkt_addstring_start(s->pktout);
9368 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9372 * The data to be signed is:
9376 * followed by everything so far placed in the
9379 sigdata_len = s->pktout->length - 5 + 4 +
9380 ssh->v2_session_id_len;
9381 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9383 sigdata = snewn(sigdata_len, unsigned char);
9385 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9386 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9389 memcpy(sigdata+p, ssh->v2_session_id,
9390 ssh->v2_session_id_len);
9391 p += ssh->v2_session_id_len;
9392 memcpy(sigdata+p, s->pktout->data + 5,
9393 s->pktout->length - 5);
9394 p += s->pktout->length - 5;
9395 assert(p == sigdata_len);
9396 sigblob = key->alg->sign(key->data, (char *)sigdata,
9397 sigdata_len, &sigblob_len);
9398 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9399 sigblob, sigblob_len);
9404 ssh2_pkt_send(ssh, s->pktout);
9405 logevent("Sent public key signature");
9406 s->type = AUTH_TYPE_PUBLICKEY;
9407 key->alg->freekey(key->data);
9411 } else if (s->can_gssapi && !s->tried_gssapi) {
9413 /* GSSAPI Authentication */
9418 s->type = AUTH_TYPE_GSSAPI;
9419 s->tried_gssapi = TRUE;
9421 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9424 * Pick the highest GSS library on the preference
9430 for (i = 0; i < ngsslibs; i++) {
9431 int want_id = conf_get_int_int(ssh->conf,
9432 CONF_ssh_gsslist, i);
9433 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
9434 if (ssh->gsslibs->libraries[j].id == want_id) {
9435 s->gsslib = &ssh->gsslibs->libraries[j];
9436 goto got_gsslib; /* double break */
9441 * We always expect to have found something in
9442 * the above loop: we only came here if there
9443 * was at least one viable GSS library, and the
9444 * preference list should always mention
9445 * everything and only change the order.
9450 if (s->gsslib->gsslogmsg)
9451 logevent(s->gsslib->gsslogmsg);
9453 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
9454 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9455 ssh2_pkt_addstring(s->pktout, ssh->username);
9456 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9457 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
9458 logevent("Attempting GSSAPI authentication");
9460 /* add mechanism info */
9461 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
9463 /* number of GSSAPI mechanisms */
9464 ssh2_pkt_adduint32(s->pktout,1);
9466 /* length of OID + 2 */
9467 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
9468 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
9471 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
9473 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
9475 ssh2_pkt_send(ssh, s->pktout);
9476 crWaitUntilV(pktin);
9477 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
9478 logevent("GSSAPI authentication request refused");
9482 /* check returned packet ... */
9484 ssh_pkt_getstring(pktin, &data, &len);
9485 s->gss_rcvtok.value = data;
9486 s->gss_rcvtok.length = len;
9487 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
9488 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
9489 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
9490 memcmp((char *)s->gss_rcvtok.value + 2,
9491 s->gss_buf.value,s->gss_buf.length) ) {
9492 logevent("GSSAPI authentication - wrong response from server");
9496 /* now start running */
9497 s->gss_stat = s->gsslib->import_name(s->gsslib,
9500 if (s->gss_stat != SSH_GSS_OK) {
9501 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
9502 logevent("GSSAPI import name failed - Bad service name");
9504 logevent("GSSAPI import name failed");
9508 /* fetch TGT into GSS engine */
9509 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
9511 if (s->gss_stat != SSH_GSS_OK) {
9512 logevent("GSSAPI authentication failed to get credentials");
9513 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9517 /* initial tokens are empty */
9518 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
9519 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
9521 /* now enter the loop */
9523 s->gss_stat = s->gsslib->init_sec_context
9527 conf_get_int(ssh->conf, CONF_gssapifwd),
9531 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
9532 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
9533 logevent("GSSAPI authentication initialisation failed");
9535 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
9536 &s->gss_buf) == SSH_GSS_OK) {
9537 logevent(s->gss_buf.value);
9538 sfree(s->gss_buf.value);
9543 logevent("GSSAPI authentication initialised");
9545 /* Client and server now exchange tokens until GSSAPI
9546 * no longer says CONTINUE_NEEDED */
9548 if (s->gss_sndtok.length != 0) {
9549 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
9550 ssh_pkt_addstring_start(s->pktout);
9551 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
9552 ssh2_pkt_send(ssh, s->pktout);
9553 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
9556 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
9557 crWaitUntilV(pktin);
9558 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
9559 logevent("GSSAPI authentication - bad server response");
9560 s->gss_stat = SSH_GSS_FAILURE;
9563 ssh_pkt_getstring(pktin, &data, &len);
9564 s->gss_rcvtok.value = data;
9565 s->gss_rcvtok.length = len;
9567 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
9569 if (s->gss_stat != SSH_GSS_OK) {
9570 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9571 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9574 logevent("GSSAPI authentication loop finished OK");
9576 /* Now send the MIC */
9578 s->pktout = ssh2_pkt_init(0);
9579 micoffset = s->pktout->length;
9580 ssh_pkt_addstring_start(s->pktout);
9581 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
9582 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
9583 ssh_pkt_addstring(s->pktout, ssh->username);
9584 ssh_pkt_addstring(s->pktout, "ssh-connection");
9585 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
9587 s->gss_buf.value = (char *)s->pktout->data + micoffset;
9588 s->gss_buf.length = s->pktout->length - micoffset;
9590 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
9591 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
9592 ssh_pkt_addstring_start(s->pktout);
9593 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
9594 ssh2_pkt_send(ssh, s->pktout);
9595 s->gsslib->free_mic(s->gsslib, &mic);
9599 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9600 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9603 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
9606 * Keyboard-interactive authentication.
9609 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
9611 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
9613 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9614 ssh2_pkt_addstring(s->pktout, ssh->username);
9615 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9616 /* service requested */
9617 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
9619 ssh2_pkt_addstring(s->pktout, ""); /* lang */
9620 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
9621 ssh2_pkt_send(ssh, s->pktout);
9623 logevent("Attempting keyboard-interactive authentication");
9625 crWaitUntilV(pktin);
9626 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
9627 /* Server is not willing to do keyboard-interactive
9628 * at all (or, bizarrely but legally, accepts the
9629 * user without actually issuing any prompts).
9630 * Give up on it entirely. */
9632 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
9633 s->kbd_inter_refused = TRUE; /* don't try it again */
9638 * Loop while the server continues to send INFO_REQUESTs.
9640 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
9642 char *name, *inst, *lang;
9643 int name_len, inst_len, lang_len;
9647 * We've got a fresh USERAUTH_INFO_REQUEST.
9648 * Get the preamble and start building a prompt.
9650 ssh_pkt_getstring(pktin, &name, &name_len);
9651 ssh_pkt_getstring(pktin, &inst, &inst_len);
9652 ssh_pkt_getstring(pktin, &lang, &lang_len);
9653 s->cur_prompt = new_prompts(ssh->frontend);
9654 s->cur_prompt->to_server = TRUE;
9657 * Get any prompt(s) from the packet.
9659 s->num_prompts = ssh_pkt_getuint32(pktin);
9660 for (i = 0; i < s->num_prompts; i++) {
9664 static char noprompt[] =
9665 "<server failed to send prompt>: ";
9667 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9668 echo = ssh2_pkt_getbool(pktin);
9671 prompt_len = lenof(noprompt)-1;
9673 add_prompt(s->cur_prompt,
9674 dupprintf("%.*s", prompt_len, prompt),
9679 /* FIXME: better prefix to distinguish from
9681 s->cur_prompt->name =
9682 dupprintf("SSH server: %.*s", name_len, name);
9683 s->cur_prompt->name_reqd = TRUE;
9685 s->cur_prompt->name =
9686 dupstr("SSH server authentication");
9687 s->cur_prompt->name_reqd = FALSE;
9689 /* We add a prefix to try to make it clear that a prompt
9690 * has come from the server.
9691 * FIXME: ugly to print "Using..." in prompt _every_
9692 * time round. Can this be done more subtly? */
9693 /* Special case: for reasons best known to themselves,
9694 * some servers send k-i requests with no prompts and
9695 * nothing to display. Keep quiet in this case. */
9696 if (s->num_prompts || name_len || inst_len) {
9697 s->cur_prompt->instruction =
9698 dupprintf("Using keyboard-interactive authentication.%s%.*s",
9699 inst_len ? "\n" : "", inst_len, inst);
9700 s->cur_prompt->instr_reqd = TRUE;
9702 s->cur_prompt->instr_reqd = FALSE;
9706 * Display any instructions, and get the user's
9710 int ret; /* not live over crReturn */
9711 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9714 crWaitUntilV(!pktin);
9715 ret = get_userpass_input(s->cur_prompt, in, inlen);
9720 * Failed to get responses. Terminate.
9722 free_prompts(s->cur_prompt);
9723 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9724 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9731 * Send the response(s) to the server.
9733 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
9734 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
9735 for (i=0; i < s->num_prompts; i++) {
9736 ssh2_pkt_addstring(s->pktout,
9737 s->cur_prompt->prompts[i]->result);
9739 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9742 * Free the prompts structure from this iteration.
9743 * If there's another, a new one will be allocated
9744 * when we return to the top of this while loop.
9746 free_prompts(s->cur_prompt);
9749 * Get the next packet in case it's another
9752 crWaitUntilV(pktin);
9757 * We should have SUCCESS or FAILURE now.
9761 } else if (s->can_passwd) {
9764 * Plain old password authentication.
9766 int ret; /* not live over crReturn */
9767 int changereq_first_time; /* not live over crReturn */
9769 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
9771 s->cur_prompt = new_prompts(ssh->frontend);
9772 s->cur_prompt->to_server = TRUE;
9773 s->cur_prompt->name = dupstr("SSH password");
9774 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
9779 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9782 crWaitUntilV(!pktin);
9783 ret = get_userpass_input(s->cur_prompt, in, inlen);
9788 * Failed to get responses. Terminate.
9790 free_prompts(s->cur_prompt);
9791 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9792 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9797 * Squirrel away the password. (We may need it later if
9798 * asked to change it.)
9800 s->password = dupstr(s->cur_prompt->prompts[0]->result);
9801 free_prompts(s->cur_prompt);
9804 * Send the password packet.
9806 * We pad out the password packet to 256 bytes to make
9807 * it harder for an attacker to find the length of the
9810 * Anyone using a password longer than 256 bytes
9811 * probably doesn't have much to worry about from
9812 * people who find out how long their password is!
9814 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9815 ssh2_pkt_addstring(s->pktout, ssh->username);
9816 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9817 /* service requested */
9818 ssh2_pkt_addstring(s->pktout, "password");
9819 ssh2_pkt_addbool(s->pktout, FALSE);
9820 ssh2_pkt_addstring(s->pktout, s->password);
9821 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9822 logevent("Sent password");
9823 s->type = AUTH_TYPE_PASSWORD;
9826 * Wait for next packet, in case it's a password change
9829 crWaitUntilV(pktin);
9830 changereq_first_time = TRUE;
9832 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
9835 * We're being asked for a new password
9836 * (perhaps not for the first time).
9837 * Loop until the server accepts it.
9840 int got_new = FALSE; /* not live over crReturn */
9841 char *prompt; /* not live over crReturn */
9842 int prompt_len; /* not live over crReturn */
9846 if (changereq_first_time)
9847 msg = "Server requested password change";
9849 msg = "Server rejected new password";
9851 c_write_str(ssh, msg);
9852 c_write_str(ssh, "\r\n");
9855 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9857 s->cur_prompt = new_prompts(ssh->frontend);
9858 s->cur_prompt->to_server = TRUE;
9859 s->cur_prompt->name = dupstr("New SSH password");
9860 s->cur_prompt->instruction =
9861 dupprintf("%.*s", prompt_len, prompt);
9862 s->cur_prompt->instr_reqd = TRUE;
9864 * There's no explicit requirement in the protocol
9865 * for the "old" passwords in the original and
9866 * password-change messages to be the same, and
9867 * apparently some Cisco kit supports password change
9868 * by the user entering a blank password originally
9869 * and the real password subsequently, so,
9870 * reluctantly, we prompt for the old password again.
9872 * (On the other hand, some servers don't even bother
9873 * to check this field.)
9875 add_prompt(s->cur_prompt,
9876 dupstr("Current password (blank for previously entered password): "),
9878 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
9880 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
9884 * Loop until the user manages to enter the same
9889 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9892 crWaitUntilV(!pktin);
9893 ret = get_userpass_input(s->cur_prompt, in, inlen);
9898 * Failed to get responses. Terminate.
9900 /* burn the evidence */
9901 free_prompts(s->cur_prompt);
9902 smemclr(s->password, strlen(s->password));
9904 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9905 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9911 * If the user specified a new original password
9912 * (IYSWIM), overwrite any previously specified
9914 * (A side effect is that the user doesn't have to
9915 * re-enter it if they louse up the new password.)
9917 if (s->cur_prompt->prompts[0]->result[0]) {
9918 smemclr(s->password, strlen(s->password));
9919 /* burn the evidence */
9922 dupstr(s->cur_prompt->prompts[0]->result);
9926 * Check the two new passwords match.
9928 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
9929 s->cur_prompt->prompts[2]->result)
9932 /* They don't. Silly user. */
9933 c_write_str(ssh, "Passwords do not match\r\n");
9938 * Send the new password (along with the old one).
9939 * (see above for padding rationale)
9941 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9942 ssh2_pkt_addstring(s->pktout, ssh->username);
9943 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9944 /* service requested */
9945 ssh2_pkt_addstring(s->pktout, "password");
9946 ssh2_pkt_addbool(s->pktout, TRUE);
9947 ssh2_pkt_addstring(s->pktout, s->password);
9948 ssh2_pkt_addstring(s->pktout,
9949 s->cur_prompt->prompts[1]->result);
9950 free_prompts(s->cur_prompt);
9951 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9952 logevent("Sent new password");
9955 * Now see what the server has to say about it.
9956 * (If it's CHANGEREQ again, it's not happy with the
9959 crWaitUntilV(pktin);
9960 changereq_first_time = FALSE;
9965 * We need to reexamine the current pktin at the top
9966 * of the loop. Either:
9967 * - we weren't asked to change password at all, in
9968 * which case it's a SUCCESS or FAILURE with the
9970 * - we sent a new password, and the server was
9971 * either OK with it (SUCCESS or FAILURE w/partial
9972 * success) or unhappy with the _old_ password
9973 * (FAILURE w/o partial success)
9974 * In any of these cases, we go back to the top of
9975 * the loop and start again.
9980 * We don't need the old password any more, in any
9981 * case. Burn the evidence.
9983 smemclr(s->password, strlen(s->password));
9987 char *str = dupprintf("No supported authentication methods available"
9988 " (server sent: %.*s)",
9991 ssh_disconnect(ssh, str,
9992 "No supported authentication methods available",
9993 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10003 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10005 /* Clear up various bits and pieces from authentication. */
10006 if (s->publickey_blob) {
10007 sfree(s->publickey_blob);
10008 sfree(s->publickey_comment);
10010 if (s->agent_response)
10011 sfree(s->agent_response);
10013 if (s->userauth_success && !ssh->bare_connection) {
10015 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10016 * packets since. Signal the transport layer to consider enacting
10017 * delayed compression.
10019 * (Relying on we_are_in is not sufficient, as
10020 * draft-miller-secsh-compression-delayed is quite clear that it
10021 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10022 * become set for other reasons.)
10024 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10027 ssh->channels = newtree234(ssh_channelcmp);
10030 * Set up handlers for some connection protocol messages, so we
10031 * don't have to handle them repeatedly in this coroutine.
10033 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10034 ssh2_msg_channel_window_adjust;
10035 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10036 ssh2_msg_global_request;
10039 * Create the main session channel.
10041 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10042 ssh->mainchan = NULL;
10044 ssh->mainchan = snew(struct ssh_channel);
10045 ssh->mainchan->ssh = ssh;
10046 ssh2_channel_init(ssh->mainchan);
10048 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10050 * Just start a direct-tcpip channel and use it as the main
10053 ssh_send_port_open(ssh->mainchan,
10054 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10055 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10057 ssh->ncmode = TRUE;
10059 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10060 logevent("Opening session as main channel");
10061 ssh2_pkt_send(ssh, s->pktout);
10062 ssh->ncmode = FALSE;
10064 crWaitUntilV(pktin);
10065 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10066 bombout(("Server refused to open channel"));
10068 /* FIXME: error data comes back in FAILURE packet */
10070 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10071 bombout(("Server's channel confirmation cited wrong channel"));
10074 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10075 ssh->mainchan->halfopen = FALSE;
10076 ssh->mainchan->type = CHAN_MAINSESSION;
10077 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10078 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10079 add234(ssh->channels, ssh->mainchan);
10080 update_specials_menu(ssh->frontend);
10081 logevent("Opened main channel");
10085 * Now we have a channel, make dispatch table entries for
10086 * general channel-based messages.
10088 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10089 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10090 ssh2_msg_channel_data;
10091 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10092 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10093 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10094 ssh2_msg_channel_open_confirmation;
10095 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10096 ssh2_msg_channel_open_failure;
10097 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10098 ssh2_msg_channel_request;
10099 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10100 ssh2_msg_channel_open;
10101 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10102 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10105 * Now the connection protocol is properly up and running, with
10106 * all those dispatch table entries, so it's safe to let
10107 * downstreams start trying to open extra channels through us.
10109 if (ssh->connshare)
10110 share_activate(ssh->connshare, ssh->v_s);
10112 if (ssh->mainchan && ssh_is_simple(ssh)) {
10114 * This message indicates to the server that we promise
10115 * not to try to run any other channel in parallel with
10116 * this one, so it's safe for it to advertise a very large
10117 * window and leave the flow control to TCP.
10119 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10120 "simple@putty.projects.tartarus.org",
10122 ssh2_pkt_send(ssh, s->pktout);
10126 * Enable port forwardings.
10128 ssh_setup_portfwd(ssh, ssh->conf);
10130 if (ssh->mainchan && !ssh->ncmode) {
10132 * Send the CHANNEL_REQUESTS for the main session channel.
10133 * Each one is handled by its own little asynchronous
10137 /* Potentially enable X11 forwarding. */
10138 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10140 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10142 if (!ssh->x11disp) {
10143 /* FIXME: return an error message from x11_setup_display */
10144 logevent("X11 forwarding not enabled: unable to"
10145 " initialise X display");
10147 ssh->x11auth = x11_invent_fake_auth
10148 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10149 ssh->x11auth->disp = ssh->x11disp;
10151 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10155 /* Potentially enable agent forwarding. */
10156 if (ssh_agent_forwarding_permitted(ssh))
10157 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10159 /* Now allocate a pty for the session. */
10160 if (!conf_get_int(ssh->conf, CONF_nopty))
10161 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10163 /* Send environment variables. */
10164 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10167 * Start a shell or a remote command. We may have to attempt
10168 * this twice if the config data has provided a second choice
10175 if (ssh->fallback_cmd) {
10176 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10177 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10179 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10180 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10184 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10185 ssh2_response_authconn, NULL);
10186 ssh2_pkt_addstring(s->pktout, cmd);
10188 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10189 ssh2_response_authconn, NULL);
10190 ssh2_pkt_addstring(s->pktout, cmd);
10192 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10193 ssh2_response_authconn, NULL);
10195 ssh2_pkt_send(ssh, s->pktout);
10197 crWaitUntilV(pktin);
10199 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10200 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10201 bombout(("Unexpected response to shell/command request:"
10202 " packet type %d", pktin->type));
10206 * We failed to start the command. If this is the
10207 * fallback command, we really are finished; if it's
10208 * not, and if the fallback command exists, try falling
10209 * back to it before complaining.
10211 if (!ssh->fallback_cmd &&
10212 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10213 logevent("Primary command failed; attempting fallback");
10214 ssh->fallback_cmd = TRUE;
10217 bombout(("Server refused to start a shell/command"));
10220 logevent("Started a shell/command");
10225 ssh->editing = ssh->echoing = TRUE;
10228 ssh->state = SSH_STATE_SESSION;
10229 if (ssh->size_needed)
10230 ssh_size(ssh, ssh->term_width, ssh->term_height);
10231 if (ssh->eof_needed)
10232 ssh_special(ssh, TS_EOF);
10238 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
10243 s->try_send = FALSE;
10247 * _All_ the connection-layer packets we expect to
10248 * receive are now handled by the dispatch table.
10249 * Anything that reaches here must be bogus.
10252 bombout(("Strange packet received: type %d", pktin->type));
10254 } else if (ssh->mainchan) {
10256 * We have spare data. Add it to the channel buffer.
10258 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
10259 s->try_send = TRUE;
10263 struct ssh_channel *c;
10265 * Try to send data on all channels if we can.
10267 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
10268 ssh2_try_send_and_unthrottle(ssh, c);
10276 * Handlers for SSH-2 messages that might arrive at any moment.
10278 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10280 /* log reason code in disconnect message */
10282 int reason, msglen;
10284 reason = ssh_pkt_getuint32(pktin);
10285 ssh_pkt_getstring(pktin, &msg, &msglen);
10287 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10288 buf = dupprintf("Received disconnect message (%s)",
10289 ssh2_disconnect_reasons[reason]);
10291 buf = dupprintf("Received disconnect message (unknown"
10292 " type %d)", reason);
10296 buf = dupprintf("Disconnection message text: %.*s",
10299 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10301 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10302 ssh2_disconnect_reasons[reason] : "unknown",
10307 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10309 /* log the debug message */
10313 /* XXX maybe we should actually take notice of the return value */
10314 ssh2_pkt_getbool(pktin);
10315 ssh_pkt_getstring(pktin, &msg, &msglen);
10317 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
10320 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10322 do_ssh2_transport(ssh, NULL, 0, pktin);
10326 * Called if we receive a packet that isn't allowed by the protocol.
10327 * This only applies to packets whose meaning PuTTY understands.
10328 * Entirely unknown packets are handled below.
10330 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10332 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10333 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10335 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10339 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10341 struct Packet *pktout;
10342 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10343 ssh2_pkt_adduint32(pktout, pktin->sequence);
10345 * UNIMPLEMENTED messages MUST appear in the same order as the
10346 * messages they respond to. Hence, never queue them.
10348 ssh2_pkt_send_noqueue(ssh, pktout);
10352 * Handle the top-level SSH-2 protocol.
10354 static void ssh2_protocol_setup(Ssh ssh)
10359 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10361 for (i = 0; i < 256; i++)
10362 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10365 * Initially, we only accept transport messages (and a few generic
10366 * ones). do_ssh2_authconn will add more when it starts.
10367 * Messages that are understood but not currently acceptable go to
10368 * ssh2_msg_unexpected.
10370 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10371 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10372 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10373 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10374 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10375 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10376 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10377 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10378 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10379 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10380 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10381 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10382 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10383 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10384 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10385 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10386 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10387 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10388 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10389 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10390 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10391 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10392 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10393 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10394 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10395 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10396 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10397 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10398 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10399 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10400 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10401 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10402 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10405 * These messages have a special handler from the start.
10407 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10408 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10409 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10412 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10417 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10419 for (i = 0; i < 256; i++)
10420 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10423 * Initially, we set all ssh-connection messages to 'unexpected';
10424 * do_ssh2_authconn will fill things in properly. We also handle a
10425 * couple of messages from the transport protocol which aren't
10426 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10429 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10430 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10431 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10432 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10433 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10434 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10435 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10436 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10437 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10438 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10439 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10440 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10441 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10442 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10444 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10447 * These messages have a special handler from the start.
10449 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10450 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
10451 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10454 static void ssh2_timer(void *ctx, unsigned long now)
10456 Ssh ssh = (Ssh)ctx;
10458 if (ssh->state == SSH_STATE_CLOSED)
10461 if (!ssh->kex_in_progress && !ssh->bare_connection &&
10462 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
10463 now == ssh->next_rekey) {
10464 do_ssh2_transport(ssh, "timeout", -1, NULL);
10468 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
10469 struct Packet *pktin)
10471 unsigned char *in = (unsigned char *)vin;
10472 if (ssh->state == SSH_STATE_CLOSED)
10476 ssh->incoming_data_size += pktin->encrypted_len;
10477 if (!ssh->kex_in_progress &&
10478 ssh->max_data_size != 0 &&
10479 ssh->incoming_data_size > ssh->max_data_size)
10480 do_ssh2_transport(ssh, "too much data received", -1, NULL);
10484 ssh->packet_dispatch[pktin->type](ssh, pktin);
10485 else if (!ssh->protocol_initial_phase_done)
10486 do_ssh2_transport(ssh, in, inlen, pktin);
10488 do_ssh2_authconn(ssh, in, inlen, pktin);
10491 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
10492 struct Packet *pktin)
10494 unsigned char *in = (unsigned char *)vin;
10495 if (ssh->state == SSH_STATE_CLOSED)
10499 ssh->packet_dispatch[pktin->type](ssh, pktin);
10501 do_ssh2_authconn(ssh, in, inlen, pktin);
10504 static void ssh_cache_conf_values(Ssh ssh)
10506 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
10510 * Called to set up the connection.
10512 * Returns an error message, or NULL on success.
10514 static const char *ssh_init(void *frontend_handle, void **backend_handle,
10515 Conf *conf, char *host, int port, char **realhost,
10516 int nodelay, int keepalive)
10521 ssh = snew(struct ssh_tag);
10522 ssh->conf = conf_copy(conf);
10523 ssh_cache_conf_values(ssh);
10524 ssh->version = 0; /* when not ready yet */
10526 ssh->cipher = NULL;
10527 ssh->v1_cipher_ctx = NULL;
10528 ssh->crcda_ctx = NULL;
10529 ssh->cscipher = NULL;
10530 ssh->cs_cipher_ctx = NULL;
10531 ssh->sccipher = NULL;
10532 ssh->sc_cipher_ctx = NULL;
10534 ssh->cs_mac_ctx = NULL;
10536 ssh->sc_mac_ctx = NULL;
10537 ssh->cscomp = NULL;
10538 ssh->cs_comp_ctx = NULL;
10539 ssh->sccomp = NULL;
10540 ssh->sc_comp_ctx = NULL;
10542 ssh->kex_ctx = NULL;
10543 ssh->hostkey = NULL;
10544 ssh->hostkey_str = NULL;
10545 ssh->exitcode = -1;
10546 ssh->close_expected = FALSE;
10547 ssh->clean_exit = FALSE;
10548 ssh->state = SSH_STATE_PREPACKET;
10549 ssh->size_needed = FALSE;
10550 ssh->eof_needed = FALSE;
10552 ssh->logctx = NULL;
10553 ssh->deferred_send_data = NULL;
10554 ssh->deferred_len = 0;
10555 ssh->deferred_size = 0;
10556 ssh->fallback_cmd = 0;
10557 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
10558 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
10559 ssh->x11disp = NULL;
10560 ssh->x11auth = NULL;
10561 ssh->x11authtree = newtree234(x11_authcmp);
10562 ssh->v1_compressing = FALSE;
10563 ssh->v2_outgoing_sequence = 0;
10564 ssh->ssh1_rdpkt_crstate = 0;
10565 ssh->ssh2_rdpkt_crstate = 0;
10566 ssh->ssh2_bare_rdpkt_crstate = 0;
10567 ssh->ssh_gotdata_crstate = 0;
10568 ssh->do_ssh1_connection_crstate = 0;
10569 ssh->do_ssh_init_state = NULL;
10570 ssh->do_ssh_connection_init_state = NULL;
10571 ssh->do_ssh1_login_state = NULL;
10572 ssh->do_ssh2_transport_state = NULL;
10573 ssh->do_ssh2_authconn_state = NULL;
10576 ssh->mainchan = NULL;
10577 ssh->throttled_all = 0;
10578 ssh->v1_stdout_throttling = 0;
10580 ssh->queuelen = ssh->queuesize = 0;
10581 ssh->queueing = FALSE;
10582 ssh->qhead = ssh->qtail = NULL;
10583 ssh->deferred_rekey_reason = NULL;
10584 bufchain_init(&ssh->queued_incoming_data);
10585 ssh->frozen = FALSE;
10586 ssh->username = NULL;
10587 ssh->sent_console_eof = FALSE;
10588 ssh->got_pty = FALSE;
10589 ssh->bare_connection = FALSE;
10590 ssh->attempting_connshare = FALSE;
10592 *backend_handle = ssh;
10595 if (crypto_startup() == 0)
10596 return "Microsoft high encryption pack not installed!";
10599 ssh->frontend = frontend_handle;
10600 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
10601 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
10603 ssh->channels = NULL;
10604 ssh->rportfwds = NULL;
10605 ssh->portfwds = NULL;
10610 ssh->conn_throttle_count = 0;
10611 ssh->overall_bufsize = 0;
10612 ssh->fallback_cmd = 0;
10614 ssh->protocol = NULL;
10616 ssh->protocol_initial_phase_done = FALSE;
10618 ssh->pinger = NULL;
10620 ssh->incoming_data_size = ssh->outgoing_data_size =
10621 ssh->deferred_data_size = 0L;
10622 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10623 CONF_ssh_rekey_data));
10624 ssh->kex_in_progress = FALSE;
10627 ssh->gsslibs = NULL;
10630 random_ref(); /* do this now - may be needed by sharing setup code */
10632 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
10641 static void ssh_free(void *handle)
10643 Ssh ssh = (Ssh) handle;
10644 struct ssh_channel *c;
10645 struct ssh_rportfwd *pf;
10646 struct X11FakeAuth *auth;
10648 if (ssh->v1_cipher_ctx)
10649 ssh->cipher->free_context(ssh->v1_cipher_ctx);
10650 if (ssh->cs_cipher_ctx)
10651 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
10652 if (ssh->sc_cipher_ctx)
10653 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
10654 if (ssh->cs_mac_ctx)
10655 ssh->csmac->free_context(ssh->cs_mac_ctx);
10656 if (ssh->sc_mac_ctx)
10657 ssh->scmac->free_context(ssh->sc_mac_ctx);
10658 if (ssh->cs_comp_ctx) {
10660 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
10662 zlib_compress_cleanup(ssh->cs_comp_ctx);
10664 if (ssh->sc_comp_ctx) {
10666 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
10668 zlib_decompress_cleanup(ssh->sc_comp_ctx);
10671 dh_cleanup(ssh->kex_ctx);
10672 sfree(ssh->savedhost);
10674 while (ssh->queuelen-- > 0)
10675 ssh_free_packet(ssh->queue[ssh->queuelen]);
10678 while (ssh->qhead) {
10679 struct queued_handler *qh = ssh->qhead;
10680 ssh->qhead = qh->next;
10683 ssh->qhead = ssh->qtail = NULL;
10685 if (ssh->channels) {
10686 while ((c = delpos234(ssh->channels, 0)) != NULL) {
10689 if (c->u.x11.xconn != NULL)
10690 x11_close(c->u.x11.xconn);
10692 case CHAN_SOCKDATA:
10693 case CHAN_SOCKDATA_DORMANT:
10694 if (c->u.pfd.pf != NULL)
10695 pfd_close(c->u.pfd.pf);
10698 if (ssh->version == 2) {
10699 struct outstanding_channel_request *ocr, *nocr;
10700 ocr = c->v.v2.chanreq_head;
10702 ocr->handler(c, NULL, ocr->ctx);
10707 bufchain_clear(&c->v.v2.outbuffer);
10711 freetree234(ssh->channels);
10712 ssh->channels = NULL;
10715 if (ssh->connshare)
10716 sharestate_free(ssh->connshare);
10718 if (ssh->rportfwds) {
10719 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
10721 freetree234(ssh->rportfwds);
10722 ssh->rportfwds = NULL;
10724 sfree(ssh->deferred_send_data);
10726 x11_free_display(ssh->x11disp);
10727 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
10728 x11_free_fake_auth(auth);
10729 freetree234(ssh->x11authtree);
10730 sfree(ssh->do_ssh_init_state);
10731 sfree(ssh->do_ssh1_login_state);
10732 sfree(ssh->do_ssh2_transport_state);
10733 sfree(ssh->do_ssh2_authconn_state);
10736 sfree(ssh->fullhostname);
10737 sfree(ssh->hostkey_str);
10738 if (ssh->crcda_ctx) {
10739 crcda_free_context(ssh->crcda_ctx);
10740 ssh->crcda_ctx = NULL;
10743 ssh_do_close(ssh, TRUE);
10744 expire_timer_context(ssh);
10746 pinger_free(ssh->pinger);
10747 bufchain_clear(&ssh->queued_incoming_data);
10748 sfree(ssh->username);
10749 conf_free(ssh->conf);
10752 ssh_gss_cleanup(ssh->gsslibs);
10760 * Reconfigure the SSH backend.
10762 static void ssh_reconfig(void *handle, Conf *conf)
10764 Ssh ssh = (Ssh) handle;
10765 char *rekeying = NULL, rekey_mandatory = FALSE;
10766 unsigned long old_max_data_size;
10769 pinger_reconfig(ssh->pinger, ssh->conf, conf);
10771 ssh_setup_portfwd(ssh, conf);
10773 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
10774 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
10776 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
10777 unsigned long now = GETTICKCOUNT();
10779 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
10780 rekeying = "timeout shortened";
10782 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
10786 old_max_data_size = ssh->max_data_size;
10787 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10788 CONF_ssh_rekey_data));
10789 if (old_max_data_size != ssh->max_data_size &&
10790 ssh->max_data_size != 0) {
10791 if (ssh->outgoing_data_size > ssh->max_data_size ||
10792 ssh->incoming_data_size > ssh->max_data_size)
10793 rekeying = "data limit lowered";
10796 if (conf_get_int(ssh->conf, CONF_compression) !=
10797 conf_get_int(conf, CONF_compression)) {
10798 rekeying = "compression setting changed";
10799 rekey_mandatory = TRUE;
10802 for (i = 0; i < CIPHER_MAX; i++)
10803 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
10804 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
10805 rekeying = "cipher settings changed";
10806 rekey_mandatory = TRUE;
10808 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
10809 conf_get_int(conf, CONF_ssh2_des_cbc)) {
10810 rekeying = "cipher settings changed";
10811 rekey_mandatory = TRUE;
10814 conf_free(ssh->conf);
10815 ssh->conf = conf_copy(conf);
10816 ssh_cache_conf_values(ssh);
10818 if (!ssh->bare_connection && rekeying) {
10819 if (!ssh->kex_in_progress) {
10820 do_ssh2_transport(ssh, rekeying, -1, NULL);
10821 } else if (rekey_mandatory) {
10822 ssh->deferred_rekey_reason = rekeying;
10828 * Called to send data down the SSH connection.
10830 static int ssh_send(void *handle, char *buf, int len)
10832 Ssh ssh = (Ssh) handle;
10834 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10837 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
10839 return ssh_sendbuffer(ssh);
10843 * Called to query the current amount of buffered stdin data.
10845 static int ssh_sendbuffer(void *handle)
10847 Ssh ssh = (Ssh) handle;
10848 int override_value;
10850 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10854 * If the SSH socket itself has backed up, add the total backup
10855 * size on that to any individual buffer on the stdin channel.
10857 override_value = 0;
10858 if (ssh->throttled_all)
10859 override_value = ssh->overall_bufsize;
10861 if (ssh->version == 1) {
10862 return override_value;
10863 } else if (ssh->version == 2) {
10864 if (!ssh->mainchan)
10865 return override_value;
10867 return (override_value +
10868 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
10875 * Called to set the size of the window from SSH's POV.
10877 static void ssh_size(void *handle, int width, int height)
10879 Ssh ssh = (Ssh) handle;
10880 struct Packet *pktout;
10882 ssh->term_width = width;
10883 ssh->term_height = height;
10885 switch (ssh->state) {
10886 case SSH_STATE_BEFORE_SIZE:
10887 case SSH_STATE_PREPACKET:
10888 case SSH_STATE_CLOSED:
10889 break; /* do nothing */
10890 case SSH_STATE_INTERMED:
10891 ssh->size_needed = TRUE; /* buffer for later */
10893 case SSH_STATE_SESSION:
10894 if (!conf_get_int(ssh->conf, CONF_nopty)) {
10895 if (ssh->version == 1) {
10896 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
10897 PKT_INT, ssh->term_height,
10898 PKT_INT, ssh->term_width,
10899 PKT_INT, 0, PKT_INT, 0, PKT_END);
10900 } else if (ssh->mainchan) {
10901 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
10903 ssh2_pkt_adduint32(pktout, ssh->term_width);
10904 ssh2_pkt_adduint32(pktout, ssh->term_height);
10905 ssh2_pkt_adduint32(pktout, 0);
10906 ssh2_pkt_adduint32(pktout, 0);
10907 ssh2_pkt_send(ssh, pktout);
10915 * Return a list of the special codes that make sense in this
10918 static const struct telnet_special *ssh_get_specials(void *handle)
10920 static const struct telnet_special ssh1_ignore_special[] = {
10921 {"IGNORE message", TS_NOP}
10923 static const struct telnet_special ssh2_ignore_special[] = {
10924 {"IGNORE message", TS_NOP},
10926 static const struct telnet_special ssh2_rekey_special[] = {
10927 {"Repeat key exchange", TS_REKEY},
10929 static const struct telnet_special ssh2_session_specials[] = {
10932 /* These are the signal names defined by RFC 4254.
10933 * They include all the ISO C signals, but are a subset of the POSIX
10934 * required signals. */
10935 {"SIGINT (Interrupt)", TS_SIGINT},
10936 {"SIGTERM (Terminate)", TS_SIGTERM},
10937 {"SIGKILL (Kill)", TS_SIGKILL},
10938 {"SIGQUIT (Quit)", TS_SIGQUIT},
10939 {"SIGHUP (Hangup)", TS_SIGHUP},
10940 {"More signals", TS_SUBMENU},
10941 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
10942 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
10943 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
10944 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
10945 {NULL, TS_EXITMENU}
10947 static const struct telnet_special specials_end[] = {
10948 {NULL, TS_EXITMENU}
10950 /* XXX review this length for any changes: */
10951 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
10952 lenof(ssh2_rekey_special) +
10953 lenof(ssh2_session_specials) +
10954 lenof(specials_end)];
10955 Ssh ssh = (Ssh) handle;
10957 #define ADD_SPECIALS(name) \
10959 assert((i + lenof(name)) <= lenof(ssh_specials)); \
10960 memcpy(&ssh_specials[i], name, sizeof name); \
10961 i += lenof(name); \
10964 if (ssh->version == 1) {
10965 /* Don't bother offering IGNORE if we've decided the remote
10966 * won't cope with it, since we wouldn't bother sending it if
10968 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
10969 ADD_SPECIALS(ssh1_ignore_special);
10970 } else if (ssh->version == 2) {
10971 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
10972 ADD_SPECIALS(ssh2_ignore_special);
10973 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
10974 ADD_SPECIALS(ssh2_rekey_special);
10976 ADD_SPECIALS(ssh2_session_specials);
10977 } /* else we're not ready yet */
10980 ADD_SPECIALS(specials_end);
10981 return ssh_specials;
10985 #undef ADD_SPECIALS
10989 * Send special codes. TS_EOF is useful for `plink', so you
10990 * can send an EOF and collect resulting output (e.g. `plink
10993 static void ssh_special(void *handle, Telnet_Special code)
10995 Ssh ssh = (Ssh) handle;
10996 struct Packet *pktout;
10998 if (code == TS_EOF) {
10999 if (ssh->state != SSH_STATE_SESSION) {
11001 * Buffer the EOF in case we are pre-SESSION, so we can
11002 * send it as soon as we reach SESSION.
11004 if (code == TS_EOF)
11005 ssh->eof_needed = TRUE;
11008 if (ssh->version == 1) {
11009 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11010 } else if (ssh->mainchan) {
11011 sshfwd_write_eof(ssh->mainchan);
11012 ssh->send_ok = 0; /* now stop trying to read from stdin */
11014 logevent("Sent EOF message");
11015 } else if (code == TS_PING || code == TS_NOP) {
11016 if (ssh->state == SSH_STATE_CLOSED
11017 || ssh->state == SSH_STATE_PREPACKET) return;
11018 if (ssh->version == 1) {
11019 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11020 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11022 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11023 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11024 ssh2_pkt_addstring_start(pktout);
11025 ssh2_pkt_send_noqueue(ssh, pktout);
11028 } else if (code == TS_REKEY) {
11029 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11030 ssh->version == 2) {
11031 do_ssh2_transport(ssh, "at user request", -1, NULL);
11033 } else if (code == TS_BRK) {
11034 if (ssh->state == SSH_STATE_CLOSED
11035 || ssh->state == SSH_STATE_PREPACKET) return;
11036 if (ssh->version == 1) {
11037 logevent("Unable to send BREAK signal in SSH-1");
11038 } else if (ssh->mainchan) {
11039 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11040 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11041 ssh2_pkt_send(ssh, pktout);
11044 /* Is is a POSIX signal? */
11045 char *signame = NULL;
11046 if (code == TS_SIGABRT) signame = "ABRT";
11047 if (code == TS_SIGALRM) signame = "ALRM";
11048 if (code == TS_SIGFPE) signame = "FPE";
11049 if (code == TS_SIGHUP) signame = "HUP";
11050 if (code == TS_SIGILL) signame = "ILL";
11051 if (code == TS_SIGINT) signame = "INT";
11052 if (code == TS_SIGKILL) signame = "KILL";
11053 if (code == TS_SIGPIPE) signame = "PIPE";
11054 if (code == TS_SIGQUIT) signame = "QUIT";
11055 if (code == TS_SIGSEGV) signame = "SEGV";
11056 if (code == TS_SIGTERM) signame = "TERM";
11057 if (code == TS_SIGUSR1) signame = "USR1";
11058 if (code == TS_SIGUSR2) signame = "USR2";
11059 /* The SSH-2 protocol does in principle support arbitrary named
11060 * signals, including signame@domain, but we don't support those. */
11062 /* It's a signal. */
11063 if (ssh->version == 2 && ssh->mainchan) {
11064 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11065 ssh2_pkt_addstring(pktout, signame);
11066 ssh2_pkt_send(ssh, pktout);
11067 logeventf(ssh, "Sent signal SIG%s", signame);
11070 /* Never heard of it. Do nothing */
11075 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11077 Ssh ssh = (Ssh) handle;
11078 struct ssh_channel *c;
11079 c = snew(struct ssh_channel);
11082 ssh2_channel_init(c);
11083 c->halfopen = TRUE;
11084 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11086 add234(ssh->channels, c);
11090 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11092 struct ssh_channel *c;
11093 c = snew(struct ssh_channel);
11096 ssh2_channel_init(c);
11097 c->type = CHAN_SHARING;
11098 c->u.sharing.ctx = sharing_ctx;
11099 add234(ssh->channels, c);
11103 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11105 struct ssh_channel *c;
11107 c = find234(ssh->channels, &localid, ssh_channelfind);
11109 ssh_channel_destroy(c);
11112 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11113 const void *data, int datalen,
11114 const char *additional_log_text)
11116 struct Packet *pkt;
11118 pkt = ssh2_pkt_init(type);
11119 pkt->downstream_id = id;
11120 pkt->additional_log_text = additional_log_text;
11121 ssh2_pkt_adddata(pkt, data, datalen);
11122 ssh2_pkt_send(ssh, pkt);
11126 * This is called when stdout/stderr (the entity to which
11127 * from_backend sends data) manages to clear some backlog.
11129 static void ssh_unthrottle(void *handle, int bufsize)
11131 Ssh ssh = (Ssh) handle;
11134 if (ssh->version == 1) {
11135 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11136 ssh->v1_stdout_throttling = 0;
11137 ssh_throttle_conn(ssh, -1);
11140 if (ssh->mainchan) {
11141 ssh2_set_window(ssh->mainchan,
11142 bufsize < ssh->mainchan->v.v2.locmaxwin ?
11143 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11144 if (ssh_is_simple(ssh))
11147 buflimit = ssh->mainchan->v.v2.locmaxwin;
11148 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11149 ssh->mainchan->throttling_conn = 0;
11150 ssh_throttle_conn(ssh, -1);
11156 * Now process any SSH connection data that was stashed in our
11157 * queue while we were frozen.
11159 ssh_process_queued_incoming_data(ssh);
11162 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
11164 struct ssh_channel *c = (struct ssh_channel *)channel;
11166 struct Packet *pktout;
11168 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11170 if (ssh->version == 1) {
11171 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11172 PKT_INT, c->localid,
11175 /* PKT_STR, <org:orgport>, */
11178 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11180 char *trimmed_host = host_strduptrim(hostname);
11181 ssh2_pkt_addstring(pktout, trimmed_host);
11182 sfree(trimmed_host);
11184 ssh2_pkt_adduint32(pktout, port);
11186 * We make up values for the originator data; partly it's
11187 * too much hassle to keep track, and partly I'm not
11188 * convinced the server should be told details like that
11189 * about my local network configuration.
11190 * The "originator IP address" is syntactically a numeric
11191 * IP address, and some servers (e.g., Tectia) get upset
11192 * if it doesn't match this syntax.
11194 ssh2_pkt_addstring(pktout, "0.0.0.0");
11195 ssh2_pkt_adduint32(pktout, 0);
11196 ssh2_pkt_send(ssh, pktout);
11200 static int ssh_connected(void *handle)
11202 Ssh ssh = (Ssh) handle;
11203 return ssh->s != NULL;
11206 static int ssh_sendok(void *handle)
11208 Ssh ssh = (Ssh) handle;
11209 return ssh->send_ok;
11212 static int ssh_ldisc(void *handle, int option)
11214 Ssh ssh = (Ssh) handle;
11215 if (option == LD_ECHO)
11216 return ssh->echoing;
11217 if (option == LD_EDIT)
11218 return ssh->editing;
11222 static void ssh_provide_ldisc(void *handle, void *ldisc)
11224 Ssh ssh = (Ssh) handle;
11225 ssh->ldisc = ldisc;
11228 static void ssh_provide_logctx(void *handle, void *logctx)
11230 Ssh ssh = (Ssh) handle;
11231 ssh->logctx = logctx;
11234 static int ssh_return_exitcode(void *handle)
11236 Ssh ssh = (Ssh) handle;
11237 if (ssh->s != NULL)
11240 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11244 * cfg_info for SSH is the protocol running in this session.
11245 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11246 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11248 static int ssh_cfg_info(void *handle)
11250 Ssh ssh = (Ssh) handle;
11251 if (ssh->version == 0)
11252 return 0; /* don't know yet */
11253 else if (ssh->bare_connection)
11256 return ssh->version;
11260 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11261 * that fails. This variable is the means by which scp.c can reach
11262 * into the SSH code and find out which one it got.
11264 extern int ssh_fallback_cmd(void *handle)
11266 Ssh ssh = (Ssh) handle;
11267 return ssh->fallback_cmd;
11270 Backend ssh_backend = {
11280 ssh_return_exitcode,
11284 ssh_provide_logctx,