28 * Packet type contexts, so that ssh2_pkt_type can correctly decode
29 * the ambiguous type numbers back into the correct type strings.
40 SSH2_PKTCTX_PUBLICKEY,
46 static const char *const ssh2_disconnect_reasons[] = {
48 "host not allowed to connect",
50 "key exchange failed",
51 "host authentication failed",
54 "service not available",
55 "protocol version not supported",
56 "host key not verifiable",
59 "too many connections",
60 "auth cancelled by user",
61 "no more auth methods available",
66 * Various remote-bug flags.
68 #define BUG_CHOKES_ON_SSH1_IGNORE 1
69 #define BUG_SSH2_HMAC 2
70 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
71 #define BUG_CHOKES_ON_RSA 8
72 #define BUG_SSH2_RSA_PADDING 16
73 #define BUG_SSH2_DERIVEKEY 32
74 #define BUG_SSH2_REKEY 64
75 #define BUG_SSH2_PK_SESSIONID 128
76 #define BUG_SSH2_MAXPKT 256
77 #define BUG_CHOKES_ON_SSH2_IGNORE 512
78 #define BUG_CHOKES_ON_WINADJ 1024
79 #define BUG_SENDS_LATE_REQUEST_REPLY 2048
82 * Codes for terminal modes.
83 * Most of these are the same in SSH-1 and SSH-2.
84 * This list is derived from RFC 4254 and
88 const char* const mode;
90 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
92 /* "V" prefix discarded for special characters relative to SSH specs */
93 { "INTR", 1, TTY_OP_CHAR },
94 { "QUIT", 2, TTY_OP_CHAR },
95 { "ERASE", 3, TTY_OP_CHAR },
96 { "KILL", 4, TTY_OP_CHAR },
97 { "EOF", 5, TTY_OP_CHAR },
98 { "EOL", 6, TTY_OP_CHAR },
99 { "EOL2", 7, TTY_OP_CHAR },
100 { "START", 8, TTY_OP_CHAR },
101 { "STOP", 9, TTY_OP_CHAR },
102 { "SUSP", 10, TTY_OP_CHAR },
103 { "DSUSP", 11, TTY_OP_CHAR },
104 { "REPRINT", 12, TTY_OP_CHAR },
105 { "WERASE", 13, TTY_OP_CHAR },
106 { "LNEXT", 14, TTY_OP_CHAR },
107 { "FLUSH", 15, TTY_OP_CHAR },
108 { "SWTCH", 16, TTY_OP_CHAR },
109 { "STATUS", 17, TTY_OP_CHAR },
110 { "DISCARD", 18, TTY_OP_CHAR },
111 { "IGNPAR", 30, TTY_OP_BOOL },
112 { "PARMRK", 31, TTY_OP_BOOL },
113 { "INPCK", 32, TTY_OP_BOOL },
114 { "ISTRIP", 33, TTY_OP_BOOL },
115 { "INLCR", 34, TTY_OP_BOOL },
116 { "IGNCR", 35, TTY_OP_BOOL },
117 { "ICRNL", 36, TTY_OP_BOOL },
118 { "IUCLC", 37, TTY_OP_BOOL },
119 { "IXON", 38, TTY_OP_BOOL },
120 { "IXANY", 39, TTY_OP_BOOL },
121 { "IXOFF", 40, TTY_OP_BOOL },
122 { "IMAXBEL", 41, TTY_OP_BOOL },
123 { "ISIG", 50, TTY_OP_BOOL },
124 { "ICANON", 51, TTY_OP_BOOL },
125 { "XCASE", 52, TTY_OP_BOOL },
126 { "ECHO", 53, TTY_OP_BOOL },
127 { "ECHOE", 54, TTY_OP_BOOL },
128 { "ECHOK", 55, TTY_OP_BOOL },
129 { "ECHONL", 56, TTY_OP_BOOL },
130 { "NOFLSH", 57, TTY_OP_BOOL },
131 { "TOSTOP", 58, TTY_OP_BOOL },
132 { "IEXTEN", 59, TTY_OP_BOOL },
133 { "ECHOCTL", 60, TTY_OP_BOOL },
134 { "ECHOKE", 61, TTY_OP_BOOL },
135 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
136 { "OPOST", 70, TTY_OP_BOOL },
137 { "OLCUC", 71, TTY_OP_BOOL },
138 { "ONLCR", 72, TTY_OP_BOOL },
139 { "OCRNL", 73, TTY_OP_BOOL },
140 { "ONOCR", 74, TTY_OP_BOOL },
141 { "ONLRET", 75, TTY_OP_BOOL },
142 { "CS7", 90, TTY_OP_BOOL },
143 { "CS8", 91, TTY_OP_BOOL },
144 { "PARENB", 92, TTY_OP_BOOL },
145 { "PARODD", 93, TTY_OP_BOOL }
148 /* Miscellaneous other tty-related constants. */
149 #define SSH_TTY_OP_END 0
150 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
151 #define SSH1_TTY_OP_ISPEED 192
152 #define SSH1_TTY_OP_OSPEED 193
153 #define SSH2_TTY_OP_ISPEED 128
154 #define SSH2_TTY_OP_OSPEED 129
156 /* Helper functions for parsing tty-related config. */
157 static unsigned int ssh_tty_parse_specchar(char *s)
162 ret = ctrlparse(s, &next);
163 if (!next) ret = s[0];
165 ret = 255; /* special value meaning "don't set" */
169 static unsigned int ssh_tty_parse_boolean(char *s)
171 if (stricmp(s, "yes") == 0 ||
172 stricmp(s, "on") == 0 ||
173 stricmp(s, "true") == 0 ||
174 stricmp(s, "+") == 0)
176 else if (stricmp(s, "no") == 0 ||
177 stricmp(s, "off") == 0 ||
178 stricmp(s, "false") == 0 ||
179 stricmp(s, "-") == 0)
180 return 0; /* false */
182 return (atoi(s) != 0);
185 #define translate(x) if (type == x) return #x
186 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
187 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
188 static char *ssh1_pkt_type(int type)
190 translate(SSH1_MSG_DISCONNECT);
191 translate(SSH1_SMSG_PUBLIC_KEY);
192 translate(SSH1_CMSG_SESSION_KEY);
193 translate(SSH1_CMSG_USER);
194 translate(SSH1_CMSG_AUTH_RSA);
195 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
196 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
197 translate(SSH1_CMSG_AUTH_PASSWORD);
198 translate(SSH1_CMSG_REQUEST_PTY);
199 translate(SSH1_CMSG_WINDOW_SIZE);
200 translate(SSH1_CMSG_EXEC_SHELL);
201 translate(SSH1_CMSG_EXEC_CMD);
202 translate(SSH1_SMSG_SUCCESS);
203 translate(SSH1_SMSG_FAILURE);
204 translate(SSH1_CMSG_STDIN_DATA);
205 translate(SSH1_SMSG_STDOUT_DATA);
206 translate(SSH1_SMSG_STDERR_DATA);
207 translate(SSH1_CMSG_EOF);
208 translate(SSH1_SMSG_EXIT_STATUS);
209 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
210 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
211 translate(SSH1_MSG_CHANNEL_DATA);
212 translate(SSH1_MSG_CHANNEL_CLOSE);
213 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
214 translate(SSH1_SMSG_X11_OPEN);
215 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
216 translate(SSH1_MSG_PORT_OPEN);
217 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
218 translate(SSH1_SMSG_AGENT_OPEN);
219 translate(SSH1_MSG_IGNORE);
220 translate(SSH1_CMSG_EXIT_CONFIRMATION);
221 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
222 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
223 translate(SSH1_MSG_DEBUG);
224 translate(SSH1_CMSG_REQUEST_COMPRESSION);
225 translate(SSH1_CMSG_AUTH_TIS);
226 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
227 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
228 translate(SSH1_CMSG_AUTH_CCARD);
229 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
230 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
233 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
235 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
236 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
237 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
238 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
239 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
240 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
241 translate(SSH2_MSG_DISCONNECT);
242 translate(SSH2_MSG_IGNORE);
243 translate(SSH2_MSG_UNIMPLEMENTED);
244 translate(SSH2_MSG_DEBUG);
245 translate(SSH2_MSG_SERVICE_REQUEST);
246 translate(SSH2_MSG_SERVICE_ACCEPT);
247 translate(SSH2_MSG_KEXINIT);
248 translate(SSH2_MSG_NEWKEYS);
249 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
250 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
251 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
252 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
253 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
254 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
255 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
256 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
257 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
258 translatek(SSH2_MSG_KEX_ECDH_INIT, SSH2_PKTCTX_ECDHKEX);
259 translatek(SSH2_MSG_KEX_ECDH_REPLY, SSH2_PKTCTX_ECDHKEX);
260 translate(SSH2_MSG_USERAUTH_REQUEST);
261 translate(SSH2_MSG_USERAUTH_FAILURE);
262 translate(SSH2_MSG_USERAUTH_SUCCESS);
263 translate(SSH2_MSG_USERAUTH_BANNER);
264 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
265 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
266 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
267 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
268 translate(SSH2_MSG_GLOBAL_REQUEST);
269 translate(SSH2_MSG_REQUEST_SUCCESS);
270 translate(SSH2_MSG_REQUEST_FAILURE);
271 translate(SSH2_MSG_CHANNEL_OPEN);
272 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
273 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
274 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
275 translate(SSH2_MSG_CHANNEL_DATA);
276 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
277 translate(SSH2_MSG_CHANNEL_EOF);
278 translate(SSH2_MSG_CHANNEL_CLOSE);
279 translate(SSH2_MSG_CHANNEL_REQUEST);
280 translate(SSH2_MSG_CHANNEL_SUCCESS);
281 translate(SSH2_MSG_CHANNEL_FAILURE);
287 /* Enumeration values for fields in SSH-1 packets */
289 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
293 * Coroutine mechanics for the sillier bits of the code. If these
294 * macros look impenetrable to you, you might find it helpful to
297 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
299 * which explains the theory behind these macros.
301 * In particular, if you are getting `case expression not constant'
302 * errors when building with MS Visual Studio, this is because MS's
303 * Edit and Continue debugging feature causes their compiler to
304 * violate ANSI C. To disable Edit and Continue debugging:
306 * - right-click ssh.c in the FileView
308 * - select the C/C++ tab and the General category
309 * - under `Debug info:', select anything _other_ than `Program
310 * Database for Edit and Continue'.
312 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
313 #define crBeginState crBegin(s->crLine)
314 #define crStateP(t, v) \
316 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
318 #define crState(t) crStateP(t, ssh->t)
319 #define crFinish(z) } *crLine = 0; return (z); }
320 #define crFinishV } *crLine = 0; return; }
321 #define crFinishFree(z) } sfree(s); return (z); }
322 #define crFinishFreeV } sfree(s); return; }
323 #define crReturn(z) \
325 *crLine =__LINE__; return (z); case __LINE__:;\
329 *crLine=__LINE__; return; case __LINE__:;\
331 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
332 #define crStopV do{ *crLine = 0; return; }while(0)
333 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
334 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
338 static struct Packet *ssh1_pkt_init(int pkt_type);
339 static struct Packet *ssh2_pkt_init(int pkt_type);
340 static void ssh_pkt_ensure(struct Packet *, int length);
341 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
342 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
343 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
344 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
345 static void ssh_pkt_addstring_start(struct Packet *);
346 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
347 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
348 static void ssh_pkt_addstring(struct Packet *, const char *data);
349 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
350 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
351 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
352 static int ssh2_pkt_construct(Ssh, struct Packet *);
353 static void ssh2_pkt_send(Ssh, struct Packet *);
354 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
355 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
356 struct Packet *pktin);
357 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
358 struct Packet *pktin);
359 static void ssh2_channel_check_close(struct ssh_channel *c);
360 static void ssh_channel_destroy(struct ssh_channel *c);
363 * Buffer management constants. There are several of these for
364 * various different purposes:
366 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
367 * on a local data stream before we throttle the whole SSH
368 * connection (in SSH-1 only). Throttling the whole connection is
369 * pretty drastic so we set this high in the hope it won't
372 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
373 * on the SSH connection itself before we defensively throttle
374 * _all_ local data streams. This is pretty drastic too (though
375 * thankfully unlikely in SSH-2 since the window mechanism should
376 * ensure that the server never has any need to throttle its end
377 * of the connection), so we set this high as well.
379 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
382 * - OUR_V2_BIGWIN is the window size we advertise for the only
383 * channel in a simple connection. It must be <= INT_MAX.
385 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
386 * to the remote side. This actually has nothing to do with the
387 * size of the _packet_, but is instead a limit on the amount
388 * of data we're willing to receive in a single SSH2 channel
391 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
392 * _packet_ we're prepared to cope with. It must be a multiple
393 * of the cipher block size, and must be at least 35000.
396 #define SSH1_BUFFER_LIMIT 32768
397 #define SSH_MAX_BACKLOG 32768
398 #define OUR_V2_WINSIZE 16384
399 #define OUR_V2_BIGWIN 0x7fffffff
400 #define OUR_V2_MAXPKT 0x4000UL
401 #define OUR_V2_PACKETLIMIT 0x9000UL
403 const static struct ssh_signkey *hostkey_algs[] = {
404 &ssh_ecdsa_nistp256, &ssh_ecdsa_nistp384, &ssh_ecdsa_nistp521,
408 const static struct ssh_mac *macs[] = {
409 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
411 const static struct ssh_mac *buggymacs[] = {
412 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
415 static void *ssh_comp_none_init(void)
419 static void ssh_comp_none_cleanup(void *handle)
422 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
423 unsigned char **outblock, int *outlen)
427 static int ssh_comp_none_disable(void *handle)
431 const static struct ssh_compress ssh_comp_none = {
433 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
434 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
435 ssh_comp_none_disable, NULL
437 extern const struct ssh_compress ssh_zlib;
438 const static struct ssh_compress *compressions[] = {
439 &ssh_zlib, &ssh_comp_none
442 enum { /* channel types */
447 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
449 * CHAN_SHARING indicates a channel which is tracked here on
450 * behalf of a connection-sharing downstream. We do almost nothing
451 * with these channels ourselves: all messages relating to them
452 * get thrown straight to sshshare.c and passed on almost
453 * unmodified to downstream.
457 * CHAN_ZOMBIE is used to indicate a channel for which we've
458 * already destroyed the local data source: for instance, if a
459 * forwarded port experiences a socket error on the local side, we
460 * immediately destroy its local socket and turn the SSH channel
466 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
467 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
468 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
471 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
474 struct outstanding_channel_request {
475 cchandler_fn_t handler;
477 struct outstanding_channel_request *next;
481 * 2-3-4 tree storing channels.
484 Ssh ssh; /* pointer back to main context */
485 unsigned remoteid, localid;
487 /* True if we opened this channel but server hasn't confirmed. */
490 * In SSH-1, this value contains four bits:
492 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
493 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
494 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
495 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
497 * A channel is completely finished with when all four bits are set.
499 * In SSH-2, the four bits mean:
501 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
502 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
503 * 4 We have received SSH2_MSG_CHANNEL_EOF.
504 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
506 * A channel is completely finished with when we have both sent
507 * and received CLOSE.
509 * The symbolic constants below use the SSH-2 terminology, which
510 * is a bit confusing in SSH-1, but we have to use _something_.
512 #define CLOSES_SENT_EOF 1
513 #define CLOSES_SENT_CLOSE 2
514 #define CLOSES_RCVD_EOF 4
515 #define CLOSES_RCVD_CLOSE 8
519 * This flag indicates that an EOF is pending on the outgoing side
520 * of the channel: that is, wherever we're getting the data for
521 * this channel has sent us some data followed by EOF. We can't
522 * actually send the EOF until we've finished sending the data, so
523 * we set this flag instead to remind us to do so once our buffer
529 * True if this channel is causing the underlying connection to be
534 struct ssh2_data_channel {
536 unsigned remwindow, remmaxpkt;
537 /* locwindow is signed so we can cope with excess data. */
538 int locwindow, locmaxwin;
540 * remlocwin is the amount of local window that we think
541 * the remote end had available to it after it sent the
542 * last data packet or window adjust ack.
546 * These store the list of channel requests that haven't
549 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
550 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
554 struct ssh_agent_channel {
555 unsigned char *message;
556 unsigned char msglen[4];
557 unsigned lensofar, totallen;
558 int outstanding_requests;
560 struct ssh_x11_channel {
561 struct X11Connection *xconn;
564 struct ssh_pfd_channel {
565 struct PortForwarding *pf;
567 struct ssh_sharing_channel {
574 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
575 * use this structure in different ways, reflecting SSH-2's
576 * altogether saner approach to port forwarding.
578 * In SSH-1, you arrange a remote forwarding by sending the server
579 * the remote port number, and the local destination host:port.
580 * When a connection comes in, the server sends you back that
581 * host:port pair, and you connect to it. This is a ready-made
582 * security hole if you're not on the ball: a malicious server
583 * could send you back _any_ host:port pair, so if you trustingly
584 * connect to the address it gives you then you've just opened the
585 * entire inside of your corporate network just by connecting
586 * through it to a dodgy SSH server. Hence, we must store a list of
587 * host:port pairs we _are_ trying to forward to, and reject a
588 * connection request from the server if it's not in the list.
590 * In SSH-2, each side of the connection minds its own business and
591 * doesn't send unnecessary information to the other. You arrange a
592 * remote forwarding by sending the server just the remote port
593 * number. When a connection comes in, the server tells you which
594 * of its ports was connected to; and _you_ have to remember what
595 * local host:port pair went with that port number.
597 * Hence, in SSH-1 this structure is indexed by destination
598 * host:port pair, whereas in SSH-2 it is indexed by source port.
600 struct ssh_portfwd; /* forward declaration */
602 struct ssh_rportfwd {
603 unsigned sport, dport;
607 struct ssh_portfwd *pfrec;
610 static void free_rportfwd(struct ssh_rportfwd *pf)
613 sfree(pf->sportdesc);
621 * Separately to the rportfwd tree (which is for looking up port
622 * open requests from the server), a tree of _these_ structures is
623 * used to keep track of all the currently open port forwardings,
624 * so that we can reconfigure in mid-session if the user requests
628 enum { DESTROY, KEEP, CREATE } status;
630 unsigned sport, dport;
633 struct ssh_rportfwd *remote;
635 struct PortListener *local;
637 #define free_portfwd(pf) ( \
638 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
639 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
642 long length; /* length of packet: see below */
643 long forcepad; /* SSH-2: force padding to at least this length */
644 int type; /* only used for incoming packets */
645 unsigned long sequence; /* SSH-2 incoming sequence number */
646 unsigned char *data; /* allocated storage */
647 unsigned char *body; /* offset of payload within `data' */
648 long savedpos; /* dual-purpose saved packet position: see below */
649 long maxlen; /* amount of storage allocated for `data' */
650 long encrypted_len; /* for SSH-2 total-size counting */
653 * A note on the 'length' and 'savedpos' fields above.
655 * Incoming packets are set up so that pkt->length is measured
656 * relative to pkt->body, which itself points to a few bytes after
657 * pkt->data (skipping some uninteresting header fields including
658 * the packet type code). The ssh_pkt_get* functions all expect
659 * this setup, and they also use pkt->savedpos to indicate how far
660 * through the packet being decoded they've got - and that, too,
661 * is an offset from pkt->body rather than pkt->data.
663 * During construction of an outgoing packet, however, pkt->length
664 * is measured relative to the base pointer pkt->data, and
665 * pkt->body is not really used for anything until the packet is
666 * ready for sending. In this mode, pkt->savedpos is reused as a
667 * temporary variable by the addstring functions, which write out
668 * a string length field and then keep going back and updating it
669 * as more data is appended to the subsequent string data field;
670 * pkt->savedpos stores the offset (again relative to pkt->data)
671 * of the start of the string data field.
674 /* Extra metadata used in SSH packet logging mode, allowing us to
675 * log in the packet header line that the packet came from a
676 * connection-sharing downstream and what if anything unusual was
677 * done to it. The additional_log_text field is expected to be a
678 * static string - it will not be freed. */
679 unsigned downstream_id;
680 const char *additional_log_text;
683 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
684 struct Packet *pktin);
685 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
686 struct Packet *pktin);
687 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
688 struct Packet *pktin);
689 static void ssh1_protocol_setup(Ssh ssh);
690 static void ssh2_protocol_setup(Ssh ssh);
691 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
692 static void ssh_size(void *handle, int width, int height);
693 static void ssh_special(void *handle, Telnet_Special);
694 static int ssh2_try_send(struct ssh_channel *c);
695 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
696 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
697 static void ssh2_set_window(struct ssh_channel *c, int newwin);
698 static int ssh_sendbuffer(void *handle);
699 static int ssh_do_close(Ssh ssh, int notify_exit);
700 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
701 static int ssh2_pkt_getbool(struct Packet *pkt);
702 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
703 static void ssh2_timer(void *ctx, unsigned long now);
704 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
705 struct Packet *pktin);
706 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
708 struct rdpkt1_state_tag {
709 long len, pad, biglen, to_read;
710 unsigned long realcrc, gotcrc;
714 struct Packet *pktin;
717 struct rdpkt2_state_tag {
718 long len, pad, payload, packetlen, maclen;
721 unsigned long incoming_sequence;
722 struct Packet *pktin;
725 struct rdpkt2_bare_state_tag {
729 unsigned long incoming_sequence;
730 struct Packet *pktin;
733 struct queued_handler;
734 struct queued_handler {
736 chandler_fn_t handler;
738 struct queued_handler *next;
742 const struct plug_function_table *fn;
743 /* the above field _must_ be first in the structure */
753 unsigned char session_key[32];
755 int v1_remote_protoflags;
756 int v1_local_protoflags;
757 int agentfwd_enabled;
760 const struct ssh_cipher *cipher;
763 const struct ssh2_cipher *cscipher, *sccipher;
764 void *cs_cipher_ctx, *sc_cipher_ctx;
765 const struct ssh_mac *csmac, *scmac;
766 void *cs_mac_ctx, *sc_mac_ctx;
767 const struct ssh_compress *cscomp, *sccomp;
768 void *cs_comp_ctx, *sc_comp_ctx;
769 const struct ssh_kex *kex;
770 const struct ssh_signkey *hostkey;
771 char *hostkey_str; /* string representation, for easy checking in rekeys */
772 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
773 int v2_session_id_len;
777 int attempting_connshare;
783 int echoing, editing;
787 int ospeed, ispeed; /* temporaries */
788 int term_width, term_height;
790 tree234 *channels; /* indexed by local id */
791 struct ssh_channel *mainchan; /* primary session channel */
792 int ncmode; /* is primary channel direct-tcpip? */
797 tree234 *rportfwds, *portfwds;
801 SSH_STATE_BEFORE_SIZE,
807 int size_needed, eof_needed;
808 int sent_console_eof;
809 int got_pty; /* affects EOF behaviour on main channel */
811 struct Packet **queue;
812 int queuelen, queuesize;
814 unsigned char *deferred_send_data;
815 int deferred_len, deferred_size;
818 * Gross hack: pscp will try to start SFTP but fall back to
819 * scp1 if that fails. This variable is the means by which
820 * scp.c can reach into the SSH code and find out which one it
825 bufchain banner; /* accumulates banners during do_ssh2_authconn */
830 struct X11Display *x11disp;
831 struct X11FakeAuth *x11auth;
832 tree234 *x11authtree;
835 int conn_throttle_count;
838 int v1_stdout_throttling;
839 unsigned long v2_outgoing_sequence;
841 int ssh1_rdpkt_crstate;
842 int ssh2_rdpkt_crstate;
843 int ssh2_bare_rdpkt_crstate;
844 int ssh_gotdata_crstate;
845 int do_ssh1_connection_crstate;
847 void *do_ssh_init_state;
848 void *do_ssh1_login_state;
849 void *do_ssh2_transport_state;
850 void *do_ssh2_authconn_state;
851 void *do_ssh_connection_init_state;
853 struct rdpkt1_state_tag rdpkt1_state;
854 struct rdpkt2_state_tag rdpkt2_state;
855 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
857 /* SSH-1 and SSH-2 use this for different things, but both use it */
858 int protocol_initial_phase_done;
860 void (*protocol) (Ssh ssh, void *vin, int inlen,
862 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
863 int (*do_ssh_init)(Ssh ssh, unsigned char c);
866 * We maintain our own copy of a Conf structure here. That way,
867 * when we're passed a new one for reconfiguration, we can check
868 * the differences and potentially reconfigure port forwardings
869 * etc in mid-session.
874 * Values cached out of conf so as to avoid the tree234 lookup
875 * cost every time they're used.
880 * Dynamically allocated username string created during SSH
881 * login. Stored in here rather than in the coroutine state so
882 * that it'll be reliably freed if we shut down the SSH session
883 * at some unexpected moment.
888 * Used to transfer data back from async callbacks.
890 void *agent_response;
891 int agent_response_len;
895 * The SSH connection can be set as `frozen', meaning we are
896 * not currently accepting incoming data from the network. This
897 * is slightly more serious than setting the _socket_ as
898 * frozen, because we may already have had data passed to us
899 * from the network which we need to delay processing until
900 * after the freeze is lifted, so we also need a bufchain to
904 bufchain queued_incoming_data;
907 * Dispatch table for packet types that we may have to deal
910 handler_fn_t packet_dispatch[256];
913 * Queues of one-off handler functions for success/failure
914 * indications from a request.
916 struct queued_handler *qhead, *qtail;
917 handler_fn_t q_saved_handler1, q_saved_handler2;
920 * This module deals with sending keepalives.
925 * Track incoming and outgoing data sizes and time, for
928 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
929 unsigned long max_data_size;
931 unsigned long next_rekey, last_rekey;
932 char *deferred_rekey_reason; /* points to STATIC string; don't free */
935 * Fully qualified host name, which we need if doing GSSAPI.
941 * GSSAPI libraries for this session.
943 struct ssh_gss_liblist *gsslibs;
947 #define logevent(s) logevent(ssh->frontend, s)
949 /* logevent, only printf-formatted. */
950 static void logeventf(Ssh ssh, const char *fmt, ...)
956 buf = dupvprintf(fmt, ap);
962 static void bomb_out(Ssh ssh, char *text)
964 ssh_do_close(ssh, FALSE);
966 connection_fatal(ssh->frontend, "%s", text);
970 #define bombout(msg) bomb_out(ssh, dupprintf msg)
972 /* Helper function for common bits of parsing ttymodes. */
973 static void parse_ttymodes(Ssh ssh,
974 void (*do_mode)(void *data, char *mode, char *val),
979 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
981 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
983 * val[0] is either 'V', indicating that an explicit value
984 * follows it, or 'A' indicating that we should pass the
985 * value through from the local environment via get_ttymode.
988 val = get_ttymode(ssh->frontend, key);
990 do_mode(data, key, val);
994 do_mode(data, key, val + 1); /* skip the 'V' */
998 static int ssh_channelcmp(void *av, void *bv)
1000 struct ssh_channel *a = (struct ssh_channel *) av;
1001 struct ssh_channel *b = (struct ssh_channel *) bv;
1002 if (a->localid < b->localid)
1004 if (a->localid > b->localid)
1008 static int ssh_channelfind(void *av, void *bv)
1010 unsigned *a = (unsigned *) av;
1011 struct ssh_channel *b = (struct ssh_channel *) bv;
1012 if (*a < b->localid)
1014 if (*a > b->localid)
1019 static int ssh_rportcmp_ssh1(void *av, void *bv)
1021 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1022 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1024 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1025 return i < 0 ? -1 : +1;
1026 if (a->dport > b->dport)
1028 if (a->dport < b->dport)
1033 static int ssh_rportcmp_ssh2(void *av, void *bv)
1035 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1036 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1038 if ( (i = strcmp(a->shost, b->shost)) != 0)
1039 return i < 0 ? -1 : +1;
1040 if (a->sport > b->sport)
1042 if (a->sport < b->sport)
1048 * Special form of strcmp which can cope with NULL inputs. NULL is
1049 * defined to sort before even the empty string.
1051 static int nullstrcmp(const char *a, const char *b)
1053 if (a == NULL && b == NULL)
1059 return strcmp(a, b);
1062 static int ssh_portcmp(void *av, void *bv)
1064 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1065 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1067 if (a->type > b->type)
1069 if (a->type < b->type)
1071 if (a->addressfamily > b->addressfamily)
1073 if (a->addressfamily < b->addressfamily)
1075 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1076 return i < 0 ? -1 : +1;
1077 if (a->sport > b->sport)
1079 if (a->sport < b->sport)
1081 if (a->type != 'D') {
1082 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1083 return i < 0 ? -1 : +1;
1084 if (a->dport > b->dport)
1086 if (a->dport < b->dport)
1092 static int alloc_channel_id(Ssh ssh)
1094 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1095 unsigned low, high, mid;
1097 struct ssh_channel *c;
1100 * First-fit allocation of channel numbers: always pick the
1101 * lowest unused one. To do this, binary-search using the
1102 * counted B-tree to find the largest channel ID which is in a
1103 * contiguous sequence from the beginning. (Precisely
1104 * everything in that sequence must have ID equal to its tree
1105 * index plus CHANNEL_NUMBER_OFFSET.)
1107 tsize = count234(ssh->channels);
1111 while (high - low > 1) {
1112 mid = (high + low) / 2;
1113 c = index234(ssh->channels, mid);
1114 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1115 low = mid; /* this one is fine */
1117 high = mid; /* this one is past it */
1120 * Now low points to either -1, or the tree index of the
1121 * largest ID in the initial sequence.
1124 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1125 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1127 return low + 1 + CHANNEL_NUMBER_OFFSET;
1130 static void c_write_stderr(int trusted, const char *buf, int len)
1133 for (i = 0; i < len; i++)
1134 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1135 fputc(buf[i], stderr);
1138 static void c_write(Ssh ssh, const char *buf, int len)
1140 if (flags & FLAG_STDERR)
1141 c_write_stderr(1, buf, len);
1143 from_backend(ssh->frontend, 1, buf, len);
1146 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1148 if (flags & FLAG_STDERR)
1149 c_write_stderr(0, buf, len);
1151 from_backend_untrusted(ssh->frontend, buf, len);
1154 static void c_write_str(Ssh ssh, const char *buf)
1156 c_write(ssh, buf, strlen(buf));
1159 static void ssh_free_packet(struct Packet *pkt)
1164 static struct Packet *ssh_new_packet(void)
1166 struct Packet *pkt = snew(struct Packet);
1168 pkt->body = pkt->data = NULL;
1174 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1177 struct logblank_t blanks[4];
1183 if (ssh->logomitdata &&
1184 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1185 pkt->type == SSH1_SMSG_STDERR_DATA ||
1186 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1187 /* "Session data" packets - omit the data string. */
1188 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1189 ssh_pkt_getuint32(pkt); /* skip channel id */
1190 blanks[nblanks].offset = pkt->savedpos + 4;
1191 blanks[nblanks].type = PKTLOG_OMIT;
1192 ssh_pkt_getstring(pkt, &str, &slen);
1194 blanks[nblanks].len = slen;
1198 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1199 ssh1_pkt_type(pkt->type),
1200 pkt->body, pkt->length, nblanks, blanks, NULL,
1204 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1207 struct logblank_t blanks[4];
1212 * For outgoing packets, pkt->length represents the length of the
1213 * whole packet starting at pkt->data (including some header), and
1214 * pkt->body refers to the point within that where the log-worthy
1215 * payload begins. However, incoming packets expect pkt->length to
1216 * represent only the payload length (that is, it's measured from
1217 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1218 * packet to conform to the incoming-packet semantics, so that we
1219 * can analyse it with the ssh_pkt_get functions.
1221 pkt->length -= (pkt->body - pkt->data);
1224 if (ssh->logomitdata &&
1225 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1226 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1227 /* "Session data" packets - omit the data string. */
1228 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1229 ssh_pkt_getuint32(pkt); /* skip channel id */
1230 blanks[nblanks].offset = pkt->savedpos + 4;
1231 blanks[nblanks].type = PKTLOG_OMIT;
1232 ssh_pkt_getstring(pkt, &str, &slen);
1234 blanks[nblanks].len = slen;
1239 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1240 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1241 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1242 conf_get_int(ssh->conf, CONF_logomitpass)) {
1243 /* If this is a password or similar packet, blank the password(s). */
1244 blanks[nblanks].offset = 0;
1245 blanks[nblanks].len = pkt->length;
1246 blanks[nblanks].type = PKTLOG_BLANK;
1248 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1249 conf_get_int(ssh->conf, CONF_logomitpass)) {
1251 * If this is an X forwarding request packet, blank the fake
1254 * Note that while we blank the X authentication data here, we
1255 * don't take any special action to blank the start of an X11
1256 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1257 * an X connection without having session blanking enabled is
1258 * likely to leak your cookie into the log.
1261 ssh_pkt_getstring(pkt, &str, &slen);
1262 blanks[nblanks].offset = pkt->savedpos;
1263 blanks[nblanks].type = PKTLOG_BLANK;
1264 ssh_pkt_getstring(pkt, &str, &slen);
1266 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1271 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1272 ssh1_pkt_type(pkt->data[12]),
1273 pkt->body, pkt->length,
1274 nblanks, blanks, NULL, 0, NULL);
1277 * Undo the above adjustment of pkt->length, to put the packet
1278 * back in the state we found it.
1280 pkt->length += (pkt->body - pkt->data);
1284 * Collect incoming data in the incoming packet buffer.
1285 * Decipher and verify the packet when it is completely read.
1286 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1287 * Update the *data and *datalen variables.
1288 * Return a Packet structure when a packet is completed.
1290 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1292 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1294 crBegin(ssh->ssh1_rdpkt_crstate);
1296 st->pktin = ssh_new_packet();
1298 st->pktin->type = 0;
1299 st->pktin->length = 0;
1301 for (st->i = st->len = 0; st->i < 4; st->i++) {
1302 while ((*datalen) == 0)
1304 st->len = (st->len << 8) + **data;
1305 (*data)++, (*datalen)--;
1308 st->pad = 8 - (st->len % 8);
1309 st->biglen = st->len + st->pad;
1310 st->pktin->length = st->len - 5;
1312 if (st->biglen < 0) {
1313 bombout(("Extremely large packet length from server suggests"
1314 " data stream corruption"));
1315 ssh_free_packet(st->pktin);
1319 st->pktin->maxlen = st->biglen;
1320 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1322 st->to_read = st->biglen;
1323 st->p = st->pktin->data;
1324 while (st->to_read > 0) {
1325 st->chunk = st->to_read;
1326 while ((*datalen) == 0)
1328 if (st->chunk > (*datalen))
1329 st->chunk = (*datalen);
1330 memcpy(st->p, *data, st->chunk);
1332 *datalen -= st->chunk;
1334 st->to_read -= st->chunk;
1337 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1338 st->biglen, NULL)) {
1339 bombout(("Network attack (CRC compensation) detected!"));
1340 ssh_free_packet(st->pktin);
1345 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1347 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1348 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1349 if (st->gotcrc != st->realcrc) {
1350 bombout(("Incorrect CRC received on packet"));
1351 ssh_free_packet(st->pktin);
1355 st->pktin->body = st->pktin->data + st->pad + 1;
1357 if (ssh->v1_compressing) {
1358 unsigned char *decompblk;
1360 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1361 st->pktin->body - 1, st->pktin->length + 1,
1362 &decompblk, &decomplen)) {
1363 bombout(("Zlib decompression encountered invalid data"));
1364 ssh_free_packet(st->pktin);
1368 if (st->pktin->maxlen < st->pad + decomplen) {
1369 st->pktin->maxlen = st->pad + decomplen;
1370 st->pktin->data = sresize(st->pktin->data,
1371 st->pktin->maxlen + APIEXTRA,
1373 st->pktin->body = st->pktin->data + st->pad + 1;
1376 memcpy(st->pktin->body - 1, decompblk, decomplen);
1378 st->pktin->length = decomplen - 1;
1381 st->pktin->type = st->pktin->body[-1];
1384 * Now pktin->body and pktin->length identify the semantic content
1385 * of the packet, excluding the initial type byte.
1389 ssh1_log_incoming_packet(ssh, st->pktin);
1391 st->pktin->savedpos = 0;
1393 crFinish(st->pktin);
1396 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1399 struct logblank_t blanks[4];
1405 if (ssh->logomitdata &&
1406 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1407 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1408 /* "Session data" packets - omit the data string. */
1409 ssh_pkt_getuint32(pkt); /* skip channel id */
1410 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1411 ssh_pkt_getuint32(pkt); /* skip extended data type */
1412 blanks[nblanks].offset = pkt->savedpos + 4;
1413 blanks[nblanks].type = PKTLOG_OMIT;
1414 ssh_pkt_getstring(pkt, &str, &slen);
1416 blanks[nblanks].len = slen;
1421 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1422 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1423 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1427 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1430 struct logblank_t blanks[4];
1435 * For outgoing packets, pkt->length represents the length of the
1436 * whole packet starting at pkt->data (including some header), and
1437 * pkt->body refers to the point within that where the log-worthy
1438 * payload begins. However, incoming packets expect pkt->length to
1439 * represent only the payload length (that is, it's measured from
1440 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1441 * packet to conform to the incoming-packet semantics, so that we
1442 * can analyse it with the ssh_pkt_get functions.
1444 pkt->length -= (pkt->body - pkt->data);
1447 if (ssh->logomitdata &&
1448 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1449 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1450 /* "Session data" packets - omit the data string. */
1451 ssh_pkt_getuint32(pkt); /* skip channel id */
1452 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1453 ssh_pkt_getuint32(pkt); /* skip extended data type */
1454 blanks[nblanks].offset = pkt->savedpos + 4;
1455 blanks[nblanks].type = PKTLOG_OMIT;
1456 ssh_pkt_getstring(pkt, &str, &slen);
1458 blanks[nblanks].len = slen;
1463 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1464 conf_get_int(ssh->conf, CONF_logomitpass)) {
1465 /* If this is a password packet, blank the password(s). */
1467 ssh_pkt_getstring(pkt, &str, &slen);
1468 ssh_pkt_getstring(pkt, &str, &slen);
1469 ssh_pkt_getstring(pkt, &str, &slen);
1470 if (slen == 8 && !memcmp(str, "password", 8)) {
1471 ssh2_pkt_getbool(pkt);
1472 /* Blank the password field. */
1473 blanks[nblanks].offset = pkt->savedpos;
1474 blanks[nblanks].type = PKTLOG_BLANK;
1475 ssh_pkt_getstring(pkt, &str, &slen);
1477 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1479 /* If there's another password field beyond it (change of
1480 * password), blank that too. */
1481 ssh_pkt_getstring(pkt, &str, &slen);
1483 blanks[nblanks-1].len =
1484 pkt->savedpos - blanks[nblanks].offset;
1487 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1488 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1489 conf_get_int(ssh->conf, CONF_logomitpass)) {
1490 /* If this is a keyboard-interactive response packet, blank
1493 ssh_pkt_getuint32(pkt);
1494 blanks[nblanks].offset = pkt->savedpos;
1495 blanks[nblanks].type = PKTLOG_BLANK;
1497 ssh_pkt_getstring(pkt, &str, &slen);
1501 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1503 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1504 conf_get_int(ssh->conf, CONF_logomitpass)) {
1506 * If this is an X forwarding request packet, blank the fake
1509 * Note that while we blank the X authentication data here, we
1510 * don't take any special action to blank the start of an X11
1511 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1512 * an X connection without having session blanking enabled is
1513 * likely to leak your cookie into the log.
1516 ssh_pkt_getuint32(pkt);
1517 ssh_pkt_getstring(pkt, &str, &slen);
1518 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1519 ssh2_pkt_getbool(pkt);
1520 ssh2_pkt_getbool(pkt);
1521 ssh_pkt_getstring(pkt, &str, &slen);
1522 blanks[nblanks].offset = pkt->savedpos;
1523 blanks[nblanks].type = PKTLOG_BLANK;
1524 ssh_pkt_getstring(pkt, &str, &slen);
1526 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1532 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1533 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1534 pkt->body, pkt->length, nblanks, blanks,
1535 &ssh->v2_outgoing_sequence,
1536 pkt->downstream_id, pkt->additional_log_text);
1539 * Undo the above adjustment of pkt->length, to put the packet
1540 * back in the state we found it.
1542 pkt->length += (pkt->body - pkt->data);
1545 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1547 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1549 crBegin(ssh->ssh2_rdpkt_crstate);
1551 st->pktin = ssh_new_packet();
1553 st->pktin->type = 0;
1554 st->pktin->length = 0;
1556 st->cipherblk = ssh->sccipher->blksize;
1559 if (st->cipherblk < 8)
1561 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1563 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1566 * When dealing with a CBC-mode cipher, we want to avoid the
1567 * possibility of an attacker's tweaking the ciphertext stream
1568 * so as to cause us to feed the same block to the block
1569 * cipher more than once and thus leak information
1570 * (VU#958563). The way we do this is not to take any
1571 * decisions on the basis of anything we've decrypted until
1572 * we've verified it with a MAC. That includes the packet
1573 * length, so we just read data and check the MAC repeatedly,
1574 * and when the MAC passes, see if the length we've got is
1578 /* May as well allocate the whole lot now. */
1579 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1582 /* Read an amount corresponding to the MAC. */
1583 for (st->i = 0; st->i < st->maclen; st->i++) {
1584 while ((*datalen) == 0)
1586 st->pktin->data[st->i] = *(*data)++;
1592 unsigned char seq[4];
1593 ssh->scmac->start(ssh->sc_mac_ctx);
1594 PUT_32BIT(seq, st->incoming_sequence);
1595 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1598 for (;;) { /* Once around this loop per cipher block. */
1599 /* Read another cipher-block's worth, and tack it onto the end. */
1600 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1601 while ((*datalen) == 0)
1603 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1606 /* Decrypt one more block (a little further back in the stream). */
1607 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1608 st->pktin->data + st->packetlen,
1610 /* Feed that block to the MAC. */
1611 ssh->scmac->bytes(ssh->sc_mac_ctx,
1612 st->pktin->data + st->packetlen, st->cipherblk);
1613 st->packetlen += st->cipherblk;
1614 /* See if that gives us a valid packet. */
1615 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1616 st->pktin->data + st->packetlen) &&
1617 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1620 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1621 bombout(("No valid incoming packet found"));
1622 ssh_free_packet(st->pktin);
1626 st->pktin->maxlen = st->packetlen + st->maclen;
1627 st->pktin->data = sresize(st->pktin->data,
1628 st->pktin->maxlen + APIEXTRA,
1631 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1634 * Acquire and decrypt the first block of the packet. This will
1635 * contain the length and padding details.
1637 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1638 while ((*datalen) == 0)
1640 st->pktin->data[st->i] = *(*data)++;
1645 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1646 st->pktin->data, st->cipherblk);
1649 * Now get the length figure.
1651 st->len = toint(GET_32BIT(st->pktin->data));
1654 * _Completely_ silly lengths should be stomped on before they
1655 * do us any more damage.
1657 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1658 (st->len + 4) % st->cipherblk != 0) {
1659 bombout(("Incoming packet was garbled on decryption"));
1660 ssh_free_packet(st->pktin);
1665 * So now we can work out the total packet length.
1667 st->packetlen = st->len + 4;
1670 * Allocate memory for the rest of the packet.
1672 st->pktin->maxlen = st->packetlen + st->maclen;
1673 st->pktin->data = sresize(st->pktin->data,
1674 st->pktin->maxlen + APIEXTRA,
1678 * Read and decrypt the remainder of the packet.
1680 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1682 while ((*datalen) == 0)
1684 st->pktin->data[st->i] = *(*data)++;
1687 /* Decrypt everything _except_ the MAC. */
1689 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1690 st->pktin->data + st->cipherblk,
1691 st->packetlen - st->cipherblk);
1697 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1698 st->len + 4, st->incoming_sequence)) {
1699 bombout(("Incorrect MAC received on packet"));
1700 ssh_free_packet(st->pktin);
1704 /* Get and sanity-check the amount of random padding. */
1705 st->pad = st->pktin->data[4];
1706 if (st->pad < 4 || st->len - st->pad < 1) {
1707 bombout(("Invalid padding length on received packet"));
1708 ssh_free_packet(st->pktin);
1712 * This enables us to deduce the payload length.
1714 st->payload = st->len - st->pad - 1;
1716 st->pktin->length = st->payload + 5;
1717 st->pktin->encrypted_len = st->packetlen;
1719 st->pktin->sequence = st->incoming_sequence++;
1721 st->pktin->length = st->packetlen - st->pad;
1722 assert(st->pktin->length >= 0);
1725 * Decompress packet payload.
1728 unsigned char *newpayload;
1731 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1732 st->pktin->data + 5, st->pktin->length - 5,
1733 &newpayload, &newlen)) {
1734 if (st->pktin->maxlen < newlen + 5) {
1735 st->pktin->maxlen = newlen + 5;
1736 st->pktin->data = sresize(st->pktin->data,
1737 st->pktin->maxlen + APIEXTRA,
1740 st->pktin->length = 5 + newlen;
1741 memcpy(st->pktin->data + 5, newpayload, newlen);
1747 * pktin->body and pktin->length should identify the semantic
1748 * content of the packet, excluding the initial type byte.
1750 st->pktin->type = st->pktin->data[5];
1751 st->pktin->body = st->pktin->data + 6;
1752 st->pktin->length -= 6;
1753 assert(st->pktin->length >= 0); /* one last double-check */
1756 ssh2_log_incoming_packet(ssh, st->pktin);
1758 st->pktin->savedpos = 0;
1760 crFinish(st->pktin);
1763 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh, unsigned char **data,
1766 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1768 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1771 * Read the packet length field.
1773 for (st->i = 0; st->i < 4; st->i++) {
1774 while ((*datalen) == 0)
1776 st->length[st->i] = *(*data)++;
1780 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1781 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1782 bombout(("Invalid packet length received"));
1786 st->pktin = ssh_new_packet();
1787 st->pktin->data = snewn(st->packetlen, unsigned char);
1789 st->pktin->encrypted_len = st->packetlen;
1791 st->pktin->sequence = st->incoming_sequence++;
1794 * Read the remainder of the packet.
1796 for (st->i = 0; st->i < st->packetlen; st->i++) {
1797 while ((*datalen) == 0)
1799 st->pktin->data[st->i] = *(*data)++;
1804 * pktin->body and pktin->length should identify the semantic
1805 * content of the packet, excluding the initial type byte.
1807 st->pktin->type = st->pktin->data[0];
1808 st->pktin->body = st->pktin->data + 1;
1809 st->pktin->length = st->packetlen - 1;
1812 * Log incoming packet, possibly omitting sensitive fields.
1815 ssh2_log_incoming_packet(ssh, st->pktin);
1817 st->pktin->savedpos = 0;
1819 crFinish(st->pktin);
1822 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1824 int pad, biglen, i, pktoffs;
1828 * XXX various versions of SC (including 8.8.4) screw up the
1829 * register allocation in this function and use the same register
1830 * (D6) for len and as a temporary, with predictable results. The
1831 * following sledgehammer prevents this.
1838 ssh1_log_outgoing_packet(ssh, pkt);
1840 if (ssh->v1_compressing) {
1841 unsigned char *compblk;
1843 zlib_compress_block(ssh->cs_comp_ctx,
1844 pkt->data + 12, pkt->length - 12,
1845 &compblk, &complen);
1846 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1847 memcpy(pkt->data + 12, compblk, complen);
1849 pkt->length = complen + 12;
1852 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1854 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1855 pad = 8 - (len % 8);
1857 biglen = len + pad; /* len(padding+type+data+CRC) */
1859 for (i = pktoffs; i < 4+8; i++)
1860 pkt->data[i] = random_byte();
1861 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1862 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1863 PUT_32BIT(pkt->data + pktoffs, len);
1866 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1867 pkt->data + pktoffs + 4, biglen);
1869 if (offset_p) *offset_p = pktoffs;
1870 return biglen + 4; /* len(length+padding+type+data+CRC) */
1873 static int s_write(Ssh ssh, void *data, int len)
1876 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1877 0, NULL, NULL, 0, NULL);
1880 return sk_write(ssh->s, (char *)data, len);
1883 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1885 int len, backlog, offset;
1886 len = s_wrpkt_prepare(ssh, pkt, &offset);
1887 backlog = s_write(ssh, pkt->data + offset, len);
1888 if (backlog > SSH_MAX_BACKLOG)
1889 ssh_throttle_all(ssh, 1, backlog);
1890 ssh_free_packet(pkt);
1893 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1896 len = s_wrpkt_prepare(ssh, pkt, &offset);
1897 if (ssh->deferred_len + len > ssh->deferred_size) {
1898 ssh->deferred_size = ssh->deferred_len + len + 128;
1899 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1903 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1904 pkt->data + offset, len);
1905 ssh->deferred_len += len;
1906 ssh_free_packet(pkt);
1910 * Construct a SSH-1 packet with the specified contents.
1911 * (This all-at-once interface used to be the only one, but now SSH-1
1912 * packets can also be constructed incrementally.)
1914 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1920 pkt = ssh1_pkt_init(pkttype);
1922 while ((argtype = va_arg(ap, int)) != PKT_END) {
1923 unsigned char *argp, argchar;
1925 unsigned long argint;
1928 /* Actual fields in the packet */
1930 argint = va_arg(ap, int);
1931 ssh_pkt_adduint32(pkt, argint);
1934 argchar = (unsigned char) va_arg(ap, int);
1935 ssh_pkt_addbyte(pkt, argchar);
1938 argp = va_arg(ap, unsigned char *);
1939 arglen = va_arg(ap, int);
1940 ssh_pkt_adddata(pkt, argp, arglen);
1943 sargp = va_arg(ap, char *);
1944 ssh_pkt_addstring(pkt, sargp);
1947 bn = va_arg(ap, Bignum);
1948 ssh1_pkt_addmp(pkt, bn);
1956 static void send_packet(Ssh ssh, int pkttype, ...)
1960 va_start(ap, pkttype);
1961 pkt = construct_packet(ssh, pkttype, ap);
1966 static void defer_packet(Ssh ssh, int pkttype, ...)
1970 va_start(ap, pkttype);
1971 pkt = construct_packet(ssh, pkttype, ap);
1973 s_wrpkt_defer(ssh, pkt);
1976 static int ssh_versioncmp(char *a, char *b)
1979 unsigned long av, bv;
1981 av = strtoul(a, &ae, 10);
1982 bv = strtoul(b, &be, 10);
1984 return (av < bv ? -1 : +1);
1989 av = strtoul(ae, &ae, 10);
1990 bv = strtoul(be, &be, 10);
1992 return (av < bv ? -1 : +1);
1997 * Utility routines for putting an SSH-protocol `string' and
1998 * `uint32' into a hash state.
2000 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2002 unsigned char lenblk[4];
2003 PUT_32BIT(lenblk, len);
2004 h->bytes(s, lenblk, 4);
2005 h->bytes(s, str, len);
2008 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2010 unsigned char intblk[4];
2011 PUT_32BIT(intblk, i);
2012 h->bytes(s, intblk, 4);
2016 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2018 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2020 if (pkt->maxlen < length) {
2021 unsigned char *body = pkt->body;
2022 int offset = body ? body - pkt->data : 0;
2023 pkt->maxlen = length + 256;
2024 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2025 if (body) pkt->body = pkt->data + offset;
2028 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2031 ssh_pkt_ensure(pkt, pkt->length);
2032 memcpy(pkt->data + pkt->length - len, data, len);
2034 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2036 ssh_pkt_adddata(pkt, &byte, 1);
2038 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2040 ssh_pkt_adddata(pkt, &value, 1);
2042 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2045 PUT_32BIT(x, value);
2046 ssh_pkt_adddata(pkt, x, 4);
2048 static void ssh_pkt_addstring_start(struct Packet *pkt)
2050 ssh_pkt_adduint32(pkt, 0);
2051 pkt->savedpos = pkt->length;
2053 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2055 ssh_pkt_adddata(pkt, data, strlen(data));
2056 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2058 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2061 ssh_pkt_adddata(pkt, data, len);
2062 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2064 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2066 ssh_pkt_addstring_start(pkt);
2067 ssh_pkt_addstring_str(pkt, data);
2069 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2071 int len = ssh1_bignum_length(b);
2072 unsigned char *data = snewn(len, unsigned char);
2073 (void) ssh1_write_bignum(data, b);
2074 ssh_pkt_adddata(pkt, data, len);
2077 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2080 int i, n = (bignum_bitcount(b) + 7) / 8;
2081 p = snewn(n + 1, unsigned char);
2083 for (i = 1; i <= n; i++)
2084 p[i] = bignum_byte(b, n - i);
2086 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2088 memmove(p, p + i, n + 1 - i);
2092 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2096 p = ssh2_mpint_fmt(b, &len);
2097 ssh_pkt_addstring_start(pkt);
2098 ssh_pkt_addstring_data(pkt, (char *)p, len);
2102 static struct Packet *ssh1_pkt_init(int pkt_type)
2104 struct Packet *pkt = ssh_new_packet();
2105 pkt->length = 4 + 8; /* space for length + max padding */
2106 ssh_pkt_addbyte(pkt, pkt_type);
2107 pkt->body = pkt->data + pkt->length;
2108 pkt->type = pkt_type;
2109 pkt->downstream_id = 0;
2110 pkt->additional_log_text = NULL;
2114 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2115 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2116 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2117 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2118 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2119 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2120 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2121 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2122 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2124 static struct Packet *ssh2_pkt_init(int pkt_type)
2126 struct Packet *pkt = ssh_new_packet();
2127 pkt->length = 5; /* space for packet length + padding length */
2129 pkt->type = pkt_type;
2130 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2131 pkt->body = pkt->data + pkt->length; /* after packet type */
2132 pkt->downstream_id = 0;
2133 pkt->additional_log_text = NULL;
2138 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2139 * put the MAC on it. Final packet, ready to be sent, is stored in
2140 * pkt->data. Total length is returned.
2142 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2144 int cipherblk, maclen, padding, i;
2147 ssh2_log_outgoing_packet(ssh, pkt);
2149 if (ssh->bare_connection) {
2151 * Trivial packet construction for the bare connection
2154 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2155 pkt->body = pkt->data + 1;
2156 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2157 return pkt->length - 1;
2161 * Compress packet payload.
2164 unsigned char *newpayload;
2167 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2169 &newpayload, &newlen)) {
2171 ssh2_pkt_adddata(pkt, newpayload, newlen);
2177 * Add padding. At least four bytes, and must also bring total
2178 * length (minus MAC) up to a multiple of the block size.
2179 * If pkt->forcepad is set, make sure the packet is at least that size
2182 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2183 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2185 if (pkt->length + padding < pkt->forcepad)
2186 padding = pkt->forcepad - pkt->length;
2188 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
2189 assert(padding <= 255);
2190 maclen = ssh->csmac ? ssh->csmac->len : 0;
2191 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2192 pkt->data[4] = padding;
2193 for (i = 0; i < padding; i++)
2194 pkt->data[pkt->length + i] = random_byte();
2195 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2197 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2198 pkt->length + padding,
2199 ssh->v2_outgoing_sequence);
2200 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2203 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2204 pkt->data, pkt->length + padding);
2206 pkt->encrypted_len = pkt->length + padding;
2208 /* Ready-to-send packet starts at pkt->data. We return length. */
2209 pkt->body = pkt->data;
2210 return pkt->length + padding + maclen;
2214 * Routines called from the main SSH code to send packets. There
2215 * are quite a few of these, because we have two separate
2216 * mechanisms for delaying the sending of packets:
2218 * - In order to send an IGNORE message and a password message in
2219 * a single fixed-length blob, we require the ability to
2220 * concatenate the encrypted forms of those two packets _into_ a
2221 * single blob and then pass it to our <network.h> transport
2222 * layer in one go. Hence, there's a deferment mechanism which
2223 * works after packet encryption.
2225 * - In order to avoid sending any connection-layer messages
2226 * during repeat key exchange, we have to queue up any such
2227 * outgoing messages _before_ they are encrypted (and in
2228 * particular before they're allocated sequence numbers), and
2229 * then send them once we've finished.
2231 * I call these mechanisms `defer' and `queue' respectively, so as
2232 * to distinguish them reasonably easily.
2234 * The functions send_noqueue() and defer_noqueue() free the packet
2235 * structure they are passed. Every outgoing packet goes through
2236 * precisely one of these functions in its life; packets passed to
2237 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2238 * these or get queued, and then when the queue is later emptied
2239 * the packets are all passed to defer_noqueue().
2241 * When using a CBC-mode cipher, it's necessary to ensure that an
2242 * attacker can't provide data to be encrypted using an IV that they
2243 * know. We ensure this by prefixing each packet that might contain
2244 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2245 * mechanism, so in this case send_noqueue() ends up redirecting to
2246 * defer_noqueue(). If you don't like this inefficiency, don't use
2250 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2251 static void ssh_pkt_defersend(Ssh);
2254 * Send an SSH-2 packet immediately, without queuing or deferring.
2256 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2260 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2261 /* We need to send two packets, so use the deferral mechanism. */
2262 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2263 ssh_pkt_defersend(ssh);
2266 len = ssh2_pkt_construct(ssh, pkt);
2267 backlog = s_write(ssh, pkt->body, len);
2268 if (backlog > SSH_MAX_BACKLOG)
2269 ssh_throttle_all(ssh, 1, backlog);
2271 ssh->outgoing_data_size += pkt->encrypted_len;
2272 if (!ssh->kex_in_progress &&
2273 !ssh->bare_connection &&
2274 ssh->max_data_size != 0 &&
2275 ssh->outgoing_data_size > ssh->max_data_size)
2276 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2278 ssh_free_packet(pkt);
2282 * Defer an SSH-2 packet.
2284 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2287 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2288 ssh->deferred_len == 0 && !noignore &&
2289 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2291 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2292 * get encrypted with a known IV.
2294 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2295 ssh2_pkt_addstring_start(ipkt);
2296 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2298 len = ssh2_pkt_construct(ssh, pkt);
2299 if (ssh->deferred_len + len > ssh->deferred_size) {
2300 ssh->deferred_size = ssh->deferred_len + len + 128;
2301 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2305 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2306 ssh->deferred_len += len;
2307 ssh->deferred_data_size += pkt->encrypted_len;
2308 ssh_free_packet(pkt);
2312 * Queue an SSH-2 packet.
2314 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2316 assert(ssh->queueing);
2318 if (ssh->queuelen >= ssh->queuesize) {
2319 ssh->queuesize = ssh->queuelen + 32;
2320 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2323 ssh->queue[ssh->queuelen++] = pkt;
2327 * Either queue or send a packet, depending on whether queueing is
2330 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2333 ssh2_pkt_queue(ssh, pkt);
2335 ssh2_pkt_send_noqueue(ssh, pkt);
2339 * Either queue or defer a packet, depending on whether queueing is
2342 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2345 ssh2_pkt_queue(ssh, pkt);
2347 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2351 * Send the whole deferred data block constructed by
2352 * ssh2_pkt_defer() or SSH-1's defer_packet().
2354 * The expected use of the defer mechanism is that you call
2355 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2356 * not currently queueing, this simply sets up deferred_send_data
2357 * and then sends it. If we _are_ currently queueing, the calls to
2358 * ssh2_pkt_defer() put the deferred packets on to the queue
2359 * instead, and therefore ssh_pkt_defersend() has no deferred data
2360 * to send. Hence, there's no need to make it conditional on
2363 static void ssh_pkt_defersend(Ssh ssh)
2366 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2367 ssh->deferred_len = ssh->deferred_size = 0;
2368 sfree(ssh->deferred_send_data);
2369 ssh->deferred_send_data = NULL;
2370 if (backlog > SSH_MAX_BACKLOG)
2371 ssh_throttle_all(ssh, 1, backlog);
2373 ssh->outgoing_data_size += ssh->deferred_data_size;
2374 if (!ssh->kex_in_progress &&
2375 !ssh->bare_connection &&
2376 ssh->max_data_size != 0 &&
2377 ssh->outgoing_data_size > ssh->max_data_size)
2378 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2379 ssh->deferred_data_size = 0;
2383 * Send a packet whose length needs to be disguised (typically
2384 * passwords or keyboard-interactive responses).
2386 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2392 * The simplest way to do this is to adjust the
2393 * variable-length padding field in the outgoing packet.
2395 * Currently compiled out, because some Cisco SSH servers
2396 * don't like excessively padded packets (bah, why's it
2399 pkt->forcepad = padsize;
2400 ssh2_pkt_send(ssh, pkt);
2405 * If we can't do that, however, an alternative approach is
2406 * to use the pkt_defer mechanism to bundle the packet
2407 * tightly together with an SSH_MSG_IGNORE such that their
2408 * combined length is a constant. So first we construct the
2409 * final form of this packet and defer its sending.
2411 ssh2_pkt_defer(ssh, pkt);
2414 * Now construct an SSH_MSG_IGNORE which includes a string
2415 * that's an exact multiple of the cipher block size. (If
2416 * the cipher is NULL so that the block size is
2417 * unavailable, we don't do this trick at all, because we
2418 * gain nothing by it.)
2420 if (ssh->cscipher &&
2421 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2424 stringlen = (256 - ssh->deferred_len);
2425 stringlen += ssh->cscipher->blksize - 1;
2426 stringlen -= (stringlen % ssh->cscipher->blksize);
2429 * Temporarily disable actual compression, so we
2430 * can guarantee to get this string exactly the
2431 * length we want it. The compression-disabling
2432 * routine should return an integer indicating how
2433 * many bytes we should adjust our string length
2437 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2439 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2440 ssh2_pkt_addstring_start(pkt);
2441 for (i = 0; i < stringlen; i++) {
2442 char c = (char) random_byte();
2443 ssh2_pkt_addstring_data(pkt, &c, 1);
2445 ssh2_pkt_defer(ssh, pkt);
2447 ssh_pkt_defersend(ssh);
2452 * Send all queued SSH-2 packets. We send them by means of
2453 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2454 * packets that needed to be lumped together.
2456 static void ssh2_pkt_queuesend(Ssh ssh)
2460 assert(!ssh->queueing);
2462 for (i = 0; i < ssh->queuelen; i++)
2463 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2466 ssh_pkt_defersend(ssh);
2470 void bndebug(char *string, Bignum b)
2474 p = ssh2_mpint_fmt(b, &len);
2475 debug(("%s", string));
2476 for (i = 0; i < len; i++)
2477 debug((" %02x", p[i]));
2483 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2487 p = ssh2_mpint_fmt(b, &len);
2488 hash_string(h, s, p, len);
2493 * Packet decode functions for both SSH-1 and SSH-2.
2495 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2497 unsigned long value;
2498 if (pkt->length - pkt->savedpos < 4)
2499 return 0; /* arrgh, no way to decline (FIXME?) */
2500 value = GET_32BIT(pkt->body + pkt->savedpos);
2504 static int ssh2_pkt_getbool(struct Packet *pkt)
2506 unsigned long value;
2507 if (pkt->length - pkt->savedpos < 1)
2508 return 0; /* arrgh, no way to decline (FIXME?) */
2509 value = pkt->body[pkt->savedpos] != 0;
2513 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2518 if (pkt->length - pkt->savedpos < 4)
2520 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2525 if (pkt->length - pkt->savedpos < *length)
2527 *p = (char *)(pkt->body + pkt->savedpos);
2528 pkt->savedpos += *length;
2530 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2532 if (pkt->length - pkt->savedpos < length)
2534 pkt->savedpos += length;
2535 return pkt->body + (pkt->savedpos - length);
2537 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2538 unsigned char **keystr)
2542 j = makekey(pkt->body + pkt->savedpos,
2543 pkt->length - pkt->savedpos,
2550 assert(pkt->savedpos < pkt->length);
2554 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2559 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2560 pkt->length - pkt->savedpos, &b);
2568 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2574 ssh_pkt_getstring(pkt, &p, &length);
2579 b = bignum_from_bytes((unsigned char *)p, length);
2584 * Helper function to add an SSH-2 signature blob to a packet.
2585 * Expects to be shown the public key blob as well as the signature
2586 * blob. Normally works just like ssh2_pkt_addstring, but will
2587 * fiddle with the signature packet if necessary for
2588 * BUG_SSH2_RSA_PADDING.
2590 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2591 void *pkblob_v, int pkblob_len,
2592 void *sigblob_v, int sigblob_len)
2594 unsigned char *pkblob = (unsigned char *)pkblob_v;
2595 unsigned char *sigblob = (unsigned char *)sigblob_v;
2597 /* dmemdump(pkblob, pkblob_len); */
2598 /* dmemdump(sigblob, sigblob_len); */
2601 * See if this is in fact an ssh-rsa signature and a buggy
2602 * server; otherwise we can just do this the easy way.
2604 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2605 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2606 int pos, len, siglen;
2609 * Find the byte length of the modulus.
2612 pos = 4+7; /* skip over "ssh-rsa" */
2613 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2614 if (len < 0 || len > pkblob_len - pos - 4)
2616 pos += 4 + len; /* skip over exponent */
2617 if (pkblob_len - pos < 4)
2619 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2620 if (len < 0 || len > pkblob_len - pos - 4)
2622 pos += 4; /* find modulus itself */
2623 while (len > 0 && pkblob[pos] == 0)
2625 /* debug(("modulus length is %d\n", len)); */
2628 * Now find the signature integer.
2630 pos = 4+7; /* skip over "ssh-rsa" */
2631 if (sigblob_len < pos+4)
2633 siglen = toint(GET_32BIT(sigblob+pos));
2634 if (siglen != sigblob_len - pos - 4)
2636 /* debug(("signature length is %d\n", siglen)); */
2638 if (len != siglen) {
2639 unsigned char newlen[4];
2640 ssh2_pkt_addstring_start(pkt);
2641 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2642 /* dmemdump(sigblob, pos); */
2643 pos += 4; /* point to start of actual sig */
2644 PUT_32BIT(newlen, len);
2645 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2646 /* dmemdump(newlen, 4); */
2648 while (len-- > siglen) {
2649 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2650 /* dmemdump(newlen, 1); */
2652 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2653 /* dmemdump(sigblob+pos, siglen); */
2657 /* Otherwise fall through and do it the easy way. We also come
2658 * here as a fallback if we discover above that the key blob
2659 * is misformatted in some way. */
2663 ssh2_pkt_addstring_start(pkt);
2664 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2668 * Examine the remote side's version string and compare it against
2669 * a list of known buggy implementations.
2671 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2673 char *imp; /* pointer to implementation part */
2675 imp += strcspn(imp, "-");
2677 imp += strcspn(imp, "-");
2680 ssh->remote_bugs = 0;
2683 * General notes on server version strings:
2684 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2685 * here -- in particular, we've heard of one that's perfectly happy
2686 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2687 * so we can't distinguish them.
2689 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2690 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2691 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2692 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2693 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2694 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2696 * These versions don't support SSH1_MSG_IGNORE, so we have
2697 * to use a different defence against password length
2700 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2701 logevent("We believe remote version has SSH-1 ignore bug");
2704 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2705 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2706 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2708 * These versions need a plain password sent; they can't
2709 * handle having a null and a random length of data after
2712 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2713 logevent("We believe remote version needs a plain SSH-1 password");
2716 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2717 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2718 (!strcmp(imp, "Cisco-1.25")))) {
2720 * These versions apparently have no clue whatever about
2721 * RSA authentication and will panic and die if they see
2722 * an AUTH_RSA message.
2724 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2725 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2728 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2729 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2730 !wc_match("* VShell", imp) &&
2731 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2732 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2733 wc_match("2.1 *", imp)))) {
2735 * These versions have the HMAC bug.
2737 ssh->remote_bugs |= BUG_SSH2_HMAC;
2738 logevent("We believe remote version has SSH-2 HMAC bug");
2741 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2742 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2743 !wc_match("* VShell", imp) &&
2744 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2746 * These versions have the key-derivation bug (failing to
2747 * include the literal shared secret in the hashes that
2748 * generate the keys).
2750 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2751 logevent("We believe remote version has SSH-2 key-derivation bug");
2754 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2755 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2756 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2757 wc_match("OpenSSH_3.[0-2]*", imp) ||
2758 wc_match("mod_sftp/0.[0-8]*", imp) ||
2759 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2761 * These versions have the SSH-2 RSA padding bug.
2763 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2764 logevent("We believe remote version has SSH-2 RSA padding bug");
2767 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2768 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2769 wc_match("OpenSSH_2.[0-2]*", imp))) {
2771 * These versions have the SSH-2 session-ID bug in
2772 * public-key authentication.
2774 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2775 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2778 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2779 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2780 (wc_match("DigiSSH_2.0", imp) ||
2781 wc_match("OpenSSH_2.[0-4]*", imp) ||
2782 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2783 wc_match("Sun_SSH_1.0", imp) ||
2784 wc_match("Sun_SSH_1.0.1", imp) ||
2785 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2786 wc_match("WeOnlyDo-*", imp)))) {
2788 * These versions have the SSH-2 rekey bug.
2790 ssh->remote_bugs |= BUG_SSH2_REKEY;
2791 logevent("We believe remote version has SSH-2 rekey bug");
2794 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2795 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2796 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2797 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2799 * This version ignores our makpkt and needs to be throttled.
2801 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2802 logevent("We believe remote version ignores SSH-2 maximum packet size");
2805 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2807 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2808 * none detected automatically.
2810 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2811 logevent("We believe remote version has SSH-2 ignore bug");
2814 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2816 * Servers that don't support our winadj request for one
2817 * reason or another. Currently, none detected automatically.
2819 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2820 logevent("We believe remote version has winadj bug");
2823 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
2824 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
2825 (wc_match("OpenSSH_[2-5].*", imp) ||
2826 wc_match("OpenSSH_6.[0-6]*", imp)))) {
2828 * These versions have the SSH-2 channel request bug. 6.7 and
2830 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
2832 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
2833 logevent("We believe remote version has SSH-2 channel request bug");
2838 * The `software version' part of an SSH version string is required
2839 * to contain no spaces or minus signs.
2841 static void ssh_fix_verstring(char *str)
2843 /* Eat "<protoversion>-". */
2844 while (*str && *str != '-') str++;
2845 assert(*str == '-'); str++;
2847 /* Convert minus signs and spaces in the remaining string into
2850 if (*str == '-' || *str == ' ')
2857 * Send an appropriate SSH version string.
2859 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
2863 if (ssh->version == 2) {
2865 * Construct a v2 version string.
2867 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
2870 * Construct a v1 version string.
2872 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
2873 verstring = dupprintf("SSH-%s-%s\012",
2874 (ssh_versioncmp(svers, "1.5") <= 0 ?
2879 ssh_fix_verstring(verstring + strlen(protoname));
2881 if (ssh->version == 2) {
2884 * Record our version string.
2886 len = strcspn(verstring, "\015\012");
2887 ssh->v_c = snewn(len + 1, char);
2888 memcpy(ssh->v_c, verstring, len);
2892 logeventf(ssh, "We claim version: %.*s",
2893 strcspn(verstring, "\015\012"), verstring);
2894 s_write(ssh, verstring, strlen(verstring));
2898 static int do_ssh_init(Ssh ssh, unsigned char c)
2900 static const char protoname[] = "SSH-";
2902 struct do_ssh_init_state {
2911 crState(do_ssh_init_state);
2915 /* Search for a line beginning with the protocol name prefix in
2918 for (s->i = 0; protoname[s->i]; s->i++) {
2919 if ((char)c != protoname[s->i]) goto no;
2929 s->vstrsize = sizeof(protoname) + 16;
2930 s->vstring = snewn(s->vstrsize, char);
2931 strcpy(s->vstring, protoname);
2932 s->vslen = strlen(protoname);
2935 if (s->vslen >= s->vstrsize - 1) {
2937 s->vstring = sresize(s->vstring, s->vstrsize, char);
2939 s->vstring[s->vslen++] = c;
2942 s->version[s->i] = '\0';
2944 } else if (s->i < sizeof(s->version) - 1)
2945 s->version[s->i++] = c;
2946 } else if (c == '\012')
2948 crReturn(1); /* get another char */
2951 ssh->agentfwd_enabled = FALSE;
2952 ssh->rdpkt2_state.incoming_sequence = 0;
2954 s->vstring[s->vslen] = 0;
2955 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2956 logeventf(ssh, "Server version: %s", s->vstring);
2957 ssh_detect_bugs(ssh, s->vstring);
2960 * Decide which SSH protocol version to support.
2963 /* Anything strictly below "2.0" means protocol 1 is supported. */
2964 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2965 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2966 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2968 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2969 bombout(("SSH protocol version 1 required by configuration but "
2970 "not provided by server"));
2973 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2974 bombout(("SSH protocol version 2 required by configuration but "
2975 "not provided by server"));
2979 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
2984 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2986 /* Send the version string, if we haven't already */
2987 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
2988 ssh_send_verstring(ssh, protoname, s->version);
2990 if (ssh->version == 2) {
2993 * Record their version string.
2995 len = strcspn(s->vstring, "\015\012");
2996 ssh->v_s = snewn(len + 1, char);
2997 memcpy(ssh->v_s, s->vstring, len);
3001 * Initialise SSH-2 protocol.
3003 ssh->protocol = ssh2_protocol;
3004 ssh2_protocol_setup(ssh);
3005 ssh->s_rdpkt = ssh2_rdpkt;
3008 * Initialise SSH-1 protocol.
3010 ssh->protocol = ssh1_protocol;
3011 ssh1_protocol_setup(ssh);
3012 ssh->s_rdpkt = ssh1_rdpkt;
3014 if (ssh->version == 2)
3015 do_ssh2_transport(ssh, NULL, -1, NULL);
3017 update_specials_menu(ssh->frontend);
3018 ssh->state = SSH_STATE_BEFORE_SIZE;
3019 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3026 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3029 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3030 * the ssh-connection part, extracted and given a trivial binary
3031 * packet protocol, so we replace 'SSH-' at the start with a new
3032 * name. In proper SSH style (though of course this part of the
3033 * proper SSH protocol _isn't_ subject to this kind of
3034 * DNS-domain-based extension), we define the new name in our
3037 static const char protoname[] =
3038 "SSHCONNECTION@putty.projects.tartarus.org-";
3040 struct do_ssh_connection_init_state {
3048 crState(do_ssh_connection_init_state);
3052 /* Search for a line beginning with the protocol name prefix in
3055 for (s->i = 0; protoname[s->i]; s->i++) {
3056 if ((char)c != protoname[s->i]) goto no;
3066 s->vstrsize = sizeof(protoname) + 16;
3067 s->vstring = snewn(s->vstrsize, char);
3068 strcpy(s->vstring, protoname);
3069 s->vslen = strlen(protoname);
3072 if (s->vslen >= s->vstrsize - 1) {
3074 s->vstring = sresize(s->vstring, s->vstrsize, char);
3076 s->vstring[s->vslen++] = c;
3079 s->version[s->i] = '\0';
3081 } else if (s->i < sizeof(s->version) - 1)
3082 s->version[s->i++] = c;
3083 } else if (c == '\012')
3085 crReturn(1); /* get another char */
3088 ssh->agentfwd_enabled = FALSE;
3089 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3091 s->vstring[s->vslen] = 0;
3092 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3093 logeventf(ssh, "Server version: %s", s->vstring);
3094 ssh_detect_bugs(ssh, s->vstring);
3097 * Decide which SSH protocol version to support. This is easy in
3098 * bare ssh-connection mode: only 2.0 is legal.
3100 if (ssh_versioncmp(s->version, "2.0") < 0) {
3101 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3104 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3105 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3111 logeventf(ssh, "Using bare ssh-connection protocol");
3113 /* Send the version string, if we haven't already */
3114 ssh_send_verstring(ssh, protoname, s->version);
3117 * Initialise bare connection protocol.
3119 ssh->protocol = ssh2_bare_connection_protocol;
3120 ssh2_bare_connection_protocol_setup(ssh);
3121 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3123 update_specials_menu(ssh->frontend);
3124 ssh->state = SSH_STATE_BEFORE_SIZE;
3125 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3128 * Get authconn (really just conn) under way.
3130 do_ssh2_authconn(ssh, NULL, 0, NULL);
3137 static void ssh_process_incoming_data(Ssh ssh,
3138 unsigned char **data, int *datalen)
3140 struct Packet *pktin;
3142 pktin = ssh->s_rdpkt(ssh, data, datalen);
3144 ssh->protocol(ssh, NULL, 0, pktin);
3145 ssh_free_packet(pktin);
3149 static void ssh_queue_incoming_data(Ssh ssh,
3150 unsigned char **data, int *datalen)
3152 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3157 static void ssh_process_queued_incoming_data(Ssh ssh)
3160 unsigned char *data;
3163 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3164 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3168 while (!ssh->frozen && len > 0)
3169 ssh_process_incoming_data(ssh, &data, &len);
3172 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3176 static void ssh_set_frozen(Ssh ssh, int frozen)
3179 sk_set_frozen(ssh->s, frozen);
3180 ssh->frozen = frozen;
3183 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
3185 /* Log raw data, if we're in that mode. */
3187 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3188 0, NULL, NULL, 0, NULL);
3190 crBegin(ssh->ssh_gotdata_crstate);
3193 * To begin with, feed the characters one by one to the
3194 * protocol initialisation / selection function do_ssh_init().
3195 * When that returns 0, we're done with the initial greeting
3196 * exchange and can move on to packet discipline.
3199 int ret; /* need not be kept across crReturn */
3201 crReturnV; /* more data please */
3202 ret = ssh->do_ssh_init(ssh, *data);
3210 * We emerge from that loop when the initial negotiation is
3211 * over and we have selected an s_rdpkt function. Now pass
3212 * everything to s_rdpkt, and then pass the resulting packets
3213 * to the proper protocol handler.
3217 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3219 ssh_queue_incoming_data(ssh, &data, &datalen);
3220 /* This uses up all data and cannot cause anything interesting
3221 * to happen; indeed, for anything to happen at all, we must
3222 * return, so break out. */
3224 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3225 /* This uses up some or all data, and may freeze the
3227 ssh_process_queued_incoming_data(ssh);
3229 /* This uses up some or all data, and may freeze the
3231 ssh_process_incoming_data(ssh, &data, &datalen);
3233 /* FIXME this is probably EBW. */
3234 if (ssh->state == SSH_STATE_CLOSED)
3237 /* We're out of data. Go and get some more. */
3243 static int ssh_do_close(Ssh ssh, int notify_exit)
3246 struct ssh_channel *c;
3248 ssh->state = SSH_STATE_CLOSED;
3249 expire_timer_context(ssh);
3254 notify_remote_exit(ssh->frontend);
3259 * Now we must shut down any port- and X-forwarded channels going
3260 * through this connection.
3262 if (ssh->channels) {
3263 while (NULL != (c = index234(ssh->channels, 0))) {
3266 x11_close(c->u.x11.xconn);
3269 case CHAN_SOCKDATA_DORMANT:
3270 pfd_close(c->u.pfd.pf);
3273 del234(ssh->channels, c); /* moving next one to index 0 */
3274 if (ssh->version == 2)
3275 bufchain_clear(&c->v.v2.outbuffer);
3280 * Go through port-forwardings, and close any associated
3281 * listening sockets.
3283 if (ssh->portfwds) {
3284 struct ssh_portfwd *pf;
3285 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3286 /* Dispose of any listening socket. */
3288 pfl_terminate(pf->local);
3289 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3292 freetree234(ssh->portfwds);
3293 ssh->portfwds = NULL;
3297 * Also stop attempting to connection-share.
3299 if (ssh->connshare) {
3300 sharestate_free(ssh->connshare);
3301 ssh->connshare = NULL;
3307 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3308 const char *error_msg, int error_code)
3310 Ssh ssh = (Ssh) plug;
3311 char addrbuf[256], *msg;
3313 if (ssh->attempting_connshare) {
3315 * While we're attempting connection sharing, don't loudly log
3316 * everything that happens. Real TCP connections need to be
3317 * logged when we _start_ trying to connect, because it might
3318 * be ages before they respond if something goes wrong; but
3319 * connection sharing is local and quick to respond, and it's
3320 * sufficient to simply wait and see whether it worked
3324 sk_getaddr(addr, addrbuf, lenof(addrbuf));
3327 if (sk_addr_needs_port(addr)) {
3328 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
3330 msg = dupprintf("Connecting to %s", addrbuf);
3333 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
3341 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3342 const char *ds_err, const char *us_err)
3344 if (event == SHARE_NONE) {
3345 /* In this case, 'logtext' is an error message indicating a
3346 * reason why connection sharing couldn't be set up _at all_.
3347 * Failing that, ds_err and us_err indicate why we couldn't be
3348 * a downstream and an upstream respectively. */
3350 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3353 logeventf(ssh, "Could not set up connection sharing"
3354 " as downstream: %s", ds_err);
3356 logeventf(ssh, "Could not set up connection sharing"
3357 " as upstream: %s", us_err);
3359 } else if (event == SHARE_DOWNSTREAM) {
3360 /* In this case, 'logtext' is a local endpoint address */
3361 logeventf(ssh, "Using existing shared connection at %s", logtext);
3362 /* Also we should mention this in the console window to avoid
3363 * confusing users as to why this window doesn't behave the
3365 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3366 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3368 } else if (event == SHARE_UPSTREAM) {
3369 /* In this case, 'logtext' is a local endpoint address too */
3370 logeventf(ssh, "Sharing this connection at %s", logtext);
3374 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3377 Ssh ssh = (Ssh) plug;
3378 int need_notify = ssh_do_close(ssh, FALSE);
3381 if (!ssh->close_expected)
3382 error_msg = "Server unexpectedly closed network connection";
3384 error_msg = "Server closed network connection";
3387 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3391 notify_remote_exit(ssh->frontend);
3394 logevent(error_msg);
3395 if (!ssh->close_expected || !ssh->clean_exit)
3396 connection_fatal(ssh->frontend, "%s", error_msg);
3400 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3402 Ssh ssh = (Ssh) plug;
3403 ssh_gotdata(ssh, (unsigned char *)data, len);
3404 if (ssh->state == SSH_STATE_CLOSED) {
3405 ssh_do_close(ssh, TRUE);
3411 static void ssh_sent(Plug plug, int bufsize)
3413 Ssh ssh = (Ssh) plug;
3415 * If the send backlog on the SSH socket itself clears, we
3416 * should unthrottle the whole world if it was throttled.
3418 if (bufsize < SSH_MAX_BACKLOG)
3419 ssh_throttle_all(ssh, 0, bufsize);
3423 * Connect to specified host and port.
3424 * Returns an error message, or NULL on success.
3425 * Also places the canonical host name into `realhost'. It must be
3426 * freed by the caller.
3428 static const char *connect_to_host(Ssh ssh, char *host, int port,
3429 char **realhost, int nodelay, int keepalive)
3431 static const struct plug_function_table fn_table = {
3442 int addressfamily, sshprot;
3444 loghost = conf_get_str(ssh->conf, CONF_loghost);
3449 tmphost = dupstr(loghost);
3450 ssh->savedport = 22; /* default ssh port */
3453 * A colon suffix on the hostname string also lets us affect
3454 * savedport. (Unless there are multiple colons, in which case
3455 * we assume this is an unbracketed IPv6 literal.)
3457 colon = host_strrchr(tmphost, ':');
3458 if (colon && colon == host_strchr(tmphost, ':')) {
3461 ssh->savedport = atoi(colon);
3464 ssh->savedhost = host_strduptrim(tmphost);
3467 ssh->savedhost = host_strduptrim(host);
3469 port = 22; /* default ssh port */
3470 ssh->savedport = port;
3473 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3476 * Try connection-sharing, in case that means we don't open a
3477 * socket after all. ssh_connection_sharing_init will connect to a
3478 * previously established upstream if it can, and failing that,
3479 * establish a listening socket for _us_ to be the upstream. In
3480 * the latter case it will return NULL just as if it had done
3481 * nothing, because here we only need to care if we're a
3482 * downstream and need to do our connection setup differently.
3484 ssh->connshare = NULL;
3485 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3486 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3487 ssh->conf, ssh, &ssh->connshare);
3488 ssh->attempting_connshare = FALSE;
3489 if (ssh->s != NULL) {
3491 * We are a downstream.
3493 ssh->bare_connection = TRUE;
3494 ssh->do_ssh_init = do_ssh_connection_init;
3495 ssh->fullhostname = NULL;
3496 *realhost = dupstr(host); /* best we can do */
3499 * We're not a downstream, so open a normal socket.
3501 ssh->do_ssh_init = do_ssh_init;
3506 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3507 logeventf(ssh, "Looking up host \"%s\"%s", host,
3508 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3509 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3510 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3511 if ((err = sk_addr_error(addr)) != NULL) {
3515 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3517 ssh->s = new_connection(addr, *realhost, port,
3518 0, 1, nodelay, keepalive,
3519 (Plug) ssh, ssh->conf);
3520 if ((err = sk_socket_error(ssh->s)) != NULL) {
3522 notify_remote_exit(ssh->frontend);
3528 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3529 * send the version string too.
3531 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3534 if (sshprot == 3 && !ssh->bare_connection) {
3536 ssh_send_verstring(ssh, "SSH-", NULL);
3540 * loghost, if configured, overrides realhost.
3544 *realhost = dupstr(loghost);
3551 * Throttle or unthrottle the SSH connection.
3553 static void ssh_throttle_conn(Ssh ssh, int adjust)
3555 int old_count = ssh->conn_throttle_count;
3556 ssh->conn_throttle_count += adjust;
3557 assert(ssh->conn_throttle_count >= 0);
3558 if (ssh->conn_throttle_count && !old_count) {
3559 ssh_set_frozen(ssh, 1);
3560 } else if (!ssh->conn_throttle_count && old_count) {
3561 ssh_set_frozen(ssh, 0);
3566 * Throttle or unthrottle _all_ local data streams (for when sends
3567 * on the SSH connection itself back up).
3569 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3572 struct ssh_channel *c;
3574 if (enable == ssh->throttled_all)
3576 ssh->throttled_all = enable;
3577 ssh->overall_bufsize = bufsize;
3580 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3582 case CHAN_MAINSESSION:
3584 * This is treated separately, outside the switch.
3588 x11_override_throttle(c->u.x11.xconn, enable);
3591 /* Agent channels require no buffer management. */
3594 pfd_override_throttle(c->u.pfd.pf, enable);
3600 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3602 Ssh ssh = (Ssh) sshv;
3604 ssh->agent_response = reply;
3605 ssh->agent_response_len = replylen;
3607 if (ssh->version == 1)
3608 do_ssh1_login(ssh, NULL, -1, NULL);
3610 do_ssh2_authconn(ssh, NULL, -1, NULL);
3613 static void ssh_dialog_callback(void *sshv, int ret)
3615 Ssh ssh = (Ssh) sshv;
3617 ssh->user_response = ret;
3619 if (ssh->version == 1)
3620 do_ssh1_login(ssh, NULL, -1, NULL);
3622 do_ssh2_transport(ssh, NULL, -1, NULL);
3625 * This may have unfrozen the SSH connection, so do a
3628 ssh_process_queued_incoming_data(ssh);
3631 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3633 struct ssh_channel *c = (struct ssh_channel *)cv;
3635 void *sentreply = reply;
3637 c->u.a.outstanding_requests--;
3639 /* Fake SSH_AGENT_FAILURE. */
3640 sentreply = "\0\0\0\1\5";
3643 if (ssh->version == 2) {
3644 ssh2_add_channel_data(c, sentreply, replylen);
3647 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3648 PKT_INT, c->remoteid,
3650 PKT_DATA, sentreply, replylen,
3656 * If we've already seen an incoming EOF but haven't sent an
3657 * outgoing one, this may be the moment to send it.
3659 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3660 sshfwd_write_eof(c);
3664 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3665 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3666 * => log `wire_reason'.
3668 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3669 int code, int clean_exit)
3673 client_reason = wire_reason;
3675 error = dupprintf("Disconnected: %s", client_reason);
3677 error = dupstr("Disconnected");
3679 if (ssh->version == 1) {
3680 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3682 } else if (ssh->version == 2) {
3683 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3684 ssh2_pkt_adduint32(pktout, code);
3685 ssh2_pkt_addstring(pktout, wire_reason);
3686 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3687 ssh2_pkt_send_noqueue(ssh, pktout);
3690 ssh->close_expected = TRUE;
3691 ssh->clean_exit = clean_exit;
3692 ssh_closing((Plug)ssh, error, 0, 0);
3696 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3697 const struct ssh_signkey *ssh2keytype,
3700 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3701 return -1; /* no manual keys configured */
3706 * The fingerprint string we've been given will have things
3707 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3708 * narrow down to just the colon-separated hex block at the
3709 * end of the string.
3711 const char *p = strrchr(fingerprint, ' ');
3712 fingerprint = p ? p+1 : fingerprint;
3713 /* Quick sanity checks, including making sure it's in lowercase */
3714 assert(strlen(fingerprint) == 16*3 - 1);
3715 assert(fingerprint[2] == ':');
3716 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3718 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3720 return 1; /* success */
3725 * Construct the base64-encoded public key blob and see if
3728 unsigned char *binblob;
3730 int binlen, atoms, i;
3731 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3732 atoms = (binlen + 2) / 3;
3733 base64blob = snewn(atoms * 4 + 1, char);
3734 for (i = 0; i < atoms; i++)
3735 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3736 base64blob[atoms * 4] = '\0';
3738 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3741 return 1; /* success */
3750 * Handle the key exchange and user authentication phases.
3752 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3753 struct Packet *pktin)
3756 unsigned char cookie[8], *ptr;
3757 struct MD5Context md5c;
3758 struct do_ssh1_login_state {
3761 unsigned char *rsabuf, *keystr1, *keystr2;
3762 unsigned long supported_ciphers_mask, supported_auths_mask;
3763 int tried_publickey, tried_agent;
3764 int tis_auth_refused, ccard_auth_refused;
3765 unsigned char session_id[16];
3767 void *publickey_blob;
3768 int publickey_bloblen;
3769 char *publickey_comment;
3770 int publickey_encrypted;
3771 prompts_t *cur_prompt;
3774 unsigned char request[5], *response, *p;
3784 struct RSAKey servkey, hostkey;
3786 crState(do_ssh1_login_state);
3793 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3794 bombout(("Public key packet not received"));
3798 logevent("Received public keys");
3800 ptr = ssh_pkt_getdata(pktin, 8);
3802 bombout(("SSH-1 public key packet stopped before random cookie"));
3805 memcpy(cookie, ptr, 8);
3807 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3808 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3809 bombout(("Failed to read SSH-1 public keys from public key packet"));
3814 * Log the host key fingerprint.
3818 logevent("Host key fingerprint is:");
3819 strcpy(logmsg, " ");
3820 s->hostkey.comment = NULL;
3821 rsa_fingerprint(logmsg + strlen(logmsg),
3822 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3826 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3827 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3828 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3829 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3830 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3832 ssh->v1_local_protoflags =
3833 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3834 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3837 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3838 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3839 MD5Update(&md5c, cookie, 8);
3840 MD5Final(s->session_id, &md5c);
3842 for (i = 0; i < 32; i++)
3843 ssh->session_key[i] = random_byte();
3846 * Verify that the `bits' and `bytes' parameters match.
3848 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3849 s->servkey.bits > s->servkey.bytes * 8) {
3850 bombout(("SSH-1 public keys were badly formatted"));
3854 s->len = (s->hostkey.bytes > s->servkey.bytes ?
3855 s->hostkey.bytes : s->servkey.bytes);
3857 s->rsabuf = snewn(s->len, unsigned char);
3860 * Verify the host key.
3864 * First format the key into a string.
3866 int len = rsastr_len(&s->hostkey);
3867 char fingerprint[100];
3868 char *keystr = snewn(len, char);
3869 rsastr_fmt(keystr, &s->hostkey);
3870 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
3872 /* First check against manually configured host keys. */
3873 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
3874 if (s->dlgret == 0) { /* did not match */
3875 bombout(("Host key did not appear in manually configured list"));
3878 } else if (s->dlgret < 0) { /* none configured; use standard handling */
3879 ssh_set_frozen(ssh, 1);
3880 s->dlgret = verify_ssh_host_key(ssh->frontend,
3881 ssh->savedhost, ssh->savedport,
3882 "rsa", keystr, fingerprint,
3883 ssh_dialog_callback, ssh);
3885 if (s->dlgret < 0) {
3889 bombout(("Unexpected data from server while waiting"
3890 " for user host key response"));
3893 } while (pktin || inlen > 0);
3894 s->dlgret = ssh->user_response;
3896 ssh_set_frozen(ssh, 0);
3898 if (s->dlgret == 0) {
3899 ssh_disconnect(ssh, "User aborted at host key verification",
3908 for (i = 0; i < 32; i++) {
3909 s->rsabuf[i] = ssh->session_key[i];
3911 s->rsabuf[i] ^= s->session_id[i];
3914 if (s->hostkey.bytes > s->servkey.bytes) {
3915 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
3917 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
3919 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
3921 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
3924 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3928 logevent("Encrypted session key");
3931 int cipher_chosen = 0, warn = 0;
3932 char *cipher_string = NULL;
3934 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3935 int next_cipher = conf_get_int_int(ssh->conf,
3936 CONF_ssh_cipherlist, i);
3937 if (next_cipher == CIPHER_WARN) {
3938 /* If/when we choose a cipher, warn about it */
3940 } else if (next_cipher == CIPHER_AES) {
3941 /* XXX Probably don't need to mention this. */
3942 logevent("AES not supported in SSH-1, skipping");
3944 switch (next_cipher) {
3945 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3946 cipher_string = "3DES"; break;
3947 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3948 cipher_string = "Blowfish"; break;
3949 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3950 cipher_string = "single-DES"; break;
3952 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3956 if (!cipher_chosen) {
3957 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3958 bombout(("Server violates SSH-1 protocol by not "
3959 "supporting 3DES encryption"));
3961 /* shouldn't happen */
3962 bombout(("No supported ciphers found"));
3966 /* Warn about chosen cipher if necessary. */
3968 ssh_set_frozen(ssh, 1);
3969 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3970 ssh_dialog_callback, ssh);
3971 if (s->dlgret < 0) {
3975 bombout(("Unexpected data from server while waiting"
3976 " for user response"));
3979 } while (pktin || inlen > 0);
3980 s->dlgret = ssh->user_response;
3982 ssh_set_frozen(ssh, 0);
3983 if (s->dlgret == 0) {
3984 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3991 switch (s->cipher_type) {
3992 case SSH_CIPHER_3DES:
3993 logevent("Using 3DES encryption");
3995 case SSH_CIPHER_DES:
3996 logevent("Using single-DES encryption");
3998 case SSH_CIPHER_BLOWFISH:
3999 logevent("Using Blowfish encryption");
4003 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4004 PKT_CHAR, s->cipher_type,
4005 PKT_DATA, cookie, 8,
4006 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4007 PKT_DATA, s->rsabuf, s->len,
4008 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4010 logevent("Trying to enable encryption...");
4014 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4015 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4017 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4018 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4019 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4021 ssh->crcda_ctx = crcda_make_context();
4022 logevent("Installing CRC compensation attack detector");
4024 if (s->servkey.modulus) {
4025 sfree(s->servkey.modulus);
4026 s->servkey.modulus = NULL;
4028 if (s->servkey.exponent) {
4029 sfree(s->servkey.exponent);
4030 s->servkey.exponent = NULL;
4032 if (s->hostkey.modulus) {
4033 sfree(s->hostkey.modulus);
4034 s->hostkey.modulus = NULL;
4036 if (s->hostkey.exponent) {
4037 sfree(s->hostkey.exponent);
4038 s->hostkey.exponent = NULL;
4042 if (pktin->type != SSH1_SMSG_SUCCESS) {
4043 bombout(("Encryption not successfully enabled"));
4047 logevent("Successfully started encryption");
4049 fflush(stdout); /* FIXME eh? */
4051 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4052 int ret; /* need not be kept over crReturn */
4053 s->cur_prompt = new_prompts(ssh->frontend);
4054 s->cur_prompt->to_server = TRUE;
4055 s->cur_prompt->name = dupstr("SSH login name");
4056 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4057 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4060 crWaitUntil(!pktin);
4061 ret = get_userpass_input(s->cur_prompt, in, inlen);
4066 * Failed to get a username. Terminate.
4068 free_prompts(s->cur_prompt);
4069 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4072 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4073 free_prompts(s->cur_prompt);
4076 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4078 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4080 if (flags & FLAG_INTERACTIVE &&
4081 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4082 c_write_str(ssh, userlog);
4083 c_write_str(ssh, "\r\n");
4091 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4092 /* We must not attempt PK auth. Pretend we've already tried it. */
4093 s->tried_publickey = s->tried_agent = 1;
4095 s->tried_publickey = s->tried_agent = 0;
4097 s->tis_auth_refused = s->ccard_auth_refused = 0;
4099 * Load the public half of any configured keyfile for later use.
4101 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4102 if (!filename_is_null(s->keyfile)) {
4104 logeventf(ssh, "Reading private key file \"%.150s\"",
4105 filename_to_str(s->keyfile));
4106 keytype = key_type(s->keyfile);
4107 if (keytype == SSH_KEYTYPE_SSH1) {
4109 if (rsakey_pubblob(s->keyfile,
4110 &s->publickey_blob, &s->publickey_bloblen,
4111 &s->publickey_comment, &error)) {
4112 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
4116 logeventf(ssh, "Unable to load private key (%s)", error);
4117 msgbuf = dupprintf("Unable to load private key file "
4118 "\"%.150s\" (%s)\r\n",
4119 filename_to_str(s->keyfile),
4121 c_write_str(ssh, msgbuf);
4123 s->publickey_blob = NULL;
4127 logeventf(ssh, "Unable to use this key file (%s)",
4128 key_type_to_str(keytype));
4129 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4131 filename_to_str(s->keyfile),
4132 key_type_to_str(keytype));
4133 c_write_str(ssh, msgbuf);
4135 s->publickey_blob = NULL;
4138 s->publickey_blob = NULL;
4140 while (pktin->type == SSH1_SMSG_FAILURE) {
4141 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4143 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4145 * Attempt RSA authentication using Pageant.
4151 logevent("Pageant is running. Requesting keys.");
4153 /* Request the keys held by the agent. */
4154 PUT_32BIT(s->request, 1);
4155 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4156 if (!agent_query(s->request, 5, &r, &s->responselen,
4157 ssh_agent_callback, ssh)) {
4161 bombout(("Unexpected data from server while waiting"
4162 " for agent response"));
4165 } while (pktin || inlen > 0);
4166 r = ssh->agent_response;
4167 s->responselen = ssh->agent_response_len;
4169 s->response = (unsigned char *) r;
4170 if (s->response && s->responselen >= 5 &&
4171 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4172 s->p = s->response + 5;
4173 s->nkeys = toint(GET_32BIT(s->p));
4175 logeventf(ssh, "Pageant reported negative key count %d",
4180 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4181 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4182 unsigned char *pkblob = s->p;
4186 do { /* do while (0) to make breaking easy */
4187 n = ssh1_read_bignum
4188 (s->p, toint(s->responselen-(s->p-s->response)),
4193 n = ssh1_read_bignum
4194 (s->p, toint(s->responselen-(s->p-s->response)),
4199 if (s->responselen - (s->p-s->response) < 4)
4201 s->commentlen = toint(GET_32BIT(s->p));
4203 if (s->commentlen < 0 ||
4204 toint(s->responselen - (s->p-s->response)) <
4207 s->commentp = (char *)s->p;
4208 s->p += s->commentlen;
4212 logevent("Pageant key list packet was truncated");
4216 if (s->publickey_blob) {
4217 if (!memcmp(pkblob, s->publickey_blob,
4218 s->publickey_bloblen)) {
4219 logeventf(ssh, "Pageant key #%d matches "
4220 "configured key file", s->keyi);
4221 s->tried_publickey = 1;
4223 /* Skip non-configured key */
4226 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4227 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4228 PKT_BIGNUM, s->key.modulus, PKT_END);
4230 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4231 logevent("Key refused");
4234 logevent("Received RSA challenge");
4235 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4236 bombout(("Server's RSA challenge was badly formatted"));
4241 char *agentreq, *q, *ret;
4244 len = 1 + 4; /* message type, bit count */
4245 len += ssh1_bignum_length(s->key.exponent);
4246 len += ssh1_bignum_length(s->key.modulus);
4247 len += ssh1_bignum_length(s->challenge);
4248 len += 16; /* session id */
4249 len += 4; /* response format */
4250 agentreq = snewn(4 + len, char);
4251 PUT_32BIT(agentreq, len);
4253 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4254 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4256 q += ssh1_write_bignum(q, s->key.exponent);
4257 q += ssh1_write_bignum(q, s->key.modulus);
4258 q += ssh1_write_bignum(q, s->challenge);
4259 memcpy(q, s->session_id, 16);
4261 PUT_32BIT(q, 1); /* response format */
4262 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4263 ssh_agent_callback, ssh)) {
4268 bombout(("Unexpected data from server"
4269 " while waiting for agent"
4273 } while (pktin || inlen > 0);
4274 vret = ssh->agent_response;
4275 retlen = ssh->agent_response_len;
4280 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4281 logevent("Sending Pageant's response");
4282 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4283 PKT_DATA, ret + 5, 16,
4287 if (pktin->type == SSH1_SMSG_SUCCESS) {
4289 ("Pageant's response accepted");
4290 if (flags & FLAG_VERBOSE) {
4291 c_write_str(ssh, "Authenticated using"
4293 c_write(ssh, s->commentp,
4295 c_write_str(ssh, "\" from agent\r\n");
4300 ("Pageant's response not accepted");
4303 ("Pageant failed to answer challenge");
4307 logevent("No reply received from Pageant");
4310 freebn(s->key.exponent);
4311 freebn(s->key.modulus);
4312 freebn(s->challenge);
4317 if (s->publickey_blob && !s->tried_publickey)
4318 logevent("Configured key file not in Pageant");
4320 logevent("Failed to get reply from Pageant");
4325 if (s->publickey_blob && !s->tried_publickey) {
4327 * Try public key authentication with the specified
4330 int got_passphrase; /* need not be kept over crReturn */
4331 if (flags & FLAG_VERBOSE)
4332 c_write_str(ssh, "Trying public key authentication.\r\n");
4333 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4334 logeventf(ssh, "Trying public key \"%s\"",
4335 filename_to_str(s->keyfile));
4336 s->tried_publickey = 1;
4337 got_passphrase = FALSE;
4338 while (!got_passphrase) {
4340 * Get a passphrase, if necessary.
4342 char *passphrase = NULL; /* only written after crReturn */
4344 if (!s->publickey_encrypted) {
4345 if (flags & FLAG_VERBOSE)
4346 c_write_str(ssh, "No passphrase required.\r\n");
4349 int ret; /* need not be kept over crReturn */
4350 s->cur_prompt = new_prompts(ssh->frontend);
4351 s->cur_prompt->to_server = FALSE;
4352 s->cur_prompt->name = dupstr("SSH key passphrase");
4353 add_prompt(s->cur_prompt,
4354 dupprintf("Passphrase for key \"%.100s\": ",
4355 s->publickey_comment), FALSE);
4356 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4359 crWaitUntil(!pktin);
4360 ret = get_userpass_input(s->cur_prompt, in, inlen);
4364 /* Failed to get a passphrase. Terminate. */
4365 free_prompts(s->cur_prompt);
4366 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4370 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4371 free_prompts(s->cur_prompt);
4374 * Try decrypting key with passphrase.
4376 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4377 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4380 smemclr(passphrase, strlen(passphrase));
4384 /* Correct passphrase. */
4385 got_passphrase = TRUE;
4386 } else if (ret == 0) {
4387 c_write_str(ssh, "Couldn't load private key from ");
4388 c_write_str(ssh, filename_to_str(s->keyfile));
4389 c_write_str(ssh, " (");
4390 c_write_str(ssh, error);
4391 c_write_str(ssh, ").\r\n");
4392 got_passphrase = FALSE;
4393 break; /* go and try something else */
4394 } else if (ret == -1) {
4395 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4396 got_passphrase = FALSE;
4399 assert(0 && "unexpected return from loadrsakey()");
4400 got_passphrase = FALSE; /* placate optimisers */
4404 if (got_passphrase) {
4407 * Send a public key attempt.
4409 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4410 PKT_BIGNUM, s->key.modulus, PKT_END);
4413 if (pktin->type == SSH1_SMSG_FAILURE) {
4414 c_write_str(ssh, "Server refused our public key.\r\n");
4415 continue; /* go and try something else */
4417 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4418 bombout(("Bizarre response to offer of public key"));
4424 unsigned char buffer[32];
4425 Bignum challenge, response;
4427 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4428 bombout(("Server's RSA challenge was badly formatted"));
4431 response = rsadecrypt(challenge, &s->key);
4432 freebn(s->key.private_exponent);/* burn the evidence */
4434 for (i = 0; i < 32; i++) {
4435 buffer[i] = bignum_byte(response, 31 - i);
4439 MD5Update(&md5c, buffer, 32);
4440 MD5Update(&md5c, s->session_id, 16);
4441 MD5Final(buffer, &md5c);
4443 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4444 PKT_DATA, buffer, 16, PKT_END);
4451 if (pktin->type == SSH1_SMSG_FAILURE) {
4452 if (flags & FLAG_VERBOSE)
4453 c_write_str(ssh, "Failed to authenticate with"
4454 " our public key.\r\n");
4455 continue; /* go and try something else */
4456 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4457 bombout(("Bizarre response to RSA authentication response"));
4461 break; /* we're through! */
4467 * Otherwise, try various forms of password-like authentication.
4469 s->cur_prompt = new_prompts(ssh->frontend);
4471 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4472 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4473 !s->tis_auth_refused) {
4474 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4475 logevent("Requested TIS authentication");
4476 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4478 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4479 logevent("TIS authentication declined");
4480 if (flags & FLAG_INTERACTIVE)
4481 c_write_str(ssh, "TIS authentication refused.\r\n");
4482 s->tis_auth_refused = 1;
4487 char *instr_suf, *prompt;
4489 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4491 bombout(("TIS challenge packet was badly formed"));
4494 logevent("Received TIS challenge");
4495 s->cur_prompt->to_server = TRUE;
4496 s->cur_prompt->name = dupstr("SSH TIS authentication");
4497 /* Prompt heuristic comes from OpenSSH */
4498 if (memchr(challenge, '\n', challengelen)) {
4499 instr_suf = dupstr("");
4500 prompt = dupprintf("%.*s", challengelen, challenge);
4502 instr_suf = dupprintf("%.*s", challengelen, challenge);
4503 prompt = dupstr("Response: ");
4505 s->cur_prompt->instruction =
4506 dupprintf("Using TIS authentication.%s%s",
4507 (*instr_suf) ? "\n" : "",
4509 s->cur_prompt->instr_reqd = TRUE;
4510 add_prompt(s->cur_prompt, prompt, FALSE);
4514 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4515 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4516 !s->ccard_auth_refused) {
4517 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4518 logevent("Requested CryptoCard authentication");
4519 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4521 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4522 logevent("CryptoCard authentication declined");
4523 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4524 s->ccard_auth_refused = 1;
4529 char *instr_suf, *prompt;
4531 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4533 bombout(("CryptoCard challenge packet was badly formed"));
4536 logevent("Received CryptoCard challenge");
4537 s->cur_prompt->to_server = TRUE;
4538 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4539 s->cur_prompt->name_reqd = FALSE;
4540 /* Prompt heuristic comes from OpenSSH */
4541 if (memchr(challenge, '\n', challengelen)) {
4542 instr_suf = dupstr("");
4543 prompt = dupprintf("%.*s", challengelen, challenge);
4545 instr_suf = dupprintf("%.*s", challengelen, challenge);
4546 prompt = dupstr("Response: ");
4548 s->cur_prompt->instruction =
4549 dupprintf("Using CryptoCard authentication.%s%s",
4550 (*instr_suf) ? "\n" : "",
4552 s->cur_prompt->instr_reqd = TRUE;
4553 add_prompt(s->cur_prompt, prompt, FALSE);
4557 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4558 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4559 bombout(("No supported authentication methods available"));
4562 s->cur_prompt->to_server = TRUE;
4563 s->cur_prompt->name = dupstr("SSH password");
4564 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4565 ssh->username, ssh->savedhost),
4570 * Show password prompt, having first obtained it via a TIS
4571 * or CryptoCard exchange if we're doing TIS or CryptoCard
4575 int ret; /* need not be kept over crReturn */
4576 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4579 crWaitUntil(!pktin);
4580 ret = get_userpass_input(s->cur_prompt, in, inlen);
4585 * Failed to get a password (for example
4586 * because one was supplied on the command line
4587 * which has already failed to work). Terminate.
4589 free_prompts(s->cur_prompt);
4590 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4595 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4597 * Defence against traffic analysis: we send a
4598 * whole bunch of packets containing strings of
4599 * different lengths. One of these strings is the
4600 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4601 * The others are all random data in
4602 * SSH1_MSG_IGNORE packets. This way a passive
4603 * listener can't tell which is the password, and
4604 * hence can't deduce the password length.
4606 * Anybody with a password length greater than 16
4607 * bytes is going to have enough entropy in their
4608 * password that a listener won't find it _that_
4609 * much help to know how long it is. So what we'll
4612 * - if password length < 16, we send 15 packets
4613 * containing string lengths 1 through 15
4615 * - otherwise, we let N be the nearest multiple
4616 * of 8 below the password length, and send 8
4617 * packets containing string lengths N through
4618 * N+7. This won't obscure the order of
4619 * magnitude of the password length, but it will
4620 * introduce a bit of extra uncertainty.
4622 * A few servers can't deal with SSH1_MSG_IGNORE, at
4623 * least in this context. For these servers, we need
4624 * an alternative defence. We make use of the fact
4625 * that the password is interpreted as a C string:
4626 * so we can append a NUL, then some random data.
4628 * A few servers can deal with neither SSH1_MSG_IGNORE
4629 * here _nor_ a padded password string.
4630 * For these servers we are left with no defences
4631 * against password length sniffing.
4633 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4634 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4636 * The server can deal with SSH1_MSG_IGNORE, so
4637 * we can use the primary defence.
4639 int bottom, top, pwlen, i;
4642 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4644 bottom = 0; /* zero length passwords are OK! :-) */
4647 bottom = pwlen & ~7;
4651 assert(pwlen >= bottom && pwlen <= top);
4653 randomstr = snewn(top + 1, char);
4655 for (i = bottom; i <= top; i++) {
4657 defer_packet(ssh, s->pwpkt_type,
4658 PKT_STR,s->cur_prompt->prompts[0]->result,
4661 for (j = 0; j < i; j++) {
4663 randomstr[j] = random_byte();
4664 } while (randomstr[j] == '\0');
4666 randomstr[i] = '\0';
4667 defer_packet(ssh, SSH1_MSG_IGNORE,
4668 PKT_STR, randomstr, PKT_END);
4671 logevent("Sending password with camouflage packets");
4672 ssh_pkt_defersend(ssh);
4675 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4677 * The server can't deal with SSH1_MSG_IGNORE
4678 * but can deal with padded passwords, so we
4679 * can use the secondary defence.
4685 len = strlen(s->cur_prompt->prompts[0]->result);
4686 if (len < sizeof(string)) {
4688 strcpy(string, s->cur_prompt->prompts[0]->result);
4689 len++; /* cover the zero byte */
4690 while (len < sizeof(string)) {
4691 string[len++] = (char) random_byte();
4694 ss = s->cur_prompt->prompts[0]->result;
4696 logevent("Sending length-padded password");
4697 send_packet(ssh, s->pwpkt_type,
4698 PKT_INT, len, PKT_DATA, ss, len,
4702 * The server is believed unable to cope with
4703 * any of our password camouflage methods.
4706 len = strlen(s->cur_prompt->prompts[0]->result);
4707 logevent("Sending unpadded password");
4708 send_packet(ssh, s->pwpkt_type,
4710 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4714 send_packet(ssh, s->pwpkt_type,
4715 PKT_STR, s->cur_prompt->prompts[0]->result,
4718 logevent("Sent password");
4719 free_prompts(s->cur_prompt);
4721 if (pktin->type == SSH1_SMSG_FAILURE) {
4722 if (flags & FLAG_VERBOSE)
4723 c_write_str(ssh, "Access denied\r\n");
4724 logevent("Authentication refused");
4725 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4726 bombout(("Strange packet received, type %d", pktin->type));
4732 if (s->publickey_blob) {
4733 sfree(s->publickey_blob);
4734 sfree(s->publickey_comment);
4737 logevent("Authentication successful");
4742 static void ssh_channel_try_eof(struct ssh_channel *c)
4745 assert(c->pending_eof); /* precondition for calling us */
4747 return; /* can't close: not even opened yet */
4748 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4749 return; /* can't send EOF: pending outgoing data */
4751 c->pending_eof = FALSE; /* we're about to send it */
4752 if (ssh->version == 1) {
4753 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4755 c->closes |= CLOSES_SENT_EOF;
4757 struct Packet *pktout;
4758 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4759 ssh2_pkt_adduint32(pktout, c->remoteid);
4760 ssh2_pkt_send(ssh, pktout);
4761 c->closes |= CLOSES_SENT_EOF;
4762 ssh2_channel_check_close(c);
4766 Conf *sshfwd_get_conf(struct ssh_channel *c)
4772 void sshfwd_write_eof(struct ssh_channel *c)
4776 if (ssh->state == SSH_STATE_CLOSED)
4779 if (c->closes & CLOSES_SENT_EOF)
4782 c->pending_eof = TRUE;
4783 ssh_channel_try_eof(c);
4786 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4790 if (ssh->state == SSH_STATE_CLOSED)
4795 x11_close(c->u.x11.xconn);
4796 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4800 case CHAN_SOCKDATA_DORMANT:
4801 pfd_close(c->u.pfd.pf);
4802 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4805 c->type = CHAN_ZOMBIE;
4806 c->pending_eof = FALSE; /* this will confuse a zombie channel */
4808 ssh2_channel_check_close(c);
4811 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4815 if (ssh->state == SSH_STATE_CLOSED)
4818 if (ssh->version == 1) {
4819 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4820 PKT_INT, c->remoteid,
4821 PKT_INT, len, PKT_DATA, buf, len,
4824 * In SSH-1 we can return 0 here - implying that forwarded
4825 * connections are never individually throttled - because
4826 * the only circumstance that can cause throttling will be
4827 * the whole SSH connection backing up, in which case
4828 * _everything_ will be throttled as a whole.
4832 ssh2_add_channel_data(c, buf, len);
4833 return ssh2_try_send(c);
4837 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4842 if (ssh->state == SSH_STATE_CLOSED)
4845 if (ssh->version == 1) {
4846 buflimit = SSH1_BUFFER_LIMIT;
4848 buflimit = c->v.v2.locmaxwin;
4849 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4851 if (c->throttling_conn && bufsize <= buflimit) {
4852 c->throttling_conn = 0;
4853 ssh_throttle_conn(ssh, -1);
4857 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4859 struct queued_handler *qh = ssh->qhead;
4863 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4866 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4867 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4870 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4871 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4875 ssh->qhead = qh->next;
4877 if (ssh->qhead->msg1 > 0) {
4878 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4879 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4881 if (ssh->qhead->msg2 > 0) {
4882 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4883 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4886 ssh->qhead = ssh->qtail = NULL;
4889 qh->handler(ssh, pktin, qh->ctx);
4894 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4895 chandler_fn_t handler, void *ctx)
4897 struct queued_handler *qh;
4899 qh = snew(struct queued_handler);
4902 qh->handler = handler;
4906 if (ssh->qtail == NULL) {
4910 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4911 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4914 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4915 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4918 ssh->qtail->next = qh;
4923 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4925 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4927 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4928 SSH2_MSG_REQUEST_SUCCESS)) {
4929 logeventf(ssh, "Remote port forwarding from %s enabled",
4932 logeventf(ssh, "Remote port forwarding from %s refused",
4935 rpf = del234(ssh->rportfwds, pf);
4937 pf->pfrec->remote = NULL;
4942 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
4945 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
4948 pf->share_ctx = share_ctx;
4949 pf->shost = dupstr(shost);
4951 pf->sportdesc = NULL;
4952 if (!ssh->rportfwds) {
4953 assert(ssh->version == 2);
4954 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4956 if (add234(ssh->rportfwds, pf) != pf) {
4964 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
4967 share_got_pkt_from_server(ctx, pktin->type,
4968 pktin->body, pktin->length);
4971 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
4973 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
4974 ssh_sharing_global_request_response, share_ctx);
4977 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4979 struct ssh_portfwd *epf;
4983 if (!ssh->portfwds) {
4984 ssh->portfwds = newtree234(ssh_portcmp);
4987 * Go through the existing port forwardings and tag them
4988 * with status==DESTROY. Any that we want to keep will be
4989 * re-enabled (status==KEEP) as we go through the
4990 * configuration and find out which bits are the same as
4993 struct ssh_portfwd *epf;
4995 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4996 epf->status = DESTROY;
4999 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5001 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5002 char *kp, *kp2, *vp, *vp2;
5003 char address_family, type;
5004 int sport,dport,sserv,dserv;
5005 char *sports, *dports, *saddr, *host;
5009 address_family = 'A';
5011 if (*kp == 'A' || *kp == '4' || *kp == '6')
5012 address_family = *kp++;
5013 if (*kp == 'L' || *kp == 'R')
5016 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5018 * There's a colon in the middle of the source port
5019 * string, which means that the part before it is
5020 * actually a source address.
5022 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5023 saddr = host_strduptrim(saddr_tmp);
5030 sport = atoi(sports);
5034 sport = net_service_lookup(sports);
5036 logeventf(ssh, "Service lookup failed for source"
5037 " port \"%s\"", sports);
5041 if (type == 'L' && !strcmp(val, "D")) {
5042 /* dynamic forwarding */
5049 /* ordinary forwarding */
5051 vp2 = vp + host_strcspn(vp, ":");
5052 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5056 dport = atoi(dports);
5060 dport = net_service_lookup(dports);
5062 logeventf(ssh, "Service lookup failed for destination"
5063 " port \"%s\"", dports);
5068 if (sport && dport) {
5069 /* Set up a description of the source port. */
5070 struct ssh_portfwd *pfrec, *epfrec;
5072 pfrec = snew(struct ssh_portfwd);
5074 pfrec->saddr = saddr;
5075 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5076 pfrec->sport = sport;
5077 pfrec->daddr = host;
5078 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5079 pfrec->dport = dport;
5080 pfrec->local = NULL;
5081 pfrec->remote = NULL;
5082 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5083 address_family == '6' ? ADDRTYPE_IPV6 :
5086 epfrec = add234(ssh->portfwds, pfrec);
5087 if (epfrec != pfrec) {
5088 if (epfrec->status == DESTROY) {
5090 * We already have a port forwarding up and running
5091 * with precisely these parameters. Hence, no need
5092 * to do anything; simply re-tag the existing one
5095 epfrec->status = KEEP;
5098 * Anything else indicates that there was a duplicate
5099 * in our input, which we'll silently ignore.
5101 free_portfwd(pfrec);
5103 pfrec->status = CREATE;
5112 * Now go through and destroy any port forwardings which were
5115 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5116 if (epf->status == DESTROY) {
5119 message = dupprintf("%s port forwarding from %s%s%d",
5120 epf->type == 'L' ? "local" :
5121 epf->type == 'R' ? "remote" : "dynamic",
5122 epf->saddr ? epf->saddr : "",
5123 epf->saddr ? ":" : "",
5126 if (epf->type != 'D') {
5127 char *msg2 = dupprintf("%s to %s:%d", message,
5128 epf->daddr, epf->dport);
5133 logeventf(ssh, "Cancelling %s", message);
5136 /* epf->remote or epf->local may be NULL if setting up a
5137 * forwarding failed. */
5139 struct ssh_rportfwd *rpf = epf->remote;
5140 struct Packet *pktout;
5143 * Cancel the port forwarding at the server
5146 if (ssh->version == 1) {
5148 * We cannot cancel listening ports on the
5149 * server side in SSH-1! There's no message
5150 * to support it. Instead, we simply remove
5151 * the rportfwd record from the local end
5152 * so that any connections the server tries
5153 * to make on it are rejected.
5156 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5157 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5158 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5160 ssh2_pkt_addstring(pktout, epf->saddr);
5161 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5162 /* XXX: rport_acceptall may not represent
5163 * what was used to open the original connection,
5164 * since it's reconfigurable. */
5165 ssh2_pkt_addstring(pktout, "");
5167 ssh2_pkt_addstring(pktout, "localhost");
5169 ssh2_pkt_adduint32(pktout, epf->sport);
5170 ssh2_pkt_send(ssh, pktout);
5173 del234(ssh->rportfwds, rpf);
5175 } else if (epf->local) {
5176 pfl_terminate(epf->local);
5179 delpos234(ssh->portfwds, i);
5181 i--; /* so we don't skip one in the list */
5185 * And finally, set up any new port forwardings (status==CREATE).
5187 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5188 if (epf->status == CREATE) {
5189 char *sportdesc, *dportdesc;
5190 sportdesc = dupprintf("%s%s%s%s%d%s",
5191 epf->saddr ? epf->saddr : "",
5192 epf->saddr ? ":" : "",
5193 epf->sserv ? epf->sserv : "",
5194 epf->sserv ? "(" : "",
5196 epf->sserv ? ")" : "");
5197 if (epf->type == 'D') {
5200 dportdesc = dupprintf("%s:%s%s%d%s",
5202 epf->dserv ? epf->dserv : "",
5203 epf->dserv ? "(" : "",
5205 epf->dserv ? ")" : "");
5208 if (epf->type == 'L') {
5209 char *err = pfl_listen(epf->daddr, epf->dport,
5210 epf->saddr, epf->sport,
5211 ssh, conf, &epf->local,
5212 epf->addressfamily);
5214 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5215 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5216 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5217 sportdesc, dportdesc,
5218 err ? " failed: " : "", err ? err : "");
5221 } else if (epf->type == 'D') {
5222 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5223 ssh, conf, &epf->local,
5224 epf->addressfamily);
5226 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5227 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5228 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5230 err ? " failed: " : "", err ? err : "");
5235 struct ssh_rportfwd *pf;
5238 * Ensure the remote port forwardings tree exists.
5240 if (!ssh->rportfwds) {
5241 if (ssh->version == 1)
5242 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5244 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5247 pf = snew(struct ssh_rportfwd);
5248 pf->share_ctx = NULL;
5249 pf->dhost = dupstr(epf->daddr);
5250 pf->dport = epf->dport;
5252 pf->shost = dupstr(epf->saddr);
5253 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5254 pf->shost = dupstr("");
5256 pf->shost = dupstr("localhost");
5258 pf->sport = epf->sport;
5259 if (add234(ssh->rportfwds, pf) != pf) {
5260 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5261 epf->daddr, epf->dport);
5264 logeventf(ssh, "Requesting remote port %s"
5265 " forward to %s", sportdesc, dportdesc);
5267 pf->sportdesc = sportdesc;
5272 if (ssh->version == 1) {
5273 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5274 PKT_INT, epf->sport,
5275 PKT_STR, epf->daddr,
5276 PKT_INT, epf->dport,
5278 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5280 ssh_rportfwd_succfail, pf);
5282 struct Packet *pktout;
5283 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5284 ssh2_pkt_addstring(pktout, "tcpip-forward");
5285 ssh2_pkt_addbool(pktout, 1);/* want reply */
5286 ssh2_pkt_addstring(pktout, pf->shost);
5287 ssh2_pkt_adduint32(pktout, pf->sport);
5288 ssh2_pkt_send(ssh, pktout);
5290 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5291 SSH2_MSG_REQUEST_FAILURE,
5292 ssh_rportfwd_succfail, pf);
5301 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5304 int stringlen, bufsize;
5306 ssh_pkt_getstring(pktin, &string, &stringlen);
5307 if (string == NULL) {
5308 bombout(("Incoming terminal data packet was badly formed"));
5312 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5314 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5315 ssh->v1_stdout_throttling = 1;
5316 ssh_throttle_conn(ssh, +1);
5320 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5322 /* Remote side is trying to open a channel to talk to our
5323 * X-Server. Give them back a local channel number. */
5324 struct ssh_channel *c;
5325 int remoteid = ssh_pkt_getuint32(pktin);
5327 logevent("Received X11 connect request");
5328 /* Refuse if X11 forwarding is disabled. */
5329 if (!ssh->X11_fwd_enabled) {
5330 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5331 PKT_INT, remoteid, PKT_END);
5332 logevent("Rejected X11 connect request");
5334 c = snew(struct ssh_channel);
5337 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5338 c->remoteid = remoteid;
5339 c->halfopen = FALSE;
5340 c->localid = alloc_channel_id(ssh);
5342 c->pending_eof = FALSE;
5343 c->throttling_conn = 0;
5344 c->type = CHAN_X11; /* identify channel type */
5345 add234(ssh->channels, c);
5346 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5347 PKT_INT, c->remoteid, PKT_INT,
5348 c->localid, PKT_END);
5349 logevent("Opened X11 forward channel");
5353 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5355 /* Remote side is trying to open a channel to talk to our
5356 * agent. Give them back a local channel number. */
5357 struct ssh_channel *c;
5358 int remoteid = ssh_pkt_getuint32(pktin);
5360 /* Refuse if agent forwarding is disabled. */
5361 if (!ssh->agentfwd_enabled) {
5362 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5363 PKT_INT, remoteid, PKT_END);
5365 c = snew(struct ssh_channel);
5367 c->remoteid = remoteid;
5368 c->halfopen = FALSE;
5369 c->localid = alloc_channel_id(ssh);
5371 c->pending_eof = FALSE;
5372 c->throttling_conn = 0;
5373 c->type = CHAN_AGENT; /* identify channel type */
5374 c->u.a.lensofar = 0;
5375 c->u.a.message = NULL;
5376 c->u.a.outstanding_requests = 0;
5377 add234(ssh->channels, c);
5378 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5379 PKT_INT, c->remoteid, PKT_INT, c->localid,
5384 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5386 /* Remote side is trying to open a channel to talk to a
5387 * forwarded port. Give them back a local channel number. */
5388 struct ssh_rportfwd pf, *pfp;
5394 remoteid = ssh_pkt_getuint32(pktin);
5395 ssh_pkt_getstring(pktin, &host, &hostsize);
5396 port = ssh_pkt_getuint32(pktin);
5398 pf.dhost = dupprintf("%.*s", hostsize, host);
5400 pfp = find234(ssh->rportfwds, &pf, NULL);
5403 logeventf(ssh, "Rejected remote port open request for %s:%d",
5405 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5406 PKT_INT, remoteid, PKT_END);
5408 struct ssh_channel *c = snew(struct ssh_channel);
5411 logeventf(ssh, "Received remote port open request for %s:%d",
5413 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5414 c, ssh->conf, pfp->pfrec->addressfamily);
5416 logeventf(ssh, "Port open failed: %s", err);
5419 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5420 PKT_INT, remoteid, PKT_END);
5422 c->remoteid = remoteid;
5423 c->halfopen = FALSE;
5424 c->localid = alloc_channel_id(ssh);
5426 c->pending_eof = FALSE;
5427 c->throttling_conn = 0;
5428 c->type = CHAN_SOCKDATA; /* identify channel type */
5429 add234(ssh->channels, c);
5430 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5431 PKT_INT, c->remoteid, PKT_INT,
5432 c->localid, PKT_END);
5433 logevent("Forwarded port opened successfully");
5440 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5442 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5443 unsigned int localid = ssh_pkt_getuint32(pktin);
5444 struct ssh_channel *c;
5446 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5447 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5448 c->remoteid = localid;
5449 c->halfopen = FALSE;
5450 c->type = CHAN_SOCKDATA;
5451 c->throttling_conn = 0;
5452 pfd_confirm(c->u.pfd.pf);
5455 if (c && c->pending_eof) {
5457 * We have a pending close on this channel,
5458 * which we decided on before the server acked
5459 * the channel open. So now we know the
5460 * remoteid, we can close it again.
5462 ssh_channel_try_eof(c);
5466 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5468 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5469 struct ssh_channel *c;
5471 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5472 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5473 logevent("Forwarded connection refused by server");
5474 pfd_close(c->u.pfd.pf);
5475 del234(ssh->channels, c);
5480 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5482 /* Remote side closes a channel. */
5483 unsigned i = ssh_pkt_getuint32(pktin);
5484 struct ssh_channel *c;
5485 c = find234(ssh->channels, &i, ssh_channelfind);
5486 if (c && !c->halfopen) {
5488 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5489 !(c->closes & CLOSES_RCVD_EOF)) {
5491 * Received CHANNEL_CLOSE, which we translate into
5494 int send_close = FALSE;
5496 c->closes |= CLOSES_RCVD_EOF;
5501 x11_send_eof(c->u.x11.xconn);
5507 pfd_send_eof(c->u.pfd.pf);
5516 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5517 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5519 c->closes |= CLOSES_SENT_EOF;
5523 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5524 !(c->closes & CLOSES_RCVD_CLOSE)) {
5526 if (!(c->closes & CLOSES_SENT_EOF)) {
5527 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5528 " for which we never sent CHANNEL_CLOSE\n", i));
5531 c->closes |= CLOSES_RCVD_CLOSE;
5534 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5535 !(c->closes & CLOSES_SENT_CLOSE)) {
5536 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5537 PKT_INT, c->remoteid, PKT_END);
5538 c->closes |= CLOSES_SENT_CLOSE;
5541 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5542 ssh_channel_destroy(c);
5544 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5545 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5546 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5551 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5553 /* Data sent down one of our channels. */
5554 int i = ssh_pkt_getuint32(pktin);
5557 struct ssh_channel *c;
5559 ssh_pkt_getstring(pktin, &p, &len);
5561 c = find234(ssh->channels, &i, ssh_channelfind);
5566 bufsize = x11_send(c->u.x11.xconn, p, len);
5569 bufsize = pfd_send(c->u.pfd.pf, p, len);
5572 /* Data for an agent message. Buffer it. */
5574 if (c->u.a.lensofar < 4) {
5575 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5576 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5580 c->u.a.lensofar += l;
5582 if (c->u.a.lensofar == 4) {
5584 4 + GET_32BIT(c->u.a.msglen);
5585 c->u.a.message = snewn(c->u.a.totallen,
5587 memcpy(c->u.a.message, c->u.a.msglen, 4);
5589 if (c->u.a.lensofar >= 4 && len > 0) {
5591 min(c->u.a.totallen - c->u.a.lensofar,
5593 memcpy(c->u.a.message + c->u.a.lensofar, p,
5597 c->u.a.lensofar += l;
5599 if (c->u.a.lensofar == c->u.a.totallen) {
5602 c->u.a.outstanding_requests++;
5603 if (agent_query(c->u.a.message,
5606 ssh_agentf_callback, c))
5607 ssh_agentf_callback(c, reply, replylen);
5608 sfree(c->u.a.message);
5609 c->u.a.lensofar = 0;
5612 bufsize = 0; /* agent channels never back up */
5615 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5616 c->throttling_conn = 1;
5617 ssh_throttle_conn(ssh, +1);
5622 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5624 ssh->exitcode = ssh_pkt_getuint32(pktin);
5625 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5626 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5628 * In case `helpful' firewalls or proxies tack
5629 * extra human-readable text on the end of the
5630 * session which we might mistake for another
5631 * encrypted packet, we close the session once
5632 * we've sent EXIT_CONFIRMATION.
5634 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5637 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5638 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5640 struct Packet *pktout = (struct Packet *)data;
5642 unsigned int arg = 0;
5643 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5644 if (i == lenof(ssh_ttymodes)) return;
5645 switch (ssh_ttymodes[i].type) {
5647 arg = ssh_tty_parse_specchar(val);
5650 arg = ssh_tty_parse_boolean(val);
5653 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5654 ssh2_pkt_addbyte(pktout, arg);
5657 int ssh_agent_forwarding_permitted(Ssh ssh)
5659 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5662 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5663 struct Packet *pktin)
5665 crBegin(ssh->do_ssh1_connection_crstate);
5667 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5668 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5669 ssh1_smsg_stdout_stderr_data;
5671 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5672 ssh1_msg_channel_open_confirmation;
5673 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5674 ssh1_msg_channel_open_failure;
5675 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5676 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5677 ssh1_msg_channel_close;
5678 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5679 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5681 if (ssh_agent_forwarding_permitted(ssh)) {
5682 logevent("Requesting agent forwarding");
5683 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5687 if (pktin->type != SSH1_SMSG_SUCCESS
5688 && pktin->type != SSH1_SMSG_FAILURE) {
5689 bombout(("Protocol confusion"));
5691 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5692 logevent("Agent forwarding refused");
5694 logevent("Agent forwarding enabled");
5695 ssh->agentfwd_enabled = TRUE;
5696 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5700 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5702 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5704 if (!ssh->x11disp) {
5705 /* FIXME: return an error message from x11_setup_display */
5706 logevent("X11 forwarding not enabled: unable to"
5707 " initialise X display");
5709 ssh->x11auth = x11_invent_fake_auth
5710 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5711 ssh->x11auth->disp = ssh->x11disp;
5713 logevent("Requesting X11 forwarding");
5714 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5715 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5716 PKT_STR, ssh->x11auth->protoname,
5717 PKT_STR, ssh->x11auth->datastring,
5718 PKT_INT, ssh->x11disp->screennum,
5721 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5722 PKT_STR, ssh->x11auth->protoname,
5723 PKT_STR, ssh->x11auth->datastring,
5729 if (pktin->type != SSH1_SMSG_SUCCESS
5730 && pktin->type != SSH1_SMSG_FAILURE) {
5731 bombout(("Protocol confusion"));
5733 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5734 logevent("X11 forwarding refused");
5736 logevent("X11 forwarding enabled");
5737 ssh->X11_fwd_enabled = TRUE;
5738 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5743 ssh_setup_portfwd(ssh, ssh->conf);
5744 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5746 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5748 /* Unpick the terminal-speed string. */
5749 /* XXX perhaps we should allow no speeds to be sent. */
5750 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5751 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5752 /* Send the pty request. */
5753 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5754 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5755 ssh_pkt_adduint32(pkt, ssh->term_height);
5756 ssh_pkt_adduint32(pkt, ssh->term_width);
5757 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5758 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5759 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5760 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5761 ssh_pkt_adduint32(pkt, ssh->ispeed);
5762 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5763 ssh_pkt_adduint32(pkt, ssh->ospeed);
5764 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5766 ssh->state = SSH_STATE_INTERMED;
5770 if (pktin->type != SSH1_SMSG_SUCCESS
5771 && pktin->type != SSH1_SMSG_FAILURE) {
5772 bombout(("Protocol confusion"));
5774 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5775 c_write_str(ssh, "Server refused to allocate pty\r\n");
5776 ssh->editing = ssh->echoing = 1;
5778 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5779 ssh->ospeed, ssh->ispeed);
5780 ssh->got_pty = TRUE;
5783 ssh->editing = ssh->echoing = 1;
5786 if (conf_get_int(ssh->conf, CONF_compression)) {
5787 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5791 if (pktin->type != SSH1_SMSG_SUCCESS
5792 && pktin->type != SSH1_SMSG_FAILURE) {
5793 bombout(("Protocol confusion"));
5795 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5796 c_write_str(ssh, "Server refused to compress\r\n");
5798 logevent("Started compression");
5799 ssh->v1_compressing = TRUE;
5800 ssh->cs_comp_ctx = zlib_compress_init();
5801 logevent("Initialised zlib (RFC1950) compression");
5802 ssh->sc_comp_ctx = zlib_decompress_init();
5803 logevent("Initialised zlib (RFC1950) decompression");
5807 * Start the shell or command.
5809 * Special case: if the first-choice command is an SSH-2
5810 * subsystem (hence not usable here) and the second choice
5811 * exists, we fall straight back to that.
5814 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5816 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5817 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5818 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5819 ssh->fallback_cmd = TRUE;
5822 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5824 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5825 logevent("Started session");
5828 ssh->state = SSH_STATE_SESSION;
5829 if (ssh->size_needed)
5830 ssh_size(ssh, ssh->term_width, ssh->term_height);
5831 if (ssh->eof_needed)
5832 ssh_special(ssh, TS_EOF);
5835 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
5837 ssh->channels = newtree234(ssh_channelcmp);
5841 * By this point, most incoming packets are already being
5842 * handled by the dispatch table, and we need only pay
5843 * attention to the unusual ones.
5848 if (pktin->type == SSH1_SMSG_SUCCESS) {
5849 /* may be from EXEC_SHELL on some servers */
5850 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5851 /* may be from EXEC_SHELL on some servers
5852 * if no pty is available or in other odd cases. Ignore */
5854 bombout(("Strange packet received: type %d", pktin->type));
5859 int len = min(inlen, 512);
5860 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5861 PKT_INT, len, PKT_DATA, in, len,
5873 * Handle the top-level SSH-2 protocol.
5875 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5880 ssh_pkt_getstring(pktin, &msg, &msglen);
5881 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5884 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5886 /* log reason code in disconnect message */
5890 ssh_pkt_getstring(pktin, &msg, &msglen);
5891 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5894 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5896 /* Do nothing, because we're ignoring it! Duhh. */
5899 static void ssh1_protocol_setup(Ssh ssh)
5904 * Most messages are handled by the coroutines.
5906 for (i = 0; i < 256; i++)
5907 ssh->packet_dispatch[i] = NULL;
5910 * These special message types we install handlers for.
5912 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5913 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5914 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5917 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5918 struct Packet *pktin)
5920 unsigned char *in=(unsigned char*)vin;
5921 if (ssh->state == SSH_STATE_CLOSED)
5924 if (pktin && ssh->packet_dispatch[pktin->type]) {
5925 ssh->packet_dispatch[pktin->type](ssh, pktin);
5929 if (!ssh->protocol_initial_phase_done) {
5930 if (do_ssh1_login(ssh, in, inlen, pktin))
5931 ssh->protocol_initial_phase_done = TRUE;
5936 do_ssh1_connection(ssh, in, inlen, pktin);
5940 * Utility routine for decoding comma-separated strings in KEXINIT.
5942 static int in_commasep_string(char const *needle, char const *haystack,
5946 if (!needle || !haystack) /* protect against null pointers */
5948 needlen = strlen(needle);
5951 * Is it at the start of the string?
5953 if (haylen >= needlen && /* haystack is long enough */
5954 !memcmp(needle, haystack, needlen) && /* initial match */
5955 (haylen == needlen || haystack[needlen] == ',')
5956 /* either , or EOS follows */
5960 * If not, search for the next comma and resume after that.
5961 * If no comma found, terminate.
5963 while (haylen > 0 && *haystack != ',')
5964 haylen--, haystack++;
5967 haylen--, haystack++; /* skip over comma itself */
5972 * Similar routine for checking whether we have the first string in a list.
5974 static int first_in_commasep_string(char const *needle, char const *haystack,
5978 if (!needle || !haystack) /* protect against null pointers */
5980 needlen = strlen(needle);
5982 * Is it at the start of the string?
5984 if (haylen >= needlen && /* haystack is long enough */
5985 !memcmp(needle, haystack, needlen) && /* initial match */
5986 (haylen == needlen || haystack[needlen] == ',')
5987 /* either , or EOS follows */
5994 * Add a value to the comma-separated string at the end of the packet.
5995 * If the value is already in the string, don't bother adding it again.
5997 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
5999 if (in_commasep_string(data, (char *)pkt->data + pkt->savedpos,
6000 pkt->length - pkt->savedpos)) return;
6001 if (pkt->length - pkt->savedpos > 0)
6002 ssh_pkt_addstring_str(pkt, ",");
6003 ssh_pkt_addstring_str(pkt, data);
6008 * SSH-2 key creation method.
6009 * (Currently assumes 2 lots of any hash are sufficient to generate
6010 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
6012 #define SSH2_MKKEY_ITERS (2)
6013 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
6014 unsigned char *keyspace)
6016 const struct ssh_hash *h = ssh->kex->hash;
6018 /* First hlen bytes. */
6020 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6021 hash_mpint(h, s, K);
6022 h->bytes(s, H, h->hlen);
6023 h->bytes(s, &chr, 1);
6024 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6025 h->final(s, keyspace);
6026 /* Next hlen bytes. */
6028 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6029 hash_mpint(h, s, K);
6030 h->bytes(s, H, h->hlen);
6031 h->bytes(s, keyspace, h->hlen);
6032 h->final(s, keyspace + h->hlen);
6036 * Handle the SSH-2 transport layer.
6038 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
6039 struct Packet *pktin)
6041 unsigned char *in = (unsigned char *)vin;
6042 struct do_ssh2_transport_state {
6044 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
6045 Bignum p, g, e, f, K;
6048 int kex_init_value, kex_reply_value;
6049 const struct ssh_mac **maclist;
6051 const struct ssh2_cipher *cscipher_tobe;
6052 const struct ssh2_cipher *sccipher_tobe;
6053 const struct ssh_mac *csmac_tobe;
6054 const struct ssh_mac *scmac_tobe;
6055 const struct ssh_compress *cscomp_tobe;
6056 const struct ssh_compress *sccomp_tobe;
6057 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6058 int hostkeylen, siglen, rsakeylen;
6059 void *hkey; /* actual host key */
6060 void *rsakey; /* for RSA kex */
6061 void *eckey; /* for ECDH kex */
6062 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6063 int n_preferred_kex;
6064 const struct ssh_kexes *preferred_kex[KEX_MAX];
6065 int n_preferred_ciphers;
6066 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6067 const struct ssh_compress *preferred_comp;
6068 int userauth_succeeded; /* for delayed compression */
6069 int pending_compression;
6070 int got_session_id, activated_authconn;
6071 struct Packet *pktout;
6076 crState(do_ssh2_transport_state);
6078 assert(!ssh->bare_connection);
6082 s->cscipher_tobe = s->sccipher_tobe = NULL;
6083 s->csmac_tobe = s->scmac_tobe = NULL;
6084 s->cscomp_tobe = s->sccomp_tobe = NULL;
6086 s->got_session_id = s->activated_authconn = FALSE;
6087 s->userauth_succeeded = FALSE;
6088 s->pending_compression = FALSE;
6091 * Be prepared to work around the buggy MAC problem.
6093 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6094 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6096 s->maclist = macs, s->nmacs = lenof(macs);
6099 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6104 * Set up the preferred key exchange. (NULL => warn below here)
6106 s->n_preferred_kex = 0;
6107 for (i = 0; i < KEX_MAX; i++) {
6108 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6110 s->preferred_kex[s->n_preferred_kex++] =
6111 &ssh_diffiehellman_gex;
6114 s->preferred_kex[s->n_preferred_kex++] =
6115 &ssh_diffiehellman_group14;
6118 s->preferred_kex[s->n_preferred_kex++] =
6119 &ssh_diffiehellman_group1;
6122 s->preferred_kex[s->n_preferred_kex++] =
6126 s->preferred_kex[s->n_preferred_kex++] =
6130 /* Flag for later. Don't bother if it's the last in
6132 if (i < KEX_MAX - 1) {
6133 s->preferred_kex[s->n_preferred_kex++] = NULL;
6140 * Set up the preferred ciphers. (NULL => warn below here)
6142 s->n_preferred_ciphers = 0;
6143 for (i = 0; i < CIPHER_MAX; i++) {
6144 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6145 case CIPHER_BLOWFISH:
6146 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6149 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6150 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6154 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6157 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6159 case CIPHER_ARCFOUR:
6160 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6163 /* Flag for later. Don't bother if it's the last in
6165 if (i < CIPHER_MAX - 1) {
6166 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6173 * Set up preferred compression.
6175 if (conf_get_int(ssh->conf, CONF_compression))
6176 s->preferred_comp = &ssh_zlib;
6178 s->preferred_comp = &ssh_comp_none;
6181 * Enable queueing of outgoing auth- or connection-layer
6182 * packets while we are in the middle of a key exchange.
6184 ssh->queueing = TRUE;
6187 * Flag that KEX is in progress.
6189 ssh->kex_in_progress = TRUE;
6192 * Construct and send our key exchange packet.
6194 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6195 for (i = 0; i < 16; i++)
6196 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6197 /* List key exchange algorithms. */
6198 ssh2_pkt_addstring_start(s->pktout);
6199 for (i = 0; i < s->n_preferred_kex; i++) {
6200 const struct ssh_kexes *k = s->preferred_kex[i];
6201 if (!k) continue; /* warning flag */
6202 for (j = 0; j < k->nkexes; j++)
6203 ssh2_pkt_addstring_commasep(s->pktout, k->list[j]->name);
6205 /* List server host key algorithms. */
6206 if (!s->got_session_id) {
6208 * In the first key exchange, we list all the algorithms
6209 * we're prepared to cope with.
6211 ssh2_pkt_addstring_start(s->pktout);
6212 for (i = 0; i < lenof(hostkey_algs); i++)
6213 ssh2_pkt_addstring_commasep(s->pktout, hostkey_algs[i]->name);
6216 * In subsequent key exchanges, we list only the kex
6217 * algorithm that was selected in the first key exchange,
6218 * so that we keep getting the same host key and hence
6219 * don't have to interrupt the user's session to ask for
6223 ssh2_pkt_addstring(s->pktout, ssh->hostkey->name);
6225 /* List encryption algorithms (client->server then server->client). */
6226 for (k = 0; k < 2; k++) {
6227 ssh2_pkt_addstring_start(s->pktout);
6228 for (i = 0; i < s->n_preferred_ciphers; i++) {
6229 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6230 if (!c) continue; /* warning flag */
6231 for (j = 0; j < c->nciphers; j++)
6232 ssh2_pkt_addstring_commasep(s->pktout, c->list[j]->name);
6235 /* List MAC algorithms (client->server then server->client). */
6236 for (j = 0; j < 2; j++) {
6237 ssh2_pkt_addstring_start(s->pktout);
6238 for (i = 0; i < s->nmacs; i++)
6239 ssh2_pkt_addstring_commasep(s->pktout, s->maclist[i]->name);
6241 /* List client->server compression algorithms,
6242 * then server->client compression algorithms. (We use the
6243 * same set twice.) */
6244 for (j = 0; j < 2; j++) {
6245 ssh2_pkt_addstring_start(s->pktout);
6246 assert(lenof(compressions) > 1);
6247 /* Prefer non-delayed versions */
6248 ssh2_pkt_addstring_commasep(s->pktout, s->preferred_comp->name);
6249 /* We don't even list delayed versions of algorithms until
6250 * they're allowed to be used, to avoid a race. See the end of
6252 if (s->userauth_succeeded && s->preferred_comp->delayed_name)
6253 ssh2_pkt_addstring_commasep(s->pktout,
6254 s->preferred_comp->delayed_name);
6255 for (i = 0; i < lenof(compressions); i++) {
6256 const struct ssh_compress *c = compressions[i];
6257 ssh2_pkt_addstring_commasep(s->pktout, c->name);
6258 if (s->userauth_succeeded && c->delayed_name)
6259 ssh2_pkt_addstring_commasep(s->pktout, c->delayed_name);
6262 /* List client->server languages. Empty list. */
6263 ssh2_pkt_addstring_start(s->pktout);
6264 /* List server->client languages. Empty list. */
6265 ssh2_pkt_addstring_start(s->pktout);
6266 /* First KEX packet does _not_ follow, because we're not that brave. */
6267 ssh2_pkt_addbool(s->pktout, FALSE);
6269 ssh2_pkt_adduint32(s->pktout, 0);
6272 s->our_kexinitlen = s->pktout->length - 5;
6273 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6274 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6276 ssh2_pkt_send_noqueue(ssh, s->pktout);
6279 crWaitUntilV(pktin);
6282 * Now examine the other side's KEXINIT to see what we're up
6286 char *str, *preferred;
6289 if (pktin->type != SSH2_MSG_KEXINIT) {
6290 bombout(("expected key exchange packet from server"));
6294 ssh->hostkey = NULL;
6295 s->cscipher_tobe = NULL;
6296 s->sccipher_tobe = NULL;
6297 s->csmac_tobe = NULL;
6298 s->scmac_tobe = NULL;
6299 s->cscomp_tobe = NULL;
6300 s->sccomp_tobe = NULL;
6301 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
6303 pktin->savedpos += 16; /* skip garbage cookie */
6304 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
6306 bombout(("KEXINIT packet was incomplete"));
6311 for (i = 0; i < s->n_preferred_kex; i++) {
6312 const struct ssh_kexes *k = s->preferred_kex[i];
6316 for (j = 0; j < k->nkexes; j++) {
6317 if (!preferred) preferred = k->list[j]->name;
6318 if (in_commasep_string(k->list[j]->name, str, len)) {
6319 ssh->kex = k->list[j];
6328 bombout(("Couldn't agree a key exchange algorithm"
6329 " (available: %.*s)", len, str));
6333 * Note that the server's guess is considered wrong if it doesn't match
6334 * the first algorithm in our list, even if it's still the algorithm
6337 s->guessok = first_in_commasep_string(preferred, str, len);
6338 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
6340 bombout(("KEXINIT packet was incomplete"));
6343 for (i = 0; i < lenof(hostkey_algs); i++) {
6344 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
6345 ssh->hostkey = hostkey_algs[i];
6349 if (!ssh->hostkey) {
6350 bombout(("Couldn't agree a host key algorithm"
6351 " (available: %.*s)", len, str));
6355 s->guessok = s->guessok &&
6356 first_in_commasep_string(hostkey_algs[0]->name, str, len);
6357 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
6359 bombout(("KEXINIT packet was incomplete"));
6362 for (i = 0; i < s->n_preferred_ciphers; i++) {
6363 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6365 s->warn_cscipher = TRUE;
6367 for (j = 0; j < c->nciphers; j++) {
6368 if (in_commasep_string(c->list[j]->name, str, len)) {
6369 s->cscipher_tobe = c->list[j];
6374 if (s->cscipher_tobe)
6377 if (!s->cscipher_tobe) {
6378 bombout(("Couldn't agree a client-to-server cipher"
6379 " (available: %.*s)", len, str));
6383 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
6385 bombout(("KEXINIT packet was incomplete"));
6388 for (i = 0; i < s->n_preferred_ciphers; i++) {
6389 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6391 s->warn_sccipher = TRUE;
6393 for (j = 0; j < c->nciphers; j++) {
6394 if (in_commasep_string(c->list[j]->name, str, len)) {
6395 s->sccipher_tobe = c->list[j];
6400 if (s->sccipher_tobe)
6403 if (!s->sccipher_tobe) {
6404 bombout(("Couldn't agree a server-to-client cipher"
6405 " (available: %.*s)", len, str));
6409 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
6411 bombout(("KEXINIT packet was incomplete"));
6414 for (i = 0; i < s->nmacs; i++) {
6415 if (in_commasep_string(s->maclist[i]->name, str, len)) {
6416 s->csmac_tobe = s->maclist[i];
6420 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
6422 bombout(("KEXINIT packet was incomplete"));
6425 for (i = 0; i < s->nmacs; i++) {
6426 if (in_commasep_string(s->maclist[i]->name, str, len)) {
6427 s->scmac_tobe = s->maclist[i];
6431 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
6433 bombout(("KEXINIT packet was incomplete"));
6436 for (i = 0; i < lenof(compressions) + 1; i++) {
6437 const struct ssh_compress *c =
6438 i == 0 ? s->preferred_comp : compressions[i - 1];
6439 if (in_commasep_string(c->name, str, len)) {
6442 } else if (in_commasep_string(c->delayed_name, str, len)) {
6443 if (s->userauth_succeeded) {
6447 s->pending_compression = TRUE; /* try this later */
6451 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
6453 bombout(("KEXINIT packet was incomplete"));
6456 for (i = 0; i < lenof(compressions) + 1; i++) {
6457 const struct ssh_compress *c =
6458 i == 0 ? s->preferred_comp : compressions[i - 1];
6459 if (in_commasep_string(c->name, str, len)) {
6462 } else if (in_commasep_string(c->delayed_name, str, len)) {
6463 if (s->userauth_succeeded) {
6467 s->pending_compression = TRUE; /* try this later */
6471 if (s->pending_compression) {
6472 logevent("Server supports delayed compression; "
6473 "will try this later");
6475 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6476 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6477 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6479 ssh->exhash = ssh->kex->hash->init();
6480 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6481 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6482 hash_string(ssh->kex->hash, ssh->exhash,
6483 s->our_kexinit, s->our_kexinitlen);
6484 sfree(s->our_kexinit);
6485 /* Include the type byte in the hash of server's KEXINIT */
6486 hash_string(ssh->kex->hash, ssh->exhash,
6487 pktin->body - 1, pktin->length + 1);
6490 ssh_set_frozen(ssh, 1);
6491 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6493 ssh_dialog_callback, ssh);
6494 if (s->dlgret < 0) {
6498 bombout(("Unexpected data from server while"
6499 " waiting for user response"));
6502 } while (pktin || inlen > 0);
6503 s->dlgret = ssh->user_response;
6505 ssh_set_frozen(ssh, 0);
6506 if (s->dlgret == 0) {
6507 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6513 if (s->warn_cscipher) {
6514 ssh_set_frozen(ssh, 1);
6515 s->dlgret = askalg(ssh->frontend,
6516 "client-to-server cipher",
6517 s->cscipher_tobe->name,
6518 ssh_dialog_callback, ssh);
6519 if (s->dlgret < 0) {
6523 bombout(("Unexpected data from server while"
6524 " waiting for user response"));
6527 } while (pktin || inlen > 0);
6528 s->dlgret = ssh->user_response;
6530 ssh_set_frozen(ssh, 0);
6531 if (s->dlgret == 0) {
6532 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6538 if (s->warn_sccipher) {
6539 ssh_set_frozen(ssh, 1);
6540 s->dlgret = askalg(ssh->frontend,
6541 "server-to-client cipher",
6542 s->sccipher_tobe->name,
6543 ssh_dialog_callback, ssh);
6544 if (s->dlgret < 0) {
6548 bombout(("Unexpected data from server while"
6549 " waiting for user response"));
6552 } while (pktin || inlen > 0);
6553 s->dlgret = ssh->user_response;
6555 ssh_set_frozen(ssh, 0);
6556 if (s->dlgret == 0) {
6557 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6563 if (s->ignorepkt) /* first_kex_packet_follows */
6564 crWaitUntilV(pktin); /* Ignore packet */
6567 if (ssh->kex->main_type == KEXTYPE_DH) {
6569 * Work out the number of bits of key we will need from the
6570 * key exchange. We start with the maximum key length of
6576 csbits = s->cscipher_tobe->keylen;
6577 scbits = s->sccipher_tobe->keylen;
6578 s->nbits = (csbits > scbits ? csbits : scbits);
6580 /* The keys only have hlen-bit entropy, since they're based on
6581 * a hash. So cap the key size at hlen bits. */
6582 if (s->nbits > ssh->kex->hash->hlen * 8)
6583 s->nbits = ssh->kex->hash->hlen * 8;
6586 * If we're doing Diffie-Hellman group exchange, start by
6587 * requesting a group.
6589 if (!ssh->kex->pdata) {
6590 logevent("Doing Diffie-Hellman group exchange");
6591 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6593 * Work out how big a DH group we will need to allow that
6596 s->pbits = 512 << ((s->nbits - 1) / 64);
6597 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6598 ssh2_pkt_adduint32(s->pktout, s->pbits);
6599 ssh2_pkt_send_noqueue(ssh, s->pktout);
6601 crWaitUntilV(pktin);
6602 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6603 bombout(("expected key exchange group packet from server"));
6606 s->p = ssh2_pkt_getmp(pktin);
6607 s->g = ssh2_pkt_getmp(pktin);
6608 if (!s->p || !s->g) {
6609 bombout(("unable to read mp-ints from incoming group packet"));
6612 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6613 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6614 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6616 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6617 ssh->kex_ctx = dh_setup_group(ssh->kex);
6618 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6619 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6620 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6621 ssh->kex->groupname);
6624 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6625 ssh->kex->hash->text_name);
6627 * Now generate and send e for Diffie-Hellman.
6629 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6630 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6631 s->pktout = ssh2_pkt_init(s->kex_init_value);
6632 ssh2_pkt_addmp(s->pktout, s->e);
6633 ssh2_pkt_send_noqueue(ssh, s->pktout);
6635 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6636 crWaitUntilV(pktin);
6637 if (pktin->type != s->kex_reply_value) {
6638 bombout(("expected key exchange reply packet from server"));
6641 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6642 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6643 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6644 s->f = ssh2_pkt_getmp(pktin);
6646 bombout(("unable to parse key exchange reply packet"));
6649 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6652 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
6654 bombout(("key exchange reply failed validation: %s", err));
6658 s->K = dh_find_K(ssh->kex_ctx, s->f);
6660 /* We assume everything from now on will be quick, and it might
6661 * involve user interaction. */
6662 set_busy_status(ssh->frontend, BUSY_NOT);
6664 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6665 if (!ssh->kex->pdata) {
6666 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6667 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6668 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6670 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6671 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6673 dh_cleanup(ssh->kex_ctx);
6675 if (!ssh->kex->pdata) {
6679 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
6681 logeventf(ssh, "Doing ECDH key exchange with hash %s",
6682 ssh->kex->hash->text_name);
6683 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
6686 if (!strcmp(ssh->kex->name, "ecdh-sha2-nistp256")) {
6687 s->eckey = ssh_ecdhkex_newkey(ec_p256());
6688 } else if (!strcmp(ssh->kex->name, "ecdh-sha2-nistp384")) {
6689 s->eckey = ssh_ecdhkex_newkey(ec_p384());
6690 } else if (!strcmp(ssh->kex->name, "ecdh-sha2-nistp521")) {
6691 s->eckey = ssh_ecdhkex_newkey(ec_p521());
6694 bombout(("Unable to generate key for ECDH"));
6700 int publicPointLength;
6701 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6703 ssh_ecdhkex_freekey(s->eckey);
6704 bombout(("Unable to encode public key for ECDH"));
6707 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
6708 ssh2_pkt_addstring_start(s->pktout);
6709 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
6713 ssh2_pkt_send_noqueue(ssh, s->pktout);
6715 crWaitUntilV(pktin);
6716 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
6717 ssh_ecdhkex_freekey(s->eckey);
6718 bombout(("expected ECDH reply packet from server"));
6722 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6723 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6724 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6728 int publicPointLength;
6729 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6731 ssh_ecdhkex_freekey(s->eckey);
6732 bombout(("Unable to encode public key for ECDH hash"));
6735 hash_string(ssh->kex->hash, ssh->exhash,
6736 publicPoint, publicPointLength);
6743 ssh_pkt_getstring(pktin, &keydata, &keylen);
6744 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
6745 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
6747 ssh_ecdhkex_freekey(s->eckey);
6748 bombout(("point received in ECDH was not valid"));
6753 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6755 ssh_ecdhkex_freekey(s->eckey);
6757 logeventf(ssh, "Doing RSA key exchange with hash %s",
6758 ssh->kex->hash->text_name);
6759 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6761 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6764 crWaitUntilV(pktin);
6765 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6766 bombout(("expected RSA public key packet from server"));
6770 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6771 hash_string(ssh->kex->hash, ssh->exhash,
6772 s->hostkeydata, s->hostkeylen);
6773 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6777 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6778 s->rsakeydata = snewn(s->rsakeylen, char);
6779 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6782 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6784 sfree(s->rsakeydata);
6785 bombout(("unable to parse RSA public key from server"));
6789 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6792 * Next, set up a shared secret K, of precisely KLEN -
6793 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6794 * RSA key modulus and HLEN is the bit length of the hash
6798 int klen = ssh_rsakex_klen(s->rsakey);
6799 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6801 unsigned char *kstr1, *kstr2, *outstr;
6802 int kstr1len, kstr2len, outstrlen;
6804 s->K = bn_power_2(nbits - 1);
6806 for (i = 0; i < nbits; i++) {
6808 byte = random_byte();
6810 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6814 * Encode this as an mpint.
6816 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6817 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6818 PUT_32BIT(kstr2, kstr1len);
6819 memcpy(kstr2 + 4, kstr1, kstr1len);
6822 * Encrypt it with the given RSA key.
6824 outstrlen = (klen + 7) / 8;
6825 outstr = snewn(outstrlen, unsigned char);
6826 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6827 outstr, outstrlen, s->rsakey);
6830 * And send it off in a return packet.
6832 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6833 ssh2_pkt_addstring_start(s->pktout);
6834 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6835 ssh2_pkt_send_noqueue(ssh, s->pktout);
6837 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6844 ssh_rsakex_freekey(s->rsakey);
6846 crWaitUntilV(pktin);
6847 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6848 sfree(s->rsakeydata);
6849 bombout(("expected signature packet from server"));
6853 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6855 sfree(s->rsakeydata);
6858 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6859 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6860 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6862 ssh->kex_ctx = NULL;
6865 debug(("Exchange hash is:\n"));
6866 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6870 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6871 (char *)s->exchange_hash,
6872 ssh->kex->hash->hlen)) {
6873 bombout(("Server's host key did not match the signature supplied"));
6877 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6878 if (!s->got_session_id) {
6880 * Authenticate remote host: verify host key. (We've already
6881 * checked the signature of the exchange hash.)
6883 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6884 logevent("Host key fingerprint is:");
6885 logevent(s->fingerprint);
6886 /* First check against manually configured host keys. */
6887 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
6888 ssh->hostkey, s->hkey);
6889 if (s->dlgret == 0) { /* did not match */
6890 bombout(("Host key did not appear in manually configured list"));
6892 } else if (s->dlgret < 0) { /* none configured; use standard handling */
6893 ssh_set_frozen(ssh, 1);
6894 s->dlgret = verify_ssh_host_key(ssh->frontend,
6895 ssh->savedhost, ssh->savedport,
6896 ssh->hostkey->keytype, s->keystr,
6898 ssh_dialog_callback, ssh);
6899 if (s->dlgret < 0) {
6903 bombout(("Unexpected data from server while waiting"
6904 " for user host key response"));
6907 } while (pktin || inlen > 0);
6908 s->dlgret = ssh->user_response;
6910 ssh_set_frozen(ssh, 0);
6911 if (s->dlgret == 0) {
6912 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
6917 sfree(s->fingerprint);
6919 * Save this host key, to check against the one presented in
6920 * subsequent rekeys.
6922 ssh->hostkey_str = s->keystr;
6925 * In a rekey, we never present an interactive host key
6926 * verification request to the user. Instead, we simply
6927 * enforce that the key we're seeing this time is identical to
6928 * the one we saw before.
6930 if (strcmp(ssh->hostkey_str, s->keystr)) {
6931 bombout(("Host key was different in repeat key exchange"));
6936 ssh->hostkey->freekey(s->hkey);
6939 * The exchange hash from the very first key exchange is also
6940 * the session id, used in session key construction and
6943 if (!s->got_session_id) {
6944 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6945 memcpy(ssh->v2_session_id, s->exchange_hash,
6946 sizeof(s->exchange_hash));
6947 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6948 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6949 s->got_session_id = TRUE;
6953 * Send SSH2_MSG_NEWKEYS.
6955 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6956 ssh2_pkt_send_noqueue(ssh, s->pktout);
6957 ssh->outgoing_data_size = 0; /* start counting from here */
6960 * We've sent client NEWKEYS, so create and initialise
6961 * client-to-server session keys.
6963 if (ssh->cs_cipher_ctx)
6964 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6965 ssh->cscipher = s->cscipher_tobe;
6966 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6968 if (ssh->cs_mac_ctx)
6969 ssh->csmac->free_context(ssh->cs_mac_ctx);
6970 ssh->csmac = s->csmac_tobe;
6971 ssh->cs_mac_ctx = ssh->csmac->make_context();
6973 if (ssh->cs_comp_ctx)
6974 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6975 ssh->cscomp = s->cscomp_tobe;
6976 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6979 * Set IVs on client-to-server keys. Here we use the exchange
6980 * hash from the _first_ key exchange.
6983 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6984 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6985 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
6986 assert((ssh->cscipher->keylen+7) / 8 <=
6987 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6988 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
6989 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
6990 assert(ssh->cscipher->blksize <=
6991 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6992 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
6993 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
6994 assert(ssh->csmac->len <=
6995 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
6996 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
6997 smemclr(keyspace, sizeof(keyspace));
7000 logeventf(ssh, "Initialised %.200s client->server encryption",
7001 ssh->cscipher->text_name);
7002 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
7003 ssh->csmac->text_name);
7004 if (ssh->cscomp->text_name)
7005 logeventf(ssh, "Initialised %s compression",
7006 ssh->cscomp->text_name);
7009 * Now our end of the key exchange is complete, we can send all
7010 * our queued higher-layer packets.
7012 ssh->queueing = FALSE;
7013 ssh2_pkt_queuesend(ssh);
7016 * Expect SSH2_MSG_NEWKEYS from server.
7018 crWaitUntilV(pktin);
7019 if (pktin->type != SSH2_MSG_NEWKEYS) {
7020 bombout(("expected new-keys packet from server"));
7023 ssh->incoming_data_size = 0; /* start counting from here */
7026 * We've seen server NEWKEYS, so create and initialise
7027 * server-to-client session keys.
7029 if (ssh->sc_cipher_ctx)
7030 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7031 ssh->sccipher = s->sccipher_tobe;
7032 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7034 if (ssh->sc_mac_ctx)
7035 ssh->scmac->free_context(ssh->sc_mac_ctx);
7036 ssh->scmac = s->scmac_tobe;
7037 ssh->sc_mac_ctx = ssh->scmac->make_context();
7039 if (ssh->sc_comp_ctx)
7040 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7041 ssh->sccomp = s->sccomp_tobe;
7042 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7045 * Set IVs on server-to-client keys. Here we use the exchange
7046 * hash from the _first_ key exchange.
7049 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
7050 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7051 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
7052 assert((ssh->sccipher->keylen+7) / 8 <=
7053 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7054 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
7055 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
7056 assert(ssh->sccipher->blksize <=
7057 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7058 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
7059 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
7060 assert(ssh->scmac->len <=
7061 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7062 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
7063 smemclr(keyspace, sizeof(keyspace));
7065 logeventf(ssh, "Initialised %.200s server->client encryption",
7066 ssh->sccipher->text_name);
7067 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
7068 ssh->scmac->text_name);
7069 if (ssh->sccomp->text_name)
7070 logeventf(ssh, "Initialised %s decompression",
7071 ssh->sccomp->text_name);
7074 * Free shared secret.
7079 * Key exchange is over. Loop straight back round if we have a
7080 * deferred rekey reason.
7082 if (ssh->deferred_rekey_reason) {
7083 logevent(ssh->deferred_rekey_reason);
7085 ssh->deferred_rekey_reason = NULL;
7086 goto begin_key_exchange;
7090 * Otherwise, schedule a timer for our next rekey.
7092 ssh->kex_in_progress = FALSE;
7093 ssh->last_rekey = GETTICKCOUNT();
7094 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7095 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7099 * Now we're encrypting. Begin returning 1 to the protocol main
7100 * function so that other things can run on top of the
7101 * transport. If we ever see a KEXINIT, we must go back to the
7104 * We _also_ go back to the start if we see pktin==NULL and
7105 * inlen negative, because this is a special signal meaning
7106 * `initiate client-driven rekey', and `in' contains a message
7107 * giving the reason for the rekey.
7109 * inlen==-1 means always initiate a rekey;
7110 * inlen==-2 means that userauth has completed successfully and
7111 * we should consider rekeying (for delayed compression).
7113 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7114 (!pktin && inlen < 0))) {
7116 if (!ssh->protocol_initial_phase_done) {
7117 ssh->protocol_initial_phase_done = TRUE;
7119 * Allow authconn to initialise itself.
7121 do_ssh2_authconn(ssh, NULL, 0, NULL);
7126 logevent("Server initiated key re-exchange");
7130 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7131 * delayed compression, if it's available.
7133 * draft-miller-secsh-compression-delayed-00 says that you
7134 * negotiate delayed compression in the first key exchange, and
7135 * both sides start compressing when the server has sent
7136 * USERAUTH_SUCCESS. This has a race condition -- the server
7137 * can't know when the client has seen it, and thus which incoming
7138 * packets it should treat as compressed.
7140 * Instead, we do the initial key exchange without offering the
7141 * delayed methods, but note if the server offers them; when we
7142 * get here, if a delayed method was available that was higher
7143 * on our list than what we got, we initiate a rekey in which we
7144 * _do_ list the delayed methods (and hopefully get it as a
7145 * result). Subsequent rekeys will do the same.
7147 assert(!s->userauth_succeeded); /* should only happen once */
7148 s->userauth_succeeded = TRUE;
7149 if (!s->pending_compression)
7150 /* Can't see any point rekeying. */
7151 goto wait_for_rekey; /* this is utterly horrid */
7152 /* else fall through to rekey... */
7153 s->pending_compression = FALSE;
7156 * Now we've decided to rekey.
7158 * Special case: if the server bug is set that doesn't
7159 * allow rekeying, we give a different log message and
7160 * continue waiting. (If such a server _initiates_ a rekey,
7161 * we process it anyway!)
7163 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7164 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7166 /* Reset the counters, so that at least this message doesn't
7167 * hit the event log _too_ often. */
7168 ssh->outgoing_data_size = 0;
7169 ssh->incoming_data_size = 0;
7170 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7172 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7175 goto wait_for_rekey; /* this is still utterly horrid */
7177 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7180 goto begin_key_exchange;
7186 * Add data to an SSH-2 channel output buffer.
7188 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
7191 bufchain_add(&c->v.v2.outbuffer, buf, len);
7195 * Attempt to send data on an SSH-2 channel.
7197 static int ssh2_try_send(struct ssh_channel *c)
7200 struct Packet *pktout;
7203 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7206 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7207 if ((unsigned)len > c->v.v2.remwindow)
7208 len = c->v.v2.remwindow;
7209 if ((unsigned)len > c->v.v2.remmaxpkt)
7210 len = c->v.v2.remmaxpkt;
7211 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7212 ssh2_pkt_adduint32(pktout, c->remoteid);
7213 ssh2_pkt_addstring_start(pktout);
7214 ssh2_pkt_addstring_data(pktout, data, len);
7215 ssh2_pkt_send(ssh, pktout);
7216 bufchain_consume(&c->v.v2.outbuffer, len);
7217 c->v.v2.remwindow -= len;
7221 * After having sent as much data as we can, return the amount
7224 ret = bufchain_size(&c->v.v2.outbuffer);
7227 * And if there's no data pending but we need to send an EOF, send
7230 if (!ret && c->pending_eof)
7231 ssh_channel_try_eof(c);
7236 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7239 if (c->closes & CLOSES_SENT_EOF)
7240 return; /* don't send on channels we've EOFed */
7241 bufsize = ssh2_try_send(c);
7244 case CHAN_MAINSESSION:
7245 /* stdin need not receive an unthrottle
7246 * notification since it will be polled */
7249 x11_unthrottle(c->u.x11.xconn);
7252 /* agent sockets are request/response and need no
7253 * buffer management */
7256 pfd_unthrottle(c->u.pfd.pf);
7262 static int ssh_is_simple(Ssh ssh)
7265 * We use the 'simple' variant of the SSH protocol if we're asked
7266 * to, except not if we're also doing connection-sharing (either
7267 * tunnelling our packets over an upstream or expecting to be
7268 * tunnelled over ourselves), since then the assumption that we
7269 * have only one channel to worry about is not true after all.
7271 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7272 !ssh->bare_connection && !ssh->connshare);
7276 * Set up most of a new ssh_channel for SSH-2.
7278 static void ssh2_channel_init(struct ssh_channel *c)
7281 c->localid = alloc_channel_id(ssh);
7283 c->pending_eof = FALSE;
7284 c->throttling_conn = FALSE;
7285 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7286 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7287 c->v.v2.chanreq_head = NULL;
7288 c->v.v2.throttle_state = UNTHROTTLED;
7289 bufchain_init(&c->v.v2.outbuffer);
7293 * Construct the common parts of a CHANNEL_OPEN.
7295 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c, char *type)
7297 struct Packet *pktout;
7299 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7300 ssh2_pkt_addstring(pktout, type);
7301 ssh2_pkt_adduint32(pktout, c->localid);
7302 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7303 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7308 * CHANNEL_FAILURE doesn't come with any indication of what message
7309 * caused it, so we have to keep track of the outstanding
7310 * CHANNEL_REQUESTs ourselves.
7312 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7313 cchandler_fn_t handler, void *ctx)
7315 struct outstanding_channel_request *ocr =
7316 snew(struct outstanding_channel_request);
7318 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7319 ocr->handler = handler;
7322 if (!c->v.v2.chanreq_head)
7323 c->v.v2.chanreq_head = ocr;
7325 c->v.v2.chanreq_tail->next = ocr;
7326 c->v.v2.chanreq_tail = ocr;
7330 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7331 * NULL then a reply will be requested and the handler will be called
7332 * when it arrives. The returned packet is ready to have any
7333 * request-specific data added and be sent. Note that if a handler is
7334 * provided, it's essential that the request actually be sent.
7336 * The handler will usually be passed the response packet in pktin. If
7337 * pktin is NULL, this means that no reply will ever be forthcoming
7338 * (e.g. because the entire connection is being destroyed, or because
7339 * the server initiated channel closure before we saw the response)
7340 * and the handler should free any storage it's holding.
7342 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c, char *type,
7343 cchandler_fn_t handler, void *ctx)
7345 struct Packet *pktout;
7347 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7348 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7349 ssh2_pkt_adduint32(pktout, c->remoteid);
7350 ssh2_pkt_addstring(pktout, type);
7351 ssh2_pkt_addbool(pktout, handler != NULL);
7352 if (handler != NULL)
7353 ssh2_queue_chanreq_handler(c, handler, ctx);
7358 * Potentially enlarge the window on an SSH-2 channel.
7360 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7362 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7367 * Never send WINDOW_ADJUST for a channel that the remote side has
7368 * already sent EOF on; there's no point, since it won't be
7369 * sending any more data anyway. Ditto if _we've_ already sent
7372 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7376 * Also, never widen the window for an X11 channel when we're
7377 * still waiting to see its initial auth and may yet hand it off
7380 if (c->type == CHAN_X11 && c->u.x11.initial)
7384 * If the remote end has a habit of ignoring maxpkt, limit the
7385 * window so that it has no choice (assuming it doesn't ignore the
7388 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7389 newwin = OUR_V2_MAXPKT;
7392 * Only send a WINDOW_ADJUST if there's significantly more window
7393 * available than the other end thinks there is. This saves us
7394 * sending a WINDOW_ADJUST for every character in a shell session.
7396 * "Significant" is arbitrarily defined as half the window size.
7398 if (newwin / 2 >= c->v.v2.locwindow) {
7399 struct Packet *pktout;
7403 * In order to keep track of how much window the client
7404 * actually has available, we'd like it to acknowledge each
7405 * WINDOW_ADJUST. We can't do that directly, so we accompany
7406 * it with a CHANNEL_REQUEST that has to be acknowledged.
7408 * This is only necessary if we're opening the window wide.
7409 * If we're not, then throughput is being constrained by
7410 * something other than the maximum window size anyway.
7412 if (newwin == c->v.v2.locmaxwin &&
7413 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7414 up = snew(unsigned);
7415 *up = newwin - c->v.v2.locwindow;
7416 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7417 ssh2_handle_winadj_response, up);
7418 ssh2_pkt_send(ssh, pktout);
7420 if (c->v.v2.throttle_state != UNTHROTTLED)
7421 c->v.v2.throttle_state = UNTHROTTLING;
7423 /* Pretend the WINDOW_ADJUST was acked immediately. */
7424 c->v.v2.remlocwin = newwin;
7425 c->v.v2.throttle_state = THROTTLED;
7427 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7428 ssh2_pkt_adduint32(pktout, c->remoteid);
7429 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7430 ssh2_pkt_send(ssh, pktout);
7431 c->v.v2.locwindow = newwin;
7436 * Find the channel associated with a message. If there's no channel,
7437 * or it's not properly open, make a noise about it and return NULL.
7439 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7441 unsigned localid = ssh_pkt_getuint32(pktin);
7442 struct ssh_channel *c;
7444 c = find234(ssh->channels, &localid, ssh_channelfind);
7446 (c->type != CHAN_SHARING && c->halfopen &&
7447 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7448 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7449 char *buf = dupprintf("Received %s for %s channel %u",
7450 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7452 c ? "half-open" : "nonexistent", localid);
7453 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7460 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7461 struct Packet *pktin, void *ctx)
7463 unsigned *sizep = ctx;
7466 * Winadj responses should always be failures. However, at least
7467 * one server ("boks_sshd") is known to return SUCCESS for channel
7468 * requests it's never heard of, such as "winadj@putty". Raised
7469 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7470 * life, we don't worry about what kind of response we got.
7473 c->v.v2.remlocwin += *sizep;
7476 * winadj messages are only sent when the window is fully open, so
7477 * if we get an ack of one, we know any pending unthrottle is
7480 if (c->v.v2.throttle_state == UNTHROTTLING)
7481 c->v.v2.throttle_state = UNTHROTTLED;
7484 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
7486 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
7487 struct outstanding_channel_request *ocr;
7490 if (c->type == CHAN_SHARING) {
7491 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7492 pktin->body, pktin->length);
7495 ocr = c->v.v2.chanreq_head;
7497 ssh2_msg_unexpected(ssh, pktin);
7500 ocr->handler(c, pktin, ocr->ctx);
7501 c->v.v2.chanreq_head = ocr->next;
7504 * We may now initiate channel-closing procedures, if that
7505 * CHANNEL_REQUEST was the last thing outstanding before we send
7508 ssh2_channel_check_close(c);
7511 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
7513 struct ssh_channel *c;
7514 c = ssh2_channel_msg(ssh, pktin);
7517 if (c->type == CHAN_SHARING) {
7518 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7519 pktin->body, pktin->length);
7522 if (!(c->closes & CLOSES_SENT_EOF)) {
7523 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
7524 ssh2_try_send_and_unthrottle(ssh, c);
7528 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
7532 struct ssh_channel *c;
7533 c = ssh2_channel_msg(ssh, pktin);
7536 if (c->type == CHAN_SHARING) {
7537 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7538 pktin->body, pktin->length);
7541 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
7542 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
7543 return; /* extended but not stderr */
7544 ssh_pkt_getstring(pktin, &data, &length);
7547 c->v.v2.locwindow -= length;
7548 c->v.v2.remlocwin -= length;
7550 case CHAN_MAINSESSION:
7552 from_backend(ssh->frontend, pktin->type ==
7553 SSH2_MSG_CHANNEL_EXTENDED_DATA,
7557 bufsize = x11_send(c->u.x11.xconn, data, length);
7560 bufsize = pfd_send(c->u.pfd.pf, data, length);
7563 while (length > 0) {
7564 if (c->u.a.lensofar < 4) {
7565 unsigned int l = min(4 - c->u.a.lensofar,
7567 memcpy(c->u.a.msglen + c->u.a.lensofar,
7571 c->u.a.lensofar += l;
7573 if (c->u.a.lensofar == 4) {
7575 4 + GET_32BIT(c->u.a.msglen);
7576 c->u.a.message = snewn(c->u.a.totallen,
7578 memcpy(c->u.a.message, c->u.a.msglen, 4);
7580 if (c->u.a.lensofar >= 4 && length > 0) {
7582 min(c->u.a.totallen - c->u.a.lensofar,
7584 memcpy(c->u.a.message + c->u.a.lensofar,
7588 c->u.a.lensofar += l;
7590 if (c->u.a.lensofar == c->u.a.totallen) {
7593 c->u.a.outstanding_requests++;
7594 if (agent_query(c->u.a.message,
7597 ssh_agentf_callback, c))
7598 ssh_agentf_callback(c, reply, replylen);
7599 sfree(c->u.a.message);
7600 c->u.a.message = NULL;
7601 c->u.a.lensofar = 0;
7608 * If it looks like the remote end hit the end of its window,
7609 * and we didn't want it to do that, think about using a
7612 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
7613 c->v.v2.locmaxwin < 0x40000000)
7614 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
7616 * If we are not buffering too much data,
7617 * enlarge the window again at the remote side.
7618 * If we are buffering too much, we may still
7619 * need to adjust the window if the server's
7622 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7623 c->v.v2.locmaxwin - bufsize : 0);
7625 * If we're either buffering way too much data, or if we're
7626 * buffering anything at all and we're in "simple" mode,
7627 * throttle the whole channel.
7629 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
7630 && !c->throttling_conn) {
7631 c->throttling_conn = 1;
7632 ssh_throttle_conn(ssh, +1);
7637 static void ssh_check_termination(Ssh ssh)
7639 if (ssh->version == 2 &&
7640 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7641 count234(ssh->channels) == 0 &&
7642 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
7644 * We used to send SSH_MSG_DISCONNECT here, because I'd
7645 * believed that _every_ conforming SSH-2 connection had to
7646 * end with a disconnect being sent by at least one side;
7647 * apparently I was wrong and it's perfectly OK to
7648 * unceremoniously slam the connection shut when you're done,
7649 * and indeed OpenSSH feels this is more polite than sending a
7650 * DISCONNECT. So now we don't.
7652 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7656 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id)
7658 logeventf(ssh, "Connection sharing downstream #%u connected", id);
7661 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
7663 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
7664 ssh_check_termination(ssh);
7667 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
7672 va_start(ap, logfmt);
7673 buf = dupvprintf(logfmt, ap);
7676 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
7678 logeventf(ssh, "Connection sharing: %s", buf);
7682 static void ssh_channel_destroy(struct ssh_channel *c)
7687 case CHAN_MAINSESSION:
7688 ssh->mainchan = NULL;
7689 update_specials_menu(ssh->frontend);
7692 if (c->u.x11.xconn != NULL)
7693 x11_close(c->u.x11.xconn);
7694 logevent("Forwarded X11 connection terminated");
7697 sfree(c->u.a.message);
7700 if (c->u.pfd.pf != NULL)
7701 pfd_close(c->u.pfd.pf);
7702 logevent("Forwarded port closed");
7706 del234(ssh->channels, c);
7707 if (ssh->version == 2) {
7708 bufchain_clear(&c->v.v2.outbuffer);
7709 assert(c->v.v2.chanreq_head == NULL);
7714 * If that was the last channel left open, we might need to
7717 ssh_check_termination(ssh);
7720 static void ssh2_channel_check_close(struct ssh_channel *c)
7723 struct Packet *pktout;
7727 * If we've sent out our own CHANNEL_OPEN but not yet seen
7728 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
7729 * it's too early to be sending close messages of any kind.
7734 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
7735 c->type == CHAN_ZOMBIE) &&
7736 !c->v.v2.chanreq_head &&
7737 !(c->closes & CLOSES_SENT_CLOSE)) {
7739 * We have both sent and received EOF (or the channel is a
7740 * zombie), and we have no outstanding channel requests, which
7741 * means the channel is in final wind-up. But we haven't sent
7742 * CLOSE, so let's do so now.
7744 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
7745 ssh2_pkt_adduint32(pktout, c->remoteid);
7746 ssh2_pkt_send(ssh, pktout);
7747 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
7750 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
7751 assert(c->v.v2.chanreq_head == NULL);
7753 * We have both sent and received CLOSE, which means we're
7754 * completely done with the channel.
7756 ssh_channel_destroy(c);
7760 static void ssh2_channel_got_eof(struct ssh_channel *c)
7762 if (c->closes & CLOSES_RCVD_EOF)
7763 return; /* already seen EOF */
7764 c->closes |= CLOSES_RCVD_EOF;
7766 if (c->type == CHAN_X11) {
7767 x11_send_eof(c->u.x11.xconn);
7768 } else if (c->type == CHAN_AGENT) {
7769 if (c->u.a.outstanding_requests == 0) {
7770 /* Manufacture an outgoing EOF in response to the incoming one. */
7771 sshfwd_write_eof(c);
7773 } else if (c->type == CHAN_SOCKDATA) {
7774 pfd_send_eof(c->u.pfd.pf);
7775 } else if (c->type == CHAN_MAINSESSION) {
7778 if (!ssh->sent_console_eof &&
7779 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
7781 * Either from_backend_eof told us that the front end
7782 * wants us to close the outgoing side of the connection
7783 * as soon as we see EOF from the far end, or else we've
7784 * unilaterally decided to do that because we've allocated
7785 * a remote pty and hence EOF isn't a particularly
7786 * meaningful concept.
7788 sshfwd_write_eof(c);
7790 ssh->sent_console_eof = TRUE;
7793 ssh2_channel_check_close(c);
7796 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
7798 struct ssh_channel *c;
7800 c = ssh2_channel_msg(ssh, pktin);
7803 if (c->type == CHAN_SHARING) {
7804 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7805 pktin->body, pktin->length);
7808 ssh2_channel_got_eof(c);
7811 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7813 struct ssh_channel *c;
7815 c = ssh2_channel_msg(ssh, pktin);
7818 if (c->type == CHAN_SHARING) {
7819 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7820 pktin->body, pktin->length);
7825 * When we receive CLOSE on a channel, we assume it comes with an
7826 * implied EOF if we haven't seen EOF yet.
7828 ssh2_channel_got_eof(c);
7830 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
7832 * It also means we stop expecting to see replies to any
7833 * outstanding channel requests, so clean those up too.
7834 * (ssh_chanreq_init will enforce by assertion that we don't
7835 * subsequently put anything back on this list.)
7837 while (c->v.v2.chanreq_head) {
7838 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
7839 ocr->handler(c, NULL, ocr->ctx);
7840 c->v.v2.chanreq_head = ocr->next;
7846 * And we also send an outgoing EOF, if we haven't already, on the
7847 * assumption that CLOSE is a pretty forceful announcement that
7848 * the remote side is doing away with the entire channel. (If it
7849 * had wanted to send us EOF and continue receiving data from us,
7850 * it would have just sent CHANNEL_EOF.)
7852 if (!(c->closes & CLOSES_SENT_EOF)) {
7854 * Make sure we don't read any more from whatever our local
7855 * data source is for this channel.
7858 case CHAN_MAINSESSION:
7859 ssh->send_ok = 0; /* stop trying to read from stdin */
7862 x11_override_throttle(c->u.x11.xconn, 1);
7865 pfd_override_throttle(c->u.pfd.pf, 1);
7870 * Abandon any buffered data we still wanted to send to this
7871 * channel. Receiving a CHANNEL_CLOSE is an indication that
7872 * the server really wants to get on and _destroy_ this
7873 * channel, and it isn't going to send us any further
7874 * WINDOW_ADJUSTs to permit us to send pending stuff.
7876 bufchain_clear(&c->v.v2.outbuffer);
7879 * Send outgoing EOF.
7881 sshfwd_write_eof(c);
7885 * Now process the actual close.
7887 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7888 c->closes |= CLOSES_RCVD_CLOSE;
7889 ssh2_channel_check_close(c);
7893 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7895 struct ssh_channel *c;
7897 c = ssh2_channel_msg(ssh, pktin);
7900 if (c->type == CHAN_SHARING) {
7901 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7902 pktin->body, pktin->length);
7905 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7906 c->remoteid = ssh_pkt_getuint32(pktin);
7907 c->halfopen = FALSE;
7908 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7909 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7911 if (c->type == CHAN_SOCKDATA_DORMANT) {
7912 c->type = CHAN_SOCKDATA;
7914 pfd_confirm(c->u.pfd.pf);
7915 } else if (c->type == CHAN_ZOMBIE) {
7917 * This case can occur if a local socket error occurred
7918 * between us sending out CHANNEL_OPEN and receiving
7919 * OPEN_CONFIRMATION. In this case, all we can do is
7920 * immediately initiate close proceedings now that we know the
7921 * server's id to put in the close message.
7923 ssh2_channel_check_close(c);
7926 * We never expect to receive OPEN_CONFIRMATION for any
7927 * *other* channel type (since only local-to-remote port
7928 * forwardings cause us to send CHANNEL_OPEN after the main
7929 * channel is live - all other auxiliary channel types are
7930 * initiated from the server end). It's safe to enforce this
7931 * by assertion rather than by ssh_disconnect, because the
7932 * real point is that we never constructed a half-open channel
7933 * structure in the first place with any type other than the
7936 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
7940 ssh_channel_try_eof(c); /* in case we had a pending EOF */
7943 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7945 static const char *const reasons[] = {
7946 "<unknown reason code>",
7947 "Administratively prohibited",
7949 "Unknown channel type",
7950 "Resource shortage",
7952 unsigned reason_code;
7953 char *reason_string;
7955 struct ssh_channel *c;
7957 c = ssh2_channel_msg(ssh, pktin);
7960 if (c->type == CHAN_SHARING) {
7961 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7962 pktin->body, pktin->length);
7965 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7967 if (c->type == CHAN_SOCKDATA_DORMANT) {
7968 reason_code = ssh_pkt_getuint32(pktin);
7969 if (reason_code >= lenof(reasons))
7970 reason_code = 0; /* ensure reasons[reason_code] in range */
7971 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
7972 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7973 reasons[reason_code], reason_length, reason_string);
7975 pfd_close(c->u.pfd.pf);
7976 } else if (c->type == CHAN_ZOMBIE) {
7978 * This case can occur if a local socket error occurred
7979 * between us sending out CHANNEL_OPEN and receiving
7980 * OPEN_FAILURE. In this case, we need do nothing except allow
7981 * the code below to throw the half-open channel away.
7985 * We never expect to receive OPEN_FAILURE for any *other*
7986 * channel type (since only local-to-remote port forwardings
7987 * cause us to send CHANNEL_OPEN after the main channel is
7988 * live - all other auxiliary channel types are initiated from
7989 * the server end). It's safe to enforce this by assertion
7990 * rather than by ssh_disconnect, because the real point is
7991 * that we never constructed a half-open channel structure in
7992 * the first place with any type other than the above.
7994 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
7997 del234(ssh->channels, c);
8001 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8004 int typelen, want_reply;
8005 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8006 struct ssh_channel *c;
8007 struct Packet *pktout;
8009 c = ssh2_channel_msg(ssh, pktin);
8012 if (c->type == CHAN_SHARING) {
8013 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8014 pktin->body, pktin->length);
8017 ssh_pkt_getstring(pktin, &type, &typelen);
8018 want_reply = ssh2_pkt_getbool(pktin);
8020 if (c->closes & CLOSES_SENT_CLOSE) {
8022 * We don't reply to channel requests after we've sent
8023 * CHANNEL_CLOSE for the channel, because our reply might
8024 * cross in the network with the other side's CHANNEL_CLOSE
8025 * and arrive after they have wound the channel up completely.
8031 * Having got the channel number, we now look at
8032 * the request type string to see if it's something
8035 if (c == ssh->mainchan) {
8037 * We recognise "exit-status" and "exit-signal" on
8038 * the primary channel.
8040 if (typelen == 11 &&
8041 !memcmp(type, "exit-status", 11)) {
8043 ssh->exitcode = ssh_pkt_getuint32(pktin);
8044 logeventf(ssh, "Server sent command exit status %d",
8046 reply = SSH2_MSG_CHANNEL_SUCCESS;
8048 } else if (typelen == 11 &&
8049 !memcmp(type, "exit-signal", 11)) {
8051 int is_plausible = TRUE, is_int = FALSE;
8052 char *fmt_sig = "", *fmt_msg = "";
8054 int msglen = 0, core = FALSE;
8055 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8056 * provide an `int' for the signal, despite its
8057 * having been a `string' in the drafts of RFC 4254 since at
8058 * least 2001. (Fixed in session.c 1.147.) Try to
8059 * infer which we can safely parse it as. */
8061 unsigned char *p = pktin->body +
8063 long len = pktin->length - pktin->savedpos;
8064 unsigned long num = GET_32BIT(p); /* what is it? */
8065 /* If it's 0, it hardly matters; assume string */
8069 int maybe_int = FALSE, maybe_str = FALSE;
8070 #define CHECK_HYPOTHESIS(offset, result) \
8073 int q = toint(offset); \
8074 if (q >= 0 && q+4 <= len) { \
8075 q = toint(q + 4 + GET_32BIT(p+q)); \
8076 if (q >= 0 && q+4 <= len && \
8077 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8082 CHECK_HYPOTHESIS(4+1, maybe_int);
8083 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8084 #undef CHECK_HYPOTHESIS
8085 if (maybe_int && !maybe_str)
8087 else if (!maybe_int && maybe_str)
8090 /* Crikey. Either or neither. Panic. */
8091 is_plausible = FALSE;
8094 ssh->exitcode = 128; /* means `unknown signal' */
8097 /* Old non-standard OpenSSH. */
8098 int signum = ssh_pkt_getuint32(pktin);
8099 fmt_sig = dupprintf(" %d", signum);
8100 ssh->exitcode = 128 + signum;
8102 /* As per RFC 4254. */
8105 ssh_pkt_getstring(pktin, &sig, &siglen);
8106 /* Signal name isn't supposed to be blank, but
8107 * let's cope gracefully if it is. */
8109 fmt_sig = dupprintf(" \"%.*s\"",
8114 * Really hideous method of translating the
8115 * signal description back into a locally
8116 * meaningful number.
8121 #define TRANSLATE_SIGNAL(s) \
8122 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8123 ssh->exitcode = 128 + SIG ## s
8125 TRANSLATE_SIGNAL(ABRT);
8128 TRANSLATE_SIGNAL(ALRM);
8131 TRANSLATE_SIGNAL(FPE);
8134 TRANSLATE_SIGNAL(HUP);
8137 TRANSLATE_SIGNAL(ILL);
8140 TRANSLATE_SIGNAL(INT);
8143 TRANSLATE_SIGNAL(KILL);
8146 TRANSLATE_SIGNAL(PIPE);
8149 TRANSLATE_SIGNAL(QUIT);
8152 TRANSLATE_SIGNAL(SEGV);
8155 TRANSLATE_SIGNAL(TERM);
8158 TRANSLATE_SIGNAL(USR1);
8161 TRANSLATE_SIGNAL(USR2);
8163 #undef TRANSLATE_SIGNAL
8165 ssh->exitcode = 128;
8167 core = ssh2_pkt_getbool(pktin);
8168 ssh_pkt_getstring(pktin, &msg, &msglen);
8170 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8172 /* ignore lang tag */
8173 } /* else don't attempt to parse */
8174 logeventf(ssh, "Server exited on signal%s%s%s",
8175 fmt_sig, core ? " (core dumped)" : "",
8177 if (*fmt_sig) sfree(fmt_sig);
8178 if (*fmt_msg) sfree(fmt_msg);
8179 reply = SSH2_MSG_CHANNEL_SUCCESS;
8184 * This is a channel request we don't know
8185 * about, so we now either ignore the request
8186 * or respond with CHANNEL_FAILURE, depending
8189 reply = SSH2_MSG_CHANNEL_FAILURE;
8192 pktout = ssh2_pkt_init(reply);
8193 ssh2_pkt_adduint32(pktout, c->remoteid);
8194 ssh2_pkt_send(ssh, pktout);
8198 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8201 int typelen, want_reply;
8202 struct Packet *pktout;
8204 ssh_pkt_getstring(pktin, &type, &typelen);
8205 want_reply = ssh2_pkt_getbool(pktin);
8208 * We currently don't support any global requests
8209 * at all, so we either ignore the request or
8210 * respond with REQUEST_FAILURE, depending on
8214 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8215 ssh2_pkt_send(ssh, pktout);
8219 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8223 struct X11FakeAuth *auth;
8226 * Make up a new set of fake X11 auth data, and add it to the tree
8227 * of currently valid ones with an indication of the sharing
8228 * context that it's relevant to.
8230 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8231 auth->share_cs = share_cs;
8232 auth->share_chan = share_chan;
8237 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8239 del234(ssh->x11authtree, auth);
8240 x11_free_fake_auth(auth);
8243 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8251 struct ssh_channel *c;
8252 unsigned remid, winsize, pktsize;
8253 unsigned our_winsize_override = 0;
8254 struct Packet *pktout;
8256 ssh_pkt_getstring(pktin, &type, &typelen);
8257 c = snew(struct ssh_channel);
8260 remid = ssh_pkt_getuint32(pktin);
8261 winsize = ssh_pkt_getuint32(pktin);
8262 pktsize = ssh_pkt_getuint32(pktin);
8264 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8267 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8268 addrstr = snewn(peeraddrlen+1, char);
8269 memcpy(addrstr, peeraddr, peeraddrlen);
8270 addrstr[peeraddrlen] = '\0';
8271 peerport = ssh_pkt_getuint32(pktin);
8273 logeventf(ssh, "Received X11 connect request from %s:%d",
8276 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8277 error = "X11 forwarding is not enabled";
8279 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8282 c->u.x11.initial = TRUE;
8285 * If we are a connection-sharing upstream, then we should
8286 * initially present a very small window, adequate to take
8287 * the X11 initial authorisation packet but not much more.
8288 * Downstream will then present us a larger window (by
8289 * fiat of the connection-sharing protocol) and we can
8290 * guarantee to send a positive-valued WINDOW_ADJUST.
8293 our_winsize_override = 128;
8295 logevent("Opened X11 forward channel");
8299 } else if (typelen == 15 &&
8300 !memcmp(type, "forwarded-tcpip", 15)) {
8301 struct ssh_rportfwd pf, *realpf;
8304 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8305 pf.shost = dupprintf("%.*s", shostlen, shost);
8306 pf.sport = ssh_pkt_getuint32(pktin);
8307 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8308 peerport = ssh_pkt_getuint32(pktin);
8309 realpf = find234(ssh->rportfwds, &pf, NULL);
8310 logeventf(ssh, "Received remote port %s:%d open request "
8311 "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
8314 if (realpf == NULL) {
8315 error = "Remote port is not recognised";
8319 if (realpf->share_ctx) {
8321 * This port forwarding is on behalf of a
8322 * connection-sharing downstream, so abandon our own
8323 * channel-open procedure and just pass the message on
8326 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8327 pktin->body, pktin->length);
8332 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8333 c, ssh->conf, realpf->pfrec->addressfamily);
8334 logeventf(ssh, "Attempting to forward remote port to "
8335 "%s:%d", realpf->dhost, realpf->dport);
8337 logeventf(ssh, "Port open failed: %s", err);
8339 error = "Port open failed";
8341 logevent("Forwarded port opened successfully");
8342 c->type = CHAN_SOCKDATA;
8345 } else if (typelen == 22 &&
8346 !memcmp(type, "auth-agent@openssh.com", 22)) {
8347 if (!ssh->agentfwd_enabled)
8348 error = "Agent forwarding is not enabled";
8350 c->type = CHAN_AGENT; /* identify channel type */
8351 c->u.a.lensofar = 0;
8352 c->u.a.message = NULL;
8353 c->u.a.outstanding_requests = 0;
8356 error = "Unsupported channel type requested";
8359 c->remoteid = remid;
8360 c->halfopen = FALSE;
8362 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8363 ssh2_pkt_adduint32(pktout, c->remoteid);
8364 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8365 ssh2_pkt_addstring(pktout, error);
8366 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8367 ssh2_pkt_send(ssh, pktout);
8368 logeventf(ssh, "Rejected channel open: %s", error);
8371 ssh2_channel_init(c);
8372 c->v.v2.remwindow = winsize;
8373 c->v.v2.remmaxpkt = pktsize;
8374 if (our_winsize_override) {
8375 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8376 our_winsize_override;
8378 add234(ssh->channels, c);
8379 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8380 ssh2_pkt_adduint32(pktout, c->remoteid);
8381 ssh2_pkt_adduint32(pktout, c->localid);
8382 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8383 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8384 ssh2_pkt_send(ssh, pktout);
8388 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8389 void *share_cs, void *share_chan,
8390 const char *peer_addr, int peer_port,
8391 int endian, int protomajor, int protominor,
8392 const void *initial_data, int initial_len)
8395 * This function is called when we've just discovered that an X
8396 * forwarding channel on which we'd been handling the initial auth
8397 * ourselves turns out to be destined for a connection-sharing
8398 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8399 * that we completely stop tracking windows and buffering data and
8400 * just pass more or less unmodified SSH messages back and forth.
8402 c->type = CHAN_SHARING;
8403 c->u.sharing.ctx = share_cs;
8404 share_setup_x11_channel(share_cs, share_chan,
8405 c->localid, c->remoteid, c->v.v2.remwindow,
8406 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8407 peer_addr, peer_port, endian,
8408 protomajor, protominor,
8409 initial_data, initial_len);
8412 void sshfwd_x11_is_local(struct ssh_channel *c)
8415 * This function is called when we've just discovered that an X
8416 * forwarding channel is _not_ destined for a connection-sharing
8417 * downstream but we're going to handle it ourselves. We stop
8418 * presenting a cautiously small window and go into ordinary data
8421 c->u.x11.initial = FALSE;
8422 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8426 * Buffer banner messages for later display at some convenient point,
8427 * if we're going to display them.
8429 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8431 /* Arbitrary limit to prevent unbounded inflation of buffer */
8432 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8433 bufchain_size(&ssh->banner) <= 131072) {
8434 char *banner = NULL;
8436 ssh_pkt_getstring(pktin, &banner, &size);
8438 bufchain_add(&ssh->banner, banner, size);
8442 /* Helper function to deal with sending tty modes for "pty-req" */
8443 static void ssh2_send_ttymode(void *data, char *mode, char *val)
8445 struct Packet *pktout = (struct Packet *)data;
8447 unsigned int arg = 0;
8448 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
8449 if (i == lenof(ssh_ttymodes)) return;
8450 switch (ssh_ttymodes[i].type) {
8452 arg = ssh_tty_parse_specchar(val);
8455 arg = ssh_tty_parse_boolean(val);
8458 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
8459 ssh2_pkt_adduint32(pktout, arg);
8462 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8465 struct ssh2_setup_x11_state {
8469 struct Packet *pktout;
8470 crStateP(ssh2_setup_x11_state, ctx);
8474 logevent("Requesting X11 forwarding");
8475 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8477 ssh2_pkt_addbool(pktout, 0); /* many connections */
8478 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8479 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8480 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8481 ssh2_pkt_send(ssh, pktout);
8483 /* Wait to be called back with either a response packet, or NULL
8484 * meaning clean up and free our data */
8488 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8489 logevent("X11 forwarding enabled");
8490 ssh->X11_fwd_enabled = TRUE;
8492 logevent("X11 forwarding refused");
8498 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8501 struct ssh2_setup_agent_state {
8505 struct Packet *pktout;
8506 crStateP(ssh2_setup_agent_state, ctx);
8510 logevent("Requesting OpenSSH-style agent forwarding");
8511 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8512 ssh2_setup_agent, s);
8513 ssh2_pkt_send(ssh, pktout);
8515 /* Wait to be called back with either a response packet, or NULL
8516 * meaning clean up and free our data */
8520 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8521 logevent("Agent forwarding enabled");
8522 ssh->agentfwd_enabled = TRUE;
8524 logevent("Agent forwarding refused");
8530 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8533 struct ssh2_setup_pty_state {
8537 struct Packet *pktout;
8538 crStateP(ssh2_setup_pty_state, ctx);
8542 /* Unpick the terminal-speed string. */
8543 /* XXX perhaps we should allow no speeds to be sent. */
8544 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8545 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8546 /* Build the pty request. */
8547 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
8549 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
8550 ssh2_pkt_adduint32(pktout, ssh->term_width);
8551 ssh2_pkt_adduint32(pktout, ssh->term_height);
8552 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
8553 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
8554 ssh2_pkt_addstring_start(pktout);
8555 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
8556 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
8557 ssh2_pkt_adduint32(pktout, ssh->ispeed);
8558 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
8559 ssh2_pkt_adduint32(pktout, ssh->ospeed);
8560 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
8561 ssh2_pkt_send(ssh, pktout);
8562 ssh->state = SSH_STATE_INTERMED;
8564 /* Wait to be called back with either a response packet, or NULL
8565 * meaning clean up and free our data */
8569 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8570 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8571 ssh->ospeed, ssh->ispeed);
8572 ssh->got_pty = TRUE;
8574 c_write_str(ssh, "Server refused to allocate pty\r\n");
8575 ssh->editing = ssh->echoing = 1;
8582 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
8585 struct ssh2_setup_env_state {
8587 int num_env, env_left, env_ok;
8590 struct Packet *pktout;
8591 crStateP(ssh2_setup_env_state, ctx);
8596 * Send environment variables.
8598 * Simplest thing here is to send all the requests at once, and
8599 * then wait for a whole bunch of successes or failures.
8605 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
8607 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
8608 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
8609 ssh2_pkt_addstring(pktout, key);
8610 ssh2_pkt_addstring(pktout, val);
8611 ssh2_pkt_send(ssh, pktout);
8616 logeventf(ssh, "Sent %d environment variables", s->num_env);
8621 s->env_left = s->num_env;
8623 while (s->env_left > 0) {
8624 /* Wait to be called back with either a response packet,
8625 * or NULL meaning clean up and free our data */
8627 if (!pktin) goto out;
8628 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
8633 if (s->env_ok == s->num_env) {
8634 logevent("All environment variables successfully set");
8635 } else if (s->env_ok == 0) {
8636 logevent("All environment variables refused");
8637 c_write_str(ssh, "Server refused to set environment variables\r\n");
8639 logeventf(ssh, "%d environment variables refused",
8640 s->num_env - s->env_ok);
8641 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8649 * Handle the SSH-2 userauth and connection layers.
8651 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
8653 do_ssh2_authconn(ssh, NULL, 0, pktin);
8656 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
8660 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
8663 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
8664 struct Packet *pktin)
8666 struct do_ssh2_authconn_state {
8670 AUTH_TYPE_PUBLICKEY,
8671 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
8672 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
8674 AUTH_TYPE_GSSAPI, /* always QUIET */
8675 AUTH_TYPE_KEYBOARD_INTERACTIVE,
8676 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
8678 int done_service_req;
8679 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
8680 int tried_pubkey_config, done_agent;
8685 int kbd_inter_refused;
8686 int we_are_in, userauth_success;
8687 prompts_t *cur_prompt;
8692 void *publickey_blob;
8693 int publickey_bloblen;
8694 int publickey_encrypted;
8695 char *publickey_algorithm;
8696 char *publickey_comment;
8697 unsigned char agent_request[5], *agent_response, *agentp;
8698 int agent_responselen;
8699 unsigned char *pkblob_in_agent;
8701 char *pkblob, *alg, *commentp;
8702 int pklen, alglen, commentlen;
8703 int siglen, retlen, len;
8704 char *q, *agentreq, *ret;
8706 struct Packet *pktout;
8709 struct ssh_gss_library *gsslib;
8710 Ssh_gss_ctx gss_ctx;
8711 Ssh_gss_buf gss_buf;
8712 Ssh_gss_buf gss_rcvtok, gss_sndtok;
8713 Ssh_gss_name gss_srv_name;
8714 Ssh_gss_stat gss_stat;
8717 crState(do_ssh2_authconn_state);
8721 /* Register as a handler for all the messages this coroutine handles. */
8722 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
8723 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
8724 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
8725 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
8726 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
8727 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
8728 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
8729 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
8730 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
8731 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
8732 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
8733 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
8734 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
8735 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
8736 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
8737 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
8738 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
8739 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
8740 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
8741 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
8743 s->done_service_req = FALSE;
8744 s->we_are_in = s->userauth_success = FALSE;
8745 s->agent_response = NULL;
8747 s->tried_gssapi = FALSE;
8750 if (!ssh->bare_connection) {
8751 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
8753 * Request userauth protocol, and await a response to it.
8755 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8756 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
8757 ssh2_pkt_send(ssh, s->pktout);
8758 crWaitUntilV(pktin);
8759 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
8760 s->done_service_req = TRUE;
8762 if (!s->done_service_req) {
8764 * Request connection protocol directly, without authentication.
8766 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8767 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8768 ssh2_pkt_send(ssh, s->pktout);
8769 crWaitUntilV(pktin);
8770 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
8771 s->we_are_in = TRUE; /* no auth required */
8773 bombout(("Server refused service request"));
8778 s->we_are_in = TRUE;
8781 /* Arrange to be able to deal with any BANNERs that come in.
8782 * (We do this now as packets may come in during the next bit.) */
8783 bufchain_init(&ssh->banner);
8784 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
8785 ssh2_msg_userauth_banner;
8788 * Misc one-time setup for authentication.
8790 s->publickey_blob = NULL;
8791 if (!s->we_are_in) {
8794 * Load the public half of any configured public key file
8797 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8798 if (!filename_is_null(s->keyfile)) {
8800 logeventf(ssh, "Reading private key file \"%.150s\"",
8801 filename_to_str(s->keyfile));
8802 keytype = key_type(s->keyfile);
8803 if (keytype == SSH_KEYTYPE_SSH2) {
8806 ssh2_userkey_loadpub(s->keyfile,
8807 &s->publickey_algorithm,
8808 &s->publickey_bloblen,
8809 &s->publickey_comment, &error);
8810 if (s->publickey_blob) {
8811 s->publickey_encrypted =
8812 ssh2_userkey_encrypted(s->keyfile, NULL);
8815 logeventf(ssh, "Unable to load private key (%s)",
8817 msgbuf = dupprintf("Unable to load private key file "
8818 "\"%.150s\" (%s)\r\n",
8819 filename_to_str(s->keyfile),
8821 c_write_str(ssh, msgbuf);
8826 logeventf(ssh, "Unable to use this key file (%s)",
8827 key_type_to_str(keytype));
8828 msgbuf = dupprintf("Unable to use key file \"%.150s\""
8830 filename_to_str(s->keyfile),
8831 key_type_to_str(keytype));
8832 c_write_str(ssh, msgbuf);
8834 s->publickey_blob = NULL;
8839 * Find out about any keys Pageant has (but if there's a
8840 * public key configured, filter out all others).
8843 s->agent_response = NULL;
8844 s->pkblob_in_agent = NULL;
8845 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
8849 logevent("Pageant is running. Requesting keys.");
8851 /* Request the keys held by the agent. */
8852 PUT_32BIT(s->agent_request, 1);
8853 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
8854 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
8855 ssh_agent_callback, ssh)) {
8859 bombout(("Unexpected data from server while"
8860 " waiting for agent response"));
8863 } while (pktin || inlen > 0);
8864 r = ssh->agent_response;
8865 s->agent_responselen = ssh->agent_response_len;
8867 s->agent_response = (unsigned char *) r;
8868 if (s->agent_response && s->agent_responselen >= 5 &&
8869 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
8872 p = s->agent_response + 5;
8873 s->nkeys = toint(GET_32BIT(p));
8876 * Vet the Pageant response to ensure that the key
8877 * count and blob lengths make sense.
8880 logeventf(ssh, "Pageant response contained a negative"
8881 " key count %d", s->nkeys);
8883 goto done_agent_query;
8885 unsigned char *q = p + 4;
8886 int lenleft = s->agent_responselen - 5 - 4;
8888 for (keyi = 0; keyi < s->nkeys; keyi++) {
8889 int bloblen, commentlen;
8891 logeventf(ssh, "Pageant response was truncated");
8893 goto done_agent_query;
8895 bloblen = toint(GET_32BIT(q));
8896 if (bloblen < 0 || bloblen > lenleft) {
8897 logeventf(ssh, "Pageant response was truncated");
8899 goto done_agent_query;
8901 lenleft -= 4 + bloblen;
8903 commentlen = toint(GET_32BIT(q));
8904 if (commentlen < 0 || commentlen > lenleft) {
8905 logeventf(ssh, "Pageant response was truncated");
8907 goto done_agent_query;
8909 lenleft -= 4 + commentlen;
8910 q += 4 + commentlen;
8915 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
8916 if (s->publickey_blob) {
8917 /* See if configured key is in agent. */
8918 for (keyi = 0; keyi < s->nkeys; keyi++) {
8919 s->pklen = toint(GET_32BIT(p));
8920 if (s->pklen == s->publickey_bloblen &&
8921 !memcmp(p+4, s->publickey_blob,
8922 s->publickey_bloblen)) {
8923 logeventf(ssh, "Pageant key #%d matches "
8924 "configured key file", keyi);
8926 s->pkblob_in_agent = p;
8930 p += toint(GET_32BIT(p)) + 4; /* comment */
8932 if (!s->pkblob_in_agent) {
8933 logevent("Configured key file not in Pageant");
8938 logevent("Failed to get reply from Pageant");
8946 * We repeat this whole loop, including the username prompt,
8947 * until we manage a successful authentication. If the user
8948 * types the wrong _password_, they can be sent back to the
8949 * beginning to try another username, if this is configured on.
8950 * (If they specify a username in the config, they are never
8951 * asked, even if they do give a wrong password.)
8953 * I think this best serves the needs of
8955 * - the people who have no configuration, no keys, and just
8956 * want to try repeated (username,password) pairs until they
8957 * type both correctly
8959 * - people who have keys and configuration but occasionally
8960 * need to fall back to passwords
8962 * - people with a key held in Pageant, who might not have
8963 * logged in to a particular machine before; so they want to
8964 * type a username, and then _either_ their key will be
8965 * accepted, _or_ they will type a password. If they mistype
8966 * the username they will want to be able to get back and
8969 s->got_username = FALSE;
8970 while (!s->we_are_in) {
8974 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
8976 * We got a username last time round this loop, and
8977 * with change_username turned off we don't try to get
8980 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
8981 int ret; /* need not be kept over crReturn */
8982 s->cur_prompt = new_prompts(ssh->frontend);
8983 s->cur_prompt->to_server = TRUE;
8984 s->cur_prompt->name = dupstr("SSH login name");
8985 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
8986 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8989 crWaitUntilV(!pktin);
8990 ret = get_userpass_input(s->cur_prompt, in, inlen);
8995 * get_userpass_input() failed to get a username.
8998 free_prompts(s->cur_prompt);
8999 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9002 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9003 free_prompts(s->cur_prompt);
9006 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9007 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9008 c_write_str(ssh, stuff);
9012 s->got_username = TRUE;
9015 * Send an authentication request using method "none": (a)
9016 * just in case it succeeds, and (b) so that we know what
9017 * authentication methods we can usefully try next.
9019 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9021 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9022 ssh2_pkt_addstring(s->pktout, ssh->username);
9023 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9024 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9025 ssh2_pkt_send(ssh, s->pktout);
9026 s->type = AUTH_TYPE_NONE;
9028 s->we_are_in = FALSE;
9030 s->tried_pubkey_config = FALSE;
9031 s->kbd_inter_refused = FALSE;
9033 /* Reset agent request state. */
9034 s->done_agent = FALSE;
9035 if (s->agent_response) {
9036 if (s->pkblob_in_agent) {
9037 s->agentp = s->pkblob_in_agent;
9039 s->agentp = s->agent_response + 5 + 4;
9045 char *methods = NULL;
9049 * Wait for the result of the last authentication request.
9052 crWaitUntilV(pktin);
9054 * Now is a convenient point to spew any banner material
9055 * that we've accumulated. (This should ensure that when
9056 * we exit the auth loop, we haven't any left to deal
9060 int size = bufchain_size(&ssh->banner);
9062 * Don't show the banner if we're operating in
9063 * non-verbose non-interactive mode. (It's probably
9064 * a script, which means nobody will read the
9065 * banner _anyway_, and moreover the printing of
9066 * the banner will screw up processing on the
9067 * output of (say) plink.)
9069 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9070 char *banner = snewn(size, char);
9071 bufchain_fetch(&ssh->banner, banner, size);
9072 c_write_untrusted(ssh, banner, size);
9075 bufchain_clear(&ssh->banner);
9077 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9078 logevent("Access granted");
9079 s->we_are_in = s->userauth_success = TRUE;
9083 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9084 bombout(("Strange packet received during authentication: "
9085 "type %d", pktin->type));
9092 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9093 * we can look at the string in it and know what we can
9094 * helpfully try next.
9096 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9097 ssh_pkt_getstring(pktin, &methods, &methlen);
9098 if (!ssh2_pkt_getbool(pktin)) {
9100 * We have received an unequivocal Access
9101 * Denied. This can translate to a variety of
9102 * messages, or no message at all.
9104 * For forms of authentication which are attempted
9105 * implicitly, by which I mean without printing
9106 * anything in the window indicating that we're
9107 * trying them, we should never print 'Access
9110 * If we do print a message saying that we're
9111 * attempting some kind of authentication, it's OK
9112 * to print a followup message saying it failed -
9113 * but the message may sometimes be more specific
9114 * than simply 'Access denied'.
9116 * Additionally, if we'd just tried password
9117 * authentication, we should break out of this
9118 * whole loop so as to go back to the username
9119 * prompt (iff we're configured to allow
9120 * username change attempts).
9122 if (s->type == AUTH_TYPE_NONE) {
9124 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9125 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9126 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9127 c_write_str(ssh, "Server refused our key\r\n");
9128 logevent("Server refused our key");
9129 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9130 /* This _shouldn't_ happen except by a
9131 * protocol bug causing client and server to
9132 * disagree on what is a correct signature. */
9133 c_write_str(ssh, "Server refused public-key signature"
9134 " despite accepting key!\r\n");
9135 logevent("Server refused public-key signature"
9136 " despite accepting key!");
9137 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9138 /* quiet, so no c_write */
9139 logevent("Server refused keyboard-interactive authentication");
9140 } else if (s->type==AUTH_TYPE_GSSAPI) {
9141 /* always quiet, so no c_write */
9142 /* also, the code down in the GSSAPI block has
9143 * already logged this in the Event Log */
9144 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9145 logevent("Keyboard-interactive authentication failed");
9146 c_write_str(ssh, "Access denied\r\n");
9148 assert(s->type == AUTH_TYPE_PASSWORD);
9149 logevent("Password authentication failed");
9150 c_write_str(ssh, "Access denied\r\n");
9152 if (conf_get_int(ssh->conf, CONF_change_username)) {
9153 /* XXX perhaps we should allow
9154 * keyboard-interactive to do this too? */
9155 s->we_are_in = FALSE;
9160 c_write_str(ssh, "Further authentication required\r\n");
9161 logevent("Further authentication required");
9165 in_commasep_string("publickey", methods, methlen);
9167 in_commasep_string("password", methods, methlen);
9168 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9169 in_commasep_string("keyboard-interactive", methods, methlen);
9172 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9173 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9174 in_commasep_string("gssapi-with-mic", methods, methlen) &&
9175 ssh->gsslibs->nlibraries > 0;
9179 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9181 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9184 * Attempt public-key authentication using a key from Pageant.
9187 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9189 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9191 /* Unpack key from agent response */
9192 s->pklen = toint(GET_32BIT(s->agentp));
9194 s->pkblob = (char *)s->agentp;
9195 s->agentp += s->pklen;
9196 s->alglen = toint(GET_32BIT(s->pkblob));
9197 s->alg = s->pkblob + 4;
9198 s->commentlen = toint(GET_32BIT(s->agentp));
9200 s->commentp = (char *)s->agentp;
9201 s->agentp += s->commentlen;
9202 /* s->agentp now points at next key, if any */
9204 /* See if server will accept it */
9205 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9206 ssh2_pkt_addstring(s->pktout, ssh->username);
9207 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9208 /* service requested */
9209 ssh2_pkt_addstring(s->pktout, "publickey");
9211 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9212 ssh2_pkt_addstring_start(s->pktout);
9213 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9214 ssh2_pkt_addstring_start(s->pktout);
9215 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9216 ssh2_pkt_send(ssh, s->pktout);
9217 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9219 crWaitUntilV(pktin);
9220 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9222 /* Offer of key refused. */
9229 if (flags & FLAG_VERBOSE) {
9230 c_write_str(ssh, "Authenticating with "
9232 c_write(ssh, s->commentp, s->commentlen);
9233 c_write_str(ssh, "\" from agent\r\n");
9237 * Server is willing to accept the key.
9238 * Construct a SIGN_REQUEST.
9240 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9241 ssh2_pkt_addstring(s->pktout, ssh->username);
9242 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9243 /* service requested */
9244 ssh2_pkt_addstring(s->pktout, "publickey");
9246 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9247 ssh2_pkt_addstring_start(s->pktout);
9248 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9249 ssh2_pkt_addstring_start(s->pktout);
9250 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9252 /* Ask agent for signature. */
9253 s->siglen = s->pktout->length - 5 + 4 +
9254 ssh->v2_session_id_len;
9255 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9257 s->len = 1; /* message type */
9258 s->len += 4 + s->pklen; /* key blob */
9259 s->len += 4 + s->siglen; /* data to sign */
9260 s->len += 4; /* flags */
9261 s->agentreq = snewn(4 + s->len, char);
9262 PUT_32BIT(s->agentreq, s->len);
9263 s->q = s->agentreq + 4;
9264 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9265 PUT_32BIT(s->q, s->pklen);
9267 memcpy(s->q, s->pkblob, s->pklen);
9269 PUT_32BIT(s->q, s->siglen);
9271 /* Now the data to be signed... */
9272 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9273 PUT_32BIT(s->q, ssh->v2_session_id_len);
9276 memcpy(s->q, ssh->v2_session_id,
9277 ssh->v2_session_id_len);
9278 s->q += ssh->v2_session_id_len;
9279 memcpy(s->q, s->pktout->data + 5,
9280 s->pktout->length - 5);
9281 s->q += s->pktout->length - 5;
9282 /* And finally the (zero) flags word. */
9284 if (!agent_query(s->agentreq, s->len + 4,
9286 ssh_agent_callback, ssh)) {
9290 bombout(("Unexpected data from server"
9291 " while waiting for agent"
9295 } while (pktin || inlen > 0);
9296 vret = ssh->agent_response;
9297 s->retlen = ssh->agent_response_len;
9302 if (s->retlen >= 9 &&
9303 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9304 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9305 logevent("Sending Pageant's response");
9306 ssh2_add_sigblob(ssh, s->pktout,
9307 s->pkblob, s->pklen,
9309 GET_32BIT(s->ret + 5));
9310 ssh2_pkt_send(ssh, s->pktout);
9311 s->type = AUTH_TYPE_PUBLICKEY;
9313 /* FIXME: less drastic response */
9314 bombout(("Pageant failed to answer challenge"));
9320 /* Do we have any keys left to try? */
9321 if (s->pkblob_in_agent) {
9322 s->done_agent = TRUE;
9323 s->tried_pubkey_config = TRUE;
9326 if (s->keyi >= s->nkeys)
9327 s->done_agent = TRUE;
9330 } else if (s->can_pubkey && s->publickey_blob &&
9331 !s->tried_pubkey_config) {
9333 struct ssh2_userkey *key; /* not live over crReturn */
9334 char *passphrase; /* not live over crReturn */
9336 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9338 s->tried_pubkey_config = TRUE;
9341 * Try the public key supplied in the configuration.
9343 * First, offer the public blob to see if the server is
9344 * willing to accept it.
9346 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9347 ssh2_pkt_addstring(s->pktout, ssh->username);
9348 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9349 /* service requested */
9350 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9351 ssh2_pkt_addbool(s->pktout, FALSE);
9352 /* no signature included */
9353 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9354 ssh2_pkt_addstring_start(s->pktout);
9355 ssh2_pkt_addstring_data(s->pktout,
9356 (char *)s->publickey_blob,
9357 s->publickey_bloblen);
9358 ssh2_pkt_send(ssh, s->pktout);
9359 logevent("Offered public key");
9361 crWaitUntilV(pktin);
9362 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9363 /* Key refused. Give up. */
9364 s->gotit = TRUE; /* reconsider message next loop */
9365 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9366 continue; /* process this new message */
9368 logevent("Offer of public key accepted");
9371 * Actually attempt a serious authentication using
9374 if (flags & FLAG_VERBOSE) {
9375 c_write_str(ssh, "Authenticating with public key \"");
9376 c_write_str(ssh, s->publickey_comment);
9377 c_write_str(ssh, "\"\r\n");
9381 const char *error; /* not live over crReturn */
9382 if (s->publickey_encrypted) {
9384 * Get a passphrase from the user.
9386 int ret; /* need not be kept over crReturn */
9387 s->cur_prompt = new_prompts(ssh->frontend);
9388 s->cur_prompt->to_server = FALSE;
9389 s->cur_prompt->name = dupstr("SSH key passphrase");
9390 add_prompt(s->cur_prompt,
9391 dupprintf("Passphrase for key \"%.100s\": ",
9392 s->publickey_comment),
9394 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9397 crWaitUntilV(!pktin);
9398 ret = get_userpass_input(s->cur_prompt,
9403 /* Failed to get a passphrase. Terminate. */
9404 free_prompts(s->cur_prompt);
9405 ssh_disconnect(ssh, NULL,
9406 "Unable to authenticate",
9407 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9412 dupstr(s->cur_prompt->prompts[0]->result);
9413 free_prompts(s->cur_prompt);
9415 passphrase = NULL; /* no passphrase needed */
9419 * Try decrypting the key.
9421 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9422 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9424 /* burn the evidence */
9425 smemclr(passphrase, strlen(passphrase));
9428 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9430 (key == SSH2_WRONG_PASSPHRASE)) {
9431 c_write_str(ssh, "Wrong passphrase\r\n");
9433 /* and loop again */
9435 c_write_str(ssh, "Unable to load private key (");
9436 c_write_str(ssh, error);
9437 c_write_str(ssh, ")\r\n");
9439 break; /* try something else */
9445 unsigned char *pkblob, *sigblob, *sigdata;
9446 int pkblob_len, sigblob_len, sigdata_len;
9450 * We have loaded the private key and the server
9451 * has announced that it's willing to accept it.
9452 * Hallelujah. Generate a signature and send it.
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 /* service requested */
9458 ssh2_pkt_addstring(s->pktout, "publickey");
9460 ssh2_pkt_addbool(s->pktout, TRUE);
9461 /* signature follows */
9462 ssh2_pkt_addstring(s->pktout, key->alg->name);
9463 pkblob = key->alg->public_blob(key->data,
9465 ssh2_pkt_addstring_start(s->pktout);
9466 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9470 * The data to be signed is:
9474 * followed by everything so far placed in the
9477 sigdata_len = s->pktout->length - 5 + 4 +
9478 ssh->v2_session_id_len;
9479 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9481 sigdata = snewn(sigdata_len, unsigned char);
9483 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9484 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9487 memcpy(sigdata+p, ssh->v2_session_id,
9488 ssh->v2_session_id_len);
9489 p += ssh->v2_session_id_len;
9490 memcpy(sigdata+p, s->pktout->data + 5,
9491 s->pktout->length - 5);
9492 p += s->pktout->length - 5;
9493 assert(p == sigdata_len);
9494 sigblob = key->alg->sign(key->data, (char *)sigdata,
9495 sigdata_len, &sigblob_len);
9496 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9497 sigblob, sigblob_len);
9502 ssh2_pkt_send(ssh, s->pktout);
9503 logevent("Sent public key signature");
9504 s->type = AUTH_TYPE_PUBLICKEY;
9505 key->alg->freekey(key->data);
9509 } else if (s->can_gssapi && !s->tried_gssapi) {
9511 /* GSSAPI Authentication */
9516 s->type = AUTH_TYPE_GSSAPI;
9517 s->tried_gssapi = TRUE;
9519 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9522 * Pick the highest GSS library on the preference
9528 for (i = 0; i < ngsslibs; i++) {
9529 int want_id = conf_get_int_int(ssh->conf,
9530 CONF_ssh_gsslist, i);
9531 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
9532 if (ssh->gsslibs->libraries[j].id == want_id) {
9533 s->gsslib = &ssh->gsslibs->libraries[j];
9534 goto got_gsslib; /* double break */
9539 * We always expect to have found something in
9540 * the above loop: we only came here if there
9541 * was at least one viable GSS library, and the
9542 * preference list should always mention
9543 * everything and only change the order.
9548 if (s->gsslib->gsslogmsg)
9549 logevent(s->gsslib->gsslogmsg);
9551 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
9552 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9553 ssh2_pkt_addstring(s->pktout, ssh->username);
9554 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9555 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
9556 logevent("Attempting GSSAPI authentication");
9558 /* add mechanism info */
9559 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
9561 /* number of GSSAPI mechanisms */
9562 ssh2_pkt_adduint32(s->pktout,1);
9564 /* length of OID + 2 */
9565 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
9566 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
9569 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
9571 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
9573 ssh2_pkt_send(ssh, s->pktout);
9574 crWaitUntilV(pktin);
9575 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
9576 logevent("GSSAPI authentication request refused");
9580 /* check returned packet ... */
9582 ssh_pkt_getstring(pktin, &data, &len);
9583 s->gss_rcvtok.value = data;
9584 s->gss_rcvtok.length = len;
9585 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
9586 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
9587 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
9588 memcmp((char *)s->gss_rcvtok.value + 2,
9589 s->gss_buf.value,s->gss_buf.length) ) {
9590 logevent("GSSAPI authentication - wrong response from server");
9594 /* now start running */
9595 s->gss_stat = s->gsslib->import_name(s->gsslib,
9598 if (s->gss_stat != SSH_GSS_OK) {
9599 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
9600 logevent("GSSAPI import name failed - Bad service name");
9602 logevent("GSSAPI import name failed");
9606 /* fetch TGT into GSS engine */
9607 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
9609 if (s->gss_stat != SSH_GSS_OK) {
9610 logevent("GSSAPI authentication failed to get credentials");
9611 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9615 /* initial tokens are empty */
9616 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
9617 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
9619 /* now enter the loop */
9621 s->gss_stat = s->gsslib->init_sec_context
9625 conf_get_int(ssh->conf, CONF_gssapifwd),
9629 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
9630 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
9631 logevent("GSSAPI authentication initialisation failed");
9633 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
9634 &s->gss_buf) == SSH_GSS_OK) {
9635 logevent(s->gss_buf.value);
9636 sfree(s->gss_buf.value);
9641 logevent("GSSAPI authentication initialised");
9643 /* Client and server now exchange tokens until GSSAPI
9644 * no longer says CONTINUE_NEEDED */
9646 if (s->gss_sndtok.length != 0) {
9647 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
9648 ssh_pkt_addstring_start(s->pktout);
9649 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
9650 ssh2_pkt_send(ssh, s->pktout);
9651 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
9654 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
9655 crWaitUntilV(pktin);
9656 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
9657 logevent("GSSAPI authentication - bad server response");
9658 s->gss_stat = SSH_GSS_FAILURE;
9661 ssh_pkt_getstring(pktin, &data, &len);
9662 s->gss_rcvtok.value = data;
9663 s->gss_rcvtok.length = len;
9665 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
9667 if (s->gss_stat != SSH_GSS_OK) {
9668 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9669 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9672 logevent("GSSAPI authentication loop finished OK");
9674 /* Now send the MIC */
9676 s->pktout = ssh2_pkt_init(0);
9677 micoffset = s->pktout->length;
9678 ssh_pkt_addstring_start(s->pktout);
9679 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
9680 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
9681 ssh_pkt_addstring(s->pktout, ssh->username);
9682 ssh_pkt_addstring(s->pktout, "ssh-connection");
9683 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
9685 s->gss_buf.value = (char *)s->pktout->data + micoffset;
9686 s->gss_buf.length = s->pktout->length - micoffset;
9688 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
9689 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
9690 ssh_pkt_addstring_start(s->pktout);
9691 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
9692 ssh2_pkt_send(ssh, s->pktout);
9693 s->gsslib->free_mic(s->gsslib, &mic);
9697 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9698 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9701 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
9704 * Keyboard-interactive authentication.
9707 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
9709 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
9711 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9712 ssh2_pkt_addstring(s->pktout, ssh->username);
9713 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9714 /* service requested */
9715 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
9717 ssh2_pkt_addstring(s->pktout, ""); /* lang */
9718 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
9719 ssh2_pkt_send(ssh, s->pktout);
9721 logevent("Attempting keyboard-interactive authentication");
9723 crWaitUntilV(pktin);
9724 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
9725 /* Server is not willing to do keyboard-interactive
9726 * at all (or, bizarrely but legally, accepts the
9727 * user without actually issuing any prompts).
9728 * Give up on it entirely. */
9730 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
9731 s->kbd_inter_refused = TRUE; /* don't try it again */
9736 * Loop while the server continues to send INFO_REQUESTs.
9738 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
9740 char *name, *inst, *lang;
9741 int name_len, inst_len, lang_len;
9745 * We've got a fresh USERAUTH_INFO_REQUEST.
9746 * Get the preamble and start building a prompt.
9748 ssh_pkt_getstring(pktin, &name, &name_len);
9749 ssh_pkt_getstring(pktin, &inst, &inst_len);
9750 ssh_pkt_getstring(pktin, &lang, &lang_len);
9751 s->cur_prompt = new_prompts(ssh->frontend);
9752 s->cur_prompt->to_server = TRUE;
9755 * Get any prompt(s) from the packet.
9757 s->num_prompts = ssh_pkt_getuint32(pktin);
9758 for (i = 0; i < s->num_prompts; i++) {
9762 static char noprompt[] =
9763 "<server failed to send prompt>: ";
9765 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9766 echo = ssh2_pkt_getbool(pktin);
9769 prompt_len = lenof(noprompt)-1;
9771 add_prompt(s->cur_prompt,
9772 dupprintf("%.*s", prompt_len, prompt),
9777 /* FIXME: better prefix to distinguish from
9779 s->cur_prompt->name =
9780 dupprintf("SSH server: %.*s", name_len, name);
9781 s->cur_prompt->name_reqd = TRUE;
9783 s->cur_prompt->name =
9784 dupstr("SSH server authentication");
9785 s->cur_prompt->name_reqd = FALSE;
9787 /* We add a prefix to try to make it clear that a prompt
9788 * has come from the server.
9789 * FIXME: ugly to print "Using..." in prompt _every_
9790 * time round. Can this be done more subtly? */
9791 /* Special case: for reasons best known to themselves,
9792 * some servers send k-i requests with no prompts and
9793 * nothing to display. Keep quiet in this case. */
9794 if (s->num_prompts || name_len || inst_len) {
9795 s->cur_prompt->instruction =
9796 dupprintf("Using keyboard-interactive authentication.%s%.*s",
9797 inst_len ? "\n" : "", inst_len, inst);
9798 s->cur_prompt->instr_reqd = TRUE;
9800 s->cur_prompt->instr_reqd = FALSE;
9804 * Display any instructions, and get the user's
9808 int ret; /* not live over crReturn */
9809 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9812 crWaitUntilV(!pktin);
9813 ret = get_userpass_input(s->cur_prompt, in, inlen);
9818 * Failed to get responses. Terminate.
9820 free_prompts(s->cur_prompt);
9821 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9822 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9829 * Send the response(s) to the server.
9831 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
9832 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
9833 for (i=0; i < s->num_prompts; i++) {
9834 ssh2_pkt_addstring(s->pktout,
9835 s->cur_prompt->prompts[i]->result);
9837 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9840 * Free the prompts structure from this iteration.
9841 * If there's another, a new one will be allocated
9842 * when we return to the top of this while loop.
9844 free_prompts(s->cur_prompt);
9847 * Get the next packet in case it's another
9850 crWaitUntilV(pktin);
9855 * We should have SUCCESS or FAILURE now.
9859 } else if (s->can_passwd) {
9862 * Plain old password authentication.
9864 int ret; /* not live over crReturn */
9865 int changereq_first_time; /* not live over crReturn */
9867 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
9869 s->cur_prompt = new_prompts(ssh->frontend);
9870 s->cur_prompt->to_server = TRUE;
9871 s->cur_prompt->name = dupstr("SSH password");
9872 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
9877 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9880 crWaitUntilV(!pktin);
9881 ret = get_userpass_input(s->cur_prompt, in, inlen);
9886 * Failed to get responses. Terminate.
9888 free_prompts(s->cur_prompt);
9889 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9890 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9895 * Squirrel away the password. (We may need it later if
9896 * asked to change it.)
9898 s->password = dupstr(s->cur_prompt->prompts[0]->result);
9899 free_prompts(s->cur_prompt);
9902 * Send the password packet.
9904 * We pad out the password packet to 256 bytes to make
9905 * it harder for an attacker to find the length of the
9908 * Anyone using a password longer than 256 bytes
9909 * probably doesn't have much to worry about from
9910 * people who find out how long their password is!
9912 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9913 ssh2_pkt_addstring(s->pktout, ssh->username);
9914 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9915 /* service requested */
9916 ssh2_pkt_addstring(s->pktout, "password");
9917 ssh2_pkt_addbool(s->pktout, FALSE);
9918 ssh2_pkt_addstring(s->pktout, s->password);
9919 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9920 logevent("Sent password");
9921 s->type = AUTH_TYPE_PASSWORD;
9924 * Wait for next packet, in case it's a password change
9927 crWaitUntilV(pktin);
9928 changereq_first_time = TRUE;
9930 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
9933 * We're being asked for a new password
9934 * (perhaps not for the first time).
9935 * Loop until the server accepts it.
9938 int got_new = FALSE; /* not live over crReturn */
9939 char *prompt; /* not live over crReturn */
9940 int prompt_len; /* not live over crReturn */
9944 if (changereq_first_time)
9945 msg = "Server requested password change";
9947 msg = "Server rejected new password";
9949 c_write_str(ssh, msg);
9950 c_write_str(ssh, "\r\n");
9953 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9955 s->cur_prompt = new_prompts(ssh->frontend);
9956 s->cur_prompt->to_server = TRUE;
9957 s->cur_prompt->name = dupstr("New SSH password");
9958 s->cur_prompt->instruction =
9959 dupprintf("%.*s", prompt_len, prompt);
9960 s->cur_prompt->instr_reqd = TRUE;
9962 * There's no explicit requirement in the protocol
9963 * for the "old" passwords in the original and
9964 * password-change messages to be the same, and
9965 * apparently some Cisco kit supports password change
9966 * by the user entering a blank password originally
9967 * and the real password subsequently, so,
9968 * reluctantly, we prompt for the old password again.
9970 * (On the other hand, some servers don't even bother
9971 * to check this field.)
9973 add_prompt(s->cur_prompt,
9974 dupstr("Current password (blank for previously entered password): "),
9976 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
9978 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
9982 * Loop until the user manages to enter the same
9987 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9990 crWaitUntilV(!pktin);
9991 ret = get_userpass_input(s->cur_prompt, in, inlen);
9996 * Failed to get responses. Terminate.
9998 /* burn the evidence */
9999 free_prompts(s->cur_prompt);
10000 smemclr(s->password, strlen(s->password));
10001 sfree(s->password);
10002 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10003 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10009 * If the user specified a new original password
10010 * (IYSWIM), overwrite any previously specified
10012 * (A side effect is that the user doesn't have to
10013 * re-enter it if they louse up the new password.)
10015 if (s->cur_prompt->prompts[0]->result[0]) {
10016 smemclr(s->password, strlen(s->password));
10017 /* burn the evidence */
10018 sfree(s->password);
10020 dupstr(s->cur_prompt->prompts[0]->result);
10024 * Check the two new passwords match.
10026 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10027 s->cur_prompt->prompts[2]->result)
10030 /* They don't. Silly user. */
10031 c_write_str(ssh, "Passwords do not match\r\n");
10036 * Send the new password (along with the old one).
10037 * (see above for padding rationale)
10039 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10040 ssh2_pkt_addstring(s->pktout, ssh->username);
10041 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10042 /* service requested */
10043 ssh2_pkt_addstring(s->pktout, "password");
10044 ssh2_pkt_addbool(s->pktout, TRUE);
10045 ssh2_pkt_addstring(s->pktout, s->password);
10046 ssh2_pkt_addstring(s->pktout,
10047 s->cur_prompt->prompts[1]->result);
10048 free_prompts(s->cur_prompt);
10049 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10050 logevent("Sent new password");
10053 * Now see what the server has to say about it.
10054 * (If it's CHANGEREQ again, it's not happy with the
10057 crWaitUntilV(pktin);
10058 changereq_first_time = FALSE;
10063 * We need to reexamine the current pktin at the top
10064 * of the loop. Either:
10065 * - we weren't asked to change password at all, in
10066 * which case it's a SUCCESS or FAILURE with the
10068 * - we sent a new password, and the server was
10069 * either OK with it (SUCCESS or FAILURE w/partial
10070 * success) or unhappy with the _old_ password
10071 * (FAILURE w/o partial success)
10072 * In any of these cases, we go back to the top of
10073 * the loop and start again.
10078 * We don't need the old password any more, in any
10079 * case. Burn the evidence.
10081 smemclr(s->password, strlen(s->password));
10082 sfree(s->password);
10085 char *str = dupprintf("No supported authentication methods available"
10086 " (server sent: %.*s)",
10089 ssh_disconnect(ssh, str,
10090 "No supported authentication methods available",
10091 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10101 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10103 /* Clear up various bits and pieces from authentication. */
10104 if (s->publickey_blob) {
10105 sfree(s->publickey_blob);
10106 sfree(s->publickey_comment);
10108 if (s->agent_response)
10109 sfree(s->agent_response);
10111 if (s->userauth_success && !ssh->bare_connection) {
10113 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10114 * packets since. Signal the transport layer to consider enacting
10115 * delayed compression.
10117 * (Relying on we_are_in is not sufficient, as
10118 * draft-miller-secsh-compression-delayed is quite clear that it
10119 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10120 * become set for other reasons.)
10122 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10125 ssh->channels = newtree234(ssh_channelcmp);
10128 * Set up handlers for some connection protocol messages, so we
10129 * don't have to handle them repeatedly in this coroutine.
10131 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10132 ssh2_msg_channel_window_adjust;
10133 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10134 ssh2_msg_global_request;
10137 * Create the main session channel.
10139 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10140 ssh->mainchan = NULL;
10142 ssh->mainchan = snew(struct ssh_channel);
10143 ssh->mainchan->ssh = ssh;
10144 ssh2_channel_init(ssh->mainchan);
10146 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10148 * Just start a direct-tcpip channel and use it as the main
10151 ssh_send_port_open(ssh->mainchan,
10152 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10153 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10155 ssh->ncmode = TRUE;
10157 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10158 logevent("Opening session as main channel");
10159 ssh2_pkt_send(ssh, s->pktout);
10160 ssh->ncmode = FALSE;
10162 crWaitUntilV(pktin);
10163 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10164 bombout(("Server refused to open channel"));
10166 /* FIXME: error data comes back in FAILURE packet */
10168 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10169 bombout(("Server's channel confirmation cited wrong channel"));
10172 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10173 ssh->mainchan->halfopen = FALSE;
10174 ssh->mainchan->type = CHAN_MAINSESSION;
10175 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10176 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10177 add234(ssh->channels, ssh->mainchan);
10178 update_specials_menu(ssh->frontend);
10179 logevent("Opened main channel");
10183 * Now we have a channel, make dispatch table entries for
10184 * general channel-based messages.
10186 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10187 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10188 ssh2_msg_channel_data;
10189 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10190 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10191 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10192 ssh2_msg_channel_open_confirmation;
10193 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10194 ssh2_msg_channel_open_failure;
10195 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10196 ssh2_msg_channel_request;
10197 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10198 ssh2_msg_channel_open;
10199 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10200 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10203 * Now the connection protocol is properly up and running, with
10204 * all those dispatch table entries, so it's safe to let
10205 * downstreams start trying to open extra channels through us.
10207 if (ssh->connshare)
10208 share_activate(ssh->connshare, ssh->v_s);
10210 if (ssh->mainchan && ssh_is_simple(ssh)) {
10212 * This message indicates to the server that we promise
10213 * not to try to run any other channel in parallel with
10214 * this one, so it's safe for it to advertise a very large
10215 * window and leave the flow control to TCP.
10217 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10218 "simple@putty.projects.tartarus.org",
10220 ssh2_pkt_send(ssh, s->pktout);
10224 * Enable port forwardings.
10226 ssh_setup_portfwd(ssh, ssh->conf);
10228 if (ssh->mainchan && !ssh->ncmode) {
10230 * Send the CHANNEL_REQUESTS for the main session channel.
10231 * Each one is handled by its own little asynchronous
10235 /* Potentially enable X11 forwarding. */
10236 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10238 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10240 if (!ssh->x11disp) {
10241 /* FIXME: return an error message from x11_setup_display */
10242 logevent("X11 forwarding not enabled: unable to"
10243 " initialise X display");
10245 ssh->x11auth = x11_invent_fake_auth
10246 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10247 ssh->x11auth->disp = ssh->x11disp;
10249 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10253 /* Potentially enable agent forwarding. */
10254 if (ssh_agent_forwarding_permitted(ssh))
10255 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10257 /* Now allocate a pty for the session. */
10258 if (!conf_get_int(ssh->conf, CONF_nopty))
10259 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10261 /* Send environment variables. */
10262 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10265 * Start a shell or a remote command. We may have to attempt
10266 * this twice if the config data has provided a second choice
10273 if (ssh->fallback_cmd) {
10274 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10275 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10277 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10278 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10282 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10283 ssh2_response_authconn, NULL);
10284 ssh2_pkt_addstring(s->pktout, cmd);
10286 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10287 ssh2_response_authconn, NULL);
10288 ssh2_pkt_addstring(s->pktout, cmd);
10290 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10291 ssh2_response_authconn, NULL);
10293 ssh2_pkt_send(ssh, s->pktout);
10295 crWaitUntilV(pktin);
10297 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10298 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10299 bombout(("Unexpected response to shell/command request:"
10300 " packet type %d", pktin->type));
10304 * We failed to start the command. If this is the
10305 * fallback command, we really are finished; if it's
10306 * not, and if the fallback command exists, try falling
10307 * back to it before complaining.
10309 if (!ssh->fallback_cmd &&
10310 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10311 logevent("Primary command failed; attempting fallback");
10312 ssh->fallback_cmd = TRUE;
10315 bombout(("Server refused to start a shell/command"));
10318 logevent("Started a shell/command");
10323 ssh->editing = ssh->echoing = TRUE;
10326 ssh->state = SSH_STATE_SESSION;
10327 if (ssh->size_needed)
10328 ssh_size(ssh, ssh->term_width, ssh->term_height);
10329 if (ssh->eof_needed)
10330 ssh_special(ssh, TS_EOF);
10336 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10341 s->try_send = FALSE;
10345 * _All_ the connection-layer packets we expect to
10346 * receive are now handled by the dispatch table.
10347 * Anything that reaches here must be bogus.
10350 bombout(("Strange packet received: type %d", pktin->type));
10352 } else if (ssh->mainchan) {
10354 * We have spare data. Add it to the channel buffer.
10356 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
10357 s->try_send = TRUE;
10361 struct ssh_channel *c;
10363 * Try to send data on all channels if we can.
10365 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
10366 ssh2_try_send_and_unthrottle(ssh, c);
10374 * Handlers for SSH-2 messages that might arrive at any moment.
10376 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10378 /* log reason code in disconnect message */
10380 int reason, msglen;
10382 reason = ssh_pkt_getuint32(pktin);
10383 ssh_pkt_getstring(pktin, &msg, &msglen);
10385 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10386 buf = dupprintf("Received disconnect message (%s)",
10387 ssh2_disconnect_reasons[reason]);
10389 buf = dupprintf("Received disconnect message (unknown"
10390 " type %d)", reason);
10394 buf = dupprintf("Disconnection message text: %.*s",
10397 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10399 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10400 ssh2_disconnect_reasons[reason] : "unknown",
10405 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10407 /* log the debug message */
10411 /* XXX maybe we should actually take notice of the return value */
10412 ssh2_pkt_getbool(pktin);
10413 ssh_pkt_getstring(pktin, &msg, &msglen);
10415 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
10418 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10420 do_ssh2_transport(ssh, NULL, 0, pktin);
10424 * Called if we receive a packet that isn't allowed by the protocol.
10425 * This only applies to packets whose meaning PuTTY understands.
10426 * Entirely unknown packets are handled below.
10428 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10430 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10431 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10433 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10437 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10439 struct Packet *pktout;
10440 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10441 ssh2_pkt_adduint32(pktout, pktin->sequence);
10443 * UNIMPLEMENTED messages MUST appear in the same order as the
10444 * messages they respond to. Hence, never queue them.
10446 ssh2_pkt_send_noqueue(ssh, pktout);
10450 * Handle the top-level SSH-2 protocol.
10452 static void ssh2_protocol_setup(Ssh ssh)
10457 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10459 for (i = 0; i < 256; i++)
10460 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10463 * Initially, we only accept transport messages (and a few generic
10464 * ones). do_ssh2_authconn will add more when it starts.
10465 * Messages that are understood but not currently acceptable go to
10466 * ssh2_msg_unexpected.
10468 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10469 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10470 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10471 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10472 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10473 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10474 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10475 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10476 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10477 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10478 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10479 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10480 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10481 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10482 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10483 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10484 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10485 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10486 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10487 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10488 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10489 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10490 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10491 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10492 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10493 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10494 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10495 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10496 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10497 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10498 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10499 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10500 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10503 * These messages have a special handler from the start.
10505 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10506 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10507 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10510 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10515 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10517 for (i = 0; i < 256; i++)
10518 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10521 * Initially, we set all ssh-connection messages to 'unexpected';
10522 * do_ssh2_authconn will fill things in properly. We also handle a
10523 * couple of messages from the transport protocol which aren't
10524 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10527 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10528 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10529 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10530 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10531 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10532 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10533 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10534 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10535 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10536 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10537 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10538 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10539 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10540 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10542 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10545 * These messages have a special handler from the start.
10547 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10548 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
10549 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10552 static void ssh2_timer(void *ctx, unsigned long now)
10554 Ssh ssh = (Ssh)ctx;
10556 if (ssh->state == SSH_STATE_CLOSED)
10559 if (!ssh->kex_in_progress && !ssh->bare_connection &&
10560 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
10561 now == ssh->next_rekey) {
10562 do_ssh2_transport(ssh, "timeout", -1, NULL);
10566 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
10567 struct Packet *pktin)
10569 unsigned char *in = (unsigned char *)vin;
10570 if (ssh->state == SSH_STATE_CLOSED)
10574 ssh->incoming_data_size += pktin->encrypted_len;
10575 if (!ssh->kex_in_progress &&
10576 ssh->max_data_size != 0 &&
10577 ssh->incoming_data_size > ssh->max_data_size)
10578 do_ssh2_transport(ssh, "too much data received", -1, NULL);
10582 ssh->packet_dispatch[pktin->type](ssh, pktin);
10583 else if (!ssh->protocol_initial_phase_done)
10584 do_ssh2_transport(ssh, in, inlen, pktin);
10586 do_ssh2_authconn(ssh, in, inlen, pktin);
10589 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
10590 struct Packet *pktin)
10592 unsigned char *in = (unsigned char *)vin;
10593 if (ssh->state == SSH_STATE_CLOSED)
10597 ssh->packet_dispatch[pktin->type](ssh, pktin);
10599 do_ssh2_authconn(ssh, in, inlen, pktin);
10602 static void ssh_cache_conf_values(Ssh ssh)
10604 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
10608 * Called to set up the connection.
10610 * Returns an error message, or NULL on success.
10612 static const char *ssh_init(void *frontend_handle, void **backend_handle,
10613 Conf *conf, char *host, int port, char **realhost,
10614 int nodelay, int keepalive)
10619 ssh = snew(struct ssh_tag);
10620 ssh->conf = conf_copy(conf);
10621 ssh_cache_conf_values(ssh);
10622 ssh->version = 0; /* when not ready yet */
10624 ssh->cipher = NULL;
10625 ssh->v1_cipher_ctx = NULL;
10626 ssh->crcda_ctx = NULL;
10627 ssh->cscipher = NULL;
10628 ssh->cs_cipher_ctx = NULL;
10629 ssh->sccipher = NULL;
10630 ssh->sc_cipher_ctx = NULL;
10632 ssh->cs_mac_ctx = NULL;
10634 ssh->sc_mac_ctx = NULL;
10635 ssh->cscomp = NULL;
10636 ssh->cs_comp_ctx = NULL;
10637 ssh->sccomp = NULL;
10638 ssh->sc_comp_ctx = NULL;
10640 ssh->kex_ctx = NULL;
10641 ssh->hostkey = NULL;
10642 ssh->hostkey_str = NULL;
10643 ssh->exitcode = -1;
10644 ssh->close_expected = FALSE;
10645 ssh->clean_exit = FALSE;
10646 ssh->state = SSH_STATE_PREPACKET;
10647 ssh->size_needed = FALSE;
10648 ssh->eof_needed = FALSE;
10650 ssh->logctx = NULL;
10651 ssh->deferred_send_data = NULL;
10652 ssh->deferred_len = 0;
10653 ssh->deferred_size = 0;
10654 ssh->fallback_cmd = 0;
10655 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
10656 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
10657 ssh->x11disp = NULL;
10658 ssh->x11auth = NULL;
10659 ssh->x11authtree = newtree234(x11_authcmp);
10660 ssh->v1_compressing = FALSE;
10661 ssh->v2_outgoing_sequence = 0;
10662 ssh->ssh1_rdpkt_crstate = 0;
10663 ssh->ssh2_rdpkt_crstate = 0;
10664 ssh->ssh2_bare_rdpkt_crstate = 0;
10665 ssh->ssh_gotdata_crstate = 0;
10666 ssh->do_ssh1_connection_crstate = 0;
10667 ssh->do_ssh_init_state = NULL;
10668 ssh->do_ssh_connection_init_state = NULL;
10669 ssh->do_ssh1_login_state = NULL;
10670 ssh->do_ssh2_transport_state = NULL;
10671 ssh->do_ssh2_authconn_state = NULL;
10674 ssh->mainchan = NULL;
10675 ssh->throttled_all = 0;
10676 ssh->v1_stdout_throttling = 0;
10678 ssh->queuelen = ssh->queuesize = 0;
10679 ssh->queueing = FALSE;
10680 ssh->qhead = ssh->qtail = NULL;
10681 ssh->deferred_rekey_reason = NULL;
10682 bufchain_init(&ssh->queued_incoming_data);
10683 ssh->frozen = FALSE;
10684 ssh->username = NULL;
10685 ssh->sent_console_eof = FALSE;
10686 ssh->got_pty = FALSE;
10687 ssh->bare_connection = FALSE;
10688 ssh->X11_fwd_enabled = FALSE;
10689 ssh->connshare = NULL;
10690 ssh->attempting_connshare = FALSE;
10692 *backend_handle = ssh;
10695 if (crypto_startup() == 0)
10696 return "Microsoft high encryption pack not installed!";
10699 ssh->frontend = frontend_handle;
10700 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
10701 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
10703 ssh->channels = NULL;
10704 ssh->rportfwds = NULL;
10705 ssh->portfwds = NULL;
10710 ssh->conn_throttle_count = 0;
10711 ssh->overall_bufsize = 0;
10712 ssh->fallback_cmd = 0;
10714 ssh->protocol = NULL;
10716 ssh->protocol_initial_phase_done = FALSE;
10718 ssh->pinger = NULL;
10720 ssh->incoming_data_size = ssh->outgoing_data_size =
10721 ssh->deferred_data_size = 0L;
10722 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10723 CONF_ssh_rekey_data));
10724 ssh->kex_in_progress = FALSE;
10727 ssh->gsslibs = NULL;
10730 random_ref(); /* do this now - may be needed by sharing setup code */
10732 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
10741 static void ssh_free(void *handle)
10743 Ssh ssh = (Ssh) handle;
10744 struct ssh_channel *c;
10745 struct ssh_rportfwd *pf;
10746 struct X11FakeAuth *auth;
10748 if (ssh->v1_cipher_ctx)
10749 ssh->cipher->free_context(ssh->v1_cipher_ctx);
10750 if (ssh->cs_cipher_ctx)
10751 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
10752 if (ssh->sc_cipher_ctx)
10753 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
10754 if (ssh->cs_mac_ctx)
10755 ssh->csmac->free_context(ssh->cs_mac_ctx);
10756 if (ssh->sc_mac_ctx)
10757 ssh->scmac->free_context(ssh->sc_mac_ctx);
10758 if (ssh->cs_comp_ctx) {
10760 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
10762 zlib_compress_cleanup(ssh->cs_comp_ctx);
10764 if (ssh->sc_comp_ctx) {
10766 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
10768 zlib_decompress_cleanup(ssh->sc_comp_ctx);
10771 dh_cleanup(ssh->kex_ctx);
10772 sfree(ssh->savedhost);
10774 while (ssh->queuelen-- > 0)
10775 ssh_free_packet(ssh->queue[ssh->queuelen]);
10778 while (ssh->qhead) {
10779 struct queued_handler *qh = ssh->qhead;
10780 ssh->qhead = qh->next;
10783 ssh->qhead = ssh->qtail = NULL;
10785 if (ssh->channels) {
10786 while ((c = delpos234(ssh->channels, 0)) != NULL) {
10789 if (c->u.x11.xconn != NULL)
10790 x11_close(c->u.x11.xconn);
10792 case CHAN_SOCKDATA:
10793 case CHAN_SOCKDATA_DORMANT:
10794 if (c->u.pfd.pf != NULL)
10795 pfd_close(c->u.pfd.pf);
10798 if (ssh->version == 2) {
10799 struct outstanding_channel_request *ocr, *nocr;
10800 ocr = c->v.v2.chanreq_head;
10802 ocr->handler(c, NULL, ocr->ctx);
10807 bufchain_clear(&c->v.v2.outbuffer);
10811 freetree234(ssh->channels);
10812 ssh->channels = NULL;
10815 if (ssh->connshare)
10816 sharestate_free(ssh->connshare);
10818 if (ssh->rportfwds) {
10819 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
10821 freetree234(ssh->rportfwds);
10822 ssh->rportfwds = NULL;
10824 sfree(ssh->deferred_send_data);
10826 x11_free_display(ssh->x11disp);
10827 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
10828 x11_free_fake_auth(auth);
10829 freetree234(ssh->x11authtree);
10830 sfree(ssh->do_ssh_init_state);
10831 sfree(ssh->do_ssh1_login_state);
10832 sfree(ssh->do_ssh2_transport_state);
10833 sfree(ssh->do_ssh2_authconn_state);
10836 sfree(ssh->fullhostname);
10837 sfree(ssh->hostkey_str);
10838 if (ssh->crcda_ctx) {
10839 crcda_free_context(ssh->crcda_ctx);
10840 ssh->crcda_ctx = NULL;
10843 ssh_do_close(ssh, TRUE);
10844 expire_timer_context(ssh);
10846 pinger_free(ssh->pinger);
10847 bufchain_clear(&ssh->queued_incoming_data);
10848 sfree(ssh->username);
10849 conf_free(ssh->conf);
10852 ssh_gss_cleanup(ssh->gsslibs);
10860 * Reconfigure the SSH backend.
10862 static void ssh_reconfig(void *handle, Conf *conf)
10864 Ssh ssh = (Ssh) handle;
10865 char *rekeying = NULL, rekey_mandatory = FALSE;
10866 unsigned long old_max_data_size;
10869 pinger_reconfig(ssh->pinger, ssh->conf, conf);
10871 ssh_setup_portfwd(ssh, conf);
10873 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
10874 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
10876 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
10877 unsigned long now = GETTICKCOUNT();
10879 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
10880 rekeying = "timeout shortened";
10882 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
10886 old_max_data_size = ssh->max_data_size;
10887 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10888 CONF_ssh_rekey_data));
10889 if (old_max_data_size != ssh->max_data_size &&
10890 ssh->max_data_size != 0) {
10891 if (ssh->outgoing_data_size > ssh->max_data_size ||
10892 ssh->incoming_data_size > ssh->max_data_size)
10893 rekeying = "data limit lowered";
10896 if (conf_get_int(ssh->conf, CONF_compression) !=
10897 conf_get_int(conf, CONF_compression)) {
10898 rekeying = "compression setting changed";
10899 rekey_mandatory = TRUE;
10902 for (i = 0; i < CIPHER_MAX; i++)
10903 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
10904 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
10905 rekeying = "cipher settings changed";
10906 rekey_mandatory = TRUE;
10908 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
10909 conf_get_int(conf, CONF_ssh2_des_cbc)) {
10910 rekeying = "cipher settings changed";
10911 rekey_mandatory = TRUE;
10914 conf_free(ssh->conf);
10915 ssh->conf = conf_copy(conf);
10916 ssh_cache_conf_values(ssh);
10918 if (!ssh->bare_connection && rekeying) {
10919 if (!ssh->kex_in_progress) {
10920 do_ssh2_transport(ssh, rekeying, -1, NULL);
10921 } else if (rekey_mandatory) {
10922 ssh->deferred_rekey_reason = rekeying;
10928 * Called to send data down the SSH connection.
10930 static int ssh_send(void *handle, char *buf, int len)
10932 Ssh ssh = (Ssh) handle;
10934 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10937 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
10939 return ssh_sendbuffer(ssh);
10943 * Called to query the current amount of buffered stdin data.
10945 static int ssh_sendbuffer(void *handle)
10947 Ssh ssh = (Ssh) handle;
10948 int override_value;
10950 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10954 * If the SSH socket itself has backed up, add the total backup
10955 * size on that to any individual buffer on the stdin channel.
10957 override_value = 0;
10958 if (ssh->throttled_all)
10959 override_value = ssh->overall_bufsize;
10961 if (ssh->version == 1) {
10962 return override_value;
10963 } else if (ssh->version == 2) {
10964 if (!ssh->mainchan)
10965 return override_value;
10967 return (override_value +
10968 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
10975 * Called to set the size of the window from SSH's POV.
10977 static void ssh_size(void *handle, int width, int height)
10979 Ssh ssh = (Ssh) handle;
10980 struct Packet *pktout;
10982 ssh->term_width = width;
10983 ssh->term_height = height;
10985 switch (ssh->state) {
10986 case SSH_STATE_BEFORE_SIZE:
10987 case SSH_STATE_PREPACKET:
10988 case SSH_STATE_CLOSED:
10989 break; /* do nothing */
10990 case SSH_STATE_INTERMED:
10991 ssh->size_needed = TRUE; /* buffer for later */
10993 case SSH_STATE_SESSION:
10994 if (!conf_get_int(ssh->conf, CONF_nopty)) {
10995 if (ssh->version == 1) {
10996 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
10997 PKT_INT, ssh->term_height,
10998 PKT_INT, ssh->term_width,
10999 PKT_INT, 0, PKT_INT, 0, PKT_END);
11000 } else if (ssh->mainchan) {
11001 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11003 ssh2_pkt_adduint32(pktout, ssh->term_width);
11004 ssh2_pkt_adduint32(pktout, ssh->term_height);
11005 ssh2_pkt_adduint32(pktout, 0);
11006 ssh2_pkt_adduint32(pktout, 0);
11007 ssh2_pkt_send(ssh, pktout);
11015 * Return a list of the special codes that make sense in this
11018 static const struct telnet_special *ssh_get_specials(void *handle)
11020 static const struct telnet_special ssh1_ignore_special[] = {
11021 {"IGNORE message", TS_NOP}
11023 static const struct telnet_special ssh2_ignore_special[] = {
11024 {"IGNORE message", TS_NOP},
11026 static const struct telnet_special ssh2_rekey_special[] = {
11027 {"Repeat key exchange", TS_REKEY},
11029 static const struct telnet_special ssh2_session_specials[] = {
11032 /* These are the signal names defined by RFC 4254.
11033 * They include all the ISO C signals, but are a subset of the POSIX
11034 * required signals. */
11035 {"SIGINT (Interrupt)", TS_SIGINT},
11036 {"SIGTERM (Terminate)", TS_SIGTERM},
11037 {"SIGKILL (Kill)", TS_SIGKILL},
11038 {"SIGQUIT (Quit)", TS_SIGQUIT},
11039 {"SIGHUP (Hangup)", TS_SIGHUP},
11040 {"More signals", TS_SUBMENU},
11041 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11042 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11043 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11044 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11045 {NULL, TS_EXITMENU}
11047 static const struct telnet_special specials_end[] = {
11048 {NULL, TS_EXITMENU}
11050 /* XXX review this length for any changes: */
11051 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
11052 lenof(ssh2_rekey_special) +
11053 lenof(ssh2_session_specials) +
11054 lenof(specials_end)];
11055 Ssh ssh = (Ssh) handle;
11057 #define ADD_SPECIALS(name) \
11059 assert((i + lenof(name)) <= lenof(ssh_specials)); \
11060 memcpy(&ssh_specials[i], name, sizeof name); \
11061 i += lenof(name); \
11064 if (ssh->version == 1) {
11065 /* Don't bother offering IGNORE if we've decided the remote
11066 * won't cope with it, since we wouldn't bother sending it if
11068 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11069 ADD_SPECIALS(ssh1_ignore_special);
11070 } else if (ssh->version == 2) {
11071 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11072 ADD_SPECIALS(ssh2_ignore_special);
11073 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11074 ADD_SPECIALS(ssh2_rekey_special);
11076 ADD_SPECIALS(ssh2_session_specials);
11077 } /* else we're not ready yet */
11080 ADD_SPECIALS(specials_end);
11081 return ssh_specials;
11085 #undef ADD_SPECIALS
11089 * Send special codes. TS_EOF is useful for `plink', so you
11090 * can send an EOF and collect resulting output (e.g. `plink
11093 static void ssh_special(void *handle, Telnet_Special code)
11095 Ssh ssh = (Ssh) handle;
11096 struct Packet *pktout;
11098 if (code == TS_EOF) {
11099 if (ssh->state != SSH_STATE_SESSION) {
11101 * Buffer the EOF in case we are pre-SESSION, so we can
11102 * send it as soon as we reach SESSION.
11104 if (code == TS_EOF)
11105 ssh->eof_needed = TRUE;
11108 if (ssh->version == 1) {
11109 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11110 } else if (ssh->mainchan) {
11111 sshfwd_write_eof(ssh->mainchan);
11112 ssh->send_ok = 0; /* now stop trying to read from stdin */
11114 logevent("Sent EOF message");
11115 } else if (code == TS_PING || code == TS_NOP) {
11116 if (ssh->state == SSH_STATE_CLOSED
11117 || ssh->state == SSH_STATE_PREPACKET) return;
11118 if (ssh->version == 1) {
11119 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11120 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11122 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11123 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11124 ssh2_pkt_addstring_start(pktout);
11125 ssh2_pkt_send_noqueue(ssh, pktout);
11128 } else if (code == TS_REKEY) {
11129 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11130 ssh->version == 2) {
11131 do_ssh2_transport(ssh, "at user request", -1, NULL);
11133 } else if (code == TS_BRK) {
11134 if (ssh->state == SSH_STATE_CLOSED
11135 || ssh->state == SSH_STATE_PREPACKET) return;
11136 if (ssh->version == 1) {
11137 logevent("Unable to send BREAK signal in SSH-1");
11138 } else if (ssh->mainchan) {
11139 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11140 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11141 ssh2_pkt_send(ssh, pktout);
11144 /* Is is a POSIX signal? */
11145 char *signame = NULL;
11146 if (code == TS_SIGABRT) signame = "ABRT";
11147 if (code == TS_SIGALRM) signame = "ALRM";
11148 if (code == TS_SIGFPE) signame = "FPE";
11149 if (code == TS_SIGHUP) signame = "HUP";
11150 if (code == TS_SIGILL) signame = "ILL";
11151 if (code == TS_SIGINT) signame = "INT";
11152 if (code == TS_SIGKILL) signame = "KILL";
11153 if (code == TS_SIGPIPE) signame = "PIPE";
11154 if (code == TS_SIGQUIT) signame = "QUIT";
11155 if (code == TS_SIGSEGV) signame = "SEGV";
11156 if (code == TS_SIGTERM) signame = "TERM";
11157 if (code == TS_SIGUSR1) signame = "USR1";
11158 if (code == TS_SIGUSR2) signame = "USR2";
11159 /* The SSH-2 protocol does in principle support arbitrary named
11160 * signals, including signame@domain, but we don't support those. */
11162 /* It's a signal. */
11163 if (ssh->version == 2 && ssh->mainchan) {
11164 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11165 ssh2_pkt_addstring(pktout, signame);
11166 ssh2_pkt_send(ssh, pktout);
11167 logeventf(ssh, "Sent signal SIG%s", signame);
11170 /* Never heard of it. Do nothing */
11175 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11177 Ssh ssh = (Ssh) handle;
11178 struct ssh_channel *c;
11179 c = snew(struct ssh_channel);
11182 ssh2_channel_init(c);
11183 c->halfopen = TRUE;
11184 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11186 add234(ssh->channels, c);
11190 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11192 struct ssh_channel *c;
11193 c = snew(struct ssh_channel);
11196 ssh2_channel_init(c);
11197 c->type = CHAN_SHARING;
11198 c->u.sharing.ctx = sharing_ctx;
11199 add234(ssh->channels, c);
11203 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11205 struct ssh_channel *c;
11207 c = find234(ssh->channels, &localid, ssh_channelfind);
11209 ssh_channel_destroy(c);
11212 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11213 const void *data, int datalen,
11214 const char *additional_log_text)
11216 struct Packet *pkt;
11218 pkt = ssh2_pkt_init(type);
11219 pkt->downstream_id = id;
11220 pkt->additional_log_text = additional_log_text;
11221 ssh2_pkt_adddata(pkt, data, datalen);
11222 ssh2_pkt_send(ssh, pkt);
11226 * This is called when stdout/stderr (the entity to which
11227 * from_backend sends data) manages to clear some backlog.
11229 static void ssh_unthrottle(void *handle, int bufsize)
11231 Ssh ssh = (Ssh) handle;
11234 if (ssh->version == 1) {
11235 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11236 ssh->v1_stdout_throttling = 0;
11237 ssh_throttle_conn(ssh, -1);
11240 if (ssh->mainchan) {
11241 ssh2_set_window(ssh->mainchan,
11242 bufsize < ssh->mainchan->v.v2.locmaxwin ?
11243 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11244 if (ssh_is_simple(ssh))
11247 buflimit = ssh->mainchan->v.v2.locmaxwin;
11248 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11249 ssh->mainchan->throttling_conn = 0;
11250 ssh_throttle_conn(ssh, -1);
11256 * Now process any SSH connection data that was stashed in our
11257 * queue while we were frozen.
11259 ssh_process_queued_incoming_data(ssh);
11262 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
11264 struct ssh_channel *c = (struct ssh_channel *)channel;
11266 struct Packet *pktout;
11268 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11270 if (ssh->version == 1) {
11271 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11272 PKT_INT, c->localid,
11275 /* PKT_STR, <org:orgport>, */
11278 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11280 char *trimmed_host = host_strduptrim(hostname);
11281 ssh2_pkt_addstring(pktout, trimmed_host);
11282 sfree(trimmed_host);
11284 ssh2_pkt_adduint32(pktout, port);
11286 * We make up values for the originator data; partly it's
11287 * too much hassle to keep track, and partly I'm not
11288 * convinced the server should be told details like that
11289 * about my local network configuration.
11290 * The "originator IP address" is syntactically a numeric
11291 * IP address, and some servers (e.g., Tectia) get upset
11292 * if it doesn't match this syntax.
11294 ssh2_pkt_addstring(pktout, "0.0.0.0");
11295 ssh2_pkt_adduint32(pktout, 0);
11296 ssh2_pkt_send(ssh, pktout);
11300 static int ssh_connected(void *handle)
11302 Ssh ssh = (Ssh) handle;
11303 return ssh->s != NULL;
11306 static int ssh_sendok(void *handle)
11308 Ssh ssh = (Ssh) handle;
11309 return ssh->send_ok;
11312 static int ssh_ldisc(void *handle, int option)
11314 Ssh ssh = (Ssh) handle;
11315 if (option == LD_ECHO)
11316 return ssh->echoing;
11317 if (option == LD_EDIT)
11318 return ssh->editing;
11322 static void ssh_provide_ldisc(void *handle, void *ldisc)
11324 Ssh ssh = (Ssh) handle;
11325 ssh->ldisc = ldisc;
11328 static void ssh_provide_logctx(void *handle, void *logctx)
11330 Ssh ssh = (Ssh) handle;
11331 ssh->logctx = logctx;
11334 static int ssh_return_exitcode(void *handle)
11336 Ssh ssh = (Ssh) handle;
11337 if (ssh->s != NULL)
11340 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11344 * cfg_info for SSH is the protocol running in this session.
11345 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11346 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11348 static int ssh_cfg_info(void *handle)
11350 Ssh ssh = (Ssh) handle;
11351 if (ssh->version == 0)
11352 return 0; /* don't know yet */
11353 else if (ssh->bare_connection)
11356 return ssh->version;
11360 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11361 * that fails. This variable is the means by which scp.c can reach
11362 * into the SSH code and find out which one it got.
11364 extern int ssh_fallback_cmd(void *handle)
11366 Ssh ssh = (Ssh) handle;
11367 return ssh->fallback_cmd;
11370 Backend ssh_backend = {
11380 ssh_return_exitcode,
11384 ssh_provide_logctx,