28 * Packet type contexts, so that ssh2_pkt_type can correctly decode
29 * the ambiguous type numbers back into the correct type strings.
40 SSH2_PKTCTX_PUBLICKEY,
46 static const char *const ssh2_disconnect_reasons[] = {
48 "host not allowed to connect",
50 "key exchange failed",
51 "host authentication failed",
54 "service not available",
55 "protocol version not supported",
56 "host key not verifiable",
59 "too many connections",
60 "auth cancelled by user",
61 "no more auth methods available",
66 * Various remote-bug flags.
68 #define BUG_CHOKES_ON_SSH1_IGNORE 1
69 #define BUG_SSH2_HMAC 2
70 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
71 #define BUG_CHOKES_ON_RSA 8
72 #define BUG_SSH2_RSA_PADDING 16
73 #define BUG_SSH2_DERIVEKEY 32
74 #define BUG_SSH2_REKEY 64
75 #define BUG_SSH2_PK_SESSIONID 128
76 #define BUG_SSH2_MAXPKT 256
77 #define BUG_CHOKES_ON_SSH2_IGNORE 512
78 #define BUG_CHOKES_ON_WINADJ 1024
79 #define BUG_SENDS_LATE_REQUEST_REPLY 2048
80 #define BUG_SSH2_OLDGEX 4096
82 #define DH_MIN_SIZE 1024
83 #define DH_MAX_SIZE 8192
86 * Codes for terminal modes.
87 * Most of these are the same in SSH-1 and SSH-2.
88 * This list is derived from RFC 4254 and
92 const char* const mode;
94 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
96 /* "V" prefix discarded for special characters relative to SSH specs */
97 { "INTR", 1, TTY_OP_CHAR },
98 { "QUIT", 2, TTY_OP_CHAR },
99 { "ERASE", 3, TTY_OP_CHAR },
100 { "KILL", 4, TTY_OP_CHAR },
101 { "EOF", 5, TTY_OP_CHAR },
102 { "EOL", 6, TTY_OP_CHAR },
103 { "EOL2", 7, TTY_OP_CHAR },
104 { "START", 8, TTY_OP_CHAR },
105 { "STOP", 9, TTY_OP_CHAR },
106 { "SUSP", 10, TTY_OP_CHAR },
107 { "DSUSP", 11, TTY_OP_CHAR },
108 { "REPRINT", 12, TTY_OP_CHAR },
109 { "WERASE", 13, TTY_OP_CHAR },
110 { "LNEXT", 14, TTY_OP_CHAR },
111 { "FLUSH", 15, TTY_OP_CHAR },
112 { "SWTCH", 16, TTY_OP_CHAR },
113 { "STATUS", 17, TTY_OP_CHAR },
114 { "DISCARD", 18, TTY_OP_CHAR },
115 { "IGNPAR", 30, TTY_OP_BOOL },
116 { "PARMRK", 31, TTY_OP_BOOL },
117 { "INPCK", 32, TTY_OP_BOOL },
118 { "ISTRIP", 33, TTY_OP_BOOL },
119 { "INLCR", 34, TTY_OP_BOOL },
120 { "IGNCR", 35, TTY_OP_BOOL },
121 { "ICRNL", 36, TTY_OP_BOOL },
122 { "IUCLC", 37, TTY_OP_BOOL },
123 { "IXON", 38, TTY_OP_BOOL },
124 { "IXANY", 39, TTY_OP_BOOL },
125 { "IXOFF", 40, TTY_OP_BOOL },
126 { "IMAXBEL", 41, TTY_OP_BOOL },
127 { "ISIG", 50, TTY_OP_BOOL },
128 { "ICANON", 51, TTY_OP_BOOL },
129 { "XCASE", 52, TTY_OP_BOOL },
130 { "ECHO", 53, TTY_OP_BOOL },
131 { "ECHOE", 54, TTY_OP_BOOL },
132 { "ECHOK", 55, TTY_OP_BOOL },
133 { "ECHONL", 56, TTY_OP_BOOL },
134 { "NOFLSH", 57, TTY_OP_BOOL },
135 { "TOSTOP", 58, TTY_OP_BOOL },
136 { "IEXTEN", 59, TTY_OP_BOOL },
137 { "ECHOCTL", 60, TTY_OP_BOOL },
138 { "ECHOKE", 61, TTY_OP_BOOL },
139 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
140 { "OPOST", 70, TTY_OP_BOOL },
141 { "OLCUC", 71, TTY_OP_BOOL },
142 { "ONLCR", 72, TTY_OP_BOOL },
143 { "OCRNL", 73, TTY_OP_BOOL },
144 { "ONOCR", 74, TTY_OP_BOOL },
145 { "ONLRET", 75, TTY_OP_BOOL },
146 { "CS7", 90, TTY_OP_BOOL },
147 { "CS8", 91, TTY_OP_BOOL },
148 { "PARENB", 92, TTY_OP_BOOL },
149 { "PARODD", 93, TTY_OP_BOOL }
152 /* Miscellaneous other tty-related constants. */
153 #define SSH_TTY_OP_END 0
154 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
155 #define SSH1_TTY_OP_ISPEED 192
156 #define SSH1_TTY_OP_OSPEED 193
157 #define SSH2_TTY_OP_ISPEED 128
158 #define SSH2_TTY_OP_OSPEED 129
160 /* Helper functions for parsing tty-related config. */
161 static unsigned int ssh_tty_parse_specchar(char *s)
166 ret = ctrlparse(s, &next);
167 if (!next) ret = s[0];
169 ret = 255; /* special value meaning "don't set" */
173 static unsigned int ssh_tty_parse_boolean(char *s)
175 if (stricmp(s, "yes") == 0 ||
176 stricmp(s, "on") == 0 ||
177 stricmp(s, "true") == 0 ||
178 stricmp(s, "+") == 0)
180 else if (stricmp(s, "no") == 0 ||
181 stricmp(s, "off") == 0 ||
182 stricmp(s, "false") == 0 ||
183 stricmp(s, "-") == 0)
184 return 0; /* false */
186 return (atoi(s) != 0);
189 #define translate(x) if (type == x) return #x
190 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
191 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
192 static char *ssh1_pkt_type(int type)
194 translate(SSH1_MSG_DISCONNECT);
195 translate(SSH1_SMSG_PUBLIC_KEY);
196 translate(SSH1_CMSG_SESSION_KEY);
197 translate(SSH1_CMSG_USER);
198 translate(SSH1_CMSG_AUTH_RSA);
199 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
200 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
201 translate(SSH1_CMSG_AUTH_PASSWORD);
202 translate(SSH1_CMSG_REQUEST_PTY);
203 translate(SSH1_CMSG_WINDOW_SIZE);
204 translate(SSH1_CMSG_EXEC_SHELL);
205 translate(SSH1_CMSG_EXEC_CMD);
206 translate(SSH1_SMSG_SUCCESS);
207 translate(SSH1_SMSG_FAILURE);
208 translate(SSH1_CMSG_STDIN_DATA);
209 translate(SSH1_SMSG_STDOUT_DATA);
210 translate(SSH1_SMSG_STDERR_DATA);
211 translate(SSH1_CMSG_EOF);
212 translate(SSH1_SMSG_EXIT_STATUS);
213 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
214 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
215 translate(SSH1_MSG_CHANNEL_DATA);
216 translate(SSH1_MSG_CHANNEL_CLOSE);
217 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
218 translate(SSH1_SMSG_X11_OPEN);
219 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
220 translate(SSH1_MSG_PORT_OPEN);
221 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
222 translate(SSH1_SMSG_AGENT_OPEN);
223 translate(SSH1_MSG_IGNORE);
224 translate(SSH1_CMSG_EXIT_CONFIRMATION);
225 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
226 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
227 translate(SSH1_MSG_DEBUG);
228 translate(SSH1_CMSG_REQUEST_COMPRESSION);
229 translate(SSH1_CMSG_AUTH_TIS);
230 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
231 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
232 translate(SSH1_CMSG_AUTH_CCARD);
233 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
234 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
237 static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
239 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
240 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
241 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
242 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
243 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
244 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
245 translate(SSH2_MSG_DISCONNECT);
246 translate(SSH2_MSG_IGNORE);
247 translate(SSH2_MSG_UNIMPLEMENTED);
248 translate(SSH2_MSG_DEBUG);
249 translate(SSH2_MSG_SERVICE_REQUEST);
250 translate(SSH2_MSG_SERVICE_ACCEPT);
251 translate(SSH2_MSG_KEXINIT);
252 translate(SSH2_MSG_NEWKEYS);
253 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
254 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
255 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD, SSH2_PKTCTX_DHGEX);
256 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
257 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
258 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
259 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
260 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
261 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
262 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
263 translatek(SSH2_MSG_KEX_ECDH_INIT, SSH2_PKTCTX_ECDHKEX);
264 translatek(SSH2_MSG_KEX_ECDH_REPLY, SSH2_PKTCTX_ECDHKEX);
265 translate(SSH2_MSG_USERAUTH_REQUEST);
266 translate(SSH2_MSG_USERAUTH_FAILURE);
267 translate(SSH2_MSG_USERAUTH_SUCCESS);
268 translate(SSH2_MSG_USERAUTH_BANNER);
269 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
270 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
271 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
272 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
273 translate(SSH2_MSG_GLOBAL_REQUEST);
274 translate(SSH2_MSG_REQUEST_SUCCESS);
275 translate(SSH2_MSG_REQUEST_FAILURE);
276 translate(SSH2_MSG_CHANNEL_OPEN);
277 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
278 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
279 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
280 translate(SSH2_MSG_CHANNEL_DATA);
281 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
282 translate(SSH2_MSG_CHANNEL_EOF);
283 translate(SSH2_MSG_CHANNEL_CLOSE);
284 translate(SSH2_MSG_CHANNEL_REQUEST);
285 translate(SSH2_MSG_CHANNEL_SUCCESS);
286 translate(SSH2_MSG_CHANNEL_FAILURE);
292 /* Enumeration values for fields in SSH-1 packets */
294 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
298 * Coroutine mechanics for the sillier bits of the code. If these
299 * macros look impenetrable to you, you might find it helpful to
302 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
304 * which explains the theory behind these macros.
306 * In particular, if you are getting `case expression not constant'
307 * errors when building with MS Visual Studio, this is because MS's
308 * Edit and Continue debugging feature causes their compiler to
309 * violate ANSI C. To disable Edit and Continue debugging:
311 * - right-click ssh.c in the FileView
313 * - select the C/C++ tab and the General category
314 * - under `Debug info:', select anything _other_ than `Program
315 * Database for Edit and Continue'.
317 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
318 #define crBeginState crBegin(s->crLine)
319 #define crStateP(t, v) \
321 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
323 #define crState(t) crStateP(t, ssh->t)
324 #define crFinish(z) } *crLine = 0; return (z); }
325 #define crFinishV } *crLine = 0; return; }
326 #define crFinishFree(z) } sfree(s); return (z); }
327 #define crFinishFreeV } sfree(s); return; }
328 #define crReturn(z) \
330 *crLine =__LINE__; return (z); case __LINE__:;\
334 *crLine=__LINE__; return; case __LINE__:;\
336 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
337 #define crStopV do{ *crLine = 0; return; }while(0)
338 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
339 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
343 static struct Packet *ssh1_pkt_init(int pkt_type);
344 static struct Packet *ssh2_pkt_init(int pkt_type);
345 static void ssh_pkt_ensure(struct Packet *, int length);
346 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
347 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
348 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
349 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
350 static void ssh_pkt_addstring_start(struct Packet *);
351 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
352 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
353 static void ssh_pkt_addstring(struct Packet *, const char *data);
354 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
355 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
356 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
357 static int ssh2_pkt_construct(Ssh, struct Packet *);
358 static void ssh2_pkt_send(Ssh, struct Packet *);
359 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
360 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
361 struct Packet *pktin);
362 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
363 struct Packet *pktin);
364 static void ssh2_channel_check_close(struct ssh_channel *c);
365 static void ssh_channel_destroy(struct ssh_channel *c);
368 * Buffer management constants. There are several of these for
369 * various different purposes:
371 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
372 * on a local data stream before we throttle the whole SSH
373 * connection (in SSH-1 only). Throttling the whole connection is
374 * pretty drastic so we set this high in the hope it won't
377 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
378 * on the SSH connection itself before we defensively throttle
379 * _all_ local data streams. This is pretty drastic too (though
380 * thankfully unlikely in SSH-2 since the window mechanism should
381 * ensure that the server never has any need to throttle its end
382 * of the connection), so we set this high as well.
384 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
387 * - OUR_V2_BIGWIN is the window size we advertise for the only
388 * channel in a simple connection. It must be <= INT_MAX.
390 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
391 * to the remote side. This actually has nothing to do with the
392 * size of the _packet_, but is instead a limit on the amount
393 * of data we're willing to receive in a single SSH2 channel
396 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
397 * _packet_ we're prepared to cope with. It must be a multiple
398 * of the cipher block size, and must be at least 35000.
401 #define SSH1_BUFFER_LIMIT 32768
402 #define SSH_MAX_BACKLOG 32768
403 #define OUR_V2_WINSIZE 16384
404 #define OUR_V2_BIGWIN 0x7fffffff
405 #define OUR_V2_MAXPKT 0x4000UL
406 #define OUR_V2_PACKETLIMIT 0x9000UL
408 const static struct ssh_signkey *hostkey_algs[] = {
409 &ssh_ecdsa_nistp256, &ssh_ecdsa_nistp384, &ssh_ecdsa_nistp521,
413 const static struct ssh_mac *macs[] = {
414 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
416 const static struct ssh_mac *buggymacs[] = {
417 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
420 static void *ssh_comp_none_init(void)
424 static void ssh_comp_none_cleanup(void *handle)
427 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
428 unsigned char **outblock, int *outlen)
432 static int ssh_comp_none_disable(void *handle)
436 const static struct ssh_compress ssh_comp_none = {
438 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
439 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
440 ssh_comp_none_disable, NULL
442 extern const struct ssh_compress ssh_zlib;
443 const static struct ssh_compress *compressions[] = {
444 &ssh_zlib, &ssh_comp_none
447 enum { /* channel types */
452 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
454 * CHAN_SHARING indicates a channel which is tracked here on
455 * behalf of a connection-sharing downstream. We do almost nothing
456 * with these channels ourselves: all messages relating to them
457 * get thrown straight to sshshare.c and passed on almost
458 * unmodified to downstream.
462 * CHAN_ZOMBIE is used to indicate a channel for which we've
463 * already destroyed the local data source: for instance, if a
464 * forwarded port experiences a socket error on the local side, we
465 * immediately destroy its local socket and turn the SSH channel
471 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
472 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
473 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
476 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
479 struct outstanding_channel_request {
480 cchandler_fn_t handler;
482 struct outstanding_channel_request *next;
486 * 2-3-4 tree storing channels.
489 Ssh ssh; /* pointer back to main context */
490 unsigned remoteid, localid;
492 /* True if we opened this channel but server hasn't confirmed. */
495 * In SSH-1, this value contains four bits:
497 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
498 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
499 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
500 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
502 * A channel is completely finished with when all four bits are set.
504 * In SSH-2, the four bits mean:
506 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
507 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
508 * 4 We have received SSH2_MSG_CHANNEL_EOF.
509 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
511 * A channel is completely finished with when we have both sent
512 * and received CLOSE.
514 * The symbolic constants below use the SSH-2 terminology, which
515 * is a bit confusing in SSH-1, but we have to use _something_.
517 #define CLOSES_SENT_EOF 1
518 #define CLOSES_SENT_CLOSE 2
519 #define CLOSES_RCVD_EOF 4
520 #define CLOSES_RCVD_CLOSE 8
524 * This flag indicates that an EOF is pending on the outgoing side
525 * of the channel: that is, wherever we're getting the data for
526 * this channel has sent us some data followed by EOF. We can't
527 * actually send the EOF until we've finished sending the data, so
528 * we set this flag instead to remind us to do so once our buffer
534 * True if this channel is causing the underlying connection to be
539 struct ssh2_data_channel {
541 unsigned remwindow, remmaxpkt;
542 /* locwindow is signed so we can cope with excess data. */
543 int locwindow, locmaxwin;
545 * remlocwin is the amount of local window that we think
546 * the remote end had available to it after it sent the
547 * last data packet or window adjust ack.
551 * These store the list of channel requests that haven't
554 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
555 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
559 struct ssh_agent_channel {
560 unsigned char *message;
561 unsigned char msglen[4];
562 unsigned lensofar, totallen;
563 int outstanding_requests;
565 struct ssh_x11_channel {
566 struct X11Connection *xconn;
569 struct ssh_pfd_channel {
570 struct PortForwarding *pf;
572 struct ssh_sharing_channel {
579 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
580 * use this structure in different ways, reflecting SSH-2's
581 * altogether saner approach to port forwarding.
583 * In SSH-1, you arrange a remote forwarding by sending the server
584 * the remote port number, and the local destination host:port.
585 * When a connection comes in, the server sends you back that
586 * host:port pair, and you connect to it. This is a ready-made
587 * security hole if you're not on the ball: a malicious server
588 * could send you back _any_ host:port pair, so if you trustingly
589 * connect to the address it gives you then you've just opened the
590 * entire inside of your corporate network just by connecting
591 * through it to a dodgy SSH server. Hence, we must store a list of
592 * host:port pairs we _are_ trying to forward to, and reject a
593 * connection request from the server if it's not in the list.
595 * In SSH-2, each side of the connection minds its own business and
596 * doesn't send unnecessary information to the other. You arrange a
597 * remote forwarding by sending the server just the remote port
598 * number. When a connection comes in, the server tells you which
599 * of its ports was connected to; and _you_ have to remember what
600 * local host:port pair went with that port number.
602 * Hence, in SSH-1 this structure is indexed by destination
603 * host:port pair, whereas in SSH-2 it is indexed by source port.
605 struct ssh_portfwd; /* forward declaration */
607 struct ssh_rportfwd {
608 unsigned sport, dport;
612 struct ssh_portfwd *pfrec;
615 static void free_rportfwd(struct ssh_rportfwd *pf)
618 sfree(pf->sportdesc);
626 * Separately to the rportfwd tree (which is for looking up port
627 * open requests from the server), a tree of _these_ structures is
628 * used to keep track of all the currently open port forwardings,
629 * so that we can reconfigure in mid-session if the user requests
633 enum { DESTROY, KEEP, CREATE } status;
635 unsigned sport, dport;
638 struct ssh_rportfwd *remote;
640 struct PortListener *local;
642 #define free_portfwd(pf) ( \
643 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
644 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
647 long length; /* length of packet: see below */
648 long forcepad; /* SSH-2: force padding to at least this length */
649 int type; /* only used for incoming packets */
650 unsigned long sequence; /* SSH-2 incoming sequence number */
651 unsigned char *data; /* allocated storage */
652 unsigned char *body; /* offset of payload within `data' */
653 long savedpos; /* dual-purpose saved packet position: see below */
654 long maxlen; /* amount of storage allocated for `data' */
655 long encrypted_len; /* for SSH-2 total-size counting */
658 * A note on the 'length' and 'savedpos' fields above.
660 * Incoming packets are set up so that pkt->length is measured
661 * relative to pkt->body, which itself points to a few bytes after
662 * pkt->data (skipping some uninteresting header fields including
663 * the packet type code). The ssh_pkt_get* functions all expect
664 * this setup, and they also use pkt->savedpos to indicate how far
665 * through the packet being decoded they've got - and that, too,
666 * is an offset from pkt->body rather than pkt->data.
668 * During construction of an outgoing packet, however, pkt->length
669 * is measured relative to the base pointer pkt->data, and
670 * pkt->body is not really used for anything until the packet is
671 * ready for sending. In this mode, pkt->savedpos is reused as a
672 * temporary variable by the addstring functions, which write out
673 * a string length field and then keep going back and updating it
674 * as more data is appended to the subsequent string data field;
675 * pkt->savedpos stores the offset (again relative to pkt->data)
676 * of the start of the string data field.
679 /* Extra metadata used in SSH packet logging mode, allowing us to
680 * log in the packet header line that the packet came from a
681 * connection-sharing downstream and what if anything unusual was
682 * done to it. The additional_log_text field is expected to be a
683 * static string - it will not be freed. */
684 unsigned downstream_id;
685 const char *additional_log_text;
688 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
689 struct Packet *pktin);
690 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
691 struct Packet *pktin);
692 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
693 struct Packet *pktin);
694 static void ssh1_protocol_setup(Ssh ssh);
695 static void ssh2_protocol_setup(Ssh ssh);
696 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
697 static void ssh_size(void *handle, int width, int height);
698 static void ssh_special(void *handle, Telnet_Special);
699 static int ssh2_try_send(struct ssh_channel *c);
700 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
701 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
702 static void ssh2_set_window(struct ssh_channel *c, int newwin);
703 static int ssh_sendbuffer(void *handle);
704 static int ssh_do_close(Ssh ssh, int notify_exit);
705 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
706 static int ssh2_pkt_getbool(struct Packet *pkt);
707 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
708 static void ssh2_timer(void *ctx, unsigned long now);
709 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
710 struct Packet *pktin);
711 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
713 struct rdpkt1_state_tag {
714 long len, pad, biglen, to_read;
715 unsigned long realcrc, gotcrc;
719 struct Packet *pktin;
722 struct rdpkt2_state_tag {
723 long len, pad, payload, packetlen, maclen;
726 unsigned long incoming_sequence;
727 struct Packet *pktin;
730 struct rdpkt2_bare_state_tag {
734 unsigned long incoming_sequence;
735 struct Packet *pktin;
738 struct queued_handler;
739 struct queued_handler {
741 chandler_fn_t handler;
743 struct queued_handler *next;
747 const struct plug_function_table *fn;
748 /* the above field _must_ be first in the structure */
758 unsigned char session_key[32];
760 int v1_remote_protoflags;
761 int v1_local_protoflags;
762 int agentfwd_enabled;
765 const struct ssh_cipher *cipher;
768 const struct ssh2_cipher *cscipher, *sccipher;
769 void *cs_cipher_ctx, *sc_cipher_ctx;
770 const struct ssh_mac *csmac, *scmac;
771 void *cs_mac_ctx, *sc_mac_ctx;
772 const struct ssh_compress *cscomp, *sccomp;
773 void *cs_comp_ctx, *sc_comp_ctx;
774 const struct ssh_kex *kex;
775 const struct ssh_signkey *hostkey;
776 char *hostkey_str; /* string representation, for easy checking in rekeys */
777 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
778 int v2_session_id_len;
782 int attempting_connshare;
788 int echoing, editing;
792 int ospeed, ispeed; /* temporaries */
793 int term_width, term_height;
795 tree234 *channels; /* indexed by local id */
796 struct ssh_channel *mainchan; /* primary session channel */
797 int ncmode; /* is primary channel direct-tcpip? */
802 tree234 *rportfwds, *portfwds;
806 SSH_STATE_BEFORE_SIZE,
812 int size_needed, eof_needed;
813 int sent_console_eof;
814 int got_pty; /* affects EOF behaviour on main channel */
816 struct Packet **queue;
817 int queuelen, queuesize;
819 unsigned char *deferred_send_data;
820 int deferred_len, deferred_size;
823 * Gross hack: pscp will try to start SFTP but fall back to
824 * scp1 if that fails. This variable is the means by which
825 * scp.c can reach into the SSH code and find out which one it
830 bufchain banner; /* accumulates banners during do_ssh2_authconn */
835 struct X11Display *x11disp;
836 struct X11FakeAuth *x11auth;
837 tree234 *x11authtree;
840 int conn_throttle_count;
843 int v1_stdout_throttling;
844 unsigned long v2_outgoing_sequence;
846 int ssh1_rdpkt_crstate;
847 int ssh2_rdpkt_crstate;
848 int ssh2_bare_rdpkt_crstate;
849 int ssh_gotdata_crstate;
850 int do_ssh1_connection_crstate;
852 void *do_ssh_init_state;
853 void *do_ssh1_login_state;
854 void *do_ssh2_transport_state;
855 void *do_ssh2_authconn_state;
856 void *do_ssh_connection_init_state;
858 struct rdpkt1_state_tag rdpkt1_state;
859 struct rdpkt2_state_tag rdpkt2_state;
860 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
862 /* SSH-1 and SSH-2 use this for different things, but both use it */
863 int protocol_initial_phase_done;
865 void (*protocol) (Ssh ssh, void *vin, int inlen,
867 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
868 int (*do_ssh_init)(Ssh ssh, unsigned char c);
871 * We maintain our own copy of a Conf structure here. That way,
872 * when we're passed a new one for reconfiguration, we can check
873 * the differences and potentially reconfigure port forwardings
874 * etc in mid-session.
879 * Values cached out of conf so as to avoid the tree234 lookup
880 * cost every time they're used.
885 * Dynamically allocated username string created during SSH
886 * login. Stored in here rather than in the coroutine state so
887 * that it'll be reliably freed if we shut down the SSH session
888 * at some unexpected moment.
893 * Used to transfer data back from async callbacks.
895 void *agent_response;
896 int agent_response_len;
900 * The SSH connection can be set as `frozen', meaning we are
901 * not currently accepting incoming data from the network. This
902 * is slightly more serious than setting the _socket_ as
903 * frozen, because we may already have had data passed to us
904 * from the network which we need to delay processing until
905 * after the freeze is lifted, so we also need a bufchain to
909 bufchain queued_incoming_data;
912 * Dispatch table for packet types that we may have to deal
915 handler_fn_t packet_dispatch[256];
918 * Queues of one-off handler functions for success/failure
919 * indications from a request.
921 struct queued_handler *qhead, *qtail;
922 handler_fn_t q_saved_handler1, q_saved_handler2;
925 * This module deals with sending keepalives.
930 * Track incoming and outgoing data sizes and time, for
933 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
934 unsigned long max_data_size;
936 unsigned long next_rekey, last_rekey;
937 char *deferred_rekey_reason; /* points to STATIC string; don't free */
940 * Fully qualified host name, which we need if doing GSSAPI.
946 * GSSAPI libraries for this session.
948 struct ssh_gss_liblist *gsslibs;
952 #define logevent(s) logevent(ssh->frontend, s)
954 /* logevent, only printf-formatted. */
955 static void logeventf(Ssh ssh, const char *fmt, ...)
961 buf = dupvprintf(fmt, ap);
967 static void bomb_out(Ssh ssh, char *text)
969 ssh_do_close(ssh, FALSE);
971 connection_fatal(ssh->frontend, "%s", text);
975 #define bombout(msg) bomb_out(ssh, dupprintf msg)
977 /* Helper function for common bits of parsing ttymodes. */
978 static void parse_ttymodes(Ssh ssh,
979 void (*do_mode)(void *data, char *mode, char *val),
984 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
986 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
988 * val[0] is either 'V', indicating that an explicit value
989 * follows it, or 'A' indicating that we should pass the
990 * value through from the local environment via get_ttymode.
993 val = get_ttymode(ssh->frontend, key);
995 do_mode(data, key, val);
999 do_mode(data, key, val + 1); /* skip the 'V' */
1003 static int ssh_channelcmp(void *av, void *bv)
1005 struct ssh_channel *a = (struct ssh_channel *) av;
1006 struct ssh_channel *b = (struct ssh_channel *) bv;
1007 if (a->localid < b->localid)
1009 if (a->localid > b->localid)
1013 static int ssh_channelfind(void *av, void *bv)
1015 unsigned *a = (unsigned *) av;
1016 struct ssh_channel *b = (struct ssh_channel *) bv;
1017 if (*a < b->localid)
1019 if (*a > b->localid)
1024 static int ssh_rportcmp_ssh1(void *av, void *bv)
1026 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1027 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1029 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1030 return i < 0 ? -1 : +1;
1031 if (a->dport > b->dport)
1033 if (a->dport < b->dport)
1038 static int ssh_rportcmp_ssh2(void *av, void *bv)
1040 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1041 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1043 if ( (i = strcmp(a->shost, b->shost)) != 0)
1044 return i < 0 ? -1 : +1;
1045 if (a->sport > b->sport)
1047 if (a->sport < b->sport)
1053 * Special form of strcmp which can cope with NULL inputs. NULL is
1054 * defined to sort before even the empty string.
1056 static int nullstrcmp(const char *a, const char *b)
1058 if (a == NULL && b == NULL)
1064 return strcmp(a, b);
1067 static int ssh_portcmp(void *av, void *bv)
1069 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1070 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1072 if (a->type > b->type)
1074 if (a->type < b->type)
1076 if (a->addressfamily > b->addressfamily)
1078 if (a->addressfamily < b->addressfamily)
1080 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1081 return i < 0 ? -1 : +1;
1082 if (a->sport > b->sport)
1084 if (a->sport < b->sport)
1086 if (a->type != 'D') {
1087 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1088 return i < 0 ? -1 : +1;
1089 if (a->dport > b->dport)
1091 if (a->dport < b->dport)
1097 static int alloc_channel_id(Ssh ssh)
1099 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1100 unsigned low, high, mid;
1102 struct ssh_channel *c;
1105 * First-fit allocation of channel numbers: always pick the
1106 * lowest unused one. To do this, binary-search using the
1107 * counted B-tree to find the largest channel ID which is in a
1108 * contiguous sequence from the beginning. (Precisely
1109 * everything in that sequence must have ID equal to its tree
1110 * index plus CHANNEL_NUMBER_OFFSET.)
1112 tsize = count234(ssh->channels);
1116 while (high - low > 1) {
1117 mid = (high + low) / 2;
1118 c = index234(ssh->channels, mid);
1119 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1120 low = mid; /* this one is fine */
1122 high = mid; /* this one is past it */
1125 * Now low points to either -1, or the tree index of the
1126 * largest ID in the initial sequence.
1129 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1130 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1132 return low + 1 + CHANNEL_NUMBER_OFFSET;
1135 static void c_write_stderr(int trusted, const char *buf, int len)
1138 for (i = 0; i < len; i++)
1139 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1140 fputc(buf[i], stderr);
1143 static void c_write(Ssh ssh, const char *buf, int len)
1145 if (flags & FLAG_STDERR)
1146 c_write_stderr(1, buf, len);
1148 from_backend(ssh->frontend, 1, buf, len);
1151 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1153 if (flags & FLAG_STDERR)
1154 c_write_stderr(0, buf, len);
1156 from_backend_untrusted(ssh->frontend, buf, len);
1159 static void c_write_str(Ssh ssh, const char *buf)
1161 c_write(ssh, buf, strlen(buf));
1164 static void ssh_free_packet(struct Packet *pkt)
1169 static struct Packet *ssh_new_packet(void)
1171 struct Packet *pkt = snew(struct Packet);
1173 pkt->body = pkt->data = NULL;
1179 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1182 struct logblank_t blanks[4];
1188 if (ssh->logomitdata &&
1189 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1190 pkt->type == SSH1_SMSG_STDERR_DATA ||
1191 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1192 /* "Session data" packets - omit the data string. */
1193 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1194 ssh_pkt_getuint32(pkt); /* skip channel id */
1195 blanks[nblanks].offset = pkt->savedpos + 4;
1196 blanks[nblanks].type = PKTLOG_OMIT;
1197 ssh_pkt_getstring(pkt, &str, &slen);
1199 blanks[nblanks].len = slen;
1203 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1204 ssh1_pkt_type(pkt->type),
1205 pkt->body, pkt->length, nblanks, blanks, NULL,
1209 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1212 struct logblank_t blanks[4];
1217 * For outgoing packets, pkt->length represents the length of the
1218 * whole packet starting at pkt->data (including some header), and
1219 * pkt->body refers to the point within that where the log-worthy
1220 * payload begins. However, incoming packets expect pkt->length to
1221 * represent only the payload length (that is, it's measured from
1222 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1223 * packet to conform to the incoming-packet semantics, so that we
1224 * can analyse it with the ssh_pkt_get functions.
1226 pkt->length -= (pkt->body - pkt->data);
1229 if (ssh->logomitdata &&
1230 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1231 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1232 /* "Session data" packets - omit the data string. */
1233 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1234 ssh_pkt_getuint32(pkt); /* skip channel id */
1235 blanks[nblanks].offset = pkt->savedpos + 4;
1236 blanks[nblanks].type = PKTLOG_OMIT;
1237 ssh_pkt_getstring(pkt, &str, &slen);
1239 blanks[nblanks].len = slen;
1244 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1245 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1246 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1247 conf_get_int(ssh->conf, CONF_logomitpass)) {
1248 /* If this is a password or similar packet, blank the password(s). */
1249 blanks[nblanks].offset = 0;
1250 blanks[nblanks].len = pkt->length;
1251 blanks[nblanks].type = PKTLOG_BLANK;
1253 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1254 conf_get_int(ssh->conf, CONF_logomitpass)) {
1256 * If this is an X forwarding request packet, blank the fake
1259 * Note that while we blank the X authentication data here, we
1260 * don't take any special action to blank the start of an X11
1261 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1262 * an X connection without having session blanking enabled is
1263 * likely to leak your cookie into the log.
1266 ssh_pkt_getstring(pkt, &str, &slen);
1267 blanks[nblanks].offset = pkt->savedpos;
1268 blanks[nblanks].type = PKTLOG_BLANK;
1269 ssh_pkt_getstring(pkt, &str, &slen);
1271 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1276 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1277 ssh1_pkt_type(pkt->data[12]),
1278 pkt->body, pkt->length,
1279 nblanks, blanks, NULL, 0, NULL);
1282 * Undo the above adjustment of pkt->length, to put the packet
1283 * back in the state we found it.
1285 pkt->length += (pkt->body - pkt->data);
1289 * Collect incoming data in the incoming packet buffer.
1290 * Decipher and verify the packet when it is completely read.
1291 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1292 * Update the *data and *datalen variables.
1293 * Return a Packet structure when a packet is completed.
1295 static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1297 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1299 crBegin(ssh->ssh1_rdpkt_crstate);
1301 st->pktin = ssh_new_packet();
1303 st->pktin->type = 0;
1304 st->pktin->length = 0;
1306 for (st->i = st->len = 0; st->i < 4; st->i++) {
1307 while ((*datalen) == 0)
1309 st->len = (st->len << 8) + **data;
1310 (*data)++, (*datalen)--;
1313 st->pad = 8 - (st->len % 8);
1314 st->biglen = st->len + st->pad;
1315 st->pktin->length = st->len - 5;
1317 if (st->biglen < 0) {
1318 bombout(("Extremely large packet length from server suggests"
1319 " data stream corruption"));
1320 ssh_free_packet(st->pktin);
1324 st->pktin->maxlen = st->biglen;
1325 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1327 st->to_read = st->biglen;
1328 st->p = st->pktin->data;
1329 while (st->to_read > 0) {
1330 st->chunk = st->to_read;
1331 while ((*datalen) == 0)
1333 if (st->chunk > (*datalen))
1334 st->chunk = (*datalen);
1335 memcpy(st->p, *data, st->chunk);
1337 *datalen -= st->chunk;
1339 st->to_read -= st->chunk;
1342 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1343 st->biglen, NULL)) {
1344 bombout(("Network attack (CRC compensation) detected!"));
1345 ssh_free_packet(st->pktin);
1350 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1352 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1353 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1354 if (st->gotcrc != st->realcrc) {
1355 bombout(("Incorrect CRC received on packet"));
1356 ssh_free_packet(st->pktin);
1360 st->pktin->body = st->pktin->data + st->pad + 1;
1362 if (ssh->v1_compressing) {
1363 unsigned char *decompblk;
1365 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1366 st->pktin->body - 1, st->pktin->length + 1,
1367 &decompblk, &decomplen)) {
1368 bombout(("Zlib decompression encountered invalid data"));
1369 ssh_free_packet(st->pktin);
1373 if (st->pktin->maxlen < st->pad + decomplen) {
1374 st->pktin->maxlen = st->pad + decomplen;
1375 st->pktin->data = sresize(st->pktin->data,
1376 st->pktin->maxlen + APIEXTRA,
1378 st->pktin->body = st->pktin->data + st->pad + 1;
1381 memcpy(st->pktin->body - 1, decompblk, decomplen);
1383 st->pktin->length = decomplen - 1;
1386 st->pktin->type = st->pktin->body[-1];
1389 * Now pktin->body and pktin->length identify the semantic content
1390 * of the packet, excluding the initial type byte.
1394 ssh1_log_incoming_packet(ssh, st->pktin);
1396 st->pktin->savedpos = 0;
1398 crFinish(st->pktin);
1401 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1404 struct logblank_t blanks[4];
1410 if (ssh->logomitdata &&
1411 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1412 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1413 /* "Session data" packets - omit the data string. */
1414 ssh_pkt_getuint32(pkt); /* skip channel id */
1415 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1416 ssh_pkt_getuint32(pkt); /* skip extended data type */
1417 blanks[nblanks].offset = pkt->savedpos + 4;
1418 blanks[nblanks].type = PKTLOG_OMIT;
1419 ssh_pkt_getstring(pkt, &str, &slen);
1421 blanks[nblanks].len = slen;
1426 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1427 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1428 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1432 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1435 struct logblank_t blanks[4];
1440 * For outgoing packets, pkt->length represents the length of the
1441 * whole packet starting at pkt->data (including some header), and
1442 * pkt->body refers to the point within that where the log-worthy
1443 * payload begins. However, incoming packets expect pkt->length to
1444 * represent only the payload length (that is, it's measured from
1445 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1446 * packet to conform to the incoming-packet semantics, so that we
1447 * can analyse it with the ssh_pkt_get functions.
1449 pkt->length -= (pkt->body - pkt->data);
1452 if (ssh->logomitdata &&
1453 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1454 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1455 /* "Session data" packets - omit the data string. */
1456 ssh_pkt_getuint32(pkt); /* skip channel id */
1457 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1458 ssh_pkt_getuint32(pkt); /* skip extended data type */
1459 blanks[nblanks].offset = pkt->savedpos + 4;
1460 blanks[nblanks].type = PKTLOG_OMIT;
1461 ssh_pkt_getstring(pkt, &str, &slen);
1463 blanks[nblanks].len = slen;
1468 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1469 conf_get_int(ssh->conf, CONF_logomitpass)) {
1470 /* If this is a password packet, blank the password(s). */
1472 ssh_pkt_getstring(pkt, &str, &slen);
1473 ssh_pkt_getstring(pkt, &str, &slen);
1474 ssh_pkt_getstring(pkt, &str, &slen);
1475 if (slen == 8 && !memcmp(str, "password", 8)) {
1476 ssh2_pkt_getbool(pkt);
1477 /* Blank the password field. */
1478 blanks[nblanks].offset = pkt->savedpos;
1479 blanks[nblanks].type = PKTLOG_BLANK;
1480 ssh_pkt_getstring(pkt, &str, &slen);
1482 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1484 /* If there's another password field beyond it (change of
1485 * password), blank that too. */
1486 ssh_pkt_getstring(pkt, &str, &slen);
1488 blanks[nblanks-1].len =
1489 pkt->savedpos - blanks[nblanks].offset;
1492 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1493 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1494 conf_get_int(ssh->conf, CONF_logomitpass)) {
1495 /* If this is a keyboard-interactive response packet, blank
1498 ssh_pkt_getuint32(pkt);
1499 blanks[nblanks].offset = pkt->savedpos;
1500 blanks[nblanks].type = PKTLOG_BLANK;
1502 ssh_pkt_getstring(pkt, &str, &slen);
1506 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1508 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1509 conf_get_int(ssh->conf, CONF_logomitpass)) {
1511 * If this is an X forwarding request packet, blank the fake
1514 * Note that while we blank the X authentication data here, we
1515 * don't take any special action to blank the start of an X11
1516 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1517 * an X connection without having session blanking enabled is
1518 * likely to leak your cookie into the log.
1521 ssh_pkt_getuint32(pkt);
1522 ssh_pkt_getstring(pkt, &str, &slen);
1523 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1524 ssh2_pkt_getbool(pkt);
1525 ssh2_pkt_getbool(pkt);
1526 ssh_pkt_getstring(pkt, &str, &slen);
1527 blanks[nblanks].offset = pkt->savedpos;
1528 blanks[nblanks].type = PKTLOG_BLANK;
1529 ssh_pkt_getstring(pkt, &str, &slen);
1531 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1537 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1538 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1539 pkt->body, pkt->length, nblanks, blanks,
1540 &ssh->v2_outgoing_sequence,
1541 pkt->downstream_id, pkt->additional_log_text);
1544 * Undo the above adjustment of pkt->length, to put the packet
1545 * back in the state we found it.
1547 pkt->length += (pkt->body - pkt->data);
1550 static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
1552 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1554 crBegin(ssh->ssh2_rdpkt_crstate);
1556 st->pktin = ssh_new_packet();
1558 st->pktin->type = 0;
1559 st->pktin->length = 0;
1561 st->cipherblk = ssh->sccipher->blksize;
1564 if (st->cipherblk < 8)
1566 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1568 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1571 * When dealing with a CBC-mode cipher, we want to avoid the
1572 * possibility of an attacker's tweaking the ciphertext stream
1573 * so as to cause us to feed the same block to the block
1574 * cipher more than once and thus leak information
1575 * (VU#958563). The way we do this is not to take any
1576 * decisions on the basis of anything we've decrypted until
1577 * we've verified it with a MAC. That includes the packet
1578 * length, so we just read data and check the MAC repeatedly,
1579 * and when the MAC passes, see if the length we've got is
1583 /* May as well allocate the whole lot now. */
1584 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1587 /* Read an amount corresponding to the MAC. */
1588 for (st->i = 0; st->i < st->maclen; st->i++) {
1589 while ((*datalen) == 0)
1591 st->pktin->data[st->i] = *(*data)++;
1597 unsigned char seq[4];
1598 ssh->scmac->start(ssh->sc_mac_ctx);
1599 PUT_32BIT(seq, st->incoming_sequence);
1600 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1603 for (;;) { /* Once around this loop per cipher block. */
1604 /* Read another cipher-block's worth, and tack it onto the end. */
1605 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1606 while ((*datalen) == 0)
1608 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1611 /* Decrypt one more block (a little further back in the stream). */
1612 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1613 st->pktin->data + st->packetlen,
1615 /* Feed that block to the MAC. */
1616 ssh->scmac->bytes(ssh->sc_mac_ctx,
1617 st->pktin->data + st->packetlen, st->cipherblk);
1618 st->packetlen += st->cipherblk;
1619 /* See if that gives us a valid packet. */
1620 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1621 st->pktin->data + st->packetlen) &&
1622 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1625 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1626 bombout(("No valid incoming packet found"));
1627 ssh_free_packet(st->pktin);
1631 st->pktin->maxlen = st->packetlen + st->maclen;
1632 st->pktin->data = sresize(st->pktin->data,
1633 st->pktin->maxlen + APIEXTRA,
1636 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1639 * Acquire and decrypt the first block of the packet. This will
1640 * contain the length and padding details.
1642 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1643 while ((*datalen) == 0)
1645 st->pktin->data[st->i] = *(*data)++;
1650 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1651 st->pktin->data, st->cipherblk);
1654 * Now get the length figure.
1656 st->len = toint(GET_32BIT(st->pktin->data));
1659 * _Completely_ silly lengths should be stomped on before they
1660 * do us any more damage.
1662 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1663 (st->len + 4) % st->cipherblk != 0) {
1664 bombout(("Incoming packet was garbled on decryption"));
1665 ssh_free_packet(st->pktin);
1670 * So now we can work out the total packet length.
1672 st->packetlen = st->len + 4;
1675 * Allocate memory for the rest of the packet.
1677 st->pktin->maxlen = st->packetlen + st->maclen;
1678 st->pktin->data = sresize(st->pktin->data,
1679 st->pktin->maxlen + APIEXTRA,
1683 * Read and decrypt the remainder of the packet.
1685 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1687 while ((*datalen) == 0)
1689 st->pktin->data[st->i] = *(*data)++;
1692 /* Decrypt everything _except_ the MAC. */
1694 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1695 st->pktin->data + st->cipherblk,
1696 st->packetlen - st->cipherblk);
1702 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1703 st->len + 4, st->incoming_sequence)) {
1704 bombout(("Incorrect MAC received on packet"));
1705 ssh_free_packet(st->pktin);
1709 /* Get and sanity-check the amount of random padding. */
1710 st->pad = st->pktin->data[4];
1711 if (st->pad < 4 || st->len - st->pad < 1) {
1712 bombout(("Invalid padding length on received packet"));
1713 ssh_free_packet(st->pktin);
1717 * This enables us to deduce the payload length.
1719 st->payload = st->len - st->pad - 1;
1721 st->pktin->length = st->payload + 5;
1722 st->pktin->encrypted_len = st->packetlen;
1724 st->pktin->sequence = st->incoming_sequence++;
1726 st->pktin->length = st->packetlen - st->pad;
1727 assert(st->pktin->length >= 0);
1730 * Decompress packet payload.
1733 unsigned char *newpayload;
1736 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1737 st->pktin->data + 5, st->pktin->length - 5,
1738 &newpayload, &newlen)) {
1739 if (st->pktin->maxlen < newlen + 5) {
1740 st->pktin->maxlen = newlen + 5;
1741 st->pktin->data = sresize(st->pktin->data,
1742 st->pktin->maxlen + APIEXTRA,
1745 st->pktin->length = 5 + newlen;
1746 memcpy(st->pktin->data + 5, newpayload, newlen);
1752 * pktin->body and pktin->length should identify the semantic
1753 * content of the packet, excluding the initial type byte.
1755 st->pktin->type = st->pktin->data[5];
1756 st->pktin->body = st->pktin->data + 6;
1757 st->pktin->length -= 6;
1758 assert(st->pktin->length >= 0); /* one last double-check */
1761 ssh2_log_incoming_packet(ssh, st->pktin);
1763 st->pktin->savedpos = 0;
1765 crFinish(st->pktin);
1768 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh, unsigned char **data,
1771 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1773 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1776 * Read the packet length field.
1778 for (st->i = 0; st->i < 4; st->i++) {
1779 while ((*datalen) == 0)
1781 st->length[st->i] = *(*data)++;
1785 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1786 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1787 bombout(("Invalid packet length received"));
1791 st->pktin = ssh_new_packet();
1792 st->pktin->data = snewn(st->packetlen, unsigned char);
1794 st->pktin->encrypted_len = st->packetlen;
1796 st->pktin->sequence = st->incoming_sequence++;
1799 * Read the remainder of the packet.
1801 for (st->i = 0; st->i < st->packetlen; st->i++) {
1802 while ((*datalen) == 0)
1804 st->pktin->data[st->i] = *(*data)++;
1809 * pktin->body and pktin->length should identify the semantic
1810 * content of the packet, excluding the initial type byte.
1812 st->pktin->type = st->pktin->data[0];
1813 st->pktin->body = st->pktin->data + 1;
1814 st->pktin->length = st->packetlen - 1;
1817 * Log incoming packet, possibly omitting sensitive fields.
1820 ssh2_log_incoming_packet(ssh, st->pktin);
1822 st->pktin->savedpos = 0;
1824 crFinish(st->pktin);
1827 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1829 int pad, biglen, i, pktoffs;
1833 * XXX various versions of SC (including 8.8.4) screw up the
1834 * register allocation in this function and use the same register
1835 * (D6) for len and as a temporary, with predictable results. The
1836 * following sledgehammer prevents this.
1843 ssh1_log_outgoing_packet(ssh, pkt);
1845 if (ssh->v1_compressing) {
1846 unsigned char *compblk;
1848 zlib_compress_block(ssh->cs_comp_ctx,
1849 pkt->data + 12, pkt->length - 12,
1850 &compblk, &complen);
1851 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1852 memcpy(pkt->data + 12, compblk, complen);
1854 pkt->length = complen + 12;
1857 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1859 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1860 pad = 8 - (len % 8);
1862 biglen = len + pad; /* len(padding+type+data+CRC) */
1864 for (i = pktoffs; i < 4+8; i++)
1865 pkt->data[i] = random_byte();
1866 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1867 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1868 PUT_32BIT(pkt->data + pktoffs, len);
1871 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1872 pkt->data + pktoffs + 4, biglen);
1874 if (offset_p) *offset_p = pktoffs;
1875 return biglen + 4; /* len(length+padding+type+data+CRC) */
1878 static int s_write(Ssh ssh, void *data, int len)
1881 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1882 0, NULL, NULL, 0, NULL);
1885 return sk_write(ssh->s, (char *)data, len);
1888 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
1890 int len, backlog, offset;
1891 len = s_wrpkt_prepare(ssh, pkt, &offset);
1892 backlog = s_write(ssh, pkt->data + offset, len);
1893 if (backlog > SSH_MAX_BACKLOG)
1894 ssh_throttle_all(ssh, 1, backlog);
1895 ssh_free_packet(pkt);
1898 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
1901 len = s_wrpkt_prepare(ssh, pkt, &offset);
1902 if (ssh->deferred_len + len > ssh->deferred_size) {
1903 ssh->deferred_size = ssh->deferred_len + len + 128;
1904 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1908 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1909 pkt->data + offset, len);
1910 ssh->deferred_len += len;
1911 ssh_free_packet(pkt);
1915 * Construct a SSH-1 packet with the specified contents.
1916 * (This all-at-once interface used to be the only one, but now SSH-1
1917 * packets can also be constructed incrementally.)
1919 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
1925 pkt = ssh1_pkt_init(pkttype);
1927 while ((argtype = va_arg(ap, int)) != PKT_END) {
1928 unsigned char *argp, argchar;
1930 unsigned long argint;
1933 /* Actual fields in the packet */
1935 argint = va_arg(ap, int);
1936 ssh_pkt_adduint32(pkt, argint);
1939 argchar = (unsigned char) va_arg(ap, int);
1940 ssh_pkt_addbyte(pkt, argchar);
1943 argp = va_arg(ap, unsigned char *);
1944 arglen = va_arg(ap, int);
1945 ssh_pkt_adddata(pkt, argp, arglen);
1948 sargp = va_arg(ap, char *);
1949 ssh_pkt_addstring(pkt, sargp);
1952 bn = va_arg(ap, Bignum);
1953 ssh1_pkt_addmp(pkt, bn);
1961 static void send_packet(Ssh ssh, int pkttype, ...)
1965 va_start(ap, pkttype);
1966 pkt = construct_packet(ssh, pkttype, ap);
1971 static void defer_packet(Ssh ssh, int pkttype, ...)
1975 va_start(ap, pkttype);
1976 pkt = construct_packet(ssh, pkttype, ap);
1978 s_wrpkt_defer(ssh, pkt);
1981 static int ssh_versioncmp(char *a, char *b)
1984 unsigned long av, bv;
1986 av = strtoul(a, &ae, 10);
1987 bv = strtoul(b, &be, 10);
1989 return (av < bv ? -1 : +1);
1994 av = strtoul(ae, &ae, 10);
1995 bv = strtoul(be, &be, 10);
1997 return (av < bv ? -1 : +1);
2002 * Utility routines for putting an SSH-protocol `string' and
2003 * `uint32' into a hash state.
2005 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2007 unsigned char lenblk[4];
2008 PUT_32BIT(lenblk, len);
2009 h->bytes(s, lenblk, 4);
2010 h->bytes(s, str, len);
2013 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2015 unsigned char intblk[4];
2016 PUT_32BIT(intblk, i);
2017 h->bytes(s, intblk, 4);
2021 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2023 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2025 if (pkt->maxlen < length) {
2026 unsigned char *body = pkt->body;
2027 int offset = body ? body - pkt->data : 0;
2028 pkt->maxlen = length + 256;
2029 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2030 if (body) pkt->body = pkt->data + offset;
2033 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2036 ssh_pkt_ensure(pkt, pkt->length);
2037 memcpy(pkt->data + pkt->length - len, data, len);
2039 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2041 ssh_pkt_adddata(pkt, &byte, 1);
2043 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2045 ssh_pkt_adddata(pkt, &value, 1);
2047 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2050 PUT_32BIT(x, value);
2051 ssh_pkt_adddata(pkt, x, 4);
2053 static void ssh_pkt_addstring_start(struct Packet *pkt)
2055 ssh_pkt_adduint32(pkt, 0);
2056 pkt->savedpos = pkt->length;
2058 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2060 ssh_pkt_adddata(pkt, data, strlen(data));
2061 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2063 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2066 ssh_pkt_adddata(pkt, data, len);
2067 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2069 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2071 ssh_pkt_addstring_start(pkt);
2072 ssh_pkt_addstring_str(pkt, data);
2074 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2076 int len = ssh1_bignum_length(b);
2077 unsigned char *data = snewn(len, unsigned char);
2078 (void) ssh1_write_bignum(data, b);
2079 ssh_pkt_adddata(pkt, data, len);
2082 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2085 int i, n = (bignum_bitcount(b) + 7) / 8;
2086 p = snewn(n + 1, unsigned char);
2088 for (i = 1; i <= n; i++)
2089 p[i] = bignum_byte(b, n - i);
2091 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2093 memmove(p, p + i, n + 1 - i);
2097 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2101 p = ssh2_mpint_fmt(b, &len);
2102 ssh_pkt_addstring_start(pkt);
2103 ssh_pkt_addstring_data(pkt, (char *)p, len);
2107 static struct Packet *ssh1_pkt_init(int pkt_type)
2109 struct Packet *pkt = ssh_new_packet();
2110 pkt->length = 4 + 8; /* space for length + max padding */
2111 ssh_pkt_addbyte(pkt, pkt_type);
2112 pkt->body = pkt->data + pkt->length;
2113 pkt->type = pkt_type;
2114 pkt->downstream_id = 0;
2115 pkt->additional_log_text = NULL;
2119 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2120 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2121 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2122 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2123 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2124 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2125 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2126 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2127 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2129 static struct Packet *ssh2_pkt_init(int pkt_type)
2131 struct Packet *pkt = ssh_new_packet();
2132 pkt->length = 5; /* space for packet length + padding length */
2134 pkt->type = pkt_type;
2135 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2136 pkt->body = pkt->data + pkt->length; /* after packet type */
2137 pkt->downstream_id = 0;
2138 pkt->additional_log_text = NULL;
2143 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2144 * put the MAC on it. Final packet, ready to be sent, is stored in
2145 * pkt->data. Total length is returned.
2147 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2149 int cipherblk, maclen, padding, i;
2152 ssh2_log_outgoing_packet(ssh, pkt);
2154 if (ssh->bare_connection) {
2156 * Trivial packet construction for the bare connection
2159 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2160 pkt->body = pkt->data + 1;
2161 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2162 return pkt->length - 1;
2166 * Compress packet payload.
2169 unsigned char *newpayload;
2172 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2174 &newpayload, &newlen)) {
2176 ssh2_pkt_adddata(pkt, newpayload, newlen);
2182 * Add padding. At least four bytes, and must also bring total
2183 * length (minus MAC) up to a multiple of the block size.
2184 * If pkt->forcepad is set, make sure the packet is at least that size
2187 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2188 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2190 if (pkt->length + padding < pkt->forcepad)
2191 padding = pkt->forcepad - pkt->length;
2193 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
2194 assert(padding <= 255);
2195 maclen = ssh->csmac ? ssh->csmac->len : 0;
2196 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2197 pkt->data[4] = padding;
2198 for (i = 0; i < padding; i++)
2199 pkt->data[pkt->length + i] = random_byte();
2200 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2202 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2203 pkt->length + padding,
2204 ssh->v2_outgoing_sequence);
2205 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2208 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2209 pkt->data, pkt->length + padding);
2211 pkt->encrypted_len = pkt->length + padding;
2213 /* Ready-to-send packet starts at pkt->data. We return length. */
2214 pkt->body = pkt->data;
2215 return pkt->length + padding + maclen;
2219 * Routines called from the main SSH code to send packets. There
2220 * are quite a few of these, because we have two separate
2221 * mechanisms for delaying the sending of packets:
2223 * - In order to send an IGNORE message and a password message in
2224 * a single fixed-length blob, we require the ability to
2225 * concatenate the encrypted forms of those two packets _into_ a
2226 * single blob and then pass it to our <network.h> transport
2227 * layer in one go. Hence, there's a deferment mechanism which
2228 * works after packet encryption.
2230 * - In order to avoid sending any connection-layer messages
2231 * during repeat key exchange, we have to queue up any such
2232 * outgoing messages _before_ they are encrypted (and in
2233 * particular before they're allocated sequence numbers), and
2234 * then send them once we've finished.
2236 * I call these mechanisms `defer' and `queue' respectively, so as
2237 * to distinguish them reasonably easily.
2239 * The functions send_noqueue() and defer_noqueue() free the packet
2240 * structure they are passed. Every outgoing packet goes through
2241 * precisely one of these functions in its life; packets passed to
2242 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2243 * these or get queued, and then when the queue is later emptied
2244 * the packets are all passed to defer_noqueue().
2246 * When using a CBC-mode cipher, it's necessary to ensure that an
2247 * attacker can't provide data to be encrypted using an IV that they
2248 * know. We ensure this by prefixing each packet that might contain
2249 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2250 * mechanism, so in this case send_noqueue() ends up redirecting to
2251 * defer_noqueue(). If you don't like this inefficiency, don't use
2255 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2256 static void ssh_pkt_defersend(Ssh);
2259 * Send an SSH-2 packet immediately, without queuing or deferring.
2261 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2265 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2266 /* We need to send two packets, so use the deferral mechanism. */
2267 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2268 ssh_pkt_defersend(ssh);
2271 len = ssh2_pkt_construct(ssh, pkt);
2272 backlog = s_write(ssh, pkt->body, len);
2273 if (backlog > SSH_MAX_BACKLOG)
2274 ssh_throttle_all(ssh, 1, backlog);
2276 ssh->outgoing_data_size += pkt->encrypted_len;
2277 if (!ssh->kex_in_progress &&
2278 !ssh->bare_connection &&
2279 ssh->max_data_size != 0 &&
2280 ssh->outgoing_data_size > ssh->max_data_size)
2281 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2283 ssh_free_packet(pkt);
2287 * Defer an SSH-2 packet.
2289 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2292 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2293 ssh->deferred_len == 0 && !noignore &&
2294 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2296 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2297 * get encrypted with a known IV.
2299 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2300 ssh2_pkt_addstring_start(ipkt);
2301 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2303 len = ssh2_pkt_construct(ssh, pkt);
2304 if (ssh->deferred_len + len > ssh->deferred_size) {
2305 ssh->deferred_size = ssh->deferred_len + len + 128;
2306 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2310 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2311 ssh->deferred_len += len;
2312 ssh->deferred_data_size += pkt->encrypted_len;
2313 ssh_free_packet(pkt);
2317 * Queue an SSH-2 packet.
2319 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2321 assert(ssh->queueing);
2323 if (ssh->queuelen >= ssh->queuesize) {
2324 ssh->queuesize = ssh->queuelen + 32;
2325 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2328 ssh->queue[ssh->queuelen++] = pkt;
2332 * Either queue or send a packet, depending on whether queueing is
2335 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2338 ssh2_pkt_queue(ssh, pkt);
2340 ssh2_pkt_send_noqueue(ssh, pkt);
2344 * Either queue or defer a packet, depending on whether queueing is
2347 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2350 ssh2_pkt_queue(ssh, pkt);
2352 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2356 * Send the whole deferred data block constructed by
2357 * ssh2_pkt_defer() or SSH-1's defer_packet().
2359 * The expected use of the defer mechanism is that you call
2360 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2361 * not currently queueing, this simply sets up deferred_send_data
2362 * and then sends it. If we _are_ currently queueing, the calls to
2363 * ssh2_pkt_defer() put the deferred packets on to the queue
2364 * instead, and therefore ssh_pkt_defersend() has no deferred data
2365 * to send. Hence, there's no need to make it conditional on
2368 static void ssh_pkt_defersend(Ssh ssh)
2371 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2372 ssh->deferred_len = ssh->deferred_size = 0;
2373 sfree(ssh->deferred_send_data);
2374 ssh->deferred_send_data = NULL;
2375 if (backlog > SSH_MAX_BACKLOG)
2376 ssh_throttle_all(ssh, 1, backlog);
2378 ssh->outgoing_data_size += ssh->deferred_data_size;
2379 if (!ssh->kex_in_progress &&
2380 !ssh->bare_connection &&
2381 ssh->max_data_size != 0 &&
2382 ssh->outgoing_data_size > ssh->max_data_size)
2383 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2384 ssh->deferred_data_size = 0;
2388 * Send a packet whose length needs to be disguised (typically
2389 * passwords or keyboard-interactive responses).
2391 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2397 * The simplest way to do this is to adjust the
2398 * variable-length padding field in the outgoing packet.
2400 * Currently compiled out, because some Cisco SSH servers
2401 * don't like excessively padded packets (bah, why's it
2404 pkt->forcepad = padsize;
2405 ssh2_pkt_send(ssh, pkt);
2410 * If we can't do that, however, an alternative approach is
2411 * to use the pkt_defer mechanism to bundle the packet
2412 * tightly together with an SSH_MSG_IGNORE such that their
2413 * combined length is a constant. So first we construct the
2414 * final form of this packet and defer its sending.
2416 ssh2_pkt_defer(ssh, pkt);
2419 * Now construct an SSH_MSG_IGNORE which includes a string
2420 * that's an exact multiple of the cipher block size. (If
2421 * the cipher is NULL so that the block size is
2422 * unavailable, we don't do this trick at all, because we
2423 * gain nothing by it.)
2425 if (ssh->cscipher &&
2426 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2429 stringlen = (256 - ssh->deferred_len);
2430 stringlen += ssh->cscipher->blksize - 1;
2431 stringlen -= (stringlen % ssh->cscipher->blksize);
2434 * Temporarily disable actual compression, so we
2435 * can guarantee to get this string exactly the
2436 * length we want it. The compression-disabling
2437 * routine should return an integer indicating how
2438 * many bytes we should adjust our string length
2442 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2444 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2445 ssh2_pkt_addstring_start(pkt);
2446 for (i = 0; i < stringlen; i++) {
2447 char c = (char) random_byte();
2448 ssh2_pkt_addstring_data(pkt, &c, 1);
2450 ssh2_pkt_defer(ssh, pkt);
2452 ssh_pkt_defersend(ssh);
2457 * Send all queued SSH-2 packets. We send them by means of
2458 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2459 * packets that needed to be lumped together.
2461 static void ssh2_pkt_queuesend(Ssh ssh)
2465 assert(!ssh->queueing);
2467 for (i = 0; i < ssh->queuelen; i++)
2468 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2471 ssh_pkt_defersend(ssh);
2475 void bndebug(char *string, Bignum b)
2479 p = ssh2_mpint_fmt(b, &len);
2480 debug(("%s", string));
2481 for (i = 0; i < len; i++)
2482 debug((" %02x", p[i]));
2488 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2492 p = ssh2_mpint_fmt(b, &len);
2493 hash_string(h, s, p, len);
2498 * Packet decode functions for both SSH-1 and SSH-2.
2500 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2502 unsigned long value;
2503 if (pkt->length - pkt->savedpos < 4)
2504 return 0; /* arrgh, no way to decline (FIXME?) */
2505 value = GET_32BIT(pkt->body + pkt->savedpos);
2509 static int ssh2_pkt_getbool(struct Packet *pkt)
2511 unsigned long value;
2512 if (pkt->length - pkt->savedpos < 1)
2513 return 0; /* arrgh, no way to decline (FIXME?) */
2514 value = pkt->body[pkt->savedpos] != 0;
2518 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2523 if (pkt->length - pkt->savedpos < 4)
2525 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2530 if (pkt->length - pkt->savedpos < *length)
2532 *p = (char *)(pkt->body + pkt->savedpos);
2533 pkt->savedpos += *length;
2535 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2537 if (pkt->length - pkt->savedpos < length)
2539 pkt->savedpos += length;
2540 return pkt->body + (pkt->savedpos - length);
2542 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2543 unsigned char **keystr)
2547 j = makekey(pkt->body + pkt->savedpos,
2548 pkt->length - pkt->savedpos,
2555 assert(pkt->savedpos < pkt->length);
2559 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2564 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2565 pkt->length - pkt->savedpos, &b);
2573 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2579 ssh_pkt_getstring(pkt, &p, &length);
2584 b = bignum_from_bytes((unsigned char *)p, length);
2589 * Helper function to add an SSH-2 signature blob to a packet.
2590 * Expects to be shown the public key blob as well as the signature
2591 * blob. Normally works just like ssh2_pkt_addstring, but will
2592 * fiddle with the signature packet if necessary for
2593 * BUG_SSH2_RSA_PADDING.
2595 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2596 void *pkblob_v, int pkblob_len,
2597 void *sigblob_v, int sigblob_len)
2599 unsigned char *pkblob = (unsigned char *)pkblob_v;
2600 unsigned char *sigblob = (unsigned char *)sigblob_v;
2602 /* dmemdump(pkblob, pkblob_len); */
2603 /* dmemdump(sigblob, sigblob_len); */
2606 * See if this is in fact an ssh-rsa signature and a buggy
2607 * server; otherwise we can just do this the easy way.
2609 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2610 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2611 int pos, len, siglen;
2614 * Find the byte length of the modulus.
2617 pos = 4+7; /* skip over "ssh-rsa" */
2618 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2619 if (len < 0 || len > pkblob_len - pos - 4)
2621 pos += 4 + len; /* skip over exponent */
2622 if (pkblob_len - pos < 4)
2624 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2625 if (len < 0 || len > pkblob_len - pos - 4)
2627 pos += 4; /* find modulus itself */
2628 while (len > 0 && pkblob[pos] == 0)
2630 /* debug(("modulus length is %d\n", len)); */
2633 * Now find the signature integer.
2635 pos = 4+7; /* skip over "ssh-rsa" */
2636 if (sigblob_len < pos+4)
2638 siglen = toint(GET_32BIT(sigblob+pos));
2639 if (siglen != sigblob_len - pos - 4)
2641 /* debug(("signature length is %d\n", siglen)); */
2643 if (len != siglen) {
2644 unsigned char newlen[4];
2645 ssh2_pkt_addstring_start(pkt);
2646 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2647 /* dmemdump(sigblob, pos); */
2648 pos += 4; /* point to start of actual sig */
2649 PUT_32BIT(newlen, len);
2650 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2651 /* dmemdump(newlen, 4); */
2653 while (len-- > siglen) {
2654 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2655 /* dmemdump(newlen, 1); */
2657 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2658 /* dmemdump(sigblob+pos, siglen); */
2662 /* Otherwise fall through and do it the easy way. We also come
2663 * here as a fallback if we discover above that the key blob
2664 * is misformatted in some way. */
2668 ssh2_pkt_addstring_start(pkt);
2669 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2673 * Examine the remote side's version string and compare it against
2674 * a list of known buggy implementations.
2676 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2678 char *imp; /* pointer to implementation part */
2680 imp += strcspn(imp, "-");
2682 imp += strcspn(imp, "-");
2685 ssh->remote_bugs = 0;
2688 * General notes on server version strings:
2689 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2690 * here -- in particular, we've heard of one that's perfectly happy
2691 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2692 * so we can't distinguish them.
2694 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2695 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2696 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2697 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2698 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2699 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2701 * These versions don't support SSH1_MSG_IGNORE, so we have
2702 * to use a different defence against password length
2705 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2706 logevent("We believe remote version has SSH-1 ignore bug");
2709 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2710 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2711 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2713 * These versions need a plain password sent; they can't
2714 * handle having a null and a random length of data after
2717 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2718 logevent("We believe remote version needs a plain SSH-1 password");
2721 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2722 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2723 (!strcmp(imp, "Cisco-1.25")))) {
2725 * These versions apparently have no clue whatever about
2726 * RSA authentication and will panic and die if they see
2727 * an AUTH_RSA message.
2729 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2730 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2733 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2734 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2735 !wc_match("* VShell", imp) &&
2736 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2737 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2738 wc_match("2.1 *", imp)))) {
2740 * These versions have the HMAC bug.
2742 ssh->remote_bugs |= BUG_SSH2_HMAC;
2743 logevent("We believe remote version has SSH-2 HMAC bug");
2746 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2747 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2748 !wc_match("* VShell", imp) &&
2749 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2751 * These versions have the key-derivation bug (failing to
2752 * include the literal shared secret in the hashes that
2753 * generate the keys).
2755 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2756 logevent("We believe remote version has SSH-2 key-derivation bug");
2759 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2760 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2761 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2762 wc_match("OpenSSH_3.[0-2]*", imp) ||
2763 wc_match("mod_sftp/0.[0-8]*", imp) ||
2764 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2766 * These versions have the SSH-2 RSA padding bug.
2768 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2769 logevent("We believe remote version has SSH-2 RSA padding bug");
2772 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2773 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2774 wc_match("OpenSSH_2.[0-2]*", imp))) {
2776 * These versions have the SSH-2 session-ID bug in
2777 * public-key authentication.
2779 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2780 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2783 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2784 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2785 (wc_match("DigiSSH_2.0", imp) ||
2786 wc_match("OpenSSH_2.[0-4]*", imp) ||
2787 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2788 wc_match("Sun_SSH_1.0", imp) ||
2789 wc_match("Sun_SSH_1.0.1", imp) ||
2790 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2791 wc_match("WeOnlyDo-*", imp)))) {
2793 * These versions have the SSH-2 rekey bug.
2795 ssh->remote_bugs |= BUG_SSH2_REKEY;
2796 logevent("We believe remote version has SSH-2 rekey bug");
2799 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2800 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2801 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2802 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2804 * This version ignores our makpkt and needs to be throttled.
2806 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2807 logevent("We believe remote version ignores SSH-2 maximum packet size");
2810 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2812 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2813 * none detected automatically.
2815 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2816 logevent("We believe remote version has SSH-2 ignore bug");
2819 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2820 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2821 (wc_match("OpenSSH_2.[235]*", imp)))) {
2823 * These versions only support the original (pre-RFC4419)
2824 * SSH-2 GEX request.
2826 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2827 logevent("We believe remote version has outdated SSH-2 GEX");
2830 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2832 * Servers that don't support our winadj request for one
2833 * reason or another. Currently, none detected automatically.
2835 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2836 logevent("We believe remote version has winadj bug");
2839 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
2840 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
2841 (wc_match("OpenSSH_[2-5].*", imp) ||
2842 wc_match("OpenSSH_6.[0-6]*", imp) ||
2843 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
2844 wc_match("dropbear_0.5[01]*", imp)))) {
2846 * These versions have the SSH-2 channel request bug.
2847 * OpenSSH 6.7 and above do not:
2848 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
2849 * dropbear_0.52 and above do not:
2850 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
2852 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
2853 logevent("We believe remote version has SSH-2 channel request bug");
2858 * The `software version' part of an SSH version string is required
2859 * to contain no spaces or minus signs.
2861 static void ssh_fix_verstring(char *str)
2863 /* Eat "<protoversion>-". */
2864 while (*str && *str != '-') str++;
2865 assert(*str == '-'); str++;
2867 /* Convert minus signs and spaces in the remaining string into
2870 if (*str == '-' || *str == ' ')
2877 * Send an appropriate SSH version string.
2879 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
2883 if (ssh->version == 2) {
2885 * Construct a v2 version string.
2887 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
2890 * Construct a v1 version string.
2892 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
2893 verstring = dupprintf("SSH-%s-%s\012",
2894 (ssh_versioncmp(svers, "1.5") <= 0 ?
2899 ssh_fix_verstring(verstring + strlen(protoname));
2901 if (ssh->version == 2) {
2904 * Record our version string.
2906 len = strcspn(verstring, "\015\012");
2907 ssh->v_c = snewn(len + 1, char);
2908 memcpy(ssh->v_c, verstring, len);
2912 logeventf(ssh, "We claim version: %.*s",
2913 strcspn(verstring, "\015\012"), verstring);
2914 s_write(ssh, verstring, strlen(verstring));
2918 static int do_ssh_init(Ssh ssh, unsigned char c)
2920 static const char protoname[] = "SSH-";
2922 struct do_ssh_init_state {
2931 crState(do_ssh_init_state);
2935 /* Search for a line beginning with the protocol name prefix in
2938 for (s->i = 0; protoname[s->i]; s->i++) {
2939 if ((char)c != protoname[s->i]) goto no;
2949 s->vstrsize = sizeof(protoname) + 16;
2950 s->vstring = snewn(s->vstrsize, char);
2951 strcpy(s->vstring, protoname);
2952 s->vslen = strlen(protoname);
2955 if (s->vslen >= s->vstrsize - 1) {
2957 s->vstring = sresize(s->vstring, s->vstrsize, char);
2959 s->vstring[s->vslen++] = c;
2962 s->version[s->i] = '\0';
2964 } else if (s->i < sizeof(s->version) - 1)
2965 s->version[s->i++] = c;
2966 } else if (c == '\012')
2968 crReturn(1); /* get another char */
2971 ssh->agentfwd_enabled = FALSE;
2972 ssh->rdpkt2_state.incoming_sequence = 0;
2974 s->vstring[s->vslen] = 0;
2975 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
2976 logeventf(ssh, "Server version: %s", s->vstring);
2977 ssh_detect_bugs(ssh, s->vstring);
2980 * Decide which SSH protocol version to support.
2983 /* Anything strictly below "2.0" means protocol 1 is supported. */
2984 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
2985 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
2986 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
2988 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
2989 bombout(("SSH protocol version 1 required by configuration but "
2990 "not provided by server"));
2993 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
2994 bombout(("SSH protocol version 2 required by configuration but "
2995 "not provided by server"));
2999 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3004 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3006 /* Send the version string, if we haven't already */
3007 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3008 ssh_send_verstring(ssh, protoname, s->version);
3010 if (ssh->version == 2) {
3013 * Record their version string.
3015 len = strcspn(s->vstring, "\015\012");
3016 ssh->v_s = snewn(len + 1, char);
3017 memcpy(ssh->v_s, s->vstring, len);
3021 * Initialise SSH-2 protocol.
3023 ssh->protocol = ssh2_protocol;
3024 ssh2_protocol_setup(ssh);
3025 ssh->s_rdpkt = ssh2_rdpkt;
3028 * Initialise SSH-1 protocol.
3030 ssh->protocol = ssh1_protocol;
3031 ssh1_protocol_setup(ssh);
3032 ssh->s_rdpkt = ssh1_rdpkt;
3034 if (ssh->version == 2)
3035 do_ssh2_transport(ssh, NULL, -1, NULL);
3037 update_specials_menu(ssh->frontend);
3038 ssh->state = SSH_STATE_BEFORE_SIZE;
3039 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3046 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3049 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3050 * the ssh-connection part, extracted and given a trivial binary
3051 * packet protocol, so we replace 'SSH-' at the start with a new
3052 * name. In proper SSH style (though of course this part of the
3053 * proper SSH protocol _isn't_ subject to this kind of
3054 * DNS-domain-based extension), we define the new name in our
3057 static const char protoname[] =
3058 "SSHCONNECTION@putty.projects.tartarus.org-";
3060 struct do_ssh_connection_init_state {
3068 crState(do_ssh_connection_init_state);
3072 /* Search for a line beginning with the protocol name prefix in
3075 for (s->i = 0; protoname[s->i]; s->i++) {
3076 if ((char)c != protoname[s->i]) goto no;
3086 s->vstrsize = sizeof(protoname) + 16;
3087 s->vstring = snewn(s->vstrsize, char);
3088 strcpy(s->vstring, protoname);
3089 s->vslen = strlen(protoname);
3092 if (s->vslen >= s->vstrsize - 1) {
3094 s->vstring = sresize(s->vstring, s->vstrsize, char);
3096 s->vstring[s->vslen++] = c;
3099 s->version[s->i] = '\0';
3101 } else if (s->i < sizeof(s->version) - 1)
3102 s->version[s->i++] = c;
3103 } else if (c == '\012')
3105 crReturn(1); /* get another char */
3108 ssh->agentfwd_enabled = FALSE;
3109 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3111 s->vstring[s->vslen] = 0;
3112 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3113 logeventf(ssh, "Server version: %s", s->vstring);
3114 ssh_detect_bugs(ssh, s->vstring);
3117 * Decide which SSH protocol version to support. This is easy in
3118 * bare ssh-connection mode: only 2.0 is legal.
3120 if (ssh_versioncmp(s->version, "2.0") < 0) {
3121 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3124 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3125 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3131 logeventf(ssh, "Using bare ssh-connection protocol");
3133 /* Send the version string, if we haven't already */
3134 ssh_send_verstring(ssh, protoname, s->version);
3137 * Initialise bare connection protocol.
3139 ssh->protocol = ssh2_bare_connection_protocol;
3140 ssh2_bare_connection_protocol_setup(ssh);
3141 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3143 update_specials_menu(ssh->frontend);
3144 ssh->state = SSH_STATE_BEFORE_SIZE;
3145 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3148 * Get authconn (really just conn) under way.
3150 do_ssh2_authconn(ssh, NULL, 0, NULL);
3157 static void ssh_process_incoming_data(Ssh ssh,
3158 unsigned char **data, int *datalen)
3160 struct Packet *pktin;
3162 pktin = ssh->s_rdpkt(ssh, data, datalen);
3164 ssh->protocol(ssh, NULL, 0, pktin);
3165 ssh_free_packet(pktin);
3169 static void ssh_queue_incoming_data(Ssh ssh,
3170 unsigned char **data, int *datalen)
3172 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3177 static void ssh_process_queued_incoming_data(Ssh ssh)
3180 unsigned char *data;
3183 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3184 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3188 while (!ssh->frozen && len > 0)
3189 ssh_process_incoming_data(ssh, &data, &len);
3192 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3196 static void ssh_set_frozen(Ssh ssh, int frozen)
3199 sk_set_frozen(ssh->s, frozen);
3200 ssh->frozen = frozen;
3203 static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
3205 /* Log raw data, if we're in that mode. */
3207 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3208 0, NULL, NULL, 0, NULL);
3210 crBegin(ssh->ssh_gotdata_crstate);
3213 * To begin with, feed the characters one by one to the
3214 * protocol initialisation / selection function do_ssh_init().
3215 * When that returns 0, we're done with the initial greeting
3216 * exchange and can move on to packet discipline.
3219 int ret; /* need not be kept across crReturn */
3221 crReturnV; /* more data please */
3222 ret = ssh->do_ssh_init(ssh, *data);
3230 * We emerge from that loop when the initial negotiation is
3231 * over and we have selected an s_rdpkt function. Now pass
3232 * everything to s_rdpkt, and then pass the resulting packets
3233 * to the proper protocol handler.
3237 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3239 ssh_queue_incoming_data(ssh, &data, &datalen);
3240 /* This uses up all data and cannot cause anything interesting
3241 * to happen; indeed, for anything to happen at all, we must
3242 * return, so break out. */
3244 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3245 /* This uses up some or all data, and may freeze the
3247 ssh_process_queued_incoming_data(ssh);
3249 /* This uses up some or all data, and may freeze the
3251 ssh_process_incoming_data(ssh, &data, &datalen);
3253 /* FIXME this is probably EBW. */
3254 if (ssh->state == SSH_STATE_CLOSED)
3257 /* We're out of data. Go and get some more. */
3263 static int ssh_do_close(Ssh ssh, int notify_exit)
3266 struct ssh_channel *c;
3268 ssh->state = SSH_STATE_CLOSED;
3269 expire_timer_context(ssh);
3274 notify_remote_exit(ssh->frontend);
3279 * Now we must shut down any port- and X-forwarded channels going
3280 * through this connection.
3282 if (ssh->channels) {
3283 while (NULL != (c = index234(ssh->channels, 0))) {
3286 x11_close(c->u.x11.xconn);
3289 case CHAN_SOCKDATA_DORMANT:
3290 pfd_close(c->u.pfd.pf);
3293 del234(ssh->channels, c); /* moving next one to index 0 */
3294 if (ssh->version == 2)
3295 bufchain_clear(&c->v.v2.outbuffer);
3300 * Go through port-forwardings, and close any associated
3301 * listening sockets.
3303 if (ssh->portfwds) {
3304 struct ssh_portfwd *pf;
3305 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3306 /* Dispose of any listening socket. */
3308 pfl_terminate(pf->local);
3309 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3312 freetree234(ssh->portfwds);
3313 ssh->portfwds = NULL;
3317 * Also stop attempting to connection-share.
3319 if (ssh->connshare) {
3320 sharestate_free(ssh->connshare);
3321 ssh->connshare = NULL;
3327 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3328 const char *error_msg, int error_code)
3330 Ssh ssh = (Ssh) plug;
3331 char addrbuf[256], *msg;
3333 if (ssh->attempting_connshare) {
3335 * While we're attempting connection sharing, don't loudly log
3336 * everything that happens. Real TCP connections need to be
3337 * logged when we _start_ trying to connect, because it might
3338 * be ages before they respond if something goes wrong; but
3339 * connection sharing is local and quick to respond, and it's
3340 * sufficient to simply wait and see whether it worked
3344 sk_getaddr(addr, addrbuf, lenof(addrbuf));
3347 if (sk_addr_needs_port(addr)) {
3348 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
3350 msg = dupprintf("Connecting to %s", addrbuf);
3353 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
3361 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3362 const char *ds_err, const char *us_err)
3364 if (event == SHARE_NONE) {
3365 /* In this case, 'logtext' is an error message indicating a
3366 * reason why connection sharing couldn't be set up _at all_.
3367 * Failing that, ds_err and us_err indicate why we couldn't be
3368 * a downstream and an upstream respectively. */
3370 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3373 logeventf(ssh, "Could not set up connection sharing"
3374 " as downstream: %s", ds_err);
3376 logeventf(ssh, "Could not set up connection sharing"
3377 " as upstream: %s", us_err);
3379 } else if (event == SHARE_DOWNSTREAM) {
3380 /* In this case, 'logtext' is a local endpoint address */
3381 logeventf(ssh, "Using existing shared connection at %s", logtext);
3382 /* Also we should mention this in the console window to avoid
3383 * confusing users as to why this window doesn't behave the
3385 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3386 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3388 } else if (event == SHARE_UPSTREAM) {
3389 /* In this case, 'logtext' is a local endpoint address too */
3390 logeventf(ssh, "Sharing this connection at %s", logtext);
3394 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3397 Ssh ssh = (Ssh) plug;
3398 int need_notify = ssh_do_close(ssh, FALSE);
3401 if (!ssh->close_expected)
3402 error_msg = "Server unexpectedly closed network connection";
3404 error_msg = "Server closed network connection";
3407 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3411 notify_remote_exit(ssh->frontend);
3414 logevent(error_msg);
3415 if (!ssh->close_expected || !ssh->clean_exit)
3416 connection_fatal(ssh->frontend, "%s", error_msg);
3420 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3422 Ssh ssh = (Ssh) plug;
3423 ssh_gotdata(ssh, (unsigned char *)data, len);
3424 if (ssh->state == SSH_STATE_CLOSED) {
3425 ssh_do_close(ssh, TRUE);
3431 static void ssh_sent(Plug plug, int bufsize)
3433 Ssh ssh = (Ssh) plug;
3435 * If the send backlog on the SSH socket itself clears, we
3436 * should unthrottle the whole world if it was throttled.
3438 if (bufsize < SSH_MAX_BACKLOG)
3439 ssh_throttle_all(ssh, 0, bufsize);
3443 * Connect to specified host and port.
3444 * Returns an error message, or NULL on success.
3445 * Also places the canonical host name into `realhost'. It must be
3446 * freed by the caller.
3448 static const char *connect_to_host(Ssh ssh, char *host, int port,
3449 char **realhost, int nodelay, int keepalive)
3451 static const struct plug_function_table fn_table = {
3462 int addressfamily, sshprot;
3464 loghost = conf_get_str(ssh->conf, CONF_loghost);
3469 tmphost = dupstr(loghost);
3470 ssh->savedport = 22; /* default ssh port */
3473 * A colon suffix on the hostname string also lets us affect
3474 * savedport. (Unless there are multiple colons, in which case
3475 * we assume this is an unbracketed IPv6 literal.)
3477 colon = host_strrchr(tmphost, ':');
3478 if (colon && colon == host_strchr(tmphost, ':')) {
3481 ssh->savedport = atoi(colon);
3484 ssh->savedhost = host_strduptrim(tmphost);
3487 ssh->savedhost = host_strduptrim(host);
3489 port = 22; /* default ssh port */
3490 ssh->savedport = port;
3493 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3496 * Try connection-sharing, in case that means we don't open a
3497 * socket after all. ssh_connection_sharing_init will connect to a
3498 * previously established upstream if it can, and failing that,
3499 * establish a listening socket for _us_ to be the upstream. In
3500 * the latter case it will return NULL just as if it had done
3501 * nothing, because here we only need to care if we're a
3502 * downstream and need to do our connection setup differently.
3504 ssh->connshare = NULL;
3505 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3506 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3507 ssh->conf, ssh, &ssh->connshare);
3508 ssh->attempting_connshare = FALSE;
3509 if (ssh->s != NULL) {
3511 * We are a downstream.
3513 ssh->bare_connection = TRUE;
3514 ssh->do_ssh_init = do_ssh_connection_init;
3515 ssh->fullhostname = NULL;
3516 *realhost = dupstr(host); /* best we can do */
3519 * We're not a downstream, so open a normal socket.
3521 ssh->do_ssh_init = do_ssh_init;
3526 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3527 logeventf(ssh, "Looking up host \"%s\"%s", host,
3528 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3529 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3530 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
3531 if ((err = sk_addr_error(addr)) != NULL) {
3535 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3537 ssh->s = new_connection(addr, *realhost, port,
3538 0, 1, nodelay, keepalive,
3539 (Plug) ssh, ssh->conf);
3540 if ((err = sk_socket_error(ssh->s)) != NULL) {
3542 notify_remote_exit(ssh->frontend);
3548 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3549 * send the version string too.
3551 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3554 if (sshprot == 3 && !ssh->bare_connection) {
3556 ssh_send_verstring(ssh, "SSH-", NULL);
3560 * loghost, if configured, overrides realhost.
3564 *realhost = dupstr(loghost);
3571 * Throttle or unthrottle the SSH connection.
3573 static void ssh_throttle_conn(Ssh ssh, int adjust)
3575 int old_count = ssh->conn_throttle_count;
3576 ssh->conn_throttle_count += adjust;
3577 assert(ssh->conn_throttle_count >= 0);
3578 if (ssh->conn_throttle_count && !old_count) {
3579 ssh_set_frozen(ssh, 1);
3580 } else if (!ssh->conn_throttle_count && old_count) {
3581 ssh_set_frozen(ssh, 0);
3586 * Throttle or unthrottle _all_ local data streams (for when sends
3587 * on the SSH connection itself back up).
3589 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3592 struct ssh_channel *c;
3594 if (enable == ssh->throttled_all)
3596 ssh->throttled_all = enable;
3597 ssh->overall_bufsize = bufsize;
3600 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3602 case CHAN_MAINSESSION:
3604 * This is treated separately, outside the switch.
3608 x11_override_throttle(c->u.x11.xconn, enable);
3611 /* Agent channels require no buffer management. */
3614 pfd_override_throttle(c->u.pfd.pf, enable);
3620 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3622 Ssh ssh = (Ssh) sshv;
3624 ssh->agent_response = reply;
3625 ssh->agent_response_len = replylen;
3627 if (ssh->version == 1)
3628 do_ssh1_login(ssh, NULL, -1, NULL);
3630 do_ssh2_authconn(ssh, NULL, -1, NULL);
3633 static void ssh_dialog_callback(void *sshv, int ret)
3635 Ssh ssh = (Ssh) sshv;
3637 ssh->user_response = ret;
3639 if (ssh->version == 1)
3640 do_ssh1_login(ssh, NULL, -1, NULL);
3642 do_ssh2_transport(ssh, NULL, -1, NULL);
3645 * This may have unfrozen the SSH connection, so do a
3648 ssh_process_queued_incoming_data(ssh);
3651 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3653 struct ssh_channel *c = (struct ssh_channel *)cv;
3655 void *sentreply = reply;
3657 c->u.a.outstanding_requests--;
3659 /* Fake SSH_AGENT_FAILURE. */
3660 sentreply = "\0\0\0\1\5";
3663 if (ssh->version == 2) {
3664 ssh2_add_channel_data(c, sentreply, replylen);
3667 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3668 PKT_INT, c->remoteid,
3670 PKT_DATA, sentreply, replylen,
3676 * If we've already seen an incoming EOF but haven't sent an
3677 * outgoing one, this may be the moment to send it.
3679 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3680 sshfwd_write_eof(c);
3684 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3685 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3686 * => log `wire_reason'.
3688 static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3689 int code, int clean_exit)
3693 client_reason = wire_reason;
3695 error = dupprintf("Disconnected: %s", client_reason);
3697 error = dupstr("Disconnected");
3699 if (ssh->version == 1) {
3700 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3702 } else if (ssh->version == 2) {
3703 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3704 ssh2_pkt_adduint32(pktout, code);
3705 ssh2_pkt_addstring(pktout, wire_reason);
3706 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3707 ssh2_pkt_send_noqueue(ssh, pktout);
3710 ssh->close_expected = TRUE;
3711 ssh->clean_exit = clean_exit;
3712 ssh_closing((Plug)ssh, error, 0, 0);
3716 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3717 const struct ssh_signkey *ssh2keytype,
3720 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3721 return -1; /* no manual keys configured */
3726 * The fingerprint string we've been given will have things
3727 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3728 * narrow down to just the colon-separated hex block at the
3729 * end of the string.
3731 const char *p = strrchr(fingerprint, ' ');
3732 fingerprint = p ? p+1 : fingerprint;
3733 /* Quick sanity checks, including making sure it's in lowercase */
3734 assert(strlen(fingerprint) == 16*3 - 1);
3735 assert(fingerprint[2] == ':');
3736 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3738 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3740 return 1; /* success */
3745 * Construct the base64-encoded public key blob and see if
3748 unsigned char *binblob;
3750 int binlen, atoms, i;
3751 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3752 atoms = (binlen + 2) / 3;
3753 base64blob = snewn(atoms * 4 + 1, char);
3754 for (i = 0; i < atoms; i++)
3755 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3756 base64blob[atoms * 4] = '\0';
3758 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3761 return 1; /* success */
3770 * Handle the key exchange and user authentication phases.
3772 static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3773 struct Packet *pktin)
3776 unsigned char cookie[8], *ptr;
3777 struct MD5Context md5c;
3778 struct do_ssh1_login_state {
3781 unsigned char *rsabuf, *keystr1, *keystr2;
3782 unsigned long supported_ciphers_mask, supported_auths_mask;
3783 int tried_publickey, tried_agent;
3784 int tis_auth_refused, ccard_auth_refused;
3785 unsigned char session_id[16];
3787 void *publickey_blob;
3788 int publickey_bloblen;
3789 char *publickey_comment;
3790 int publickey_encrypted;
3791 prompts_t *cur_prompt;
3794 unsigned char request[5], *response, *p;
3804 struct RSAKey servkey, hostkey;
3806 crState(do_ssh1_login_state);
3813 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3814 bombout(("Public key packet not received"));
3818 logevent("Received public keys");
3820 ptr = ssh_pkt_getdata(pktin, 8);
3822 bombout(("SSH-1 public key packet stopped before random cookie"));
3825 memcpy(cookie, ptr, 8);
3827 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3828 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3829 bombout(("Failed to read SSH-1 public keys from public key packet"));
3834 * Log the host key fingerprint.
3838 logevent("Host key fingerprint is:");
3839 strcpy(logmsg, " ");
3840 s->hostkey.comment = NULL;
3841 rsa_fingerprint(logmsg + strlen(logmsg),
3842 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
3846 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3847 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3848 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
3849 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3850 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
3852 ssh->v1_local_protoflags =
3853 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3854 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
3857 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
3858 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
3859 MD5Update(&md5c, cookie, 8);
3860 MD5Final(s->session_id, &md5c);
3862 for (i = 0; i < 32; i++)
3863 ssh->session_key[i] = random_byte();
3866 * Verify that the `bits' and `bytes' parameters match.
3868 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
3869 s->servkey.bits > s->servkey.bytes * 8) {
3870 bombout(("SSH-1 public keys were badly formatted"));
3874 s->len = (s->hostkey.bytes > s->servkey.bytes ?
3875 s->hostkey.bytes : s->servkey.bytes);
3877 s->rsabuf = snewn(s->len, unsigned char);
3880 * Verify the host key.
3884 * First format the key into a string.
3886 int len = rsastr_len(&s->hostkey);
3887 char fingerprint[100];
3888 char *keystr = snewn(len, char);
3889 rsastr_fmt(keystr, &s->hostkey);
3890 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
3892 /* First check against manually configured host keys. */
3893 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
3894 if (s->dlgret == 0) { /* did not match */
3895 bombout(("Host key did not appear in manually configured list"));
3898 } else if (s->dlgret < 0) { /* none configured; use standard handling */
3899 ssh_set_frozen(ssh, 1);
3900 s->dlgret = verify_ssh_host_key(ssh->frontend,
3901 ssh->savedhost, ssh->savedport,
3902 "rsa", keystr, fingerprint,
3903 ssh_dialog_callback, ssh);
3905 if (s->dlgret < 0) {
3909 bombout(("Unexpected data from server while waiting"
3910 " for user host key response"));
3913 } while (pktin || inlen > 0);
3914 s->dlgret = ssh->user_response;
3916 ssh_set_frozen(ssh, 0);
3918 if (s->dlgret == 0) {
3919 ssh_disconnect(ssh, "User aborted at host key verification",
3928 for (i = 0; i < 32; i++) {
3929 s->rsabuf[i] = ssh->session_key[i];
3931 s->rsabuf[i] ^= s->session_id[i];
3934 if (s->hostkey.bytes > s->servkey.bytes) {
3935 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
3937 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
3939 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
3941 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
3944 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
3948 logevent("Encrypted session key");
3951 int cipher_chosen = 0, warn = 0;
3952 char *cipher_string = NULL;
3954 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
3955 int next_cipher = conf_get_int_int(ssh->conf,
3956 CONF_ssh_cipherlist, i);
3957 if (next_cipher == CIPHER_WARN) {
3958 /* If/when we choose a cipher, warn about it */
3960 } else if (next_cipher == CIPHER_AES) {
3961 /* XXX Probably don't need to mention this. */
3962 logevent("AES not supported in SSH-1, skipping");
3964 switch (next_cipher) {
3965 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
3966 cipher_string = "3DES"; break;
3967 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
3968 cipher_string = "Blowfish"; break;
3969 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
3970 cipher_string = "single-DES"; break;
3972 if (s->supported_ciphers_mask & (1 << s->cipher_type))
3976 if (!cipher_chosen) {
3977 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
3978 bombout(("Server violates SSH-1 protocol by not "
3979 "supporting 3DES encryption"));
3981 /* shouldn't happen */
3982 bombout(("No supported ciphers found"));
3986 /* Warn about chosen cipher if necessary. */
3988 ssh_set_frozen(ssh, 1);
3989 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3990 ssh_dialog_callback, ssh);
3991 if (s->dlgret < 0) {
3995 bombout(("Unexpected data from server while waiting"
3996 " for user response"));
3999 } while (pktin || inlen > 0);
4000 s->dlgret = ssh->user_response;
4002 ssh_set_frozen(ssh, 0);
4003 if (s->dlgret == 0) {
4004 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4011 switch (s->cipher_type) {
4012 case SSH_CIPHER_3DES:
4013 logevent("Using 3DES encryption");
4015 case SSH_CIPHER_DES:
4016 logevent("Using single-DES encryption");
4018 case SSH_CIPHER_BLOWFISH:
4019 logevent("Using Blowfish encryption");
4023 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4024 PKT_CHAR, s->cipher_type,
4025 PKT_DATA, cookie, 8,
4026 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4027 PKT_DATA, s->rsabuf, s->len,
4028 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4030 logevent("Trying to enable encryption...");
4034 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4035 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4037 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4038 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4039 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4041 ssh->crcda_ctx = crcda_make_context();
4042 logevent("Installing CRC compensation attack detector");
4044 if (s->servkey.modulus) {
4045 sfree(s->servkey.modulus);
4046 s->servkey.modulus = NULL;
4048 if (s->servkey.exponent) {
4049 sfree(s->servkey.exponent);
4050 s->servkey.exponent = NULL;
4052 if (s->hostkey.modulus) {
4053 sfree(s->hostkey.modulus);
4054 s->hostkey.modulus = NULL;
4056 if (s->hostkey.exponent) {
4057 sfree(s->hostkey.exponent);
4058 s->hostkey.exponent = NULL;
4062 if (pktin->type != SSH1_SMSG_SUCCESS) {
4063 bombout(("Encryption not successfully enabled"));
4067 logevent("Successfully started encryption");
4069 fflush(stdout); /* FIXME eh? */
4071 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4072 int ret; /* need not be kept over crReturn */
4073 s->cur_prompt = new_prompts(ssh->frontend);
4074 s->cur_prompt->to_server = TRUE;
4075 s->cur_prompt->name = dupstr("SSH login name");
4076 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4077 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4080 crWaitUntil(!pktin);
4081 ret = get_userpass_input(s->cur_prompt, in, inlen);
4086 * Failed to get a username. Terminate.
4088 free_prompts(s->cur_prompt);
4089 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4092 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4093 free_prompts(s->cur_prompt);
4096 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4098 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4100 if (flags & FLAG_INTERACTIVE &&
4101 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4102 c_write_str(ssh, userlog);
4103 c_write_str(ssh, "\r\n");
4111 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4112 /* We must not attempt PK auth. Pretend we've already tried it. */
4113 s->tried_publickey = s->tried_agent = 1;
4115 s->tried_publickey = s->tried_agent = 0;
4117 s->tis_auth_refused = s->ccard_auth_refused = 0;
4119 * Load the public half of any configured keyfile for later use.
4121 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4122 if (!filename_is_null(s->keyfile)) {
4124 logeventf(ssh, "Reading private key file \"%.150s\"",
4125 filename_to_str(s->keyfile));
4126 keytype = key_type(s->keyfile);
4127 if (keytype == SSH_KEYTYPE_SSH1) {
4129 if (rsakey_pubblob(s->keyfile,
4130 &s->publickey_blob, &s->publickey_bloblen,
4131 &s->publickey_comment, &error)) {
4132 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
4136 logeventf(ssh, "Unable to load private key (%s)", error);
4137 msgbuf = dupprintf("Unable to load private key file "
4138 "\"%.150s\" (%s)\r\n",
4139 filename_to_str(s->keyfile),
4141 c_write_str(ssh, msgbuf);
4143 s->publickey_blob = NULL;
4147 logeventf(ssh, "Unable to use this key file (%s)",
4148 key_type_to_str(keytype));
4149 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4151 filename_to_str(s->keyfile),
4152 key_type_to_str(keytype));
4153 c_write_str(ssh, msgbuf);
4155 s->publickey_blob = NULL;
4158 s->publickey_blob = NULL;
4160 while (pktin->type == SSH1_SMSG_FAILURE) {
4161 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4163 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4165 * Attempt RSA authentication using Pageant.
4171 logevent("Pageant is running. Requesting keys.");
4173 /* Request the keys held by the agent. */
4174 PUT_32BIT(s->request, 1);
4175 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4176 if (!agent_query(s->request, 5, &r, &s->responselen,
4177 ssh_agent_callback, ssh)) {
4181 bombout(("Unexpected data from server while waiting"
4182 " for agent response"));
4185 } while (pktin || inlen > 0);
4186 r = ssh->agent_response;
4187 s->responselen = ssh->agent_response_len;
4189 s->response = (unsigned char *) r;
4190 if (s->response && s->responselen >= 5 &&
4191 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4192 s->p = s->response + 5;
4193 s->nkeys = toint(GET_32BIT(s->p));
4195 logeventf(ssh, "Pageant reported negative key count %d",
4200 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4201 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4202 unsigned char *pkblob = s->p;
4206 do { /* do while (0) to make breaking easy */
4207 n = ssh1_read_bignum
4208 (s->p, toint(s->responselen-(s->p-s->response)),
4213 n = ssh1_read_bignum
4214 (s->p, toint(s->responselen-(s->p-s->response)),
4219 if (s->responselen - (s->p-s->response) < 4)
4221 s->commentlen = toint(GET_32BIT(s->p));
4223 if (s->commentlen < 0 ||
4224 toint(s->responselen - (s->p-s->response)) <
4227 s->commentp = (char *)s->p;
4228 s->p += s->commentlen;
4232 logevent("Pageant key list packet was truncated");
4236 if (s->publickey_blob) {
4237 if (!memcmp(pkblob, s->publickey_blob,
4238 s->publickey_bloblen)) {
4239 logeventf(ssh, "Pageant key #%d matches "
4240 "configured key file", s->keyi);
4241 s->tried_publickey = 1;
4243 /* Skip non-configured key */
4246 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4247 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4248 PKT_BIGNUM, s->key.modulus, PKT_END);
4250 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4251 logevent("Key refused");
4254 logevent("Received RSA challenge");
4255 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4256 bombout(("Server's RSA challenge was badly formatted"));
4261 char *agentreq, *q, *ret;
4264 len = 1 + 4; /* message type, bit count */
4265 len += ssh1_bignum_length(s->key.exponent);
4266 len += ssh1_bignum_length(s->key.modulus);
4267 len += ssh1_bignum_length(s->challenge);
4268 len += 16; /* session id */
4269 len += 4; /* response format */
4270 agentreq = snewn(4 + len, char);
4271 PUT_32BIT(agentreq, len);
4273 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4274 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4276 q += ssh1_write_bignum(q, s->key.exponent);
4277 q += ssh1_write_bignum(q, s->key.modulus);
4278 q += ssh1_write_bignum(q, s->challenge);
4279 memcpy(q, s->session_id, 16);
4281 PUT_32BIT(q, 1); /* response format */
4282 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4283 ssh_agent_callback, ssh)) {
4288 bombout(("Unexpected data from server"
4289 " while waiting for agent"
4293 } while (pktin || inlen > 0);
4294 vret = ssh->agent_response;
4295 retlen = ssh->agent_response_len;
4300 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4301 logevent("Sending Pageant's response");
4302 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4303 PKT_DATA, ret + 5, 16,
4307 if (pktin->type == SSH1_SMSG_SUCCESS) {
4309 ("Pageant's response accepted");
4310 if (flags & FLAG_VERBOSE) {
4311 c_write_str(ssh, "Authenticated using"
4313 c_write(ssh, s->commentp,
4315 c_write_str(ssh, "\" from agent\r\n");
4320 ("Pageant's response not accepted");
4323 ("Pageant failed to answer challenge");
4327 logevent("No reply received from Pageant");
4330 freebn(s->key.exponent);
4331 freebn(s->key.modulus);
4332 freebn(s->challenge);
4337 if (s->publickey_blob && !s->tried_publickey)
4338 logevent("Configured key file not in Pageant");
4340 logevent("Failed to get reply from Pageant");
4345 if (s->publickey_blob && !s->tried_publickey) {
4347 * Try public key authentication with the specified
4350 int got_passphrase; /* need not be kept over crReturn */
4351 if (flags & FLAG_VERBOSE)
4352 c_write_str(ssh, "Trying public key authentication.\r\n");
4353 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4354 logeventf(ssh, "Trying public key \"%s\"",
4355 filename_to_str(s->keyfile));
4356 s->tried_publickey = 1;
4357 got_passphrase = FALSE;
4358 while (!got_passphrase) {
4360 * Get a passphrase, if necessary.
4362 char *passphrase = NULL; /* only written after crReturn */
4364 if (!s->publickey_encrypted) {
4365 if (flags & FLAG_VERBOSE)
4366 c_write_str(ssh, "No passphrase required.\r\n");
4369 int ret; /* need not be kept over crReturn */
4370 s->cur_prompt = new_prompts(ssh->frontend);
4371 s->cur_prompt->to_server = FALSE;
4372 s->cur_prompt->name = dupstr("SSH key passphrase");
4373 add_prompt(s->cur_prompt,
4374 dupprintf("Passphrase for key \"%.100s\": ",
4375 s->publickey_comment), FALSE);
4376 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4379 crWaitUntil(!pktin);
4380 ret = get_userpass_input(s->cur_prompt, in, inlen);
4384 /* Failed to get a passphrase. Terminate. */
4385 free_prompts(s->cur_prompt);
4386 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4390 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4391 free_prompts(s->cur_prompt);
4394 * Try decrypting key with passphrase.
4396 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4397 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4400 smemclr(passphrase, strlen(passphrase));
4404 /* Correct passphrase. */
4405 got_passphrase = TRUE;
4406 } else if (ret == 0) {
4407 c_write_str(ssh, "Couldn't load private key from ");
4408 c_write_str(ssh, filename_to_str(s->keyfile));
4409 c_write_str(ssh, " (");
4410 c_write_str(ssh, error);
4411 c_write_str(ssh, ").\r\n");
4412 got_passphrase = FALSE;
4413 break; /* go and try something else */
4414 } else if (ret == -1) {
4415 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4416 got_passphrase = FALSE;
4419 assert(0 && "unexpected return from loadrsakey()");
4420 got_passphrase = FALSE; /* placate optimisers */
4424 if (got_passphrase) {
4427 * Send a public key attempt.
4429 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4430 PKT_BIGNUM, s->key.modulus, PKT_END);
4433 if (pktin->type == SSH1_SMSG_FAILURE) {
4434 c_write_str(ssh, "Server refused our public key.\r\n");
4435 continue; /* go and try something else */
4437 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4438 bombout(("Bizarre response to offer of public key"));
4444 unsigned char buffer[32];
4445 Bignum challenge, response;
4447 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4448 bombout(("Server's RSA challenge was badly formatted"));
4451 response = rsadecrypt(challenge, &s->key);
4452 freebn(s->key.private_exponent);/* burn the evidence */
4454 for (i = 0; i < 32; i++) {
4455 buffer[i] = bignum_byte(response, 31 - i);
4459 MD5Update(&md5c, buffer, 32);
4460 MD5Update(&md5c, s->session_id, 16);
4461 MD5Final(buffer, &md5c);
4463 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4464 PKT_DATA, buffer, 16, PKT_END);
4471 if (pktin->type == SSH1_SMSG_FAILURE) {
4472 if (flags & FLAG_VERBOSE)
4473 c_write_str(ssh, "Failed to authenticate with"
4474 " our public key.\r\n");
4475 continue; /* go and try something else */
4476 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4477 bombout(("Bizarre response to RSA authentication response"));
4481 break; /* we're through! */
4487 * Otherwise, try various forms of password-like authentication.
4489 s->cur_prompt = new_prompts(ssh->frontend);
4491 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4492 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4493 !s->tis_auth_refused) {
4494 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4495 logevent("Requested TIS authentication");
4496 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4498 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4499 logevent("TIS authentication declined");
4500 if (flags & FLAG_INTERACTIVE)
4501 c_write_str(ssh, "TIS authentication refused.\r\n");
4502 s->tis_auth_refused = 1;
4507 char *instr_suf, *prompt;
4509 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4511 bombout(("TIS challenge packet was badly formed"));
4514 logevent("Received TIS challenge");
4515 s->cur_prompt->to_server = TRUE;
4516 s->cur_prompt->name = dupstr("SSH TIS authentication");
4517 /* Prompt heuristic comes from OpenSSH */
4518 if (memchr(challenge, '\n', challengelen)) {
4519 instr_suf = dupstr("");
4520 prompt = dupprintf("%.*s", challengelen, challenge);
4522 instr_suf = dupprintf("%.*s", challengelen, challenge);
4523 prompt = dupstr("Response: ");
4525 s->cur_prompt->instruction =
4526 dupprintf("Using TIS authentication.%s%s",
4527 (*instr_suf) ? "\n" : "",
4529 s->cur_prompt->instr_reqd = TRUE;
4530 add_prompt(s->cur_prompt, prompt, FALSE);
4534 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4535 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4536 !s->ccard_auth_refused) {
4537 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4538 logevent("Requested CryptoCard authentication");
4539 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4541 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4542 logevent("CryptoCard authentication declined");
4543 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4544 s->ccard_auth_refused = 1;
4549 char *instr_suf, *prompt;
4551 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4553 bombout(("CryptoCard challenge packet was badly formed"));
4556 logevent("Received CryptoCard challenge");
4557 s->cur_prompt->to_server = TRUE;
4558 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4559 s->cur_prompt->name_reqd = FALSE;
4560 /* Prompt heuristic comes from OpenSSH */
4561 if (memchr(challenge, '\n', challengelen)) {
4562 instr_suf = dupstr("");
4563 prompt = dupprintf("%.*s", challengelen, challenge);
4565 instr_suf = dupprintf("%.*s", challengelen, challenge);
4566 prompt = dupstr("Response: ");
4568 s->cur_prompt->instruction =
4569 dupprintf("Using CryptoCard authentication.%s%s",
4570 (*instr_suf) ? "\n" : "",
4572 s->cur_prompt->instr_reqd = TRUE;
4573 add_prompt(s->cur_prompt, prompt, FALSE);
4577 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4578 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4579 bombout(("No supported authentication methods available"));
4582 s->cur_prompt->to_server = TRUE;
4583 s->cur_prompt->name = dupstr("SSH password");
4584 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4585 ssh->username, ssh->savedhost),
4590 * Show password prompt, having first obtained it via a TIS
4591 * or CryptoCard exchange if we're doing TIS or CryptoCard
4595 int ret; /* need not be kept over crReturn */
4596 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4599 crWaitUntil(!pktin);
4600 ret = get_userpass_input(s->cur_prompt, in, inlen);
4605 * Failed to get a password (for example
4606 * because one was supplied on the command line
4607 * which has already failed to work). Terminate.
4609 free_prompts(s->cur_prompt);
4610 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4615 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4617 * Defence against traffic analysis: we send a
4618 * whole bunch of packets containing strings of
4619 * different lengths. One of these strings is the
4620 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4621 * The others are all random data in
4622 * SSH1_MSG_IGNORE packets. This way a passive
4623 * listener can't tell which is the password, and
4624 * hence can't deduce the password length.
4626 * Anybody with a password length greater than 16
4627 * bytes is going to have enough entropy in their
4628 * password that a listener won't find it _that_
4629 * much help to know how long it is. So what we'll
4632 * - if password length < 16, we send 15 packets
4633 * containing string lengths 1 through 15
4635 * - otherwise, we let N be the nearest multiple
4636 * of 8 below the password length, and send 8
4637 * packets containing string lengths N through
4638 * N+7. This won't obscure the order of
4639 * magnitude of the password length, but it will
4640 * introduce a bit of extra uncertainty.
4642 * A few servers can't deal with SSH1_MSG_IGNORE, at
4643 * least in this context. For these servers, we need
4644 * an alternative defence. We make use of the fact
4645 * that the password is interpreted as a C string:
4646 * so we can append a NUL, then some random data.
4648 * A few servers can deal with neither SSH1_MSG_IGNORE
4649 * here _nor_ a padded password string.
4650 * For these servers we are left with no defences
4651 * against password length sniffing.
4653 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4654 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4656 * The server can deal with SSH1_MSG_IGNORE, so
4657 * we can use the primary defence.
4659 int bottom, top, pwlen, i;
4662 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4664 bottom = 0; /* zero length passwords are OK! :-) */
4667 bottom = pwlen & ~7;
4671 assert(pwlen >= bottom && pwlen <= top);
4673 randomstr = snewn(top + 1, char);
4675 for (i = bottom; i <= top; i++) {
4677 defer_packet(ssh, s->pwpkt_type,
4678 PKT_STR,s->cur_prompt->prompts[0]->result,
4681 for (j = 0; j < i; j++) {
4683 randomstr[j] = random_byte();
4684 } while (randomstr[j] == '\0');
4686 randomstr[i] = '\0';
4687 defer_packet(ssh, SSH1_MSG_IGNORE,
4688 PKT_STR, randomstr, PKT_END);
4691 logevent("Sending password with camouflage packets");
4692 ssh_pkt_defersend(ssh);
4695 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4697 * The server can't deal with SSH1_MSG_IGNORE
4698 * but can deal with padded passwords, so we
4699 * can use the secondary defence.
4705 len = strlen(s->cur_prompt->prompts[0]->result);
4706 if (len < sizeof(string)) {
4708 strcpy(string, s->cur_prompt->prompts[0]->result);
4709 len++; /* cover the zero byte */
4710 while (len < sizeof(string)) {
4711 string[len++] = (char) random_byte();
4714 ss = s->cur_prompt->prompts[0]->result;
4716 logevent("Sending length-padded password");
4717 send_packet(ssh, s->pwpkt_type,
4718 PKT_INT, len, PKT_DATA, ss, len,
4722 * The server is believed unable to cope with
4723 * any of our password camouflage methods.
4726 len = strlen(s->cur_prompt->prompts[0]->result);
4727 logevent("Sending unpadded password");
4728 send_packet(ssh, s->pwpkt_type,
4730 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4734 send_packet(ssh, s->pwpkt_type,
4735 PKT_STR, s->cur_prompt->prompts[0]->result,
4738 logevent("Sent password");
4739 free_prompts(s->cur_prompt);
4741 if (pktin->type == SSH1_SMSG_FAILURE) {
4742 if (flags & FLAG_VERBOSE)
4743 c_write_str(ssh, "Access denied\r\n");
4744 logevent("Authentication refused");
4745 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4746 bombout(("Strange packet received, type %d", pktin->type));
4752 if (s->publickey_blob) {
4753 sfree(s->publickey_blob);
4754 sfree(s->publickey_comment);
4757 logevent("Authentication successful");
4762 static void ssh_channel_try_eof(struct ssh_channel *c)
4765 assert(c->pending_eof); /* precondition for calling us */
4767 return; /* can't close: not even opened yet */
4768 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4769 return; /* can't send EOF: pending outgoing data */
4771 c->pending_eof = FALSE; /* we're about to send it */
4772 if (ssh->version == 1) {
4773 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4775 c->closes |= CLOSES_SENT_EOF;
4777 struct Packet *pktout;
4778 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4779 ssh2_pkt_adduint32(pktout, c->remoteid);
4780 ssh2_pkt_send(ssh, pktout);
4781 c->closes |= CLOSES_SENT_EOF;
4782 ssh2_channel_check_close(c);
4786 Conf *sshfwd_get_conf(struct ssh_channel *c)
4792 void sshfwd_write_eof(struct ssh_channel *c)
4796 if (ssh->state == SSH_STATE_CLOSED)
4799 if (c->closes & CLOSES_SENT_EOF)
4802 c->pending_eof = TRUE;
4803 ssh_channel_try_eof(c);
4806 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4810 if (ssh->state == SSH_STATE_CLOSED)
4815 x11_close(c->u.x11.xconn);
4816 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4820 case CHAN_SOCKDATA_DORMANT:
4821 pfd_close(c->u.pfd.pf);
4822 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4825 c->type = CHAN_ZOMBIE;
4826 c->pending_eof = FALSE; /* this will confuse a zombie channel */
4828 ssh2_channel_check_close(c);
4831 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
4835 if (ssh->state == SSH_STATE_CLOSED)
4838 if (ssh->version == 1) {
4839 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
4840 PKT_INT, c->remoteid,
4841 PKT_INT, len, PKT_DATA, buf, len,
4844 * In SSH-1 we can return 0 here - implying that forwarded
4845 * connections are never individually throttled - because
4846 * the only circumstance that can cause throttling will be
4847 * the whole SSH connection backing up, in which case
4848 * _everything_ will be throttled as a whole.
4852 ssh2_add_channel_data(c, buf, len);
4853 return ssh2_try_send(c);
4857 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4862 if (ssh->state == SSH_STATE_CLOSED)
4865 if (ssh->version == 1) {
4866 buflimit = SSH1_BUFFER_LIMIT;
4868 buflimit = c->v.v2.locmaxwin;
4869 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4871 if (c->throttling_conn && bufsize <= buflimit) {
4872 c->throttling_conn = 0;
4873 ssh_throttle_conn(ssh, -1);
4877 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4879 struct queued_handler *qh = ssh->qhead;
4883 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4886 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4887 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
4890 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4891 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
4895 ssh->qhead = qh->next;
4897 if (ssh->qhead->msg1 > 0) {
4898 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4899 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4901 if (ssh->qhead->msg2 > 0) {
4902 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4903 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4906 ssh->qhead = ssh->qtail = NULL;
4909 qh->handler(ssh, pktin, qh->ctx);
4914 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4915 chandler_fn_t handler, void *ctx)
4917 struct queued_handler *qh;
4919 qh = snew(struct queued_handler);
4922 qh->handler = handler;
4926 if (ssh->qtail == NULL) {
4930 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
4931 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4934 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
4935 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4938 ssh->qtail->next = qh;
4943 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4945 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4947 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4948 SSH2_MSG_REQUEST_SUCCESS)) {
4949 logeventf(ssh, "Remote port forwarding from %s enabled",
4952 logeventf(ssh, "Remote port forwarding from %s refused",
4955 rpf = del234(ssh->rportfwds, pf);
4957 pf->pfrec->remote = NULL;
4962 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
4965 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
4968 pf->share_ctx = share_ctx;
4969 pf->shost = dupstr(shost);
4971 pf->sportdesc = NULL;
4972 if (!ssh->rportfwds) {
4973 assert(ssh->version == 2);
4974 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4976 if (add234(ssh->rportfwds, pf) != pf) {
4984 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
4987 share_got_pkt_from_server(ctx, pktin->type,
4988 pktin->body, pktin->length);
4991 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
4993 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
4994 ssh_sharing_global_request_response, share_ctx);
4997 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
4999 struct ssh_portfwd *epf;
5003 if (!ssh->portfwds) {
5004 ssh->portfwds = newtree234(ssh_portcmp);
5007 * Go through the existing port forwardings and tag them
5008 * with status==DESTROY. Any that we want to keep will be
5009 * re-enabled (status==KEEP) as we go through the
5010 * configuration and find out which bits are the same as
5013 struct ssh_portfwd *epf;
5015 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5016 epf->status = DESTROY;
5019 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5021 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5022 char *kp, *kp2, *vp, *vp2;
5023 char address_family, type;
5024 int sport,dport,sserv,dserv;
5025 char *sports, *dports, *saddr, *host;
5029 address_family = 'A';
5031 if (*kp == 'A' || *kp == '4' || *kp == '6')
5032 address_family = *kp++;
5033 if (*kp == 'L' || *kp == 'R')
5036 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5038 * There's a colon in the middle of the source port
5039 * string, which means that the part before it is
5040 * actually a source address.
5042 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5043 saddr = host_strduptrim(saddr_tmp);
5050 sport = atoi(sports);
5054 sport = net_service_lookup(sports);
5056 logeventf(ssh, "Service lookup failed for source"
5057 " port \"%s\"", sports);
5061 if (type == 'L' && !strcmp(val, "D")) {
5062 /* dynamic forwarding */
5069 /* ordinary forwarding */
5071 vp2 = vp + host_strcspn(vp, ":");
5072 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5076 dport = atoi(dports);
5080 dport = net_service_lookup(dports);
5082 logeventf(ssh, "Service lookup failed for destination"
5083 " port \"%s\"", dports);
5088 if (sport && dport) {
5089 /* Set up a description of the source port. */
5090 struct ssh_portfwd *pfrec, *epfrec;
5092 pfrec = snew(struct ssh_portfwd);
5094 pfrec->saddr = saddr;
5095 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5096 pfrec->sport = sport;
5097 pfrec->daddr = host;
5098 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5099 pfrec->dport = dport;
5100 pfrec->local = NULL;
5101 pfrec->remote = NULL;
5102 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5103 address_family == '6' ? ADDRTYPE_IPV6 :
5106 epfrec = add234(ssh->portfwds, pfrec);
5107 if (epfrec != pfrec) {
5108 if (epfrec->status == DESTROY) {
5110 * We already have a port forwarding up and running
5111 * with precisely these parameters. Hence, no need
5112 * to do anything; simply re-tag the existing one
5115 epfrec->status = KEEP;
5118 * Anything else indicates that there was a duplicate
5119 * in our input, which we'll silently ignore.
5121 free_portfwd(pfrec);
5123 pfrec->status = CREATE;
5132 * Now go through and destroy any port forwardings which were
5135 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5136 if (epf->status == DESTROY) {
5139 message = dupprintf("%s port forwarding from %s%s%d",
5140 epf->type == 'L' ? "local" :
5141 epf->type == 'R' ? "remote" : "dynamic",
5142 epf->saddr ? epf->saddr : "",
5143 epf->saddr ? ":" : "",
5146 if (epf->type != 'D') {
5147 char *msg2 = dupprintf("%s to %s:%d", message,
5148 epf->daddr, epf->dport);
5153 logeventf(ssh, "Cancelling %s", message);
5156 /* epf->remote or epf->local may be NULL if setting up a
5157 * forwarding failed. */
5159 struct ssh_rportfwd *rpf = epf->remote;
5160 struct Packet *pktout;
5163 * Cancel the port forwarding at the server
5166 if (ssh->version == 1) {
5168 * We cannot cancel listening ports on the
5169 * server side in SSH-1! There's no message
5170 * to support it. Instead, we simply remove
5171 * the rportfwd record from the local end
5172 * so that any connections the server tries
5173 * to make on it are rejected.
5176 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5177 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5178 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5180 ssh2_pkt_addstring(pktout, epf->saddr);
5181 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5182 /* XXX: rport_acceptall may not represent
5183 * what was used to open the original connection,
5184 * since it's reconfigurable. */
5185 ssh2_pkt_addstring(pktout, "");
5187 ssh2_pkt_addstring(pktout, "localhost");
5189 ssh2_pkt_adduint32(pktout, epf->sport);
5190 ssh2_pkt_send(ssh, pktout);
5193 del234(ssh->rportfwds, rpf);
5195 } else if (epf->local) {
5196 pfl_terminate(epf->local);
5199 delpos234(ssh->portfwds, i);
5201 i--; /* so we don't skip one in the list */
5205 * And finally, set up any new port forwardings (status==CREATE).
5207 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5208 if (epf->status == CREATE) {
5209 char *sportdesc, *dportdesc;
5210 sportdesc = dupprintf("%s%s%s%s%d%s",
5211 epf->saddr ? epf->saddr : "",
5212 epf->saddr ? ":" : "",
5213 epf->sserv ? epf->sserv : "",
5214 epf->sserv ? "(" : "",
5216 epf->sserv ? ")" : "");
5217 if (epf->type == 'D') {
5220 dportdesc = dupprintf("%s:%s%s%d%s",
5222 epf->dserv ? epf->dserv : "",
5223 epf->dserv ? "(" : "",
5225 epf->dserv ? ")" : "");
5228 if (epf->type == 'L') {
5229 char *err = pfl_listen(epf->daddr, epf->dport,
5230 epf->saddr, epf->sport,
5231 ssh, conf, &epf->local,
5232 epf->addressfamily);
5234 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5235 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5236 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5237 sportdesc, dportdesc,
5238 err ? " failed: " : "", err ? err : "");
5241 } else if (epf->type == 'D') {
5242 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5243 ssh, conf, &epf->local,
5244 epf->addressfamily);
5246 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5247 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5248 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5250 err ? " failed: " : "", err ? err : "");
5255 struct ssh_rportfwd *pf;
5258 * Ensure the remote port forwardings tree exists.
5260 if (!ssh->rportfwds) {
5261 if (ssh->version == 1)
5262 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5264 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5267 pf = snew(struct ssh_rportfwd);
5268 pf->share_ctx = NULL;
5269 pf->dhost = dupstr(epf->daddr);
5270 pf->dport = epf->dport;
5272 pf->shost = dupstr(epf->saddr);
5273 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5274 pf->shost = dupstr("");
5276 pf->shost = dupstr("localhost");
5278 pf->sport = epf->sport;
5279 if (add234(ssh->rportfwds, pf) != pf) {
5280 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5281 epf->daddr, epf->dport);
5284 logeventf(ssh, "Requesting remote port %s"
5285 " forward to %s", sportdesc, dportdesc);
5287 pf->sportdesc = sportdesc;
5292 if (ssh->version == 1) {
5293 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5294 PKT_INT, epf->sport,
5295 PKT_STR, epf->daddr,
5296 PKT_INT, epf->dport,
5298 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5300 ssh_rportfwd_succfail, pf);
5302 struct Packet *pktout;
5303 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5304 ssh2_pkt_addstring(pktout, "tcpip-forward");
5305 ssh2_pkt_addbool(pktout, 1);/* want reply */
5306 ssh2_pkt_addstring(pktout, pf->shost);
5307 ssh2_pkt_adduint32(pktout, pf->sport);
5308 ssh2_pkt_send(ssh, pktout);
5310 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5311 SSH2_MSG_REQUEST_FAILURE,
5312 ssh_rportfwd_succfail, pf);
5321 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5324 int stringlen, bufsize;
5326 ssh_pkt_getstring(pktin, &string, &stringlen);
5327 if (string == NULL) {
5328 bombout(("Incoming terminal data packet was badly formed"));
5332 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5334 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5335 ssh->v1_stdout_throttling = 1;
5336 ssh_throttle_conn(ssh, +1);
5340 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5342 /* Remote side is trying to open a channel to talk to our
5343 * X-Server. Give them back a local channel number. */
5344 struct ssh_channel *c;
5345 int remoteid = ssh_pkt_getuint32(pktin);
5347 logevent("Received X11 connect request");
5348 /* Refuse if X11 forwarding is disabled. */
5349 if (!ssh->X11_fwd_enabled) {
5350 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5351 PKT_INT, remoteid, PKT_END);
5352 logevent("Rejected X11 connect request");
5354 c = snew(struct ssh_channel);
5357 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5358 c->remoteid = remoteid;
5359 c->halfopen = FALSE;
5360 c->localid = alloc_channel_id(ssh);
5362 c->pending_eof = FALSE;
5363 c->throttling_conn = 0;
5364 c->type = CHAN_X11; /* identify channel type */
5365 add234(ssh->channels, c);
5366 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5367 PKT_INT, c->remoteid, PKT_INT,
5368 c->localid, PKT_END);
5369 logevent("Opened X11 forward channel");
5373 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5375 /* Remote side is trying to open a channel to talk to our
5376 * agent. Give them back a local channel number. */
5377 struct ssh_channel *c;
5378 int remoteid = ssh_pkt_getuint32(pktin);
5380 /* Refuse if agent forwarding is disabled. */
5381 if (!ssh->agentfwd_enabled) {
5382 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5383 PKT_INT, remoteid, PKT_END);
5385 c = snew(struct ssh_channel);
5387 c->remoteid = remoteid;
5388 c->halfopen = FALSE;
5389 c->localid = alloc_channel_id(ssh);
5391 c->pending_eof = FALSE;
5392 c->throttling_conn = 0;
5393 c->type = CHAN_AGENT; /* identify channel type */
5394 c->u.a.lensofar = 0;
5395 c->u.a.message = NULL;
5396 c->u.a.outstanding_requests = 0;
5397 add234(ssh->channels, c);
5398 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5399 PKT_INT, c->remoteid, PKT_INT, c->localid,
5404 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5406 /* Remote side is trying to open a channel to talk to a
5407 * forwarded port. Give them back a local channel number. */
5408 struct ssh_rportfwd pf, *pfp;
5414 remoteid = ssh_pkt_getuint32(pktin);
5415 ssh_pkt_getstring(pktin, &host, &hostsize);
5416 port = ssh_pkt_getuint32(pktin);
5418 pf.dhost = dupprintf("%.*s", hostsize, host);
5420 pfp = find234(ssh->rportfwds, &pf, NULL);
5423 logeventf(ssh, "Rejected remote port open request for %s:%d",
5425 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5426 PKT_INT, remoteid, PKT_END);
5428 struct ssh_channel *c = snew(struct ssh_channel);
5431 logeventf(ssh, "Received remote port open request for %s:%d",
5433 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5434 c, ssh->conf, pfp->pfrec->addressfamily);
5436 logeventf(ssh, "Port open failed: %s", err);
5439 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5440 PKT_INT, remoteid, PKT_END);
5442 c->remoteid = remoteid;
5443 c->halfopen = FALSE;
5444 c->localid = alloc_channel_id(ssh);
5446 c->pending_eof = FALSE;
5447 c->throttling_conn = 0;
5448 c->type = CHAN_SOCKDATA; /* identify channel type */
5449 add234(ssh->channels, c);
5450 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5451 PKT_INT, c->remoteid, PKT_INT,
5452 c->localid, PKT_END);
5453 logevent("Forwarded port opened successfully");
5460 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5462 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5463 unsigned int localid = ssh_pkt_getuint32(pktin);
5464 struct ssh_channel *c;
5466 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5467 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5468 c->remoteid = localid;
5469 c->halfopen = FALSE;
5470 c->type = CHAN_SOCKDATA;
5471 c->throttling_conn = 0;
5472 pfd_confirm(c->u.pfd.pf);
5475 if (c && c->pending_eof) {
5477 * We have a pending close on this channel,
5478 * which we decided on before the server acked
5479 * the channel open. So now we know the
5480 * remoteid, we can close it again.
5482 ssh_channel_try_eof(c);
5486 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5488 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5489 struct ssh_channel *c;
5491 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5492 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5493 logevent("Forwarded connection refused by server");
5494 pfd_close(c->u.pfd.pf);
5495 del234(ssh->channels, c);
5500 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5502 /* Remote side closes a channel. */
5503 unsigned i = ssh_pkt_getuint32(pktin);
5504 struct ssh_channel *c;
5505 c = find234(ssh->channels, &i, ssh_channelfind);
5506 if (c && !c->halfopen) {
5508 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5509 !(c->closes & CLOSES_RCVD_EOF)) {
5511 * Received CHANNEL_CLOSE, which we translate into
5514 int send_close = FALSE;
5516 c->closes |= CLOSES_RCVD_EOF;
5521 x11_send_eof(c->u.x11.xconn);
5527 pfd_send_eof(c->u.pfd.pf);
5536 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5537 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5539 c->closes |= CLOSES_SENT_EOF;
5543 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5544 !(c->closes & CLOSES_RCVD_CLOSE)) {
5546 if (!(c->closes & CLOSES_SENT_EOF)) {
5547 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5548 " for which we never sent CHANNEL_CLOSE\n", i));
5551 c->closes |= CLOSES_RCVD_CLOSE;
5554 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5555 !(c->closes & CLOSES_SENT_CLOSE)) {
5556 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5557 PKT_INT, c->remoteid, PKT_END);
5558 c->closes |= CLOSES_SENT_CLOSE;
5561 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5562 ssh_channel_destroy(c);
5564 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5565 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5566 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5571 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5573 /* Data sent down one of our channels. */
5574 int i = ssh_pkt_getuint32(pktin);
5577 struct ssh_channel *c;
5579 ssh_pkt_getstring(pktin, &p, &len);
5581 c = find234(ssh->channels, &i, ssh_channelfind);
5586 bufsize = x11_send(c->u.x11.xconn, p, len);
5589 bufsize = pfd_send(c->u.pfd.pf, p, len);
5592 /* Data for an agent message. Buffer it. */
5594 if (c->u.a.lensofar < 4) {
5595 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5596 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5600 c->u.a.lensofar += l;
5602 if (c->u.a.lensofar == 4) {
5604 4 + GET_32BIT(c->u.a.msglen);
5605 c->u.a.message = snewn(c->u.a.totallen,
5607 memcpy(c->u.a.message, c->u.a.msglen, 4);
5609 if (c->u.a.lensofar >= 4 && len > 0) {
5611 min(c->u.a.totallen - c->u.a.lensofar,
5613 memcpy(c->u.a.message + c->u.a.lensofar, p,
5617 c->u.a.lensofar += l;
5619 if (c->u.a.lensofar == c->u.a.totallen) {
5622 c->u.a.outstanding_requests++;
5623 if (agent_query(c->u.a.message,
5626 ssh_agentf_callback, c))
5627 ssh_agentf_callback(c, reply, replylen);
5628 sfree(c->u.a.message);
5629 c->u.a.lensofar = 0;
5632 bufsize = 0; /* agent channels never back up */
5635 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5636 c->throttling_conn = 1;
5637 ssh_throttle_conn(ssh, +1);
5642 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5644 ssh->exitcode = ssh_pkt_getuint32(pktin);
5645 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5646 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5648 * In case `helpful' firewalls or proxies tack
5649 * extra human-readable text on the end of the
5650 * session which we might mistake for another
5651 * encrypted packet, we close the session once
5652 * we've sent EXIT_CONFIRMATION.
5654 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5657 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5658 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5660 struct Packet *pktout = (struct Packet *)data;
5662 unsigned int arg = 0;
5663 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5664 if (i == lenof(ssh_ttymodes)) return;
5665 switch (ssh_ttymodes[i].type) {
5667 arg = ssh_tty_parse_specchar(val);
5670 arg = ssh_tty_parse_boolean(val);
5673 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5674 ssh2_pkt_addbyte(pktout, arg);
5677 int ssh_agent_forwarding_permitted(Ssh ssh)
5679 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5682 static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5683 struct Packet *pktin)
5685 crBegin(ssh->do_ssh1_connection_crstate);
5687 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5688 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5689 ssh1_smsg_stdout_stderr_data;
5691 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5692 ssh1_msg_channel_open_confirmation;
5693 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5694 ssh1_msg_channel_open_failure;
5695 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5696 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5697 ssh1_msg_channel_close;
5698 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5699 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5701 if (ssh_agent_forwarding_permitted(ssh)) {
5702 logevent("Requesting agent forwarding");
5703 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5707 if (pktin->type != SSH1_SMSG_SUCCESS
5708 && pktin->type != SSH1_SMSG_FAILURE) {
5709 bombout(("Protocol confusion"));
5711 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5712 logevent("Agent forwarding refused");
5714 logevent("Agent forwarding enabled");
5715 ssh->agentfwd_enabled = TRUE;
5716 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5720 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5722 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5724 if (!ssh->x11disp) {
5725 /* FIXME: return an error message from x11_setup_display */
5726 logevent("X11 forwarding not enabled: unable to"
5727 " initialise X display");
5729 ssh->x11auth = x11_invent_fake_auth
5730 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5731 ssh->x11auth->disp = ssh->x11disp;
5733 logevent("Requesting X11 forwarding");
5734 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5735 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5736 PKT_STR, ssh->x11auth->protoname,
5737 PKT_STR, ssh->x11auth->datastring,
5738 PKT_INT, ssh->x11disp->screennum,
5741 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5742 PKT_STR, ssh->x11auth->protoname,
5743 PKT_STR, ssh->x11auth->datastring,
5749 if (pktin->type != SSH1_SMSG_SUCCESS
5750 && pktin->type != SSH1_SMSG_FAILURE) {
5751 bombout(("Protocol confusion"));
5753 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5754 logevent("X11 forwarding refused");
5756 logevent("X11 forwarding enabled");
5757 ssh->X11_fwd_enabled = TRUE;
5758 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5763 ssh_setup_portfwd(ssh, ssh->conf);
5764 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5766 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5768 /* Unpick the terminal-speed string. */
5769 /* XXX perhaps we should allow no speeds to be sent. */
5770 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5771 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5772 /* Send the pty request. */
5773 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5774 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5775 ssh_pkt_adduint32(pkt, ssh->term_height);
5776 ssh_pkt_adduint32(pkt, ssh->term_width);
5777 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5778 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5779 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5780 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5781 ssh_pkt_adduint32(pkt, ssh->ispeed);
5782 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5783 ssh_pkt_adduint32(pkt, ssh->ospeed);
5784 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5786 ssh->state = SSH_STATE_INTERMED;
5790 if (pktin->type != SSH1_SMSG_SUCCESS
5791 && pktin->type != SSH1_SMSG_FAILURE) {
5792 bombout(("Protocol confusion"));
5794 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5795 c_write_str(ssh, "Server refused to allocate pty\r\n");
5796 ssh->editing = ssh->echoing = 1;
5798 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5799 ssh->ospeed, ssh->ispeed);
5800 ssh->got_pty = TRUE;
5803 ssh->editing = ssh->echoing = 1;
5806 if (conf_get_int(ssh->conf, CONF_compression)) {
5807 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5811 if (pktin->type != SSH1_SMSG_SUCCESS
5812 && pktin->type != SSH1_SMSG_FAILURE) {
5813 bombout(("Protocol confusion"));
5815 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5816 c_write_str(ssh, "Server refused to compress\r\n");
5818 logevent("Started compression");
5819 ssh->v1_compressing = TRUE;
5820 ssh->cs_comp_ctx = zlib_compress_init();
5821 logevent("Initialised zlib (RFC1950) compression");
5822 ssh->sc_comp_ctx = zlib_decompress_init();
5823 logevent("Initialised zlib (RFC1950) decompression");
5827 * Start the shell or command.
5829 * Special case: if the first-choice command is an SSH-2
5830 * subsystem (hence not usable here) and the second choice
5831 * exists, we fall straight back to that.
5834 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5836 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5837 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5838 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5839 ssh->fallback_cmd = TRUE;
5842 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5844 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5845 logevent("Started session");
5848 ssh->state = SSH_STATE_SESSION;
5849 if (ssh->size_needed)
5850 ssh_size(ssh, ssh->term_width, ssh->term_height);
5851 if (ssh->eof_needed)
5852 ssh_special(ssh, TS_EOF);
5855 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
5857 ssh->channels = newtree234(ssh_channelcmp);
5861 * By this point, most incoming packets are already being
5862 * handled by the dispatch table, and we need only pay
5863 * attention to the unusual ones.
5868 if (pktin->type == SSH1_SMSG_SUCCESS) {
5869 /* may be from EXEC_SHELL on some servers */
5870 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5871 /* may be from EXEC_SHELL on some servers
5872 * if no pty is available or in other odd cases. Ignore */
5874 bombout(("Strange packet received: type %d", pktin->type));
5879 int len = min(inlen, 512);
5880 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5881 PKT_INT, len, PKT_DATA, in, len,
5893 * Handle the top-level SSH-2 protocol.
5895 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5900 ssh_pkt_getstring(pktin, &msg, &msglen);
5901 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
5904 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5906 /* log reason code in disconnect message */
5910 ssh_pkt_getstring(pktin, &msg, &msglen);
5911 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5914 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
5916 /* Do nothing, because we're ignoring it! Duhh. */
5919 static void ssh1_protocol_setup(Ssh ssh)
5924 * Most messages are handled by the coroutines.
5926 for (i = 0; i < 256; i++)
5927 ssh->packet_dispatch[i] = NULL;
5930 * These special message types we install handlers for.
5932 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5933 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5934 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5937 static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
5938 struct Packet *pktin)
5940 unsigned char *in=(unsigned char*)vin;
5941 if (ssh->state == SSH_STATE_CLOSED)
5944 if (pktin && ssh->packet_dispatch[pktin->type]) {
5945 ssh->packet_dispatch[pktin->type](ssh, pktin);
5949 if (!ssh->protocol_initial_phase_done) {
5950 if (do_ssh1_login(ssh, in, inlen, pktin))
5951 ssh->protocol_initial_phase_done = TRUE;
5956 do_ssh1_connection(ssh, in, inlen, pktin);
5960 * Utility routine for decoding comma-separated strings in KEXINIT.
5962 static int in_commasep_string(char const *needle, char const *haystack,
5966 if (!needle || !haystack) /* protect against null pointers */
5968 needlen = strlen(needle);
5971 * Is it at the start of the string?
5973 if (haylen >= needlen && /* haystack is long enough */
5974 !memcmp(needle, haystack, needlen) && /* initial match */
5975 (haylen == needlen || haystack[needlen] == ',')
5976 /* either , or EOS follows */
5980 * If not, search for the next comma and resume after that.
5981 * If no comma found, terminate.
5983 while (haylen > 0 && *haystack != ',')
5984 haylen--, haystack++;
5987 haylen--, haystack++; /* skip over comma itself */
5992 * Similar routine for checking whether we have the first string in a list.
5994 static int first_in_commasep_string(char const *needle, char const *haystack,
5998 if (!needle || !haystack) /* protect against null pointers */
6000 needlen = strlen(needle);
6002 * Is it at the start of the string?
6004 if (haylen >= needlen && /* haystack is long enough */
6005 !memcmp(needle, haystack, needlen) && /* initial match */
6006 (haylen == needlen || haystack[needlen] == ',')
6007 /* either , or EOS follows */
6014 * Add a value to the comma-separated string at the end of the packet.
6015 * If the value is already in the string, don't bother adding it again.
6017 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6019 if (in_commasep_string(data, (char *)pkt->data + pkt->savedpos,
6020 pkt->length - pkt->savedpos)) return;
6021 if (pkt->length - pkt->savedpos > 0)
6022 ssh_pkt_addstring_str(pkt, ",");
6023 ssh_pkt_addstring_str(pkt, data);
6028 * SSH-2 key creation method.
6029 * (Currently assumes 2 lots of any hash are sufficient to generate
6030 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
6032 #define SSH2_MKKEY_ITERS (2)
6033 static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
6034 unsigned char *keyspace)
6036 const struct ssh_hash *h = ssh->kex->hash;
6038 /* First hlen bytes. */
6040 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6041 hash_mpint(h, s, K);
6042 h->bytes(s, H, h->hlen);
6043 h->bytes(s, &chr, 1);
6044 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6045 h->final(s, keyspace);
6046 /* Next hlen bytes. */
6048 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6049 hash_mpint(h, s, K);
6050 h->bytes(s, H, h->hlen);
6051 h->bytes(s, keyspace, h->hlen);
6052 h->final(s, keyspace + h->hlen);
6056 * Handle the SSH-2 transport layer.
6058 static void do_ssh2_transport(Ssh ssh, void *vin, int inlen,
6059 struct Packet *pktin)
6061 unsigned char *in = (unsigned char *)vin;
6062 struct do_ssh2_transport_state {
6064 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
6065 Bignum p, g, e, f, K;
6068 int kex_init_value, kex_reply_value;
6069 const struct ssh_mac **maclist;
6071 const struct ssh2_cipher *cscipher_tobe;
6072 const struct ssh2_cipher *sccipher_tobe;
6073 const struct ssh_mac *csmac_tobe;
6074 const struct ssh_mac *scmac_tobe;
6075 const struct ssh_compress *cscomp_tobe;
6076 const struct ssh_compress *sccomp_tobe;
6077 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6078 int hostkeylen, siglen, rsakeylen;
6079 void *hkey; /* actual host key */
6080 void *rsakey; /* for RSA kex */
6081 void *eckey; /* for ECDH kex */
6082 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6083 int n_preferred_kex;
6084 const struct ssh_kexes *preferred_kex[KEX_MAX];
6085 int n_preferred_ciphers;
6086 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6087 const struct ssh_compress *preferred_comp;
6088 int userauth_succeeded; /* for delayed compression */
6089 int pending_compression;
6090 int got_session_id, activated_authconn;
6091 struct Packet *pktout;
6096 crState(do_ssh2_transport_state);
6098 assert(!ssh->bare_connection);
6102 s->cscipher_tobe = s->sccipher_tobe = NULL;
6103 s->csmac_tobe = s->scmac_tobe = NULL;
6104 s->cscomp_tobe = s->sccomp_tobe = NULL;
6106 s->got_session_id = s->activated_authconn = FALSE;
6107 s->userauth_succeeded = FALSE;
6108 s->pending_compression = FALSE;
6111 * Be prepared to work around the buggy MAC problem.
6113 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6114 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6116 s->maclist = macs, s->nmacs = lenof(macs);
6119 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6124 * Set up the preferred key exchange. (NULL => warn below here)
6126 s->n_preferred_kex = 0;
6127 for (i = 0; i < KEX_MAX; i++) {
6128 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6130 s->preferred_kex[s->n_preferred_kex++] =
6131 &ssh_diffiehellman_gex;
6134 s->preferred_kex[s->n_preferred_kex++] =
6135 &ssh_diffiehellman_group14;
6138 s->preferred_kex[s->n_preferred_kex++] =
6139 &ssh_diffiehellman_group1;
6142 s->preferred_kex[s->n_preferred_kex++] =
6146 s->preferred_kex[s->n_preferred_kex++] =
6150 /* Flag for later. Don't bother if it's the last in
6152 if (i < KEX_MAX - 1) {
6153 s->preferred_kex[s->n_preferred_kex++] = NULL;
6160 * Set up the preferred ciphers. (NULL => warn below here)
6162 s->n_preferred_ciphers = 0;
6163 for (i = 0; i < CIPHER_MAX; i++) {
6164 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6165 case CIPHER_BLOWFISH:
6166 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6169 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6170 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6174 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6177 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6179 case CIPHER_ARCFOUR:
6180 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6183 /* Flag for later. Don't bother if it's the last in
6185 if (i < CIPHER_MAX - 1) {
6186 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6193 * Set up preferred compression.
6195 if (conf_get_int(ssh->conf, CONF_compression))
6196 s->preferred_comp = &ssh_zlib;
6198 s->preferred_comp = &ssh_comp_none;
6201 * Enable queueing of outgoing auth- or connection-layer
6202 * packets while we are in the middle of a key exchange.
6204 ssh->queueing = TRUE;
6207 * Flag that KEX is in progress.
6209 ssh->kex_in_progress = TRUE;
6212 * Construct and send our key exchange packet.
6214 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6215 for (i = 0; i < 16; i++)
6216 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6217 /* List key exchange algorithms. */
6218 ssh2_pkt_addstring_start(s->pktout);
6219 for (i = 0; i < s->n_preferred_kex; i++) {
6220 const struct ssh_kexes *k = s->preferred_kex[i];
6221 if (!k) continue; /* warning flag */
6222 for (j = 0; j < k->nkexes; j++)
6223 ssh2_pkt_addstring_commasep(s->pktout, k->list[j]->name);
6225 /* List server host key algorithms. */
6226 if (!s->got_session_id) {
6228 * In the first key exchange, we list all the algorithms
6229 * we're prepared to cope with.
6231 ssh2_pkt_addstring_start(s->pktout);
6232 for (i = 0; i < lenof(hostkey_algs); i++)
6233 ssh2_pkt_addstring_commasep(s->pktout, hostkey_algs[i]->name);
6236 * In subsequent key exchanges, we list only the kex
6237 * algorithm that was selected in the first key exchange,
6238 * so that we keep getting the same host key and hence
6239 * don't have to interrupt the user's session to ask for
6243 ssh2_pkt_addstring(s->pktout, ssh->hostkey->name);
6245 /* List encryption algorithms (client->server then server->client). */
6246 for (k = 0; k < 2; k++) {
6247 ssh2_pkt_addstring_start(s->pktout);
6248 for (i = 0; i < s->n_preferred_ciphers; i++) {
6249 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6250 if (!c) continue; /* warning flag */
6251 for (j = 0; j < c->nciphers; j++)
6252 ssh2_pkt_addstring_commasep(s->pktout, c->list[j]->name);
6255 /* List MAC algorithms (client->server then server->client). */
6256 for (j = 0; j < 2; j++) {
6257 ssh2_pkt_addstring_start(s->pktout);
6258 for (i = 0; i < s->nmacs; i++)
6259 ssh2_pkt_addstring_commasep(s->pktout, s->maclist[i]->name);
6261 /* List client->server compression algorithms,
6262 * then server->client compression algorithms. (We use the
6263 * same set twice.) */
6264 for (j = 0; j < 2; j++) {
6265 ssh2_pkt_addstring_start(s->pktout);
6266 assert(lenof(compressions) > 1);
6267 /* Prefer non-delayed versions */
6268 ssh2_pkt_addstring_commasep(s->pktout, s->preferred_comp->name);
6269 /* We don't even list delayed versions of algorithms until
6270 * they're allowed to be used, to avoid a race. See the end of
6272 if (s->userauth_succeeded && s->preferred_comp->delayed_name)
6273 ssh2_pkt_addstring_commasep(s->pktout,
6274 s->preferred_comp->delayed_name);
6275 for (i = 0; i < lenof(compressions); i++) {
6276 const struct ssh_compress *c = compressions[i];
6277 ssh2_pkt_addstring_commasep(s->pktout, c->name);
6278 if (s->userauth_succeeded && c->delayed_name)
6279 ssh2_pkt_addstring_commasep(s->pktout, c->delayed_name);
6282 /* List client->server languages. Empty list. */
6283 ssh2_pkt_addstring_start(s->pktout);
6284 /* List server->client languages. Empty list. */
6285 ssh2_pkt_addstring_start(s->pktout);
6286 /* First KEX packet does _not_ follow, because we're not that brave. */
6287 ssh2_pkt_addbool(s->pktout, FALSE);
6289 ssh2_pkt_adduint32(s->pktout, 0);
6292 s->our_kexinitlen = s->pktout->length - 5;
6293 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6294 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6296 ssh2_pkt_send_noqueue(ssh, s->pktout);
6299 crWaitUntilV(pktin);
6302 * Now examine the other side's KEXINIT to see what we're up
6306 char *str, *preferred;
6309 if (pktin->type != SSH2_MSG_KEXINIT) {
6310 bombout(("expected key exchange packet from server"));
6314 ssh->hostkey = NULL;
6315 s->cscipher_tobe = NULL;
6316 s->sccipher_tobe = NULL;
6317 s->csmac_tobe = NULL;
6318 s->scmac_tobe = NULL;
6319 s->cscomp_tobe = NULL;
6320 s->sccomp_tobe = NULL;
6321 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
6323 pktin->savedpos += 16; /* skip garbage cookie */
6324 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
6326 bombout(("KEXINIT packet was incomplete"));
6331 for (i = 0; i < s->n_preferred_kex; i++) {
6332 const struct ssh_kexes *k = s->preferred_kex[i];
6336 for (j = 0; j < k->nkexes; j++) {
6337 if (!preferred) preferred = k->list[j]->name;
6338 if (in_commasep_string(k->list[j]->name, str, len)) {
6339 ssh->kex = k->list[j];
6348 bombout(("Couldn't agree a key exchange algorithm"
6349 " (available: %.*s)", len, str));
6353 * Note that the server's guess is considered wrong if it doesn't match
6354 * the first algorithm in our list, even if it's still the algorithm
6357 s->guessok = first_in_commasep_string(preferred, str, len);
6358 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
6360 bombout(("KEXINIT packet was incomplete"));
6363 for (i = 0; i < lenof(hostkey_algs); i++) {
6364 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
6365 ssh->hostkey = hostkey_algs[i];
6369 if (!ssh->hostkey) {
6370 bombout(("Couldn't agree a host key algorithm"
6371 " (available: %.*s)", len, str));
6375 s->guessok = s->guessok &&
6376 first_in_commasep_string(hostkey_algs[0]->name, str, len);
6377 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
6379 bombout(("KEXINIT packet was incomplete"));
6382 for (i = 0; i < s->n_preferred_ciphers; i++) {
6383 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6385 s->warn_cscipher = TRUE;
6387 for (j = 0; j < c->nciphers; j++) {
6388 if (in_commasep_string(c->list[j]->name, str, len)) {
6389 s->cscipher_tobe = c->list[j];
6394 if (s->cscipher_tobe)
6397 if (!s->cscipher_tobe) {
6398 bombout(("Couldn't agree a client-to-server cipher"
6399 " (available: %.*s)", len, str));
6403 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
6405 bombout(("KEXINIT packet was incomplete"));
6408 for (i = 0; i < s->n_preferred_ciphers; i++) {
6409 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6411 s->warn_sccipher = TRUE;
6413 for (j = 0; j < c->nciphers; j++) {
6414 if (in_commasep_string(c->list[j]->name, str, len)) {
6415 s->sccipher_tobe = c->list[j];
6420 if (s->sccipher_tobe)
6423 if (!s->sccipher_tobe) {
6424 bombout(("Couldn't agree a server-to-client cipher"
6425 " (available: %.*s)", len, str));
6429 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
6431 bombout(("KEXINIT packet was incomplete"));
6434 for (i = 0; i < s->nmacs; i++) {
6435 if (in_commasep_string(s->maclist[i]->name, str, len)) {
6436 s->csmac_tobe = s->maclist[i];
6440 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
6442 bombout(("KEXINIT packet was incomplete"));
6445 for (i = 0; i < s->nmacs; i++) {
6446 if (in_commasep_string(s->maclist[i]->name, str, len)) {
6447 s->scmac_tobe = s->maclist[i];
6451 ssh_pkt_getstring(pktin, &str, &len); /* client->server 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 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
6473 bombout(("KEXINIT packet was incomplete"));
6476 for (i = 0; i < lenof(compressions) + 1; i++) {
6477 const struct ssh_compress *c =
6478 i == 0 ? s->preferred_comp : compressions[i - 1];
6479 if (in_commasep_string(c->name, str, len)) {
6482 } else if (in_commasep_string(c->delayed_name, str, len)) {
6483 if (s->userauth_succeeded) {
6487 s->pending_compression = TRUE; /* try this later */
6491 if (s->pending_compression) {
6492 logevent("Server supports delayed compression; "
6493 "will try this later");
6495 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6496 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6497 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6499 ssh->exhash = ssh->kex->hash->init();
6500 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6501 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6502 hash_string(ssh->kex->hash, ssh->exhash,
6503 s->our_kexinit, s->our_kexinitlen);
6504 sfree(s->our_kexinit);
6505 /* Include the type byte in the hash of server's KEXINIT */
6506 hash_string(ssh->kex->hash, ssh->exhash,
6507 pktin->body - 1, pktin->length + 1);
6510 ssh_set_frozen(ssh, 1);
6511 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6513 ssh_dialog_callback, ssh);
6514 if (s->dlgret < 0) {
6518 bombout(("Unexpected data from server while"
6519 " waiting for user response"));
6522 } while (pktin || inlen > 0);
6523 s->dlgret = ssh->user_response;
6525 ssh_set_frozen(ssh, 0);
6526 if (s->dlgret == 0) {
6527 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6533 if (s->warn_cscipher) {
6534 ssh_set_frozen(ssh, 1);
6535 s->dlgret = askalg(ssh->frontend,
6536 "client-to-server cipher",
6537 s->cscipher_tobe->name,
6538 ssh_dialog_callback, ssh);
6539 if (s->dlgret < 0) {
6543 bombout(("Unexpected data from server while"
6544 " waiting for user response"));
6547 } while (pktin || inlen > 0);
6548 s->dlgret = ssh->user_response;
6550 ssh_set_frozen(ssh, 0);
6551 if (s->dlgret == 0) {
6552 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6558 if (s->warn_sccipher) {
6559 ssh_set_frozen(ssh, 1);
6560 s->dlgret = askalg(ssh->frontend,
6561 "server-to-client cipher",
6562 s->sccipher_tobe->name,
6563 ssh_dialog_callback, ssh);
6564 if (s->dlgret < 0) {
6568 bombout(("Unexpected data from server while"
6569 " waiting for user response"));
6572 } while (pktin || inlen > 0);
6573 s->dlgret = ssh->user_response;
6575 ssh_set_frozen(ssh, 0);
6576 if (s->dlgret == 0) {
6577 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6583 if (s->ignorepkt) /* first_kex_packet_follows */
6584 crWaitUntilV(pktin); /* Ignore packet */
6587 if (ssh->kex->main_type == KEXTYPE_DH) {
6589 * Work out the number of bits of key we will need from the
6590 * key exchange. We start with the maximum key length of
6596 csbits = s->cscipher_tobe->keylen;
6597 scbits = s->sccipher_tobe->keylen;
6598 s->nbits = (csbits > scbits ? csbits : scbits);
6600 /* The keys only have hlen-bit entropy, since they're based on
6601 * a hash. So cap the key size at hlen bits. */
6602 if (s->nbits > ssh->kex->hash->hlen * 8)
6603 s->nbits = ssh->kex->hash->hlen * 8;
6606 * If we're doing Diffie-Hellman group exchange, start by
6607 * requesting a group.
6609 if (!ssh->kex->pdata) {
6610 logevent("Doing Diffie-Hellman group exchange");
6611 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6613 * Work out how big a DH group we will need to allow that
6616 s->pbits = 512 << ((s->nbits - 1) / 64);
6617 if (s->pbits < DH_MIN_SIZE)
6618 s->pbits = DH_MIN_SIZE;
6619 if (s->pbits > DH_MAX_SIZE)
6620 s->pbits = DH_MAX_SIZE;
6621 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6622 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6623 ssh2_pkt_adduint32(s->pktout, s->pbits);
6625 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6626 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6627 ssh2_pkt_adduint32(s->pktout, s->pbits);
6628 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6630 ssh2_pkt_send_noqueue(ssh, s->pktout);
6632 crWaitUntilV(pktin);
6633 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6634 bombout(("expected key exchange group packet from server"));
6637 s->p = ssh2_pkt_getmp(pktin);
6638 s->g = ssh2_pkt_getmp(pktin);
6639 if (!s->p || !s->g) {
6640 bombout(("unable to read mp-ints from incoming group packet"));
6643 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6644 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6645 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6647 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6648 ssh->kex_ctx = dh_setup_group(ssh->kex);
6649 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6650 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6651 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6652 ssh->kex->groupname);
6655 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6656 ssh->kex->hash->text_name);
6658 * Now generate and send e for Diffie-Hellman.
6660 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6661 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6662 s->pktout = ssh2_pkt_init(s->kex_init_value);
6663 ssh2_pkt_addmp(s->pktout, s->e);
6664 ssh2_pkt_send_noqueue(ssh, s->pktout);
6666 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6667 crWaitUntilV(pktin);
6668 if (pktin->type != s->kex_reply_value) {
6669 bombout(("expected key exchange reply packet from server"));
6672 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6673 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6674 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6675 s->f = ssh2_pkt_getmp(pktin);
6677 bombout(("unable to parse key exchange reply packet"));
6680 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6683 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
6685 bombout(("key exchange reply failed validation: %s", err));
6689 s->K = dh_find_K(ssh->kex_ctx, s->f);
6691 /* We assume everything from now on will be quick, and it might
6692 * involve user interaction. */
6693 set_busy_status(ssh->frontend, BUSY_NOT);
6695 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6696 if (!ssh->kex->pdata) {
6697 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6698 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
6699 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6700 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6701 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
6702 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6703 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6705 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6706 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6708 dh_cleanup(ssh->kex_ctx);
6710 if (!ssh->kex->pdata) {
6714 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
6716 logeventf(ssh, "Doing ECDH key exchange with hash %s",
6717 ssh->kex->hash->text_name);
6718 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
6721 if (!strcmp(ssh->kex->name, "ecdh-sha2-nistp256")) {
6722 s->eckey = ssh_ecdhkex_newkey(ec_p256());
6723 } else if (!strcmp(ssh->kex->name, "ecdh-sha2-nistp384")) {
6724 s->eckey = ssh_ecdhkex_newkey(ec_p384());
6725 } else if (!strcmp(ssh->kex->name, "ecdh-sha2-nistp521")) {
6726 s->eckey = ssh_ecdhkex_newkey(ec_p521());
6729 bombout(("Unable to generate key for ECDH"));
6735 int publicPointLength;
6736 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6738 ssh_ecdhkex_freekey(s->eckey);
6739 bombout(("Unable to encode public key for ECDH"));
6742 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
6743 ssh2_pkt_addstring_start(s->pktout);
6744 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
6748 ssh2_pkt_send_noqueue(ssh, s->pktout);
6750 crWaitUntilV(pktin);
6751 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
6752 ssh_ecdhkex_freekey(s->eckey);
6753 bombout(("expected ECDH reply packet from server"));
6757 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6758 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6759 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6763 int publicPointLength;
6764 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6766 ssh_ecdhkex_freekey(s->eckey);
6767 bombout(("Unable to encode public key for ECDH hash"));
6770 hash_string(ssh->kex->hash, ssh->exhash,
6771 publicPoint, publicPointLength);
6778 ssh_pkt_getstring(pktin, &keydata, &keylen);
6779 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
6780 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
6782 ssh_ecdhkex_freekey(s->eckey);
6783 bombout(("point received in ECDH was not valid"));
6788 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6790 ssh_ecdhkex_freekey(s->eckey);
6792 logeventf(ssh, "Doing RSA key exchange with hash %s",
6793 ssh->kex->hash->text_name);
6794 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
6796 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6799 crWaitUntilV(pktin);
6800 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6801 bombout(("expected RSA public key packet from server"));
6805 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6806 hash_string(ssh->kex->hash, ssh->exhash,
6807 s->hostkeydata, s->hostkeylen);
6808 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6812 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6813 s->rsakeydata = snewn(s->rsakeylen, char);
6814 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6817 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6819 sfree(s->rsakeydata);
6820 bombout(("unable to parse RSA public key from server"));
6824 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6827 * Next, set up a shared secret K, of precisely KLEN -
6828 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6829 * RSA key modulus and HLEN is the bit length of the hash
6833 int klen = ssh_rsakex_klen(s->rsakey);
6834 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6836 unsigned char *kstr1, *kstr2, *outstr;
6837 int kstr1len, kstr2len, outstrlen;
6839 s->K = bn_power_2(nbits - 1);
6841 for (i = 0; i < nbits; i++) {
6843 byte = random_byte();
6845 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6849 * Encode this as an mpint.
6851 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6852 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6853 PUT_32BIT(kstr2, kstr1len);
6854 memcpy(kstr2 + 4, kstr1, kstr1len);
6857 * Encrypt it with the given RSA key.
6859 outstrlen = (klen + 7) / 8;
6860 outstr = snewn(outstrlen, unsigned char);
6861 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6862 outstr, outstrlen, s->rsakey);
6865 * And send it off in a return packet.
6867 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6868 ssh2_pkt_addstring_start(s->pktout);
6869 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
6870 ssh2_pkt_send_noqueue(ssh, s->pktout);
6872 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6879 ssh_rsakex_freekey(s->rsakey);
6881 crWaitUntilV(pktin);
6882 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6883 sfree(s->rsakeydata);
6884 bombout(("expected signature packet from server"));
6888 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6890 sfree(s->rsakeydata);
6893 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6894 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6895 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
6897 ssh->kex_ctx = NULL;
6900 debug(("Exchange hash is:\n"));
6901 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
6905 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
6906 (char *)s->exchange_hash,
6907 ssh->kex->hash->hlen)) {
6908 bombout(("Server's host key did not match the signature supplied"));
6912 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6913 if (!s->got_session_id) {
6915 * Authenticate remote host: verify host key. (We've already
6916 * checked the signature of the exchange hash.)
6918 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
6919 logevent("Host key fingerprint is:");
6920 logevent(s->fingerprint);
6921 /* First check against manually configured host keys. */
6922 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
6923 ssh->hostkey, s->hkey);
6924 if (s->dlgret == 0) { /* did not match */
6925 bombout(("Host key did not appear in manually configured list"));
6927 } else if (s->dlgret < 0) { /* none configured; use standard handling */
6928 ssh_set_frozen(ssh, 1);
6929 s->dlgret = verify_ssh_host_key(ssh->frontend,
6930 ssh->savedhost, ssh->savedport,
6931 ssh->hostkey->keytype, s->keystr,
6933 ssh_dialog_callback, ssh);
6934 if (s->dlgret < 0) {
6938 bombout(("Unexpected data from server while waiting"
6939 " for user host key response"));
6942 } while (pktin || inlen > 0);
6943 s->dlgret = ssh->user_response;
6945 ssh_set_frozen(ssh, 0);
6946 if (s->dlgret == 0) {
6947 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
6952 sfree(s->fingerprint);
6954 * Save this host key, to check against the one presented in
6955 * subsequent rekeys.
6957 ssh->hostkey_str = s->keystr;
6960 * In a rekey, we never present an interactive host key
6961 * verification request to the user. Instead, we simply
6962 * enforce that the key we're seeing this time is identical to
6963 * the one we saw before.
6965 if (strcmp(ssh->hostkey_str, s->keystr)) {
6966 bombout(("Host key was different in repeat key exchange"));
6971 ssh->hostkey->freekey(s->hkey);
6974 * The exchange hash from the very first key exchange is also
6975 * the session id, used in session key construction and
6978 if (!s->got_session_id) {
6979 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
6980 memcpy(ssh->v2_session_id, s->exchange_hash,
6981 sizeof(s->exchange_hash));
6982 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6983 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
6984 s->got_session_id = TRUE;
6988 * Send SSH2_MSG_NEWKEYS.
6990 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
6991 ssh2_pkt_send_noqueue(ssh, s->pktout);
6992 ssh->outgoing_data_size = 0; /* start counting from here */
6995 * We've sent client NEWKEYS, so create and initialise
6996 * client-to-server session keys.
6998 if (ssh->cs_cipher_ctx)
6999 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7000 ssh->cscipher = s->cscipher_tobe;
7001 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7003 if (ssh->cs_mac_ctx)
7004 ssh->csmac->free_context(ssh->cs_mac_ctx);
7005 ssh->csmac = s->csmac_tobe;
7006 ssh->cs_mac_ctx = ssh->csmac->make_context();
7008 if (ssh->cs_comp_ctx)
7009 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7010 ssh->cscomp = s->cscomp_tobe;
7011 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7014 * Set IVs on client-to-server keys. Here we use the exchange
7015 * hash from the _first_ key exchange.
7018 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
7019 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7020 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
7021 assert((ssh->cscipher->keylen+7) / 8 <=
7022 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7023 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
7024 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
7025 assert(ssh->cscipher->blksize <=
7026 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7027 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
7028 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
7029 assert(ssh->csmac->len <=
7030 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7031 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
7032 smemclr(keyspace, sizeof(keyspace));
7035 logeventf(ssh, "Initialised %.200s client->server encryption",
7036 ssh->cscipher->text_name);
7037 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
7038 ssh->csmac->text_name);
7039 if (ssh->cscomp->text_name)
7040 logeventf(ssh, "Initialised %s compression",
7041 ssh->cscomp->text_name);
7044 * Now our end of the key exchange is complete, we can send all
7045 * our queued higher-layer packets.
7047 ssh->queueing = FALSE;
7048 ssh2_pkt_queuesend(ssh);
7051 * Expect SSH2_MSG_NEWKEYS from server.
7053 crWaitUntilV(pktin);
7054 if (pktin->type != SSH2_MSG_NEWKEYS) {
7055 bombout(("expected new-keys packet from server"));
7058 ssh->incoming_data_size = 0; /* start counting from here */
7061 * We've seen server NEWKEYS, so create and initialise
7062 * server-to-client session keys.
7064 if (ssh->sc_cipher_ctx)
7065 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7066 ssh->sccipher = s->sccipher_tobe;
7067 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7069 if (ssh->sc_mac_ctx)
7070 ssh->scmac->free_context(ssh->sc_mac_ctx);
7071 ssh->scmac = s->scmac_tobe;
7072 ssh->sc_mac_ctx = ssh->scmac->make_context();
7074 if (ssh->sc_comp_ctx)
7075 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7076 ssh->sccomp = s->sccomp_tobe;
7077 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7080 * Set IVs on server-to-client keys. Here we use the exchange
7081 * hash from the _first_ key exchange.
7084 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
7085 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7086 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
7087 assert((ssh->sccipher->keylen+7) / 8 <=
7088 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7089 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
7090 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
7091 assert(ssh->sccipher->blksize <=
7092 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7093 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
7094 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
7095 assert(ssh->scmac->len <=
7096 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
7097 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
7098 smemclr(keyspace, sizeof(keyspace));
7100 logeventf(ssh, "Initialised %.200s server->client encryption",
7101 ssh->sccipher->text_name);
7102 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
7103 ssh->scmac->text_name);
7104 if (ssh->sccomp->text_name)
7105 logeventf(ssh, "Initialised %s decompression",
7106 ssh->sccomp->text_name);
7109 * Free shared secret.
7114 * Key exchange is over. Loop straight back round if we have a
7115 * deferred rekey reason.
7117 if (ssh->deferred_rekey_reason) {
7118 logevent(ssh->deferred_rekey_reason);
7120 ssh->deferred_rekey_reason = NULL;
7121 goto begin_key_exchange;
7125 * Otherwise, schedule a timer for our next rekey.
7127 ssh->kex_in_progress = FALSE;
7128 ssh->last_rekey = GETTICKCOUNT();
7129 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7130 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7134 * Now we're encrypting. Begin returning 1 to the protocol main
7135 * function so that other things can run on top of the
7136 * transport. If we ever see a KEXINIT, we must go back to the
7139 * We _also_ go back to the start if we see pktin==NULL and
7140 * inlen negative, because this is a special signal meaning
7141 * `initiate client-driven rekey', and `in' contains a message
7142 * giving the reason for the rekey.
7144 * inlen==-1 means always initiate a rekey;
7145 * inlen==-2 means that userauth has completed successfully and
7146 * we should consider rekeying (for delayed compression).
7148 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7149 (!pktin && inlen < 0))) {
7151 if (!ssh->protocol_initial_phase_done) {
7152 ssh->protocol_initial_phase_done = TRUE;
7154 * Allow authconn to initialise itself.
7156 do_ssh2_authconn(ssh, NULL, 0, NULL);
7161 logevent("Server initiated key re-exchange");
7165 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7166 * delayed compression, if it's available.
7168 * draft-miller-secsh-compression-delayed-00 says that you
7169 * negotiate delayed compression in the first key exchange, and
7170 * both sides start compressing when the server has sent
7171 * USERAUTH_SUCCESS. This has a race condition -- the server
7172 * can't know when the client has seen it, and thus which incoming
7173 * packets it should treat as compressed.
7175 * Instead, we do the initial key exchange without offering the
7176 * delayed methods, but note if the server offers them; when we
7177 * get here, if a delayed method was available that was higher
7178 * on our list than what we got, we initiate a rekey in which we
7179 * _do_ list the delayed methods (and hopefully get it as a
7180 * result). Subsequent rekeys will do the same.
7182 assert(!s->userauth_succeeded); /* should only happen once */
7183 s->userauth_succeeded = TRUE;
7184 if (!s->pending_compression)
7185 /* Can't see any point rekeying. */
7186 goto wait_for_rekey; /* this is utterly horrid */
7187 /* else fall through to rekey... */
7188 s->pending_compression = FALSE;
7191 * Now we've decided to rekey.
7193 * Special case: if the server bug is set that doesn't
7194 * allow rekeying, we give a different log message and
7195 * continue waiting. (If such a server _initiates_ a rekey,
7196 * we process it anyway!)
7198 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7199 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7201 /* Reset the counters, so that at least this message doesn't
7202 * hit the event log _too_ often. */
7203 ssh->outgoing_data_size = 0;
7204 ssh->incoming_data_size = 0;
7205 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7207 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7210 goto wait_for_rekey; /* this is still utterly horrid */
7212 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7215 goto begin_key_exchange;
7221 * Add data to an SSH-2 channel output buffer.
7223 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
7226 bufchain_add(&c->v.v2.outbuffer, buf, len);
7230 * Attempt to send data on an SSH-2 channel.
7232 static int ssh2_try_send(struct ssh_channel *c)
7235 struct Packet *pktout;
7238 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7241 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7242 if ((unsigned)len > c->v.v2.remwindow)
7243 len = c->v.v2.remwindow;
7244 if ((unsigned)len > c->v.v2.remmaxpkt)
7245 len = c->v.v2.remmaxpkt;
7246 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7247 ssh2_pkt_adduint32(pktout, c->remoteid);
7248 ssh2_pkt_addstring_start(pktout);
7249 ssh2_pkt_addstring_data(pktout, data, len);
7250 ssh2_pkt_send(ssh, pktout);
7251 bufchain_consume(&c->v.v2.outbuffer, len);
7252 c->v.v2.remwindow -= len;
7256 * After having sent as much data as we can, return the amount
7259 ret = bufchain_size(&c->v.v2.outbuffer);
7262 * And if there's no data pending but we need to send an EOF, send
7265 if (!ret && c->pending_eof)
7266 ssh_channel_try_eof(c);
7271 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7274 if (c->closes & CLOSES_SENT_EOF)
7275 return; /* don't send on channels we've EOFed */
7276 bufsize = ssh2_try_send(c);
7279 case CHAN_MAINSESSION:
7280 /* stdin need not receive an unthrottle
7281 * notification since it will be polled */
7284 x11_unthrottle(c->u.x11.xconn);
7287 /* agent sockets are request/response and need no
7288 * buffer management */
7291 pfd_unthrottle(c->u.pfd.pf);
7297 static int ssh_is_simple(Ssh ssh)
7300 * We use the 'simple' variant of the SSH protocol if we're asked
7301 * to, except not if we're also doing connection-sharing (either
7302 * tunnelling our packets over an upstream or expecting to be
7303 * tunnelled over ourselves), since then the assumption that we
7304 * have only one channel to worry about is not true after all.
7306 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7307 !ssh->bare_connection && !ssh->connshare);
7311 * Set up most of a new ssh_channel for SSH-2.
7313 static void ssh2_channel_init(struct ssh_channel *c)
7316 c->localid = alloc_channel_id(ssh);
7318 c->pending_eof = FALSE;
7319 c->throttling_conn = FALSE;
7320 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7321 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7322 c->v.v2.chanreq_head = NULL;
7323 c->v.v2.throttle_state = UNTHROTTLED;
7324 bufchain_init(&c->v.v2.outbuffer);
7328 * Construct the common parts of a CHANNEL_OPEN.
7330 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c, char *type)
7332 struct Packet *pktout;
7334 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7335 ssh2_pkt_addstring(pktout, type);
7336 ssh2_pkt_adduint32(pktout, c->localid);
7337 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7338 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7343 * CHANNEL_FAILURE doesn't come with any indication of what message
7344 * caused it, so we have to keep track of the outstanding
7345 * CHANNEL_REQUESTs ourselves.
7347 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7348 cchandler_fn_t handler, void *ctx)
7350 struct outstanding_channel_request *ocr =
7351 snew(struct outstanding_channel_request);
7353 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7354 ocr->handler = handler;
7357 if (!c->v.v2.chanreq_head)
7358 c->v.v2.chanreq_head = ocr;
7360 c->v.v2.chanreq_tail->next = ocr;
7361 c->v.v2.chanreq_tail = ocr;
7365 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7366 * NULL then a reply will be requested and the handler will be called
7367 * when it arrives. The returned packet is ready to have any
7368 * request-specific data added and be sent. Note that if a handler is
7369 * provided, it's essential that the request actually be sent.
7371 * The handler will usually be passed the response packet in pktin. If
7372 * pktin is NULL, this means that no reply will ever be forthcoming
7373 * (e.g. because the entire connection is being destroyed, or because
7374 * the server initiated channel closure before we saw the response)
7375 * and the handler should free any storage it's holding.
7377 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c, char *type,
7378 cchandler_fn_t handler, void *ctx)
7380 struct Packet *pktout;
7382 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7383 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7384 ssh2_pkt_adduint32(pktout, c->remoteid);
7385 ssh2_pkt_addstring(pktout, type);
7386 ssh2_pkt_addbool(pktout, handler != NULL);
7387 if (handler != NULL)
7388 ssh2_queue_chanreq_handler(c, handler, ctx);
7393 * Potentially enlarge the window on an SSH-2 channel.
7395 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7397 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7402 * Never send WINDOW_ADJUST for a channel that the remote side has
7403 * already sent EOF on; there's no point, since it won't be
7404 * sending any more data anyway. Ditto if _we've_ already sent
7407 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7411 * Also, never widen the window for an X11 channel when we're
7412 * still waiting to see its initial auth and may yet hand it off
7415 if (c->type == CHAN_X11 && c->u.x11.initial)
7419 * If the remote end has a habit of ignoring maxpkt, limit the
7420 * window so that it has no choice (assuming it doesn't ignore the
7423 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7424 newwin = OUR_V2_MAXPKT;
7427 * Only send a WINDOW_ADJUST if there's significantly more window
7428 * available than the other end thinks there is. This saves us
7429 * sending a WINDOW_ADJUST for every character in a shell session.
7431 * "Significant" is arbitrarily defined as half the window size.
7433 if (newwin / 2 >= c->v.v2.locwindow) {
7434 struct Packet *pktout;
7438 * In order to keep track of how much window the client
7439 * actually has available, we'd like it to acknowledge each
7440 * WINDOW_ADJUST. We can't do that directly, so we accompany
7441 * it with a CHANNEL_REQUEST that has to be acknowledged.
7443 * This is only necessary if we're opening the window wide.
7444 * If we're not, then throughput is being constrained by
7445 * something other than the maximum window size anyway.
7447 if (newwin == c->v.v2.locmaxwin &&
7448 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7449 up = snew(unsigned);
7450 *up = newwin - c->v.v2.locwindow;
7451 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7452 ssh2_handle_winadj_response, up);
7453 ssh2_pkt_send(ssh, pktout);
7455 if (c->v.v2.throttle_state != UNTHROTTLED)
7456 c->v.v2.throttle_state = UNTHROTTLING;
7458 /* Pretend the WINDOW_ADJUST was acked immediately. */
7459 c->v.v2.remlocwin = newwin;
7460 c->v.v2.throttle_state = THROTTLED;
7462 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7463 ssh2_pkt_adduint32(pktout, c->remoteid);
7464 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7465 ssh2_pkt_send(ssh, pktout);
7466 c->v.v2.locwindow = newwin;
7471 * Find the channel associated with a message. If there's no channel,
7472 * or it's not properly open, make a noise about it and return NULL.
7474 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7476 unsigned localid = ssh_pkt_getuint32(pktin);
7477 struct ssh_channel *c;
7479 c = find234(ssh->channels, &localid, ssh_channelfind);
7481 (c->type != CHAN_SHARING && c->halfopen &&
7482 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7483 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7484 char *buf = dupprintf("Received %s for %s channel %u",
7485 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7487 c ? "half-open" : "nonexistent", localid);
7488 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7495 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7496 struct Packet *pktin, void *ctx)
7498 unsigned *sizep = ctx;
7501 * Winadj responses should always be failures. However, at least
7502 * one server ("boks_sshd") is known to return SUCCESS for channel
7503 * requests it's never heard of, such as "winadj@putty". Raised
7504 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7505 * life, we don't worry about what kind of response we got.
7508 c->v.v2.remlocwin += *sizep;
7511 * winadj messages are only sent when the window is fully open, so
7512 * if we get an ack of one, we know any pending unthrottle is
7515 if (c->v.v2.throttle_state == UNTHROTTLING)
7516 c->v.v2.throttle_state = UNTHROTTLED;
7519 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
7521 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
7522 struct outstanding_channel_request *ocr;
7525 if (c->type == CHAN_SHARING) {
7526 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7527 pktin->body, pktin->length);
7530 ocr = c->v.v2.chanreq_head;
7532 ssh2_msg_unexpected(ssh, pktin);
7535 ocr->handler(c, pktin, ocr->ctx);
7536 c->v.v2.chanreq_head = ocr->next;
7539 * We may now initiate channel-closing procedures, if that
7540 * CHANNEL_REQUEST was the last thing outstanding before we send
7543 ssh2_channel_check_close(c);
7546 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
7548 struct ssh_channel *c;
7549 c = ssh2_channel_msg(ssh, pktin);
7552 if (c->type == CHAN_SHARING) {
7553 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7554 pktin->body, pktin->length);
7557 if (!(c->closes & CLOSES_SENT_EOF)) {
7558 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
7559 ssh2_try_send_and_unthrottle(ssh, c);
7563 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
7567 struct ssh_channel *c;
7568 c = ssh2_channel_msg(ssh, pktin);
7571 if (c->type == CHAN_SHARING) {
7572 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7573 pktin->body, pktin->length);
7576 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
7577 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
7578 return; /* extended but not stderr */
7579 ssh_pkt_getstring(pktin, &data, &length);
7582 c->v.v2.locwindow -= length;
7583 c->v.v2.remlocwin -= length;
7585 case CHAN_MAINSESSION:
7587 from_backend(ssh->frontend, pktin->type ==
7588 SSH2_MSG_CHANNEL_EXTENDED_DATA,
7592 bufsize = x11_send(c->u.x11.xconn, data, length);
7595 bufsize = pfd_send(c->u.pfd.pf, data, length);
7598 while (length > 0) {
7599 if (c->u.a.lensofar < 4) {
7600 unsigned int l = min(4 - c->u.a.lensofar,
7602 memcpy(c->u.a.msglen + c->u.a.lensofar,
7606 c->u.a.lensofar += l;
7608 if (c->u.a.lensofar == 4) {
7610 4 + GET_32BIT(c->u.a.msglen);
7611 c->u.a.message = snewn(c->u.a.totallen,
7613 memcpy(c->u.a.message, c->u.a.msglen, 4);
7615 if (c->u.a.lensofar >= 4 && length > 0) {
7617 min(c->u.a.totallen - c->u.a.lensofar,
7619 memcpy(c->u.a.message + c->u.a.lensofar,
7623 c->u.a.lensofar += l;
7625 if (c->u.a.lensofar == c->u.a.totallen) {
7628 c->u.a.outstanding_requests++;
7629 if (agent_query(c->u.a.message,
7632 ssh_agentf_callback, c))
7633 ssh_agentf_callback(c, reply, replylen);
7634 sfree(c->u.a.message);
7635 c->u.a.message = NULL;
7636 c->u.a.lensofar = 0;
7643 * If it looks like the remote end hit the end of its window,
7644 * and we didn't want it to do that, think about using a
7647 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
7648 c->v.v2.locmaxwin < 0x40000000)
7649 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
7651 * If we are not buffering too much data,
7652 * enlarge the window again at the remote side.
7653 * If we are buffering too much, we may still
7654 * need to adjust the window if the server's
7657 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7658 c->v.v2.locmaxwin - bufsize : 0);
7660 * If we're either buffering way too much data, or if we're
7661 * buffering anything at all and we're in "simple" mode,
7662 * throttle the whole channel.
7664 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
7665 && !c->throttling_conn) {
7666 c->throttling_conn = 1;
7667 ssh_throttle_conn(ssh, +1);
7672 static void ssh_check_termination(Ssh ssh)
7674 if (ssh->version == 2 &&
7675 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7676 count234(ssh->channels) == 0 &&
7677 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
7679 * We used to send SSH_MSG_DISCONNECT here, because I'd
7680 * believed that _every_ conforming SSH-2 connection had to
7681 * end with a disconnect being sent by at least one side;
7682 * apparently I was wrong and it's perfectly OK to
7683 * unceremoniously slam the connection shut when you're done,
7684 * and indeed OpenSSH feels this is more polite than sending a
7685 * DISCONNECT. So now we don't.
7687 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7691 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id)
7693 logeventf(ssh, "Connection sharing downstream #%u connected", id);
7696 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
7698 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
7699 ssh_check_termination(ssh);
7702 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
7707 va_start(ap, logfmt);
7708 buf = dupvprintf(logfmt, ap);
7711 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
7713 logeventf(ssh, "Connection sharing: %s", buf);
7717 static void ssh_channel_destroy(struct ssh_channel *c)
7722 case CHAN_MAINSESSION:
7723 ssh->mainchan = NULL;
7724 update_specials_menu(ssh->frontend);
7727 if (c->u.x11.xconn != NULL)
7728 x11_close(c->u.x11.xconn);
7729 logevent("Forwarded X11 connection terminated");
7732 sfree(c->u.a.message);
7735 if (c->u.pfd.pf != NULL)
7736 pfd_close(c->u.pfd.pf);
7737 logevent("Forwarded port closed");
7741 del234(ssh->channels, c);
7742 if (ssh->version == 2) {
7743 bufchain_clear(&c->v.v2.outbuffer);
7744 assert(c->v.v2.chanreq_head == NULL);
7749 * If that was the last channel left open, we might need to
7752 ssh_check_termination(ssh);
7755 static void ssh2_channel_check_close(struct ssh_channel *c)
7758 struct Packet *pktout;
7762 * If we've sent out our own CHANNEL_OPEN but not yet seen
7763 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
7764 * it's too early to be sending close messages of any kind.
7769 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
7770 c->type == CHAN_ZOMBIE) &&
7771 !c->v.v2.chanreq_head &&
7772 !(c->closes & CLOSES_SENT_CLOSE)) {
7774 * We have both sent and received EOF (or the channel is a
7775 * zombie), and we have no outstanding channel requests, which
7776 * means the channel is in final wind-up. But we haven't sent
7777 * CLOSE, so let's do so now.
7779 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
7780 ssh2_pkt_adduint32(pktout, c->remoteid);
7781 ssh2_pkt_send(ssh, pktout);
7782 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
7785 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
7786 assert(c->v.v2.chanreq_head == NULL);
7788 * We have both sent and received CLOSE, which means we're
7789 * completely done with the channel.
7791 ssh_channel_destroy(c);
7795 static void ssh2_channel_got_eof(struct ssh_channel *c)
7797 if (c->closes & CLOSES_RCVD_EOF)
7798 return; /* already seen EOF */
7799 c->closes |= CLOSES_RCVD_EOF;
7801 if (c->type == CHAN_X11) {
7802 x11_send_eof(c->u.x11.xconn);
7803 } else if (c->type == CHAN_AGENT) {
7804 if (c->u.a.outstanding_requests == 0) {
7805 /* Manufacture an outgoing EOF in response to the incoming one. */
7806 sshfwd_write_eof(c);
7808 } else if (c->type == CHAN_SOCKDATA) {
7809 pfd_send_eof(c->u.pfd.pf);
7810 } else if (c->type == CHAN_MAINSESSION) {
7813 if (!ssh->sent_console_eof &&
7814 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
7816 * Either from_backend_eof told us that the front end
7817 * wants us to close the outgoing side of the connection
7818 * as soon as we see EOF from the far end, or else we've
7819 * unilaterally decided to do that because we've allocated
7820 * a remote pty and hence EOF isn't a particularly
7821 * meaningful concept.
7823 sshfwd_write_eof(c);
7825 ssh->sent_console_eof = TRUE;
7828 ssh2_channel_check_close(c);
7831 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
7833 struct ssh_channel *c;
7835 c = ssh2_channel_msg(ssh, pktin);
7838 if (c->type == CHAN_SHARING) {
7839 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7840 pktin->body, pktin->length);
7843 ssh2_channel_got_eof(c);
7846 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7848 struct ssh_channel *c;
7850 c = ssh2_channel_msg(ssh, pktin);
7853 if (c->type == CHAN_SHARING) {
7854 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7855 pktin->body, pktin->length);
7860 * When we receive CLOSE on a channel, we assume it comes with an
7861 * implied EOF if we haven't seen EOF yet.
7863 ssh2_channel_got_eof(c);
7865 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
7867 * It also means we stop expecting to see replies to any
7868 * outstanding channel requests, so clean those up too.
7869 * (ssh_chanreq_init will enforce by assertion that we don't
7870 * subsequently put anything back on this list.)
7872 while (c->v.v2.chanreq_head) {
7873 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
7874 ocr->handler(c, NULL, ocr->ctx);
7875 c->v.v2.chanreq_head = ocr->next;
7881 * And we also send an outgoing EOF, if we haven't already, on the
7882 * assumption that CLOSE is a pretty forceful announcement that
7883 * the remote side is doing away with the entire channel. (If it
7884 * had wanted to send us EOF and continue receiving data from us,
7885 * it would have just sent CHANNEL_EOF.)
7887 if (!(c->closes & CLOSES_SENT_EOF)) {
7889 * Make sure we don't read any more from whatever our local
7890 * data source is for this channel.
7893 case CHAN_MAINSESSION:
7894 ssh->send_ok = 0; /* stop trying to read from stdin */
7897 x11_override_throttle(c->u.x11.xconn, 1);
7900 pfd_override_throttle(c->u.pfd.pf, 1);
7905 * Abandon any buffered data we still wanted to send to this
7906 * channel. Receiving a CHANNEL_CLOSE is an indication that
7907 * the server really wants to get on and _destroy_ this
7908 * channel, and it isn't going to send us any further
7909 * WINDOW_ADJUSTs to permit us to send pending stuff.
7911 bufchain_clear(&c->v.v2.outbuffer);
7914 * Send outgoing EOF.
7916 sshfwd_write_eof(c);
7920 * Now process the actual close.
7922 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7923 c->closes |= CLOSES_RCVD_CLOSE;
7924 ssh2_channel_check_close(c);
7928 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7930 struct ssh_channel *c;
7932 c = ssh2_channel_msg(ssh, pktin);
7935 if (c->type == CHAN_SHARING) {
7936 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7937 pktin->body, pktin->length);
7940 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
7941 c->remoteid = ssh_pkt_getuint32(pktin);
7942 c->halfopen = FALSE;
7943 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7944 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7946 if (c->type == CHAN_SOCKDATA_DORMANT) {
7947 c->type = CHAN_SOCKDATA;
7949 pfd_confirm(c->u.pfd.pf);
7950 } else if (c->type == CHAN_ZOMBIE) {
7952 * This case can occur if a local socket error occurred
7953 * between us sending out CHANNEL_OPEN and receiving
7954 * OPEN_CONFIRMATION. In this case, all we can do is
7955 * immediately initiate close proceedings now that we know the
7956 * server's id to put in the close message.
7958 ssh2_channel_check_close(c);
7961 * We never expect to receive OPEN_CONFIRMATION for any
7962 * *other* channel type (since only local-to-remote port
7963 * forwardings cause us to send CHANNEL_OPEN after the main
7964 * channel is live - all other auxiliary channel types are
7965 * initiated from the server end). It's safe to enforce this
7966 * by assertion rather than by ssh_disconnect, because the
7967 * real point is that we never constructed a half-open channel
7968 * structure in the first place with any type other than the
7971 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
7975 ssh_channel_try_eof(c); /* in case we had a pending EOF */
7978 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7980 static const char *const reasons[] = {
7981 "<unknown reason code>",
7982 "Administratively prohibited",
7984 "Unknown channel type",
7985 "Resource shortage",
7987 unsigned reason_code;
7988 char *reason_string;
7990 struct ssh_channel *c;
7992 c = ssh2_channel_msg(ssh, pktin);
7995 if (c->type == CHAN_SHARING) {
7996 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7997 pktin->body, pktin->length);
8000 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8002 if (c->type == CHAN_SOCKDATA_DORMANT) {
8003 reason_code = ssh_pkt_getuint32(pktin);
8004 if (reason_code >= lenof(reasons))
8005 reason_code = 0; /* ensure reasons[reason_code] in range */
8006 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8007 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8008 reasons[reason_code], reason_length, reason_string);
8010 pfd_close(c->u.pfd.pf);
8011 } else if (c->type == CHAN_ZOMBIE) {
8013 * This case can occur if a local socket error occurred
8014 * between us sending out CHANNEL_OPEN and receiving
8015 * OPEN_FAILURE. In this case, we need do nothing except allow
8016 * the code below to throw the half-open channel away.
8020 * We never expect to receive OPEN_FAILURE for any *other*
8021 * channel type (since only local-to-remote port forwardings
8022 * cause us to send CHANNEL_OPEN after the main channel is
8023 * live - all other auxiliary channel types are initiated from
8024 * the server end). It's safe to enforce this by assertion
8025 * rather than by ssh_disconnect, because the real point is
8026 * that we never constructed a half-open channel structure in
8027 * the first place with any type other than the above.
8029 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8032 del234(ssh->channels, c);
8036 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8039 int typelen, want_reply;
8040 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8041 struct ssh_channel *c;
8042 struct Packet *pktout;
8044 c = ssh2_channel_msg(ssh, pktin);
8047 if (c->type == CHAN_SHARING) {
8048 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8049 pktin->body, pktin->length);
8052 ssh_pkt_getstring(pktin, &type, &typelen);
8053 want_reply = ssh2_pkt_getbool(pktin);
8055 if (c->closes & CLOSES_SENT_CLOSE) {
8057 * We don't reply to channel requests after we've sent
8058 * CHANNEL_CLOSE for the channel, because our reply might
8059 * cross in the network with the other side's CHANNEL_CLOSE
8060 * and arrive after they have wound the channel up completely.
8066 * Having got the channel number, we now look at
8067 * the request type string to see if it's something
8070 if (c == ssh->mainchan) {
8072 * We recognise "exit-status" and "exit-signal" on
8073 * the primary channel.
8075 if (typelen == 11 &&
8076 !memcmp(type, "exit-status", 11)) {
8078 ssh->exitcode = ssh_pkt_getuint32(pktin);
8079 logeventf(ssh, "Server sent command exit status %d",
8081 reply = SSH2_MSG_CHANNEL_SUCCESS;
8083 } else if (typelen == 11 &&
8084 !memcmp(type, "exit-signal", 11)) {
8086 int is_plausible = TRUE, is_int = FALSE;
8087 char *fmt_sig = "", *fmt_msg = "";
8089 int msglen = 0, core = FALSE;
8090 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8091 * provide an `int' for the signal, despite its
8092 * having been a `string' in the drafts of RFC 4254 since at
8093 * least 2001. (Fixed in session.c 1.147.) Try to
8094 * infer which we can safely parse it as. */
8096 unsigned char *p = pktin->body +
8098 long len = pktin->length - pktin->savedpos;
8099 unsigned long num = GET_32BIT(p); /* what is it? */
8100 /* If it's 0, it hardly matters; assume string */
8104 int maybe_int = FALSE, maybe_str = FALSE;
8105 #define CHECK_HYPOTHESIS(offset, result) \
8108 int q = toint(offset); \
8109 if (q >= 0 && q+4 <= len) { \
8110 q = toint(q + 4 + GET_32BIT(p+q)); \
8111 if (q >= 0 && q+4 <= len && \
8112 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8117 CHECK_HYPOTHESIS(4+1, maybe_int);
8118 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8119 #undef CHECK_HYPOTHESIS
8120 if (maybe_int && !maybe_str)
8122 else if (!maybe_int && maybe_str)
8125 /* Crikey. Either or neither. Panic. */
8126 is_plausible = FALSE;
8129 ssh->exitcode = 128; /* means `unknown signal' */
8132 /* Old non-standard OpenSSH. */
8133 int signum = ssh_pkt_getuint32(pktin);
8134 fmt_sig = dupprintf(" %d", signum);
8135 ssh->exitcode = 128 + signum;
8137 /* As per RFC 4254. */
8140 ssh_pkt_getstring(pktin, &sig, &siglen);
8141 /* Signal name isn't supposed to be blank, but
8142 * let's cope gracefully if it is. */
8144 fmt_sig = dupprintf(" \"%.*s\"",
8149 * Really hideous method of translating the
8150 * signal description back into a locally
8151 * meaningful number.
8156 #define TRANSLATE_SIGNAL(s) \
8157 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8158 ssh->exitcode = 128 + SIG ## s
8160 TRANSLATE_SIGNAL(ABRT);
8163 TRANSLATE_SIGNAL(ALRM);
8166 TRANSLATE_SIGNAL(FPE);
8169 TRANSLATE_SIGNAL(HUP);
8172 TRANSLATE_SIGNAL(ILL);
8175 TRANSLATE_SIGNAL(INT);
8178 TRANSLATE_SIGNAL(KILL);
8181 TRANSLATE_SIGNAL(PIPE);
8184 TRANSLATE_SIGNAL(QUIT);
8187 TRANSLATE_SIGNAL(SEGV);
8190 TRANSLATE_SIGNAL(TERM);
8193 TRANSLATE_SIGNAL(USR1);
8196 TRANSLATE_SIGNAL(USR2);
8198 #undef TRANSLATE_SIGNAL
8200 ssh->exitcode = 128;
8202 core = ssh2_pkt_getbool(pktin);
8203 ssh_pkt_getstring(pktin, &msg, &msglen);
8205 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8207 /* ignore lang tag */
8208 } /* else don't attempt to parse */
8209 logeventf(ssh, "Server exited on signal%s%s%s",
8210 fmt_sig, core ? " (core dumped)" : "",
8212 if (*fmt_sig) sfree(fmt_sig);
8213 if (*fmt_msg) sfree(fmt_msg);
8214 reply = SSH2_MSG_CHANNEL_SUCCESS;
8219 * This is a channel request we don't know
8220 * about, so we now either ignore the request
8221 * or respond with CHANNEL_FAILURE, depending
8224 reply = SSH2_MSG_CHANNEL_FAILURE;
8227 pktout = ssh2_pkt_init(reply);
8228 ssh2_pkt_adduint32(pktout, c->remoteid);
8229 ssh2_pkt_send(ssh, pktout);
8233 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8236 int typelen, want_reply;
8237 struct Packet *pktout;
8239 ssh_pkt_getstring(pktin, &type, &typelen);
8240 want_reply = ssh2_pkt_getbool(pktin);
8243 * We currently don't support any global requests
8244 * at all, so we either ignore the request or
8245 * respond with REQUEST_FAILURE, depending on
8249 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8250 ssh2_pkt_send(ssh, pktout);
8254 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8258 struct X11FakeAuth *auth;
8261 * Make up a new set of fake X11 auth data, and add it to the tree
8262 * of currently valid ones with an indication of the sharing
8263 * context that it's relevant to.
8265 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8266 auth->share_cs = share_cs;
8267 auth->share_chan = share_chan;
8272 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8274 del234(ssh->x11authtree, auth);
8275 x11_free_fake_auth(auth);
8278 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8286 struct ssh_channel *c;
8287 unsigned remid, winsize, pktsize;
8288 unsigned our_winsize_override = 0;
8289 struct Packet *pktout;
8291 ssh_pkt_getstring(pktin, &type, &typelen);
8292 c = snew(struct ssh_channel);
8295 remid = ssh_pkt_getuint32(pktin);
8296 winsize = ssh_pkt_getuint32(pktin);
8297 pktsize = ssh_pkt_getuint32(pktin);
8299 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8302 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8303 addrstr = snewn(peeraddrlen+1, char);
8304 memcpy(addrstr, peeraddr, peeraddrlen);
8305 addrstr[peeraddrlen] = '\0';
8306 peerport = ssh_pkt_getuint32(pktin);
8308 logeventf(ssh, "Received X11 connect request from %s:%d",
8311 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8312 error = "X11 forwarding is not enabled";
8314 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8317 c->u.x11.initial = TRUE;
8320 * If we are a connection-sharing upstream, then we should
8321 * initially present a very small window, adequate to take
8322 * the X11 initial authorisation packet but not much more.
8323 * Downstream will then present us a larger window (by
8324 * fiat of the connection-sharing protocol) and we can
8325 * guarantee to send a positive-valued WINDOW_ADJUST.
8328 our_winsize_override = 128;
8330 logevent("Opened X11 forward channel");
8334 } else if (typelen == 15 &&
8335 !memcmp(type, "forwarded-tcpip", 15)) {
8336 struct ssh_rportfwd pf, *realpf;
8339 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8340 pf.shost = dupprintf("%.*s", shostlen, shost);
8341 pf.sport = ssh_pkt_getuint32(pktin);
8342 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8343 peerport = ssh_pkt_getuint32(pktin);
8344 realpf = find234(ssh->rportfwds, &pf, NULL);
8345 logeventf(ssh, "Received remote port %s:%d open request "
8346 "from %s:%d", pf.shost, pf.sport, peeraddr, peerport);
8349 if (realpf == NULL) {
8350 error = "Remote port is not recognised";
8354 if (realpf->share_ctx) {
8356 * This port forwarding is on behalf of a
8357 * connection-sharing downstream, so abandon our own
8358 * channel-open procedure and just pass the message on
8361 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8362 pktin->body, pktin->length);
8367 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8368 c, ssh->conf, realpf->pfrec->addressfamily);
8369 logeventf(ssh, "Attempting to forward remote port to "
8370 "%s:%d", realpf->dhost, realpf->dport);
8372 logeventf(ssh, "Port open failed: %s", err);
8374 error = "Port open failed";
8376 logevent("Forwarded port opened successfully");
8377 c->type = CHAN_SOCKDATA;
8380 } else if (typelen == 22 &&
8381 !memcmp(type, "auth-agent@openssh.com", 22)) {
8382 if (!ssh->agentfwd_enabled)
8383 error = "Agent forwarding is not enabled";
8385 c->type = CHAN_AGENT; /* identify channel type */
8386 c->u.a.lensofar = 0;
8387 c->u.a.message = NULL;
8388 c->u.a.outstanding_requests = 0;
8391 error = "Unsupported channel type requested";
8394 c->remoteid = remid;
8395 c->halfopen = FALSE;
8397 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8398 ssh2_pkt_adduint32(pktout, c->remoteid);
8399 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8400 ssh2_pkt_addstring(pktout, error);
8401 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8402 ssh2_pkt_send(ssh, pktout);
8403 logeventf(ssh, "Rejected channel open: %s", error);
8406 ssh2_channel_init(c);
8407 c->v.v2.remwindow = winsize;
8408 c->v.v2.remmaxpkt = pktsize;
8409 if (our_winsize_override) {
8410 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8411 our_winsize_override;
8413 add234(ssh->channels, c);
8414 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8415 ssh2_pkt_adduint32(pktout, c->remoteid);
8416 ssh2_pkt_adduint32(pktout, c->localid);
8417 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8418 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8419 ssh2_pkt_send(ssh, pktout);
8423 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8424 void *share_cs, void *share_chan,
8425 const char *peer_addr, int peer_port,
8426 int endian, int protomajor, int protominor,
8427 const void *initial_data, int initial_len)
8430 * This function is called when we've just discovered that an X
8431 * forwarding channel on which we'd been handling the initial auth
8432 * ourselves turns out to be destined for a connection-sharing
8433 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8434 * that we completely stop tracking windows and buffering data and
8435 * just pass more or less unmodified SSH messages back and forth.
8437 c->type = CHAN_SHARING;
8438 c->u.sharing.ctx = share_cs;
8439 share_setup_x11_channel(share_cs, share_chan,
8440 c->localid, c->remoteid, c->v.v2.remwindow,
8441 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8442 peer_addr, peer_port, endian,
8443 protomajor, protominor,
8444 initial_data, initial_len);
8447 void sshfwd_x11_is_local(struct ssh_channel *c)
8450 * This function is called when we've just discovered that an X
8451 * forwarding channel is _not_ destined for a connection-sharing
8452 * downstream but we're going to handle it ourselves. We stop
8453 * presenting a cautiously small window and go into ordinary data
8456 c->u.x11.initial = FALSE;
8457 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8461 * Buffer banner messages for later display at some convenient point,
8462 * if we're going to display them.
8464 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8466 /* Arbitrary limit to prevent unbounded inflation of buffer */
8467 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8468 bufchain_size(&ssh->banner) <= 131072) {
8469 char *banner = NULL;
8471 ssh_pkt_getstring(pktin, &banner, &size);
8473 bufchain_add(&ssh->banner, banner, size);
8477 /* Helper function to deal with sending tty modes for "pty-req" */
8478 static void ssh2_send_ttymode(void *data, char *mode, char *val)
8480 struct Packet *pktout = (struct Packet *)data;
8482 unsigned int arg = 0;
8483 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
8484 if (i == lenof(ssh_ttymodes)) return;
8485 switch (ssh_ttymodes[i].type) {
8487 arg = ssh_tty_parse_specchar(val);
8490 arg = ssh_tty_parse_boolean(val);
8493 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
8494 ssh2_pkt_adduint32(pktout, arg);
8497 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8500 struct ssh2_setup_x11_state {
8504 struct Packet *pktout;
8505 crStateP(ssh2_setup_x11_state, ctx);
8509 logevent("Requesting X11 forwarding");
8510 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8512 ssh2_pkt_addbool(pktout, 0); /* many connections */
8513 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8514 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8515 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8516 ssh2_pkt_send(ssh, pktout);
8518 /* Wait to be called back with either a response packet, or NULL
8519 * meaning clean up and free our data */
8523 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8524 logevent("X11 forwarding enabled");
8525 ssh->X11_fwd_enabled = TRUE;
8527 logevent("X11 forwarding refused");
8533 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8536 struct ssh2_setup_agent_state {
8540 struct Packet *pktout;
8541 crStateP(ssh2_setup_agent_state, ctx);
8545 logevent("Requesting OpenSSH-style agent forwarding");
8546 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8547 ssh2_setup_agent, s);
8548 ssh2_pkt_send(ssh, pktout);
8550 /* Wait to be called back with either a response packet, or NULL
8551 * meaning clean up and free our data */
8555 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8556 logevent("Agent forwarding enabled");
8557 ssh->agentfwd_enabled = TRUE;
8559 logevent("Agent forwarding refused");
8565 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8568 struct ssh2_setup_pty_state {
8572 struct Packet *pktout;
8573 crStateP(ssh2_setup_pty_state, ctx);
8577 /* Unpick the terminal-speed string. */
8578 /* XXX perhaps we should allow no speeds to be sent. */
8579 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8580 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8581 /* Build the pty request. */
8582 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
8584 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
8585 ssh2_pkt_adduint32(pktout, ssh->term_width);
8586 ssh2_pkt_adduint32(pktout, ssh->term_height);
8587 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
8588 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
8589 ssh2_pkt_addstring_start(pktout);
8590 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
8591 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
8592 ssh2_pkt_adduint32(pktout, ssh->ispeed);
8593 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
8594 ssh2_pkt_adduint32(pktout, ssh->ospeed);
8595 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
8596 ssh2_pkt_send(ssh, pktout);
8597 ssh->state = SSH_STATE_INTERMED;
8599 /* Wait to be called back with either a response packet, or NULL
8600 * meaning clean up and free our data */
8604 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8605 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8606 ssh->ospeed, ssh->ispeed);
8607 ssh->got_pty = TRUE;
8609 c_write_str(ssh, "Server refused to allocate pty\r\n");
8610 ssh->editing = ssh->echoing = 1;
8617 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
8620 struct ssh2_setup_env_state {
8622 int num_env, env_left, env_ok;
8625 struct Packet *pktout;
8626 crStateP(ssh2_setup_env_state, ctx);
8631 * Send environment variables.
8633 * Simplest thing here is to send all the requests at once, and
8634 * then wait for a whole bunch of successes or failures.
8640 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
8642 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
8643 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
8644 ssh2_pkt_addstring(pktout, key);
8645 ssh2_pkt_addstring(pktout, val);
8646 ssh2_pkt_send(ssh, pktout);
8651 logeventf(ssh, "Sent %d environment variables", s->num_env);
8656 s->env_left = s->num_env;
8658 while (s->env_left > 0) {
8659 /* Wait to be called back with either a response packet,
8660 * or NULL meaning clean up and free our data */
8662 if (!pktin) goto out;
8663 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
8668 if (s->env_ok == s->num_env) {
8669 logevent("All environment variables successfully set");
8670 } else if (s->env_ok == 0) {
8671 logevent("All environment variables refused");
8672 c_write_str(ssh, "Server refused to set environment variables\r\n");
8674 logeventf(ssh, "%d environment variables refused",
8675 s->num_env - s->env_ok);
8676 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8684 * Handle the SSH-2 userauth and connection layers.
8686 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
8688 do_ssh2_authconn(ssh, NULL, 0, pktin);
8691 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
8695 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
8698 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
8699 struct Packet *pktin)
8701 struct do_ssh2_authconn_state {
8705 AUTH_TYPE_PUBLICKEY,
8706 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
8707 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
8709 AUTH_TYPE_GSSAPI, /* always QUIET */
8710 AUTH_TYPE_KEYBOARD_INTERACTIVE,
8711 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
8713 int done_service_req;
8714 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
8715 int tried_pubkey_config, done_agent;
8720 int kbd_inter_refused;
8721 int we_are_in, userauth_success;
8722 prompts_t *cur_prompt;
8727 void *publickey_blob;
8728 int publickey_bloblen;
8729 int publickey_encrypted;
8730 char *publickey_algorithm;
8731 char *publickey_comment;
8732 unsigned char agent_request[5], *agent_response, *agentp;
8733 int agent_responselen;
8734 unsigned char *pkblob_in_agent;
8736 char *pkblob, *alg, *commentp;
8737 int pklen, alglen, commentlen;
8738 int siglen, retlen, len;
8739 char *q, *agentreq, *ret;
8741 struct Packet *pktout;
8744 struct ssh_gss_library *gsslib;
8745 Ssh_gss_ctx gss_ctx;
8746 Ssh_gss_buf gss_buf;
8747 Ssh_gss_buf gss_rcvtok, gss_sndtok;
8748 Ssh_gss_name gss_srv_name;
8749 Ssh_gss_stat gss_stat;
8752 crState(do_ssh2_authconn_state);
8756 /* Register as a handler for all the messages this coroutine handles. */
8757 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
8758 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
8759 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
8760 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
8761 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
8762 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
8763 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
8764 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
8765 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
8766 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
8767 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
8768 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
8769 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
8770 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
8771 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
8772 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
8773 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
8774 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
8775 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
8776 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
8778 s->done_service_req = FALSE;
8779 s->we_are_in = s->userauth_success = FALSE;
8780 s->agent_response = NULL;
8782 s->tried_gssapi = FALSE;
8785 if (!ssh->bare_connection) {
8786 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
8788 * Request userauth protocol, and await a response to it.
8790 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8791 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
8792 ssh2_pkt_send(ssh, s->pktout);
8793 crWaitUntilV(pktin);
8794 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
8795 s->done_service_req = TRUE;
8797 if (!s->done_service_req) {
8799 * Request connection protocol directly, without authentication.
8801 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
8802 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8803 ssh2_pkt_send(ssh, s->pktout);
8804 crWaitUntilV(pktin);
8805 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
8806 s->we_are_in = TRUE; /* no auth required */
8808 bombout(("Server refused service request"));
8813 s->we_are_in = TRUE;
8816 /* Arrange to be able to deal with any BANNERs that come in.
8817 * (We do this now as packets may come in during the next bit.) */
8818 bufchain_init(&ssh->banner);
8819 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
8820 ssh2_msg_userauth_banner;
8823 * Misc one-time setup for authentication.
8825 s->publickey_blob = NULL;
8826 if (!s->we_are_in) {
8829 * Load the public half of any configured public key file
8832 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8833 if (!filename_is_null(s->keyfile)) {
8835 logeventf(ssh, "Reading private key file \"%.150s\"",
8836 filename_to_str(s->keyfile));
8837 keytype = key_type(s->keyfile);
8838 if (keytype == SSH_KEYTYPE_SSH2) {
8841 ssh2_userkey_loadpub(s->keyfile,
8842 &s->publickey_algorithm,
8843 &s->publickey_bloblen,
8844 &s->publickey_comment, &error);
8845 if (s->publickey_blob) {
8846 s->publickey_encrypted =
8847 ssh2_userkey_encrypted(s->keyfile, NULL);
8850 logeventf(ssh, "Unable to load private key (%s)",
8852 msgbuf = dupprintf("Unable to load private key file "
8853 "\"%.150s\" (%s)\r\n",
8854 filename_to_str(s->keyfile),
8856 c_write_str(ssh, msgbuf);
8861 logeventf(ssh, "Unable to use this key file (%s)",
8862 key_type_to_str(keytype));
8863 msgbuf = dupprintf("Unable to use key file \"%.150s\""
8865 filename_to_str(s->keyfile),
8866 key_type_to_str(keytype));
8867 c_write_str(ssh, msgbuf);
8869 s->publickey_blob = NULL;
8874 * Find out about any keys Pageant has (but if there's a
8875 * public key configured, filter out all others).
8878 s->agent_response = NULL;
8879 s->pkblob_in_agent = NULL;
8880 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
8884 logevent("Pageant is running. Requesting keys.");
8886 /* Request the keys held by the agent. */
8887 PUT_32BIT(s->agent_request, 1);
8888 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
8889 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
8890 ssh_agent_callback, ssh)) {
8894 bombout(("Unexpected data from server while"
8895 " waiting for agent response"));
8898 } while (pktin || inlen > 0);
8899 r = ssh->agent_response;
8900 s->agent_responselen = ssh->agent_response_len;
8902 s->agent_response = (unsigned char *) r;
8903 if (s->agent_response && s->agent_responselen >= 5 &&
8904 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
8907 p = s->agent_response + 5;
8908 s->nkeys = toint(GET_32BIT(p));
8911 * Vet the Pageant response to ensure that the key
8912 * count and blob lengths make sense.
8915 logeventf(ssh, "Pageant response contained a negative"
8916 " key count %d", s->nkeys);
8918 goto done_agent_query;
8920 unsigned char *q = p + 4;
8921 int lenleft = s->agent_responselen - 5 - 4;
8923 for (keyi = 0; keyi < s->nkeys; keyi++) {
8924 int bloblen, commentlen;
8926 logeventf(ssh, "Pageant response was truncated");
8928 goto done_agent_query;
8930 bloblen = toint(GET_32BIT(q));
8931 if (bloblen < 0 || bloblen > lenleft) {
8932 logeventf(ssh, "Pageant response was truncated");
8934 goto done_agent_query;
8936 lenleft -= 4 + bloblen;
8938 commentlen = toint(GET_32BIT(q));
8939 if (commentlen < 0 || commentlen > lenleft) {
8940 logeventf(ssh, "Pageant response was truncated");
8942 goto done_agent_query;
8944 lenleft -= 4 + commentlen;
8945 q += 4 + commentlen;
8950 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
8951 if (s->publickey_blob) {
8952 /* See if configured key is in agent. */
8953 for (keyi = 0; keyi < s->nkeys; keyi++) {
8954 s->pklen = toint(GET_32BIT(p));
8955 if (s->pklen == s->publickey_bloblen &&
8956 !memcmp(p+4, s->publickey_blob,
8957 s->publickey_bloblen)) {
8958 logeventf(ssh, "Pageant key #%d matches "
8959 "configured key file", keyi);
8961 s->pkblob_in_agent = p;
8965 p += toint(GET_32BIT(p)) + 4; /* comment */
8967 if (!s->pkblob_in_agent) {
8968 logevent("Configured key file not in Pageant");
8973 logevent("Failed to get reply from Pageant");
8981 * We repeat this whole loop, including the username prompt,
8982 * until we manage a successful authentication. If the user
8983 * types the wrong _password_, they can be sent back to the
8984 * beginning to try another username, if this is configured on.
8985 * (If they specify a username in the config, they are never
8986 * asked, even if they do give a wrong password.)
8988 * I think this best serves the needs of
8990 * - the people who have no configuration, no keys, and just
8991 * want to try repeated (username,password) pairs until they
8992 * type both correctly
8994 * - people who have keys and configuration but occasionally
8995 * need to fall back to passwords
8997 * - people with a key held in Pageant, who might not have
8998 * logged in to a particular machine before; so they want to
8999 * type a username, and then _either_ their key will be
9000 * accepted, _or_ they will type a password. If they mistype
9001 * the username they will want to be able to get back and
9004 s->got_username = FALSE;
9005 while (!s->we_are_in) {
9009 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9011 * We got a username last time round this loop, and
9012 * with change_username turned off we don't try to get
9015 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9016 int ret; /* need not be kept over crReturn */
9017 s->cur_prompt = new_prompts(ssh->frontend);
9018 s->cur_prompt->to_server = TRUE;
9019 s->cur_prompt->name = dupstr("SSH login name");
9020 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9021 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9024 crWaitUntilV(!pktin);
9025 ret = get_userpass_input(s->cur_prompt, in, inlen);
9030 * get_userpass_input() failed to get a username.
9033 free_prompts(s->cur_prompt);
9034 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9037 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9038 free_prompts(s->cur_prompt);
9041 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9042 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9043 c_write_str(ssh, stuff);
9047 s->got_username = TRUE;
9050 * Send an authentication request using method "none": (a)
9051 * just in case it succeeds, and (b) so that we know what
9052 * authentication methods we can usefully try next.
9054 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9056 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9057 ssh2_pkt_addstring(s->pktout, ssh->username);
9058 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9059 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9060 ssh2_pkt_send(ssh, s->pktout);
9061 s->type = AUTH_TYPE_NONE;
9063 s->we_are_in = FALSE;
9065 s->tried_pubkey_config = FALSE;
9066 s->kbd_inter_refused = FALSE;
9068 /* Reset agent request state. */
9069 s->done_agent = FALSE;
9070 if (s->agent_response) {
9071 if (s->pkblob_in_agent) {
9072 s->agentp = s->pkblob_in_agent;
9074 s->agentp = s->agent_response + 5 + 4;
9080 char *methods = NULL;
9084 * Wait for the result of the last authentication request.
9087 crWaitUntilV(pktin);
9089 * Now is a convenient point to spew any banner material
9090 * that we've accumulated. (This should ensure that when
9091 * we exit the auth loop, we haven't any left to deal
9095 int size = bufchain_size(&ssh->banner);
9097 * Don't show the banner if we're operating in
9098 * non-verbose non-interactive mode. (It's probably
9099 * a script, which means nobody will read the
9100 * banner _anyway_, and moreover the printing of
9101 * the banner will screw up processing on the
9102 * output of (say) plink.)
9104 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9105 char *banner = snewn(size, char);
9106 bufchain_fetch(&ssh->banner, banner, size);
9107 c_write_untrusted(ssh, banner, size);
9110 bufchain_clear(&ssh->banner);
9112 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9113 logevent("Access granted");
9114 s->we_are_in = s->userauth_success = TRUE;
9118 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9119 bombout(("Strange packet received during authentication: "
9120 "type %d", pktin->type));
9127 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9128 * we can look at the string in it and know what we can
9129 * helpfully try next.
9131 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9132 ssh_pkt_getstring(pktin, &methods, &methlen);
9133 if (!ssh2_pkt_getbool(pktin)) {
9135 * We have received an unequivocal Access
9136 * Denied. This can translate to a variety of
9137 * messages, or no message at all.
9139 * For forms of authentication which are attempted
9140 * implicitly, by which I mean without printing
9141 * anything in the window indicating that we're
9142 * trying them, we should never print 'Access
9145 * If we do print a message saying that we're
9146 * attempting some kind of authentication, it's OK
9147 * to print a followup message saying it failed -
9148 * but the message may sometimes be more specific
9149 * than simply 'Access denied'.
9151 * Additionally, if we'd just tried password
9152 * authentication, we should break out of this
9153 * whole loop so as to go back to the username
9154 * prompt (iff we're configured to allow
9155 * username change attempts).
9157 if (s->type == AUTH_TYPE_NONE) {
9159 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9160 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9161 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9162 c_write_str(ssh, "Server refused our key\r\n");
9163 logevent("Server refused our key");
9164 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9165 /* This _shouldn't_ happen except by a
9166 * protocol bug causing client and server to
9167 * disagree on what is a correct signature. */
9168 c_write_str(ssh, "Server refused public-key signature"
9169 " despite accepting key!\r\n");
9170 logevent("Server refused public-key signature"
9171 " despite accepting key!");
9172 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9173 /* quiet, so no c_write */
9174 logevent("Server refused keyboard-interactive authentication");
9175 } else if (s->type==AUTH_TYPE_GSSAPI) {
9176 /* always quiet, so no c_write */
9177 /* also, the code down in the GSSAPI block has
9178 * already logged this in the Event Log */
9179 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9180 logevent("Keyboard-interactive authentication failed");
9181 c_write_str(ssh, "Access denied\r\n");
9183 assert(s->type == AUTH_TYPE_PASSWORD);
9184 logevent("Password authentication failed");
9185 c_write_str(ssh, "Access denied\r\n");
9187 if (conf_get_int(ssh->conf, CONF_change_username)) {
9188 /* XXX perhaps we should allow
9189 * keyboard-interactive to do this too? */
9190 s->we_are_in = FALSE;
9195 c_write_str(ssh, "Further authentication required\r\n");
9196 logevent("Further authentication required");
9200 in_commasep_string("publickey", methods, methlen);
9202 in_commasep_string("password", methods, methlen);
9203 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9204 in_commasep_string("keyboard-interactive", methods, methlen);
9207 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9208 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9209 in_commasep_string("gssapi-with-mic", methods, methlen) &&
9210 ssh->gsslibs->nlibraries > 0;
9214 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9216 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9219 * Attempt public-key authentication using a key from Pageant.
9222 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9224 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9226 /* Unpack key from agent response */
9227 s->pklen = toint(GET_32BIT(s->agentp));
9229 s->pkblob = (char *)s->agentp;
9230 s->agentp += s->pklen;
9231 s->alglen = toint(GET_32BIT(s->pkblob));
9232 s->alg = s->pkblob + 4;
9233 s->commentlen = toint(GET_32BIT(s->agentp));
9235 s->commentp = (char *)s->agentp;
9236 s->agentp += s->commentlen;
9237 /* s->agentp now points at next key, if any */
9239 /* See if server will accept it */
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, FALSE); /* no 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);
9251 ssh2_pkt_send(ssh, s->pktout);
9252 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9254 crWaitUntilV(pktin);
9255 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9257 /* Offer of key refused. */
9264 if (flags & FLAG_VERBOSE) {
9265 c_write_str(ssh, "Authenticating with "
9267 c_write(ssh, s->commentp, s->commentlen);
9268 c_write_str(ssh, "\" from agent\r\n");
9272 * Server is willing to accept the key.
9273 * Construct a SIGN_REQUEST.
9275 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9276 ssh2_pkt_addstring(s->pktout, ssh->username);
9277 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9278 /* service requested */
9279 ssh2_pkt_addstring(s->pktout, "publickey");
9281 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9282 ssh2_pkt_addstring_start(s->pktout);
9283 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9284 ssh2_pkt_addstring_start(s->pktout);
9285 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9287 /* Ask agent for signature. */
9288 s->siglen = s->pktout->length - 5 + 4 +
9289 ssh->v2_session_id_len;
9290 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9292 s->len = 1; /* message type */
9293 s->len += 4 + s->pklen; /* key blob */
9294 s->len += 4 + s->siglen; /* data to sign */
9295 s->len += 4; /* flags */
9296 s->agentreq = snewn(4 + s->len, char);
9297 PUT_32BIT(s->agentreq, s->len);
9298 s->q = s->agentreq + 4;
9299 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9300 PUT_32BIT(s->q, s->pklen);
9302 memcpy(s->q, s->pkblob, s->pklen);
9304 PUT_32BIT(s->q, s->siglen);
9306 /* Now the data to be signed... */
9307 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9308 PUT_32BIT(s->q, ssh->v2_session_id_len);
9311 memcpy(s->q, ssh->v2_session_id,
9312 ssh->v2_session_id_len);
9313 s->q += ssh->v2_session_id_len;
9314 memcpy(s->q, s->pktout->data + 5,
9315 s->pktout->length - 5);
9316 s->q += s->pktout->length - 5;
9317 /* And finally the (zero) flags word. */
9319 if (!agent_query(s->agentreq, s->len + 4,
9321 ssh_agent_callback, ssh)) {
9325 bombout(("Unexpected data from server"
9326 " while waiting for agent"
9330 } while (pktin || inlen > 0);
9331 vret = ssh->agent_response;
9332 s->retlen = ssh->agent_response_len;
9337 if (s->retlen >= 9 &&
9338 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9339 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9340 logevent("Sending Pageant's response");
9341 ssh2_add_sigblob(ssh, s->pktout,
9342 s->pkblob, s->pklen,
9344 GET_32BIT(s->ret + 5));
9345 ssh2_pkt_send(ssh, s->pktout);
9346 s->type = AUTH_TYPE_PUBLICKEY;
9348 /* FIXME: less drastic response */
9349 bombout(("Pageant failed to answer challenge"));
9355 /* Do we have any keys left to try? */
9356 if (s->pkblob_in_agent) {
9357 s->done_agent = TRUE;
9358 s->tried_pubkey_config = TRUE;
9361 if (s->keyi >= s->nkeys)
9362 s->done_agent = TRUE;
9365 } else if (s->can_pubkey && s->publickey_blob &&
9366 !s->tried_pubkey_config) {
9368 struct ssh2_userkey *key; /* not live over crReturn */
9369 char *passphrase; /* not live over crReturn */
9371 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9373 s->tried_pubkey_config = TRUE;
9376 * Try the public key supplied in the configuration.
9378 * First, offer the public blob to see if the server is
9379 * willing to accept it.
9381 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9382 ssh2_pkt_addstring(s->pktout, ssh->username);
9383 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9384 /* service requested */
9385 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9386 ssh2_pkt_addbool(s->pktout, FALSE);
9387 /* no signature included */
9388 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9389 ssh2_pkt_addstring_start(s->pktout);
9390 ssh2_pkt_addstring_data(s->pktout,
9391 (char *)s->publickey_blob,
9392 s->publickey_bloblen);
9393 ssh2_pkt_send(ssh, s->pktout);
9394 logevent("Offered public key");
9396 crWaitUntilV(pktin);
9397 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9398 /* Key refused. Give up. */
9399 s->gotit = TRUE; /* reconsider message next loop */
9400 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9401 continue; /* process this new message */
9403 logevent("Offer of public key accepted");
9406 * Actually attempt a serious authentication using
9409 if (flags & FLAG_VERBOSE) {
9410 c_write_str(ssh, "Authenticating with public key \"");
9411 c_write_str(ssh, s->publickey_comment);
9412 c_write_str(ssh, "\"\r\n");
9416 const char *error; /* not live over crReturn */
9417 if (s->publickey_encrypted) {
9419 * Get a passphrase from the user.
9421 int ret; /* need not be kept over crReturn */
9422 s->cur_prompt = new_prompts(ssh->frontend);
9423 s->cur_prompt->to_server = FALSE;
9424 s->cur_prompt->name = dupstr("SSH key passphrase");
9425 add_prompt(s->cur_prompt,
9426 dupprintf("Passphrase for key \"%.100s\": ",
9427 s->publickey_comment),
9429 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9432 crWaitUntilV(!pktin);
9433 ret = get_userpass_input(s->cur_prompt,
9438 /* Failed to get a passphrase. Terminate. */
9439 free_prompts(s->cur_prompt);
9440 ssh_disconnect(ssh, NULL,
9441 "Unable to authenticate",
9442 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9447 dupstr(s->cur_prompt->prompts[0]->result);
9448 free_prompts(s->cur_prompt);
9450 passphrase = NULL; /* no passphrase needed */
9454 * Try decrypting the key.
9456 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9457 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9459 /* burn the evidence */
9460 smemclr(passphrase, strlen(passphrase));
9463 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9465 (key == SSH2_WRONG_PASSPHRASE)) {
9466 c_write_str(ssh, "Wrong passphrase\r\n");
9468 /* and loop again */
9470 c_write_str(ssh, "Unable to load private key (");
9471 c_write_str(ssh, error);
9472 c_write_str(ssh, ")\r\n");
9474 break; /* try something else */
9480 unsigned char *pkblob, *sigblob, *sigdata;
9481 int pkblob_len, sigblob_len, sigdata_len;
9485 * We have loaded the private key and the server
9486 * has announced that it's willing to accept it.
9487 * Hallelujah. Generate a signature and send it.
9489 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9490 ssh2_pkt_addstring(s->pktout, ssh->username);
9491 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9492 /* service requested */
9493 ssh2_pkt_addstring(s->pktout, "publickey");
9495 ssh2_pkt_addbool(s->pktout, TRUE);
9496 /* signature follows */
9497 ssh2_pkt_addstring(s->pktout, key->alg->name);
9498 pkblob = key->alg->public_blob(key->data,
9500 ssh2_pkt_addstring_start(s->pktout);
9501 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9505 * The data to be signed is:
9509 * followed by everything so far placed in the
9512 sigdata_len = s->pktout->length - 5 + 4 +
9513 ssh->v2_session_id_len;
9514 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9516 sigdata = snewn(sigdata_len, unsigned char);
9518 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9519 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9522 memcpy(sigdata+p, ssh->v2_session_id,
9523 ssh->v2_session_id_len);
9524 p += ssh->v2_session_id_len;
9525 memcpy(sigdata+p, s->pktout->data + 5,
9526 s->pktout->length - 5);
9527 p += s->pktout->length - 5;
9528 assert(p == sigdata_len);
9529 sigblob = key->alg->sign(key->data, (char *)sigdata,
9530 sigdata_len, &sigblob_len);
9531 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9532 sigblob, sigblob_len);
9537 ssh2_pkt_send(ssh, s->pktout);
9538 logevent("Sent public key signature");
9539 s->type = AUTH_TYPE_PUBLICKEY;
9540 key->alg->freekey(key->data);
9541 sfree(key->comment);
9546 } else if (s->can_gssapi && !s->tried_gssapi) {
9548 /* GSSAPI Authentication */
9553 s->type = AUTH_TYPE_GSSAPI;
9554 s->tried_gssapi = TRUE;
9556 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9559 * Pick the highest GSS library on the preference
9565 for (i = 0; i < ngsslibs; i++) {
9566 int want_id = conf_get_int_int(ssh->conf,
9567 CONF_ssh_gsslist, i);
9568 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
9569 if (ssh->gsslibs->libraries[j].id == want_id) {
9570 s->gsslib = &ssh->gsslibs->libraries[j];
9571 goto got_gsslib; /* double break */
9576 * We always expect to have found something in
9577 * the above loop: we only came here if there
9578 * was at least one viable GSS library, and the
9579 * preference list should always mention
9580 * everything and only change the order.
9585 if (s->gsslib->gsslogmsg)
9586 logevent(s->gsslib->gsslogmsg);
9588 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
9589 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9590 ssh2_pkt_addstring(s->pktout, ssh->username);
9591 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9592 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
9593 logevent("Attempting GSSAPI authentication");
9595 /* add mechanism info */
9596 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
9598 /* number of GSSAPI mechanisms */
9599 ssh2_pkt_adduint32(s->pktout,1);
9601 /* length of OID + 2 */
9602 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
9603 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
9606 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
9608 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
9610 ssh2_pkt_send(ssh, s->pktout);
9611 crWaitUntilV(pktin);
9612 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
9613 logevent("GSSAPI authentication request refused");
9617 /* check returned packet ... */
9619 ssh_pkt_getstring(pktin, &data, &len);
9620 s->gss_rcvtok.value = data;
9621 s->gss_rcvtok.length = len;
9622 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
9623 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
9624 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
9625 memcmp((char *)s->gss_rcvtok.value + 2,
9626 s->gss_buf.value,s->gss_buf.length) ) {
9627 logevent("GSSAPI authentication - wrong response from server");
9631 /* now start running */
9632 s->gss_stat = s->gsslib->import_name(s->gsslib,
9635 if (s->gss_stat != SSH_GSS_OK) {
9636 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
9637 logevent("GSSAPI import name failed - Bad service name");
9639 logevent("GSSAPI import name failed");
9643 /* fetch TGT into GSS engine */
9644 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
9646 if (s->gss_stat != SSH_GSS_OK) {
9647 logevent("GSSAPI authentication failed to get credentials");
9648 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9652 /* initial tokens are empty */
9653 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
9654 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
9656 /* now enter the loop */
9658 s->gss_stat = s->gsslib->init_sec_context
9662 conf_get_int(ssh->conf, CONF_gssapifwd),
9666 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
9667 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
9668 logevent("GSSAPI authentication initialisation failed");
9670 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
9671 &s->gss_buf) == SSH_GSS_OK) {
9672 logevent(s->gss_buf.value);
9673 sfree(s->gss_buf.value);
9678 logevent("GSSAPI authentication initialised");
9680 /* Client and server now exchange tokens until GSSAPI
9681 * no longer says CONTINUE_NEEDED */
9683 if (s->gss_sndtok.length != 0) {
9684 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
9685 ssh_pkt_addstring_start(s->pktout);
9686 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
9687 ssh2_pkt_send(ssh, s->pktout);
9688 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
9691 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
9692 crWaitUntilV(pktin);
9693 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
9694 logevent("GSSAPI authentication - bad server response");
9695 s->gss_stat = SSH_GSS_FAILURE;
9698 ssh_pkt_getstring(pktin, &data, &len);
9699 s->gss_rcvtok.value = data;
9700 s->gss_rcvtok.length = len;
9702 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
9704 if (s->gss_stat != SSH_GSS_OK) {
9705 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9706 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9709 logevent("GSSAPI authentication loop finished OK");
9711 /* Now send the MIC */
9713 s->pktout = ssh2_pkt_init(0);
9714 micoffset = s->pktout->length;
9715 ssh_pkt_addstring_start(s->pktout);
9716 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
9717 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
9718 ssh_pkt_addstring(s->pktout, ssh->username);
9719 ssh_pkt_addstring(s->pktout, "ssh-connection");
9720 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
9722 s->gss_buf.value = (char *)s->pktout->data + micoffset;
9723 s->gss_buf.length = s->pktout->length - micoffset;
9725 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
9726 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
9727 ssh_pkt_addstring_start(s->pktout);
9728 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
9729 ssh2_pkt_send(ssh, s->pktout);
9730 s->gsslib->free_mic(s->gsslib, &mic);
9734 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9735 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
9738 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
9741 * Keyboard-interactive authentication.
9744 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
9746 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
9748 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9749 ssh2_pkt_addstring(s->pktout, ssh->username);
9750 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9751 /* service requested */
9752 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
9754 ssh2_pkt_addstring(s->pktout, ""); /* lang */
9755 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
9756 ssh2_pkt_send(ssh, s->pktout);
9758 logevent("Attempting keyboard-interactive authentication");
9760 crWaitUntilV(pktin);
9761 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
9762 /* Server is not willing to do keyboard-interactive
9763 * at all (or, bizarrely but legally, accepts the
9764 * user without actually issuing any prompts).
9765 * Give up on it entirely. */
9767 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
9768 s->kbd_inter_refused = TRUE; /* don't try it again */
9773 * Loop while the server continues to send INFO_REQUESTs.
9775 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
9777 char *name, *inst, *lang;
9778 int name_len, inst_len, lang_len;
9782 * We've got a fresh USERAUTH_INFO_REQUEST.
9783 * Get the preamble and start building a prompt.
9785 ssh_pkt_getstring(pktin, &name, &name_len);
9786 ssh_pkt_getstring(pktin, &inst, &inst_len);
9787 ssh_pkt_getstring(pktin, &lang, &lang_len);
9788 s->cur_prompt = new_prompts(ssh->frontend);
9789 s->cur_prompt->to_server = TRUE;
9792 * Get any prompt(s) from the packet.
9794 s->num_prompts = ssh_pkt_getuint32(pktin);
9795 for (i = 0; i < s->num_prompts; i++) {
9799 static char noprompt[] =
9800 "<server failed to send prompt>: ";
9802 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9803 echo = ssh2_pkt_getbool(pktin);
9806 prompt_len = lenof(noprompt)-1;
9808 add_prompt(s->cur_prompt,
9809 dupprintf("%.*s", prompt_len, prompt),
9814 /* FIXME: better prefix to distinguish from
9816 s->cur_prompt->name =
9817 dupprintf("SSH server: %.*s", name_len, name);
9818 s->cur_prompt->name_reqd = TRUE;
9820 s->cur_prompt->name =
9821 dupstr("SSH server authentication");
9822 s->cur_prompt->name_reqd = FALSE;
9824 /* We add a prefix to try to make it clear that a prompt
9825 * has come from the server.
9826 * FIXME: ugly to print "Using..." in prompt _every_
9827 * time round. Can this be done more subtly? */
9828 /* Special case: for reasons best known to themselves,
9829 * some servers send k-i requests with no prompts and
9830 * nothing to display. Keep quiet in this case. */
9831 if (s->num_prompts || name_len || inst_len) {
9832 s->cur_prompt->instruction =
9833 dupprintf("Using keyboard-interactive authentication.%s%.*s",
9834 inst_len ? "\n" : "", inst_len, inst);
9835 s->cur_prompt->instr_reqd = TRUE;
9837 s->cur_prompt->instr_reqd = FALSE;
9841 * Display any instructions, and get the user's
9845 int ret; /* not live over crReturn */
9846 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9849 crWaitUntilV(!pktin);
9850 ret = get_userpass_input(s->cur_prompt, in, inlen);
9855 * Failed to get responses. Terminate.
9857 free_prompts(s->cur_prompt);
9858 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9859 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9866 * Send the response(s) to the server.
9868 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
9869 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
9870 for (i=0; i < s->num_prompts; i++) {
9871 ssh2_pkt_addstring(s->pktout,
9872 s->cur_prompt->prompts[i]->result);
9874 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9877 * Free the prompts structure from this iteration.
9878 * If there's another, a new one will be allocated
9879 * when we return to the top of this while loop.
9881 free_prompts(s->cur_prompt);
9884 * Get the next packet in case it's another
9887 crWaitUntilV(pktin);
9892 * We should have SUCCESS or FAILURE now.
9896 } else if (s->can_passwd) {
9899 * Plain old password authentication.
9901 int ret; /* not live over crReturn */
9902 int changereq_first_time; /* not live over crReturn */
9904 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
9906 s->cur_prompt = new_prompts(ssh->frontend);
9907 s->cur_prompt->to_server = TRUE;
9908 s->cur_prompt->name = dupstr("SSH password");
9909 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
9914 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9917 crWaitUntilV(!pktin);
9918 ret = get_userpass_input(s->cur_prompt, in, inlen);
9923 * Failed to get responses. Terminate.
9925 free_prompts(s->cur_prompt);
9926 ssh_disconnect(ssh, NULL, "Unable to authenticate",
9927 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9932 * Squirrel away the password. (We may need it later if
9933 * asked to change it.)
9935 s->password = dupstr(s->cur_prompt->prompts[0]->result);
9936 free_prompts(s->cur_prompt);
9939 * Send the password packet.
9941 * We pad out the password packet to 256 bytes to make
9942 * it harder for an attacker to find the length of the
9945 * Anyone using a password longer than 256 bytes
9946 * probably doesn't have much to worry about from
9947 * people who find out how long their password is!
9949 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9950 ssh2_pkt_addstring(s->pktout, ssh->username);
9951 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9952 /* service requested */
9953 ssh2_pkt_addstring(s->pktout, "password");
9954 ssh2_pkt_addbool(s->pktout, FALSE);
9955 ssh2_pkt_addstring(s->pktout, s->password);
9956 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
9957 logevent("Sent password");
9958 s->type = AUTH_TYPE_PASSWORD;
9961 * Wait for next packet, in case it's a password change
9964 crWaitUntilV(pktin);
9965 changereq_first_time = TRUE;
9967 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
9970 * We're being asked for a new password
9971 * (perhaps not for the first time).
9972 * Loop until the server accepts it.
9975 int got_new = FALSE; /* not live over crReturn */
9976 char *prompt; /* not live over crReturn */
9977 int prompt_len; /* not live over crReturn */
9981 if (changereq_first_time)
9982 msg = "Server requested password change";
9984 msg = "Server rejected new password";
9986 c_write_str(ssh, msg);
9987 c_write_str(ssh, "\r\n");
9990 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
9992 s->cur_prompt = new_prompts(ssh->frontend);
9993 s->cur_prompt->to_server = TRUE;
9994 s->cur_prompt->name = dupstr("New SSH password");
9995 s->cur_prompt->instruction =
9996 dupprintf("%.*s", prompt_len, prompt);
9997 s->cur_prompt->instr_reqd = TRUE;
9999 * There's no explicit requirement in the protocol
10000 * for the "old" passwords in the original and
10001 * password-change messages to be the same, and
10002 * apparently some Cisco kit supports password change
10003 * by the user entering a blank password originally
10004 * and the real password subsequently, so,
10005 * reluctantly, we prompt for the old password again.
10007 * (On the other hand, some servers don't even bother
10008 * to check this field.)
10010 add_prompt(s->cur_prompt,
10011 dupstr("Current password (blank for previously entered password): "),
10013 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10015 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10019 * Loop until the user manages to enter the same
10024 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10027 crWaitUntilV(!pktin);
10028 ret = get_userpass_input(s->cur_prompt, in, inlen);
10033 * Failed to get responses. Terminate.
10035 /* burn the evidence */
10036 free_prompts(s->cur_prompt);
10037 smemclr(s->password, strlen(s->password));
10038 sfree(s->password);
10039 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10040 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10046 * If the user specified a new original password
10047 * (IYSWIM), overwrite any previously specified
10049 * (A side effect is that the user doesn't have to
10050 * re-enter it if they louse up the new password.)
10052 if (s->cur_prompt->prompts[0]->result[0]) {
10053 smemclr(s->password, strlen(s->password));
10054 /* burn the evidence */
10055 sfree(s->password);
10057 dupstr(s->cur_prompt->prompts[0]->result);
10061 * Check the two new passwords match.
10063 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10064 s->cur_prompt->prompts[2]->result)
10067 /* They don't. Silly user. */
10068 c_write_str(ssh, "Passwords do not match\r\n");
10073 * Send the new password (along with the old one).
10074 * (see above for padding rationale)
10076 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10077 ssh2_pkt_addstring(s->pktout, ssh->username);
10078 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10079 /* service requested */
10080 ssh2_pkt_addstring(s->pktout, "password");
10081 ssh2_pkt_addbool(s->pktout, TRUE);
10082 ssh2_pkt_addstring(s->pktout, s->password);
10083 ssh2_pkt_addstring(s->pktout,
10084 s->cur_prompt->prompts[1]->result);
10085 free_prompts(s->cur_prompt);
10086 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10087 logevent("Sent new password");
10090 * Now see what the server has to say about it.
10091 * (If it's CHANGEREQ again, it's not happy with the
10094 crWaitUntilV(pktin);
10095 changereq_first_time = FALSE;
10100 * We need to reexamine the current pktin at the top
10101 * of the loop. Either:
10102 * - we weren't asked to change password at all, in
10103 * which case it's a SUCCESS or FAILURE with the
10105 * - we sent a new password, and the server was
10106 * either OK with it (SUCCESS or FAILURE w/partial
10107 * success) or unhappy with the _old_ password
10108 * (FAILURE w/o partial success)
10109 * In any of these cases, we go back to the top of
10110 * the loop and start again.
10115 * We don't need the old password any more, in any
10116 * case. Burn the evidence.
10118 smemclr(s->password, strlen(s->password));
10119 sfree(s->password);
10122 char *str = dupprintf("No supported authentication methods available"
10123 " (server sent: %.*s)",
10126 ssh_disconnect(ssh, str,
10127 "No supported authentication methods available",
10128 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10138 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10140 /* Clear up various bits and pieces from authentication. */
10141 if (s->publickey_blob) {
10142 sfree(s->publickey_blob);
10143 sfree(s->publickey_comment);
10145 if (s->agent_response)
10146 sfree(s->agent_response);
10148 if (s->userauth_success && !ssh->bare_connection) {
10150 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10151 * packets since. Signal the transport layer to consider enacting
10152 * delayed compression.
10154 * (Relying on we_are_in is not sufficient, as
10155 * draft-miller-secsh-compression-delayed is quite clear that it
10156 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10157 * become set for other reasons.)
10159 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10162 ssh->channels = newtree234(ssh_channelcmp);
10165 * Set up handlers for some connection protocol messages, so we
10166 * don't have to handle them repeatedly in this coroutine.
10168 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10169 ssh2_msg_channel_window_adjust;
10170 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10171 ssh2_msg_global_request;
10174 * Create the main session channel.
10176 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10177 ssh->mainchan = NULL;
10179 ssh->mainchan = snew(struct ssh_channel);
10180 ssh->mainchan->ssh = ssh;
10181 ssh2_channel_init(ssh->mainchan);
10183 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10185 * Just start a direct-tcpip channel and use it as the main
10188 ssh_send_port_open(ssh->mainchan,
10189 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10190 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10192 ssh->ncmode = TRUE;
10194 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10195 logevent("Opening session as main channel");
10196 ssh2_pkt_send(ssh, s->pktout);
10197 ssh->ncmode = FALSE;
10199 crWaitUntilV(pktin);
10200 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10201 bombout(("Server refused to open channel"));
10203 /* FIXME: error data comes back in FAILURE packet */
10205 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10206 bombout(("Server's channel confirmation cited wrong channel"));
10209 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10210 ssh->mainchan->halfopen = FALSE;
10211 ssh->mainchan->type = CHAN_MAINSESSION;
10212 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10213 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10214 add234(ssh->channels, ssh->mainchan);
10215 update_specials_menu(ssh->frontend);
10216 logevent("Opened main channel");
10220 * Now we have a channel, make dispatch table entries for
10221 * general channel-based messages.
10223 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10224 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10225 ssh2_msg_channel_data;
10226 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10227 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10228 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10229 ssh2_msg_channel_open_confirmation;
10230 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10231 ssh2_msg_channel_open_failure;
10232 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10233 ssh2_msg_channel_request;
10234 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10235 ssh2_msg_channel_open;
10236 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10237 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10240 * Now the connection protocol is properly up and running, with
10241 * all those dispatch table entries, so it's safe to let
10242 * downstreams start trying to open extra channels through us.
10244 if (ssh->connshare)
10245 share_activate(ssh->connshare, ssh->v_s);
10247 if (ssh->mainchan && ssh_is_simple(ssh)) {
10249 * This message indicates to the server that we promise
10250 * not to try to run any other channel in parallel with
10251 * this one, so it's safe for it to advertise a very large
10252 * window and leave the flow control to TCP.
10254 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10255 "simple@putty.projects.tartarus.org",
10257 ssh2_pkt_send(ssh, s->pktout);
10261 * Enable port forwardings.
10263 ssh_setup_portfwd(ssh, ssh->conf);
10265 if (ssh->mainchan && !ssh->ncmode) {
10267 * Send the CHANNEL_REQUESTS for the main session channel.
10268 * Each one is handled by its own little asynchronous
10272 /* Potentially enable X11 forwarding. */
10273 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10275 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10277 if (!ssh->x11disp) {
10278 /* FIXME: return an error message from x11_setup_display */
10279 logevent("X11 forwarding not enabled: unable to"
10280 " initialise X display");
10282 ssh->x11auth = x11_invent_fake_auth
10283 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10284 ssh->x11auth->disp = ssh->x11disp;
10286 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10290 /* Potentially enable agent forwarding. */
10291 if (ssh_agent_forwarding_permitted(ssh))
10292 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10294 /* Now allocate a pty for the session. */
10295 if (!conf_get_int(ssh->conf, CONF_nopty))
10296 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10298 /* Send environment variables. */
10299 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10302 * Start a shell or a remote command. We may have to attempt
10303 * this twice if the config data has provided a second choice
10310 if (ssh->fallback_cmd) {
10311 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10312 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10314 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10315 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10319 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10320 ssh2_response_authconn, NULL);
10321 ssh2_pkt_addstring(s->pktout, cmd);
10323 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10324 ssh2_response_authconn, NULL);
10325 ssh2_pkt_addstring(s->pktout, cmd);
10327 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10328 ssh2_response_authconn, NULL);
10330 ssh2_pkt_send(ssh, s->pktout);
10332 crWaitUntilV(pktin);
10334 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10335 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10336 bombout(("Unexpected response to shell/command request:"
10337 " packet type %d", pktin->type));
10341 * We failed to start the command. If this is the
10342 * fallback command, we really are finished; if it's
10343 * not, and if the fallback command exists, try falling
10344 * back to it before complaining.
10346 if (!ssh->fallback_cmd &&
10347 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10348 logevent("Primary command failed; attempting fallback");
10349 ssh->fallback_cmd = TRUE;
10352 bombout(("Server refused to start a shell/command"));
10355 logevent("Started a shell/command");
10360 ssh->editing = ssh->echoing = TRUE;
10363 ssh->state = SSH_STATE_SESSION;
10364 if (ssh->size_needed)
10365 ssh_size(ssh, ssh->term_width, ssh->term_height);
10366 if (ssh->eof_needed)
10367 ssh_special(ssh, TS_EOF);
10373 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10378 s->try_send = FALSE;
10382 * _All_ the connection-layer packets we expect to
10383 * receive are now handled by the dispatch table.
10384 * Anything that reaches here must be bogus.
10387 bombout(("Strange packet received: type %d", pktin->type));
10389 } else if (ssh->mainchan) {
10391 * We have spare data. Add it to the channel buffer.
10393 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
10394 s->try_send = TRUE;
10398 struct ssh_channel *c;
10400 * Try to send data on all channels if we can.
10402 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
10403 ssh2_try_send_and_unthrottle(ssh, c);
10411 * Handlers for SSH-2 messages that might arrive at any moment.
10413 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10415 /* log reason code in disconnect message */
10417 int reason, msglen;
10419 reason = ssh_pkt_getuint32(pktin);
10420 ssh_pkt_getstring(pktin, &msg, &msglen);
10422 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10423 buf = dupprintf("Received disconnect message (%s)",
10424 ssh2_disconnect_reasons[reason]);
10426 buf = dupprintf("Received disconnect message (unknown"
10427 " type %d)", reason);
10431 buf = dupprintf("Disconnection message text: %.*s",
10434 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10436 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10437 ssh2_disconnect_reasons[reason] : "unknown",
10442 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10444 /* log the debug message */
10448 /* XXX maybe we should actually take notice of the return value */
10449 ssh2_pkt_getbool(pktin);
10450 ssh_pkt_getstring(pktin, &msg, &msglen);
10452 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
10455 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10457 do_ssh2_transport(ssh, NULL, 0, pktin);
10461 * Called if we receive a packet that isn't allowed by the protocol.
10462 * This only applies to packets whose meaning PuTTY understands.
10463 * Entirely unknown packets are handled below.
10465 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10467 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10468 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10470 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10474 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10476 struct Packet *pktout;
10477 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10478 ssh2_pkt_adduint32(pktout, pktin->sequence);
10480 * UNIMPLEMENTED messages MUST appear in the same order as the
10481 * messages they respond to. Hence, never queue them.
10483 ssh2_pkt_send_noqueue(ssh, pktout);
10487 * Handle the top-level SSH-2 protocol.
10489 static void ssh2_protocol_setup(Ssh ssh)
10494 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10496 for (i = 0; i < 256; i++)
10497 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10500 * Initially, we only accept transport messages (and a few generic
10501 * ones). do_ssh2_authconn will add more when it starts.
10502 * Messages that are understood but not currently acceptable go to
10503 * ssh2_msg_unexpected.
10505 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10506 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10507 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10508 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10509 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10510 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10511 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10512 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10513 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10514 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10515 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10516 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10517 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10518 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10519 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10520 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10521 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10522 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10523 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10524 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10525 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10526 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10527 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10528 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10529 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10530 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10531 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10532 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10533 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10534 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10535 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10536 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10537 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10540 * These messages have a special handler from the start.
10542 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10543 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10544 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10547 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10552 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10554 for (i = 0; i < 256; i++)
10555 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10558 * Initially, we set all ssh-connection messages to 'unexpected';
10559 * do_ssh2_authconn will fill things in properly. We also handle a
10560 * couple of messages from the transport protocol which aren't
10561 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10564 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10565 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10566 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10567 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10568 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10569 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10570 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10571 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10572 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10573 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10574 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10575 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10576 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10577 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10579 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10582 * These messages have a special handler from the start.
10584 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10585 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
10586 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10589 static void ssh2_timer(void *ctx, unsigned long now)
10591 Ssh ssh = (Ssh)ctx;
10593 if (ssh->state == SSH_STATE_CLOSED)
10596 if (!ssh->kex_in_progress && !ssh->bare_connection &&
10597 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
10598 now == ssh->next_rekey) {
10599 do_ssh2_transport(ssh, "timeout", -1, NULL);
10603 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
10604 struct Packet *pktin)
10606 unsigned char *in = (unsigned char *)vin;
10607 if (ssh->state == SSH_STATE_CLOSED)
10611 ssh->incoming_data_size += pktin->encrypted_len;
10612 if (!ssh->kex_in_progress &&
10613 ssh->max_data_size != 0 &&
10614 ssh->incoming_data_size > ssh->max_data_size)
10615 do_ssh2_transport(ssh, "too much data received", -1, NULL);
10619 ssh->packet_dispatch[pktin->type](ssh, pktin);
10620 else if (!ssh->protocol_initial_phase_done)
10621 do_ssh2_transport(ssh, in, inlen, pktin);
10623 do_ssh2_authconn(ssh, in, inlen, pktin);
10626 static void ssh2_bare_connection_protocol(Ssh ssh, void *vin, int inlen,
10627 struct Packet *pktin)
10629 unsigned char *in = (unsigned char *)vin;
10630 if (ssh->state == SSH_STATE_CLOSED)
10634 ssh->packet_dispatch[pktin->type](ssh, pktin);
10636 do_ssh2_authconn(ssh, in, inlen, pktin);
10639 static void ssh_cache_conf_values(Ssh ssh)
10641 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
10645 * Called to set up the connection.
10647 * Returns an error message, or NULL on success.
10649 static const char *ssh_init(void *frontend_handle, void **backend_handle,
10650 Conf *conf, char *host, int port, char **realhost,
10651 int nodelay, int keepalive)
10656 ssh = snew(struct ssh_tag);
10657 ssh->conf = conf_copy(conf);
10658 ssh_cache_conf_values(ssh);
10659 ssh->version = 0; /* when not ready yet */
10661 ssh->cipher = NULL;
10662 ssh->v1_cipher_ctx = NULL;
10663 ssh->crcda_ctx = NULL;
10664 ssh->cscipher = NULL;
10665 ssh->cs_cipher_ctx = NULL;
10666 ssh->sccipher = NULL;
10667 ssh->sc_cipher_ctx = NULL;
10669 ssh->cs_mac_ctx = NULL;
10671 ssh->sc_mac_ctx = NULL;
10672 ssh->cscomp = NULL;
10673 ssh->cs_comp_ctx = NULL;
10674 ssh->sccomp = NULL;
10675 ssh->sc_comp_ctx = NULL;
10677 ssh->kex_ctx = NULL;
10678 ssh->hostkey = NULL;
10679 ssh->hostkey_str = NULL;
10680 ssh->exitcode = -1;
10681 ssh->close_expected = FALSE;
10682 ssh->clean_exit = FALSE;
10683 ssh->state = SSH_STATE_PREPACKET;
10684 ssh->size_needed = FALSE;
10685 ssh->eof_needed = FALSE;
10687 ssh->logctx = NULL;
10688 ssh->deferred_send_data = NULL;
10689 ssh->deferred_len = 0;
10690 ssh->deferred_size = 0;
10691 ssh->fallback_cmd = 0;
10692 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
10693 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
10694 ssh->x11disp = NULL;
10695 ssh->x11auth = NULL;
10696 ssh->x11authtree = newtree234(x11_authcmp);
10697 ssh->v1_compressing = FALSE;
10698 ssh->v2_outgoing_sequence = 0;
10699 ssh->ssh1_rdpkt_crstate = 0;
10700 ssh->ssh2_rdpkt_crstate = 0;
10701 ssh->ssh2_bare_rdpkt_crstate = 0;
10702 ssh->ssh_gotdata_crstate = 0;
10703 ssh->do_ssh1_connection_crstate = 0;
10704 ssh->do_ssh_init_state = NULL;
10705 ssh->do_ssh_connection_init_state = NULL;
10706 ssh->do_ssh1_login_state = NULL;
10707 ssh->do_ssh2_transport_state = NULL;
10708 ssh->do_ssh2_authconn_state = NULL;
10711 ssh->mainchan = NULL;
10712 ssh->throttled_all = 0;
10713 ssh->v1_stdout_throttling = 0;
10715 ssh->queuelen = ssh->queuesize = 0;
10716 ssh->queueing = FALSE;
10717 ssh->qhead = ssh->qtail = NULL;
10718 ssh->deferred_rekey_reason = NULL;
10719 bufchain_init(&ssh->queued_incoming_data);
10720 ssh->frozen = FALSE;
10721 ssh->username = NULL;
10722 ssh->sent_console_eof = FALSE;
10723 ssh->got_pty = FALSE;
10724 ssh->bare_connection = FALSE;
10725 ssh->X11_fwd_enabled = FALSE;
10726 ssh->connshare = NULL;
10727 ssh->attempting_connshare = FALSE;
10729 *backend_handle = ssh;
10732 if (crypto_startup() == 0)
10733 return "Microsoft high encryption pack not installed!";
10736 ssh->frontend = frontend_handle;
10737 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
10738 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
10740 ssh->channels = NULL;
10741 ssh->rportfwds = NULL;
10742 ssh->portfwds = NULL;
10747 ssh->conn_throttle_count = 0;
10748 ssh->overall_bufsize = 0;
10749 ssh->fallback_cmd = 0;
10751 ssh->protocol = NULL;
10753 ssh->protocol_initial_phase_done = FALSE;
10755 ssh->pinger = NULL;
10757 ssh->incoming_data_size = ssh->outgoing_data_size =
10758 ssh->deferred_data_size = 0L;
10759 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10760 CONF_ssh_rekey_data));
10761 ssh->kex_in_progress = FALSE;
10764 ssh->gsslibs = NULL;
10767 random_ref(); /* do this now - may be needed by sharing setup code */
10769 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
10778 static void ssh_free(void *handle)
10780 Ssh ssh = (Ssh) handle;
10781 struct ssh_channel *c;
10782 struct ssh_rportfwd *pf;
10783 struct X11FakeAuth *auth;
10785 if (ssh->v1_cipher_ctx)
10786 ssh->cipher->free_context(ssh->v1_cipher_ctx);
10787 if (ssh->cs_cipher_ctx)
10788 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
10789 if (ssh->sc_cipher_ctx)
10790 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
10791 if (ssh->cs_mac_ctx)
10792 ssh->csmac->free_context(ssh->cs_mac_ctx);
10793 if (ssh->sc_mac_ctx)
10794 ssh->scmac->free_context(ssh->sc_mac_ctx);
10795 if (ssh->cs_comp_ctx) {
10797 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
10799 zlib_compress_cleanup(ssh->cs_comp_ctx);
10801 if (ssh->sc_comp_ctx) {
10803 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
10805 zlib_decompress_cleanup(ssh->sc_comp_ctx);
10808 dh_cleanup(ssh->kex_ctx);
10809 sfree(ssh->savedhost);
10811 while (ssh->queuelen-- > 0)
10812 ssh_free_packet(ssh->queue[ssh->queuelen]);
10815 while (ssh->qhead) {
10816 struct queued_handler *qh = ssh->qhead;
10817 ssh->qhead = qh->next;
10820 ssh->qhead = ssh->qtail = NULL;
10822 if (ssh->channels) {
10823 while ((c = delpos234(ssh->channels, 0)) != NULL) {
10826 if (c->u.x11.xconn != NULL)
10827 x11_close(c->u.x11.xconn);
10829 case CHAN_SOCKDATA:
10830 case CHAN_SOCKDATA_DORMANT:
10831 if (c->u.pfd.pf != NULL)
10832 pfd_close(c->u.pfd.pf);
10835 if (ssh->version == 2) {
10836 struct outstanding_channel_request *ocr, *nocr;
10837 ocr = c->v.v2.chanreq_head;
10839 ocr->handler(c, NULL, ocr->ctx);
10844 bufchain_clear(&c->v.v2.outbuffer);
10848 freetree234(ssh->channels);
10849 ssh->channels = NULL;
10852 if (ssh->connshare)
10853 sharestate_free(ssh->connshare);
10855 if (ssh->rportfwds) {
10856 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
10858 freetree234(ssh->rportfwds);
10859 ssh->rportfwds = NULL;
10861 sfree(ssh->deferred_send_data);
10863 x11_free_display(ssh->x11disp);
10864 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
10865 x11_free_fake_auth(auth);
10866 freetree234(ssh->x11authtree);
10867 sfree(ssh->do_ssh_init_state);
10868 sfree(ssh->do_ssh1_login_state);
10869 sfree(ssh->do_ssh2_transport_state);
10870 sfree(ssh->do_ssh2_authconn_state);
10873 sfree(ssh->fullhostname);
10874 sfree(ssh->hostkey_str);
10875 if (ssh->crcda_ctx) {
10876 crcda_free_context(ssh->crcda_ctx);
10877 ssh->crcda_ctx = NULL;
10880 ssh_do_close(ssh, TRUE);
10881 expire_timer_context(ssh);
10883 pinger_free(ssh->pinger);
10884 bufchain_clear(&ssh->queued_incoming_data);
10885 sfree(ssh->username);
10886 conf_free(ssh->conf);
10889 ssh_gss_cleanup(ssh->gsslibs);
10897 * Reconfigure the SSH backend.
10899 static void ssh_reconfig(void *handle, Conf *conf)
10901 Ssh ssh = (Ssh) handle;
10902 char *rekeying = NULL, rekey_mandatory = FALSE;
10903 unsigned long old_max_data_size;
10906 pinger_reconfig(ssh->pinger, ssh->conf, conf);
10908 ssh_setup_portfwd(ssh, conf);
10910 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
10911 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
10913 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
10914 unsigned long now = GETTICKCOUNT();
10916 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
10917 rekeying = "timeout shortened";
10919 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
10923 old_max_data_size = ssh->max_data_size;
10924 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
10925 CONF_ssh_rekey_data));
10926 if (old_max_data_size != ssh->max_data_size &&
10927 ssh->max_data_size != 0) {
10928 if (ssh->outgoing_data_size > ssh->max_data_size ||
10929 ssh->incoming_data_size > ssh->max_data_size)
10930 rekeying = "data limit lowered";
10933 if (conf_get_int(ssh->conf, CONF_compression) !=
10934 conf_get_int(conf, CONF_compression)) {
10935 rekeying = "compression setting changed";
10936 rekey_mandatory = TRUE;
10939 for (i = 0; i < CIPHER_MAX; i++)
10940 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
10941 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
10942 rekeying = "cipher settings changed";
10943 rekey_mandatory = TRUE;
10945 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
10946 conf_get_int(conf, CONF_ssh2_des_cbc)) {
10947 rekeying = "cipher settings changed";
10948 rekey_mandatory = TRUE;
10951 conf_free(ssh->conf);
10952 ssh->conf = conf_copy(conf);
10953 ssh_cache_conf_values(ssh);
10955 if (!ssh->bare_connection && rekeying) {
10956 if (!ssh->kex_in_progress) {
10957 do_ssh2_transport(ssh, rekeying, -1, NULL);
10958 } else if (rekey_mandatory) {
10959 ssh->deferred_rekey_reason = rekeying;
10965 * Called to send data down the SSH connection.
10967 static int ssh_send(void *handle, char *buf, int len)
10969 Ssh ssh = (Ssh) handle;
10971 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10974 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
10976 return ssh_sendbuffer(ssh);
10980 * Called to query the current amount of buffered stdin data.
10982 static int ssh_sendbuffer(void *handle)
10984 Ssh ssh = (Ssh) handle;
10985 int override_value;
10987 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
10991 * If the SSH socket itself has backed up, add the total backup
10992 * size on that to any individual buffer on the stdin channel.
10994 override_value = 0;
10995 if (ssh->throttled_all)
10996 override_value = ssh->overall_bufsize;
10998 if (ssh->version == 1) {
10999 return override_value;
11000 } else if (ssh->version == 2) {
11001 if (!ssh->mainchan)
11002 return override_value;
11004 return (override_value +
11005 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11012 * Called to set the size of the window from SSH's POV.
11014 static void ssh_size(void *handle, int width, int height)
11016 Ssh ssh = (Ssh) handle;
11017 struct Packet *pktout;
11019 ssh->term_width = width;
11020 ssh->term_height = height;
11022 switch (ssh->state) {
11023 case SSH_STATE_BEFORE_SIZE:
11024 case SSH_STATE_PREPACKET:
11025 case SSH_STATE_CLOSED:
11026 break; /* do nothing */
11027 case SSH_STATE_INTERMED:
11028 ssh->size_needed = TRUE; /* buffer for later */
11030 case SSH_STATE_SESSION:
11031 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11032 if (ssh->version == 1) {
11033 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11034 PKT_INT, ssh->term_height,
11035 PKT_INT, ssh->term_width,
11036 PKT_INT, 0, PKT_INT, 0, PKT_END);
11037 } else if (ssh->mainchan) {
11038 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11040 ssh2_pkt_adduint32(pktout, ssh->term_width);
11041 ssh2_pkt_adduint32(pktout, ssh->term_height);
11042 ssh2_pkt_adduint32(pktout, 0);
11043 ssh2_pkt_adduint32(pktout, 0);
11044 ssh2_pkt_send(ssh, pktout);
11052 * Return a list of the special codes that make sense in this
11055 static const struct telnet_special *ssh_get_specials(void *handle)
11057 static const struct telnet_special ssh1_ignore_special[] = {
11058 {"IGNORE message", TS_NOP}
11060 static const struct telnet_special ssh2_ignore_special[] = {
11061 {"IGNORE message", TS_NOP},
11063 static const struct telnet_special ssh2_rekey_special[] = {
11064 {"Repeat key exchange", TS_REKEY},
11066 static const struct telnet_special ssh2_session_specials[] = {
11069 /* These are the signal names defined by RFC 4254.
11070 * They include all the ISO C signals, but are a subset of the POSIX
11071 * required signals. */
11072 {"SIGINT (Interrupt)", TS_SIGINT},
11073 {"SIGTERM (Terminate)", TS_SIGTERM},
11074 {"SIGKILL (Kill)", TS_SIGKILL},
11075 {"SIGQUIT (Quit)", TS_SIGQUIT},
11076 {"SIGHUP (Hangup)", TS_SIGHUP},
11077 {"More signals", TS_SUBMENU},
11078 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11079 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11080 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11081 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11082 {NULL, TS_EXITMENU}
11084 static const struct telnet_special specials_end[] = {
11085 {NULL, TS_EXITMENU}
11087 /* XXX review this length for any changes: */
11088 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
11089 lenof(ssh2_rekey_special) +
11090 lenof(ssh2_session_specials) +
11091 lenof(specials_end)];
11092 Ssh ssh = (Ssh) handle;
11094 #define ADD_SPECIALS(name) \
11096 assert((i + lenof(name)) <= lenof(ssh_specials)); \
11097 memcpy(&ssh_specials[i], name, sizeof name); \
11098 i += lenof(name); \
11101 if (ssh->version == 1) {
11102 /* Don't bother offering IGNORE if we've decided the remote
11103 * won't cope with it, since we wouldn't bother sending it if
11105 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11106 ADD_SPECIALS(ssh1_ignore_special);
11107 } else if (ssh->version == 2) {
11108 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11109 ADD_SPECIALS(ssh2_ignore_special);
11110 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11111 ADD_SPECIALS(ssh2_rekey_special);
11113 ADD_SPECIALS(ssh2_session_specials);
11114 } /* else we're not ready yet */
11117 ADD_SPECIALS(specials_end);
11118 return ssh_specials;
11122 #undef ADD_SPECIALS
11126 * Send special codes. TS_EOF is useful for `plink', so you
11127 * can send an EOF and collect resulting output (e.g. `plink
11130 static void ssh_special(void *handle, Telnet_Special code)
11132 Ssh ssh = (Ssh) handle;
11133 struct Packet *pktout;
11135 if (code == TS_EOF) {
11136 if (ssh->state != SSH_STATE_SESSION) {
11138 * Buffer the EOF in case we are pre-SESSION, so we can
11139 * send it as soon as we reach SESSION.
11141 if (code == TS_EOF)
11142 ssh->eof_needed = TRUE;
11145 if (ssh->version == 1) {
11146 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11147 } else if (ssh->mainchan) {
11148 sshfwd_write_eof(ssh->mainchan);
11149 ssh->send_ok = 0; /* now stop trying to read from stdin */
11151 logevent("Sent EOF message");
11152 } else if (code == TS_PING || code == TS_NOP) {
11153 if (ssh->state == SSH_STATE_CLOSED
11154 || ssh->state == SSH_STATE_PREPACKET) return;
11155 if (ssh->version == 1) {
11156 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11157 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11159 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11160 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11161 ssh2_pkt_addstring_start(pktout);
11162 ssh2_pkt_send_noqueue(ssh, pktout);
11165 } else if (code == TS_REKEY) {
11166 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11167 ssh->version == 2) {
11168 do_ssh2_transport(ssh, "at user request", -1, NULL);
11170 } else if (code == TS_BRK) {
11171 if (ssh->state == SSH_STATE_CLOSED
11172 || ssh->state == SSH_STATE_PREPACKET) return;
11173 if (ssh->version == 1) {
11174 logevent("Unable to send BREAK signal in SSH-1");
11175 } else if (ssh->mainchan) {
11176 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11177 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11178 ssh2_pkt_send(ssh, pktout);
11181 /* Is is a POSIX signal? */
11182 char *signame = NULL;
11183 if (code == TS_SIGABRT) signame = "ABRT";
11184 if (code == TS_SIGALRM) signame = "ALRM";
11185 if (code == TS_SIGFPE) signame = "FPE";
11186 if (code == TS_SIGHUP) signame = "HUP";
11187 if (code == TS_SIGILL) signame = "ILL";
11188 if (code == TS_SIGINT) signame = "INT";
11189 if (code == TS_SIGKILL) signame = "KILL";
11190 if (code == TS_SIGPIPE) signame = "PIPE";
11191 if (code == TS_SIGQUIT) signame = "QUIT";
11192 if (code == TS_SIGSEGV) signame = "SEGV";
11193 if (code == TS_SIGTERM) signame = "TERM";
11194 if (code == TS_SIGUSR1) signame = "USR1";
11195 if (code == TS_SIGUSR2) signame = "USR2";
11196 /* The SSH-2 protocol does in principle support arbitrary named
11197 * signals, including signame@domain, but we don't support those. */
11199 /* It's a signal. */
11200 if (ssh->version == 2 && ssh->mainchan) {
11201 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11202 ssh2_pkt_addstring(pktout, signame);
11203 ssh2_pkt_send(ssh, pktout);
11204 logeventf(ssh, "Sent signal SIG%s", signame);
11207 /* Never heard of it. Do nothing */
11212 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11214 Ssh ssh = (Ssh) handle;
11215 struct ssh_channel *c;
11216 c = snew(struct ssh_channel);
11219 ssh2_channel_init(c);
11220 c->halfopen = TRUE;
11221 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11223 add234(ssh->channels, c);
11227 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11229 struct ssh_channel *c;
11230 c = snew(struct ssh_channel);
11233 ssh2_channel_init(c);
11234 c->type = CHAN_SHARING;
11235 c->u.sharing.ctx = sharing_ctx;
11236 add234(ssh->channels, c);
11240 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11242 struct ssh_channel *c;
11244 c = find234(ssh->channels, &localid, ssh_channelfind);
11246 ssh_channel_destroy(c);
11249 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11250 const void *data, int datalen,
11251 const char *additional_log_text)
11253 struct Packet *pkt;
11255 pkt = ssh2_pkt_init(type);
11256 pkt->downstream_id = id;
11257 pkt->additional_log_text = additional_log_text;
11258 ssh2_pkt_adddata(pkt, data, datalen);
11259 ssh2_pkt_send(ssh, pkt);
11263 * This is called when stdout/stderr (the entity to which
11264 * from_backend sends data) manages to clear some backlog.
11266 static void ssh_unthrottle(void *handle, int bufsize)
11268 Ssh ssh = (Ssh) handle;
11271 if (ssh->version == 1) {
11272 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11273 ssh->v1_stdout_throttling = 0;
11274 ssh_throttle_conn(ssh, -1);
11277 if (ssh->mainchan) {
11278 ssh2_set_window(ssh->mainchan,
11279 bufsize < ssh->mainchan->v.v2.locmaxwin ?
11280 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11281 if (ssh_is_simple(ssh))
11284 buflimit = ssh->mainchan->v.v2.locmaxwin;
11285 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11286 ssh->mainchan->throttling_conn = 0;
11287 ssh_throttle_conn(ssh, -1);
11293 * Now process any SSH connection data that was stashed in our
11294 * queue while we were frozen.
11296 ssh_process_queued_incoming_data(ssh);
11299 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
11301 struct ssh_channel *c = (struct ssh_channel *)channel;
11303 struct Packet *pktout;
11305 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11307 if (ssh->version == 1) {
11308 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11309 PKT_INT, c->localid,
11312 /* PKT_STR, <org:orgport>, */
11315 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11317 char *trimmed_host = host_strduptrim(hostname);
11318 ssh2_pkt_addstring(pktout, trimmed_host);
11319 sfree(trimmed_host);
11321 ssh2_pkt_adduint32(pktout, port);
11323 * We make up values for the originator data; partly it's
11324 * too much hassle to keep track, and partly I'm not
11325 * convinced the server should be told details like that
11326 * about my local network configuration.
11327 * The "originator IP address" is syntactically a numeric
11328 * IP address, and some servers (e.g., Tectia) get upset
11329 * if it doesn't match this syntax.
11331 ssh2_pkt_addstring(pktout, "0.0.0.0");
11332 ssh2_pkt_adduint32(pktout, 0);
11333 ssh2_pkt_send(ssh, pktout);
11337 static int ssh_connected(void *handle)
11339 Ssh ssh = (Ssh) handle;
11340 return ssh->s != NULL;
11343 static int ssh_sendok(void *handle)
11345 Ssh ssh = (Ssh) handle;
11346 return ssh->send_ok;
11349 static int ssh_ldisc(void *handle, int option)
11351 Ssh ssh = (Ssh) handle;
11352 if (option == LD_ECHO)
11353 return ssh->echoing;
11354 if (option == LD_EDIT)
11355 return ssh->editing;
11359 static void ssh_provide_ldisc(void *handle, void *ldisc)
11361 Ssh ssh = (Ssh) handle;
11362 ssh->ldisc = ldisc;
11365 static void ssh_provide_logctx(void *handle, void *logctx)
11367 Ssh ssh = (Ssh) handle;
11368 ssh->logctx = logctx;
11371 static int ssh_return_exitcode(void *handle)
11373 Ssh ssh = (Ssh) handle;
11374 if (ssh->s != NULL)
11377 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11381 * cfg_info for SSH is the protocol running in this session.
11382 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11383 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11385 static int ssh_cfg_info(void *handle)
11387 Ssh ssh = (Ssh) handle;
11388 if (ssh->version == 0)
11389 return 0; /* don't know yet */
11390 else if (ssh->bare_connection)
11393 return ssh->version;
11397 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11398 * that fails. This variable is the means by which scp.c can reach
11399 * into the SSH code and find out which one it got.
11401 extern int ssh_fallback_cmd(void *handle)
11403 Ssh ssh = (Ssh) handle;
11404 return ssh->fallback_cmd;
11407 Backend ssh_backend = {
11417 ssh_return_exitcode,
11421 ssh_provide_logctx,