29 * Packet type contexts, so that ssh2_pkt_type can correctly decode
30 * the ambiguous type numbers back into the correct type strings.
41 SSH2_PKTCTX_PUBLICKEY,
47 static const char *const ssh2_disconnect_reasons[] = {
49 "host not allowed to connect",
51 "key exchange failed",
52 "host authentication failed",
55 "service not available",
56 "protocol version not supported",
57 "host key not verifiable",
60 "too many connections",
61 "auth cancelled by user",
62 "no more auth methods available",
67 * Various remote-bug flags.
69 #define BUG_CHOKES_ON_SSH1_IGNORE 1
70 #define BUG_SSH2_HMAC 2
71 #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
72 #define BUG_CHOKES_ON_RSA 8
73 #define BUG_SSH2_RSA_PADDING 16
74 #define BUG_SSH2_DERIVEKEY 32
75 #define BUG_SSH2_REKEY 64
76 #define BUG_SSH2_PK_SESSIONID 128
77 #define BUG_SSH2_MAXPKT 256
78 #define BUG_CHOKES_ON_SSH2_IGNORE 512
79 #define BUG_CHOKES_ON_WINADJ 1024
80 #define BUG_SENDS_LATE_REQUEST_REPLY 2048
81 #define BUG_SSH2_OLDGEX 4096
83 #define DH_MIN_SIZE 1024
84 #define DH_MAX_SIZE 8192
87 * Codes for terminal modes.
88 * Most of these are the same in SSH-1 and SSH-2.
89 * This list is derived from RFC 4254 and
93 const char* const mode;
95 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
97 /* "V" prefix discarded for special characters relative to SSH specs */
98 { "INTR", 1, TTY_OP_CHAR },
99 { "QUIT", 2, TTY_OP_CHAR },
100 { "ERASE", 3, TTY_OP_CHAR },
101 { "KILL", 4, TTY_OP_CHAR },
102 { "EOF", 5, TTY_OP_CHAR },
103 { "EOL", 6, TTY_OP_CHAR },
104 { "EOL2", 7, TTY_OP_CHAR },
105 { "START", 8, TTY_OP_CHAR },
106 { "STOP", 9, TTY_OP_CHAR },
107 { "SUSP", 10, TTY_OP_CHAR },
108 { "DSUSP", 11, TTY_OP_CHAR },
109 { "REPRINT", 12, TTY_OP_CHAR },
110 { "WERASE", 13, TTY_OP_CHAR },
111 { "LNEXT", 14, TTY_OP_CHAR },
112 { "FLUSH", 15, TTY_OP_CHAR },
113 { "SWTCH", 16, TTY_OP_CHAR },
114 { "STATUS", 17, TTY_OP_CHAR },
115 { "DISCARD", 18, TTY_OP_CHAR },
116 { "IGNPAR", 30, TTY_OP_BOOL },
117 { "PARMRK", 31, TTY_OP_BOOL },
118 { "INPCK", 32, TTY_OP_BOOL },
119 { "ISTRIP", 33, TTY_OP_BOOL },
120 { "INLCR", 34, TTY_OP_BOOL },
121 { "IGNCR", 35, TTY_OP_BOOL },
122 { "ICRNL", 36, TTY_OP_BOOL },
123 { "IUCLC", 37, TTY_OP_BOOL },
124 { "IXON", 38, TTY_OP_BOOL },
125 { "IXANY", 39, TTY_OP_BOOL },
126 { "IXOFF", 40, TTY_OP_BOOL },
127 { "IMAXBEL", 41, TTY_OP_BOOL },
128 { "ISIG", 50, TTY_OP_BOOL },
129 { "ICANON", 51, TTY_OP_BOOL },
130 { "XCASE", 52, TTY_OP_BOOL },
131 { "ECHO", 53, TTY_OP_BOOL },
132 { "ECHOE", 54, TTY_OP_BOOL },
133 { "ECHOK", 55, TTY_OP_BOOL },
134 { "ECHONL", 56, TTY_OP_BOOL },
135 { "NOFLSH", 57, TTY_OP_BOOL },
136 { "TOSTOP", 58, TTY_OP_BOOL },
137 { "IEXTEN", 59, TTY_OP_BOOL },
138 { "ECHOCTL", 60, TTY_OP_BOOL },
139 { "ECHOKE", 61, TTY_OP_BOOL },
140 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
141 { "OPOST", 70, TTY_OP_BOOL },
142 { "OLCUC", 71, TTY_OP_BOOL },
143 { "ONLCR", 72, TTY_OP_BOOL },
144 { "OCRNL", 73, TTY_OP_BOOL },
145 { "ONOCR", 74, TTY_OP_BOOL },
146 { "ONLRET", 75, TTY_OP_BOOL },
147 { "CS7", 90, TTY_OP_BOOL },
148 { "CS8", 91, TTY_OP_BOOL },
149 { "PARENB", 92, TTY_OP_BOOL },
150 { "PARODD", 93, TTY_OP_BOOL }
153 /* Miscellaneous other tty-related constants. */
154 #define SSH_TTY_OP_END 0
155 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
156 #define SSH1_TTY_OP_ISPEED 192
157 #define SSH1_TTY_OP_OSPEED 193
158 #define SSH2_TTY_OP_ISPEED 128
159 #define SSH2_TTY_OP_OSPEED 129
161 /* Helper functions for parsing tty-related config. */
162 static unsigned int ssh_tty_parse_specchar(char *s)
167 ret = ctrlparse(s, &next);
168 if (!next) ret = s[0];
170 ret = 255; /* special value meaning "don't set" */
174 static unsigned int ssh_tty_parse_boolean(char *s)
176 if (stricmp(s, "yes") == 0 ||
177 stricmp(s, "on") == 0 ||
178 stricmp(s, "true") == 0 ||
179 stricmp(s, "+") == 0)
181 else if (stricmp(s, "no") == 0 ||
182 stricmp(s, "off") == 0 ||
183 stricmp(s, "false") == 0 ||
184 stricmp(s, "-") == 0)
185 return 0; /* false */
187 return (atoi(s) != 0);
190 #define translate(x) if (type == x) return #x
191 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
192 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
193 static const char *ssh1_pkt_type(int type)
195 translate(SSH1_MSG_DISCONNECT);
196 translate(SSH1_SMSG_PUBLIC_KEY);
197 translate(SSH1_CMSG_SESSION_KEY);
198 translate(SSH1_CMSG_USER);
199 translate(SSH1_CMSG_AUTH_RSA);
200 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
201 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
202 translate(SSH1_CMSG_AUTH_PASSWORD);
203 translate(SSH1_CMSG_REQUEST_PTY);
204 translate(SSH1_CMSG_WINDOW_SIZE);
205 translate(SSH1_CMSG_EXEC_SHELL);
206 translate(SSH1_CMSG_EXEC_CMD);
207 translate(SSH1_SMSG_SUCCESS);
208 translate(SSH1_SMSG_FAILURE);
209 translate(SSH1_CMSG_STDIN_DATA);
210 translate(SSH1_SMSG_STDOUT_DATA);
211 translate(SSH1_SMSG_STDERR_DATA);
212 translate(SSH1_CMSG_EOF);
213 translate(SSH1_SMSG_EXIT_STATUS);
214 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
215 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
216 translate(SSH1_MSG_CHANNEL_DATA);
217 translate(SSH1_MSG_CHANNEL_CLOSE);
218 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
219 translate(SSH1_SMSG_X11_OPEN);
220 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
221 translate(SSH1_MSG_PORT_OPEN);
222 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
223 translate(SSH1_SMSG_AGENT_OPEN);
224 translate(SSH1_MSG_IGNORE);
225 translate(SSH1_CMSG_EXIT_CONFIRMATION);
226 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
227 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
228 translate(SSH1_MSG_DEBUG);
229 translate(SSH1_CMSG_REQUEST_COMPRESSION);
230 translate(SSH1_CMSG_AUTH_TIS);
231 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
232 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
233 translate(SSH1_CMSG_AUTH_CCARD);
234 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
235 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
238 static const char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx,
241 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
242 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
243 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
244 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
245 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
246 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
247 translate(SSH2_MSG_DISCONNECT);
248 translate(SSH2_MSG_IGNORE);
249 translate(SSH2_MSG_UNIMPLEMENTED);
250 translate(SSH2_MSG_DEBUG);
251 translate(SSH2_MSG_SERVICE_REQUEST);
252 translate(SSH2_MSG_SERVICE_ACCEPT);
253 translate(SSH2_MSG_KEXINIT);
254 translate(SSH2_MSG_NEWKEYS);
255 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
256 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
257 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD, SSH2_PKTCTX_DHGEX);
258 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
259 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
260 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
261 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
262 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
263 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
264 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
265 translatek(SSH2_MSG_KEX_ECDH_INIT, SSH2_PKTCTX_ECDHKEX);
266 translatek(SSH2_MSG_KEX_ECDH_REPLY, SSH2_PKTCTX_ECDHKEX);
267 translate(SSH2_MSG_USERAUTH_REQUEST);
268 translate(SSH2_MSG_USERAUTH_FAILURE);
269 translate(SSH2_MSG_USERAUTH_SUCCESS);
270 translate(SSH2_MSG_USERAUTH_BANNER);
271 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
272 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
273 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
274 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
275 translate(SSH2_MSG_GLOBAL_REQUEST);
276 translate(SSH2_MSG_REQUEST_SUCCESS);
277 translate(SSH2_MSG_REQUEST_FAILURE);
278 translate(SSH2_MSG_CHANNEL_OPEN);
279 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
280 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
281 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
282 translate(SSH2_MSG_CHANNEL_DATA);
283 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
284 translate(SSH2_MSG_CHANNEL_EOF);
285 translate(SSH2_MSG_CHANNEL_CLOSE);
286 translate(SSH2_MSG_CHANNEL_REQUEST);
287 translate(SSH2_MSG_CHANNEL_SUCCESS);
288 translate(SSH2_MSG_CHANNEL_FAILURE);
294 /* Enumeration values for fields in SSH-1 packets */
296 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
300 * Coroutine mechanics for the sillier bits of the code. If these
301 * macros look impenetrable to you, you might find it helpful to
304 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
306 * which explains the theory behind these macros.
308 * In particular, if you are getting `case expression not constant'
309 * errors when building with MS Visual Studio, this is because MS's
310 * Edit and Continue debugging feature causes their compiler to
311 * violate ANSI C. To disable Edit and Continue debugging:
313 * - right-click ssh.c in the FileView
315 * - select the C/C++ tab and the General category
316 * - under `Debug info:', select anything _other_ than `Program
317 * Database for Edit and Continue'.
319 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
320 #define crBeginState crBegin(s->crLine)
321 #define crStateP(t, v) \
323 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
325 #define crState(t) crStateP(t, ssh->t)
326 #define crFinish(z) } *crLine = 0; return (z); }
327 #define crFinishV } *crLine = 0; return; }
328 #define crFinishFree(z) } sfree(s); return (z); }
329 #define crFinishFreeV } sfree(s); return; }
330 #define crReturn(z) \
332 *crLine =__LINE__; return (z); case __LINE__:;\
336 *crLine=__LINE__; return; case __LINE__:;\
338 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
339 #define crStopV do{ *crLine = 0; return; }while(0)
340 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
341 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
345 static struct Packet *ssh1_pkt_init(int pkt_type);
346 static struct Packet *ssh2_pkt_init(int pkt_type);
347 static void ssh_pkt_ensure(struct Packet *, int length);
348 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
349 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
350 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
351 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
352 static void ssh_pkt_addstring_start(struct Packet *);
353 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
354 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
355 static void ssh_pkt_addstring(struct Packet *, const char *data);
356 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
357 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
358 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
359 static int ssh2_pkt_construct(Ssh, struct Packet *);
360 static void ssh2_pkt_send(Ssh, struct Packet *);
361 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
362 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
363 struct Packet *pktin);
364 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
365 struct Packet *pktin);
366 static void ssh2_channel_check_close(struct ssh_channel *c);
367 static void ssh_channel_destroy(struct ssh_channel *c);
368 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin);
371 * Buffer management constants. There are several of these for
372 * various different purposes:
374 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
375 * on a local data stream before we throttle the whole SSH
376 * connection (in SSH-1 only). Throttling the whole connection is
377 * pretty drastic so we set this high in the hope it won't
380 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
381 * on the SSH connection itself before we defensively throttle
382 * _all_ local data streams. This is pretty drastic too (though
383 * thankfully unlikely in SSH-2 since the window mechanism should
384 * ensure that the server never has any need to throttle its end
385 * of the connection), so we set this high as well.
387 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
390 * - OUR_V2_BIGWIN is the window size we advertise for the only
391 * channel in a simple connection. It must be <= INT_MAX.
393 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
394 * to the remote side. This actually has nothing to do with the
395 * size of the _packet_, but is instead a limit on the amount
396 * of data we're willing to receive in a single SSH2 channel
399 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
400 * _packet_ we're prepared to cope with. It must be a multiple
401 * of the cipher block size, and must be at least 35000.
404 #define SSH1_BUFFER_LIMIT 32768
405 #define SSH_MAX_BACKLOG 32768
406 #define OUR_V2_WINSIZE 16384
407 #define OUR_V2_BIGWIN 0x7fffffff
408 #define OUR_V2_MAXPKT 0x4000UL
409 #define OUR_V2_PACKETLIMIT 0x9000UL
411 const static struct ssh_signkey *hostkey_algs[] = {
413 &ssh_ecdsa_nistp256, &ssh_ecdsa_nistp384, &ssh_ecdsa_nistp521,
417 const static struct ssh_mac *macs[] = {
418 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
420 const static struct ssh_mac *buggymacs[] = {
421 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
424 static void *ssh_comp_none_init(void)
428 static void ssh_comp_none_cleanup(void *handle)
431 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
432 unsigned char **outblock, int *outlen)
436 static int ssh_comp_none_disable(void *handle)
440 const static struct ssh_compress ssh_comp_none = {
442 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
443 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
444 ssh_comp_none_disable, NULL
446 extern const struct ssh_compress ssh_zlib;
447 const static struct ssh_compress *compressions[] = {
448 &ssh_zlib, &ssh_comp_none
451 enum { /* channel types */
456 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
458 * CHAN_SHARING indicates a channel which is tracked here on
459 * behalf of a connection-sharing downstream. We do almost nothing
460 * with these channels ourselves: all messages relating to them
461 * get thrown straight to sshshare.c and passed on almost
462 * unmodified to downstream.
466 * CHAN_ZOMBIE is used to indicate a channel for which we've
467 * already destroyed the local data source: for instance, if a
468 * forwarded port experiences a socket error on the local side, we
469 * immediately destroy its local socket and turn the SSH channel
475 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
476 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
477 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
480 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
483 struct outstanding_channel_request {
484 cchandler_fn_t handler;
486 struct outstanding_channel_request *next;
490 * 2-3-4 tree storing channels.
493 Ssh ssh; /* pointer back to main context */
494 unsigned remoteid, localid;
496 /* True if we opened this channel but server hasn't confirmed. */
499 * In SSH-1, this value contains four bits:
501 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
502 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
503 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
504 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
506 * A channel is completely finished with when all four bits are set.
508 * In SSH-2, the four bits mean:
510 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
511 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
512 * 4 We have received SSH2_MSG_CHANNEL_EOF.
513 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
515 * A channel is completely finished with when we have both sent
516 * and received CLOSE.
518 * The symbolic constants below use the SSH-2 terminology, which
519 * is a bit confusing in SSH-1, but we have to use _something_.
521 #define CLOSES_SENT_EOF 1
522 #define CLOSES_SENT_CLOSE 2
523 #define CLOSES_RCVD_EOF 4
524 #define CLOSES_RCVD_CLOSE 8
528 * This flag indicates that an EOF is pending on the outgoing side
529 * of the channel: that is, wherever we're getting the data for
530 * this channel has sent us some data followed by EOF. We can't
531 * actually send the EOF until we've finished sending the data, so
532 * we set this flag instead to remind us to do so once our buffer
538 * True if this channel is causing the underlying connection to be
543 struct ssh2_data_channel {
545 unsigned remwindow, remmaxpkt;
546 /* locwindow is signed so we can cope with excess data. */
547 int locwindow, locmaxwin;
549 * remlocwin is the amount of local window that we think
550 * the remote end had available to it after it sent the
551 * last data packet or window adjust ack.
555 * These store the list of channel requests that haven't
558 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
559 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
563 struct ssh_agent_channel {
564 unsigned char *message;
565 unsigned char msglen[4];
566 unsigned lensofar, totallen;
567 int outstanding_requests;
569 struct ssh_x11_channel {
570 struct X11Connection *xconn;
573 struct ssh_pfd_channel {
574 struct PortForwarding *pf;
576 struct ssh_sharing_channel {
583 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
584 * use this structure in different ways, reflecting SSH-2's
585 * altogether saner approach to port forwarding.
587 * In SSH-1, you arrange a remote forwarding by sending the server
588 * the remote port number, and the local destination host:port.
589 * When a connection comes in, the server sends you back that
590 * host:port pair, and you connect to it. This is a ready-made
591 * security hole if you're not on the ball: a malicious server
592 * could send you back _any_ host:port pair, so if you trustingly
593 * connect to the address it gives you then you've just opened the
594 * entire inside of your corporate network just by connecting
595 * through it to a dodgy SSH server. Hence, we must store a list of
596 * host:port pairs we _are_ trying to forward to, and reject a
597 * connection request from the server if it's not in the list.
599 * In SSH-2, each side of the connection minds its own business and
600 * doesn't send unnecessary information to the other. You arrange a
601 * remote forwarding by sending the server just the remote port
602 * number. When a connection comes in, the server tells you which
603 * of its ports was connected to; and _you_ have to remember what
604 * local host:port pair went with that port number.
606 * Hence, in SSH-1 this structure is indexed by destination
607 * host:port pair, whereas in SSH-2 it is indexed by source port.
609 struct ssh_portfwd; /* forward declaration */
611 struct ssh_rportfwd {
612 unsigned sport, dport;
616 struct ssh_portfwd *pfrec;
619 static void free_rportfwd(struct ssh_rportfwd *pf)
622 sfree(pf->sportdesc);
630 * Separately to the rportfwd tree (which is for looking up port
631 * open requests from the server), a tree of _these_ structures is
632 * used to keep track of all the currently open port forwardings,
633 * so that we can reconfigure in mid-session if the user requests
637 enum { DESTROY, KEEP, CREATE } status;
639 unsigned sport, dport;
642 struct ssh_rportfwd *remote;
644 struct PortListener *local;
646 #define free_portfwd(pf) ( \
647 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
648 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
651 long length; /* length of packet: see below */
652 long forcepad; /* SSH-2: force padding to at least this length */
653 int type; /* only used for incoming packets */
654 unsigned long sequence; /* SSH-2 incoming sequence number */
655 unsigned char *data; /* allocated storage */
656 unsigned char *body; /* offset of payload within `data' */
657 long savedpos; /* dual-purpose saved packet position: see below */
658 long maxlen; /* amount of storage allocated for `data' */
659 long encrypted_len; /* for SSH-2 total-size counting */
662 * A note on the 'length' and 'savedpos' fields above.
664 * Incoming packets are set up so that pkt->length is measured
665 * relative to pkt->body, which itself points to a few bytes after
666 * pkt->data (skipping some uninteresting header fields including
667 * the packet type code). The ssh_pkt_get* functions all expect
668 * this setup, and they also use pkt->savedpos to indicate how far
669 * through the packet being decoded they've got - and that, too,
670 * is an offset from pkt->body rather than pkt->data.
672 * During construction of an outgoing packet, however, pkt->length
673 * is measured relative to the base pointer pkt->data, and
674 * pkt->body is not really used for anything until the packet is
675 * ready for sending. In this mode, pkt->savedpos is reused as a
676 * temporary variable by the addstring functions, which write out
677 * a string length field and then keep going back and updating it
678 * as more data is appended to the subsequent string data field;
679 * pkt->savedpos stores the offset (again relative to pkt->data)
680 * of the start of the string data field.
683 /* Extra metadata used in SSH packet logging mode, allowing us to
684 * log in the packet header line that the packet came from a
685 * connection-sharing downstream and what if anything unusual was
686 * done to it. The additional_log_text field is expected to be a
687 * static string - it will not be freed. */
688 unsigned downstream_id;
689 const char *additional_log_text;
692 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
693 struct Packet *pktin);
694 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
695 struct Packet *pktin);
696 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
697 struct Packet *pktin);
698 static void ssh1_protocol_setup(Ssh ssh);
699 static void ssh2_protocol_setup(Ssh ssh);
700 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
701 static void ssh_size(void *handle, int width, int height);
702 static void ssh_special(void *handle, Telnet_Special);
703 static int ssh2_try_send(struct ssh_channel *c);
704 static void ssh2_add_channel_data(struct ssh_channel *c,
705 const char *buf, int len);
706 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
707 static void ssh2_set_window(struct ssh_channel *c, int newwin);
708 static int ssh_sendbuffer(void *handle);
709 static int ssh_do_close(Ssh ssh, int notify_exit);
710 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
711 static int ssh2_pkt_getbool(struct Packet *pkt);
712 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
713 static void ssh2_timer(void *ctx, unsigned long now);
714 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
715 struct Packet *pktin);
716 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
718 struct rdpkt1_state_tag {
719 long len, pad, biglen, to_read;
720 unsigned long realcrc, gotcrc;
724 struct Packet *pktin;
727 struct rdpkt2_state_tag {
728 long len, pad, payload, packetlen, maclen;
731 unsigned long incoming_sequence;
732 struct Packet *pktin;
735 struct rdpkt2_bare_state_tag {
739 unsigned long incoming_sequence;
740 struct Packet *pktin;
743 struct queued_handler;
744 struct queued_handler {
746 chandler_fn_t handler;
748 struct queued_handler *next;
752 const struct plug_function_table *fn;
753 /* the above field _must_ be first in the structure */
763 unsigned char session_key[32];
765 int v1_remote_protoflags;
766 int v1_local_protoflags;
767 int agentfwd_enabled;
770 const struct ssh_cipher *cipher;
773 const struct ssh2_cipher *cscipher, *sccipher;
774 void *cs_cipher_ctx, *sc_cipher_ctx;
775 const struct ssh_mac *csmac, *scmac;
776 int csmac_etm, scmac_etm;
777 void *cs_mac_ctx, *sc_mac_ctx;
778 const struct ssh_compress *cscomp, *sccomp;
779 void *cs_comp_ctx, *sc_comp_ctx;
780 const struct ssh_kex *kex;
781 const struct ssh_signkey *hostkey;
782 char *hostkey_str; /* string representation, for easy checking in rekeys */
783 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
784 int v2_session_id_len;
788 int attempting_connshare;
794 int echoing, editing;
799 int ospeed, ispeed; /* temporaries */
800 int term_width, term_height;
802 tree234 *channels; /* indexed by local id */
803 struct ssh_channel *mainchan; /* primary session channel */
804 int ncmode; /* is primary channel direct-tcpip? */
809 tree234 *rportfwds, *portfwds;
813 SSH_STATE_BEFORE_SIZE,
819 int size_needed, eof_needed;
820 int sent_console_eof;
821 int got_pty; /* affects EOF behaviour on main channel */
823 struct Packet **queue;
824 int queuelen, queuesize;
826 unsigned char *deferred_send_data;
827 int deferred_len, deferred_size;
830 * Gross hack: pscp will try to start SFTP but fall back to
831 * scp1 if that fails. This variable is the means by which
832 * scp.c can reach into the SSH code and find out which one it
837 bufchain banner; /* accumulates banners during do_ssh2_authconn */
842 struct X11Display *x11disp;
843 struct X11FakeAuth *x11auth;
844 tree234 *x11authtree;
847 int conn_throttle_count;
850 int v1_stdout_throttling;
851 unsigned long v2_outgoing_sequence;
853 int ssh1_rdpkt_crstate;
854 int ssh2_rdpkt_crstate;
855 int ssh2_bare_rdpkt_crstate;
856 int ssh_gotdata_crstate;
857 int do_ssh1_connection_crstate;
859 void *do_ssh_init_state;
860 void *do_ssh1_login_state;
861 void *do_ssh2_transport_state;
862 void *do_ssh2_authconn_state;
863 void *do_ssh_connection_init_state;
865 struct rdpkt1_state_tag rdpkt1_state;
866 struct rdpkt2_state_tag rdpkt2_state;
867 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
869 /* SSH-1 and SSH-2 use this for different things, but both use it */
870 int protocol_initial_phase_done;
872 void (*protocol) (Ssh ssh, const void *vin, int inlen,
874 struct Packet *(*s_rdpkt) (Ssh ssh, const unsigned char **data,
876 int (*do_ssh_init)(Ssh ssh, unsigned char c);
879 * We maintain our own copy of a Conf structure here. That way,
880 * when we're passed a new one for reconfiguration, we can check
881 * the differences and potentially reconfigure port forwardings
882 * etc in mid-session.
887 * Values cached out of conf so as to avoid the tree234 lookup
888 * cost every time they're used.
893 * Dynamically allocated username string created during SSH
894 * login. Stored in here rather than in the coroutine state so
895 * that it'll be reliably freed if we shut down the SSH session
896 * at some unexpected moment.
901 * Used to transfer data back from async callbacks.
903 void *agent_response;
904 int agent_response_len;
908 * The SSH connection can be set as `frozen', meaning we are
909 * not currently accepting incoming data from the network. This
910 * is slightly more serious than setting the _socket_ as
911 * frozen, because we may already have had data passed to us
912 * from the network which we need to delay processing until
913 * after the freeze is lifted, so we also need a bufchain to
917 bufchain queued_incoming_data;
920 * Dispatch table for packet types that we may have to deal
923 handler_fn_t packet_dispatch[256];
926 * Queues of one-off handler functions for success/failure
927 * indications from a request.
929 struct queued_handler *qhead, *qtail;
930 handler_fn_t q_saved_handler1, q_saved_handler2;
933 * This module deals with sending keepalives.
938 * Track incoming and outgoing data sizes and time, for
941 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
942 unsigned long max_data_size;
944 unsigned long next_rekey, last_rekey;
945 const char *deferred_rekey_reason;
948 * Fully qualified host name, which we need if doing GSSAPI.
954 * GSSAPI libraries for this session.
956 struct ssh_gss_liblist *gsslibs;
960 * The last list returned from get_specials.
962 struct telnet_special *specials;
965 * List of host key algorithms for which we _don't_ have a stored
966 * host key. These are indices into the main hostkey_algs[] array
968 int uncert_hostkeys[lenof(hostkey_algs)];
969 int n_uncert_hostkeys;
972 * Flag indicating that the current rekey is intended to finish
973 * with a newly cross-certified host key.
975 int cross_certifying;
978 #define logevent(s) logevent(ssh->frontend, s)
980 /* logevent, only printf-formatted. */
981 static void logeventf(Ssh ssh, const char *fmt, ...)
987 buf = dupvprintf(fmt, ap);
993 static void bomb_out(Ssh ssh, char *text)
995 ssh_do_close(ssh, FALSE);
997 connection_fatal(ssh->frontend, "%s", text);
1001 #define bombout(msg) bomb_out(ssh, dupprintf msg)
1003 /* Helper function for common bits of parsing ttymodes. */
1004 static void parse_ttymodes(Ssh ssh,
1005 void (*do_mode)(void *data, char *mode, char *val),
1010 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
1012 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
1014 * val[0] is either 'V', indicating that an explicit value
1015 * follows it, or 'A' indicating that we should pass the
1016 * value through from the local environment via get_ttymode.
1018 if (val[0] == 'A') {
1019 val = get_ttymode(ssh->frontend, key);
1021 do_mode(data, key, val);
1025 do_mode(data, key, val + 1); /* skip the 'V' */
1029 static int ssh_channelcmp(void *av, void *bv)
1031 struct ssh_channel *a = (struct ssh_channel *) av;
1032 struct ssh_channel *b = (struct ssh_channel *) bv;
1033 if (a->localid < b->localid)
1035 if (a->localid > b->localid)
1039 static int ssh_channelfind(void *av, void *bv)
1041 unsigned *a = (unsigned *) av;
1042 struct ssh_channel *b = (struct ssh_channel *) bv;
1043 if (*a < b->localid)
1045 if (*a > b->localid)
1050 static int ssh_rportcmp_ssh1(void *av, void *bv)
1052 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1053 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1055 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1056 return i < 0 ? -1 : +1;
1057 if (a->dport > b->dport)
1059 if (a->dport < b->dport)
1064 static int ssh_rportcmp_ssh2(void *av, void *bv)
1066 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1067 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1069 if ( (i = strcmp(a->shost, b->shost)) != 0)
1070 return i < 0 ? -1 : +1;
1071 if (a->sport > b->sport)
1073 if (a->sport < b->sport)
1079 * Special form of strcmp which can cope with NULL inputs. NULL is
1080 * defined to sort before even the empty string.
1082 static int nullstrcmp(const char *a, const char *b)
1084 if (a == NULL && b == NULL)
1090 return strcmp(a, b);
1093 static int ssh_portcmp(void *av, void *bv)
1095 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1096 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1098 if (a->type > b->type)
1100 if (a->type < b->type)
1102 if (a->addressfamily > b->addressfamily)
1104 if (a->addressfamily < b->addressfamily)
1106 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1107 return i < 0 ? -1 : +1;
1108 if (a->sport > b->sport)
1110 if (a->sport < b->sport)
1112 if (a->type != 'D') {
1113 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1114 return i < 0 ? -1 : +1;
1115 if (a->dport > b->dport)
1117 if (a->dport < b->dport)
1123 static int alloc_channel_id(Ssh ssh)
1125 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1126 unsigned low, high, mid;
1128 struct ssh_channel *c;
1131 * First-fit allocation of channel numbers: always pick the
1132 * lowest unused one. To do this, binary-search using the
1133 * counted B-tree to find the largest channel ID which is in a
1134 * contiguous sequence from the beginning. (Precisely
1135 * everything in that sequence must have ID equal to its tree
1136 * index plus CHANNEL_NUMBER_OFFSET.)
1138 tsize = count234(ssh->channels);
1142 while (high - low > 1) {
1143 mid = (high + low) / 2;
1144 c = index234(ssh->channels, mid);
1145 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1146 low = mid; /* this one is fine */
1148 high = mid; /* this one is past it */
1151 * Now low points to either -1, or the tree index of the
1152 * largest ID in the initial sequence.
1155 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1156 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1158 return low + 1 + CHANNEL_NUMBER_OFFSET;
1161 static void c_write_stderr(int trusted, const char *buf, int len)
1164 for (i = 0; i < len; i++)
1165 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1166 fputc(buf[i], stderr);
1169 static void c_write(Ssh ssh, const char *buf, int len)
1171 if (flags & FLAG_STDERR)
1172 c_write_stderr(1, buf, len);
1174 from_backend(ssh->frontend, 1, buf, len);
1177 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1179 if (flags & FLAG_STDERR)
1180 c_write_stderr(0, buf, len);
1182 from_backend_untrusted(ssh->frontend, buf, len);
1185 static void c_write_str(Ssh ssh, const char *buf)
1187 c_write(ssh, buf, strlen(buf));
1190 static void ssh_free_packet(struct Packet *pkt)
1195 static struct Packet *ssh_new_packet(void)
1197 struct Packet *pkt = snew(struct Packet);
1199 pkt->body = pkt->data = NULL;
1205 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1208 struct logblank_t blanks[4];
1214 if (ssh->logomitdata &&
1215 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1216 pkt->type == SSH1_SMSG_STDERR_DATA ||
1217 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1218 /* "Session data" packets - omit the data string. */
1219 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1220 ssh_pkt_getuint32(pkt); /* skip channel id */
1221 blanks[nblanks].offset = pkt->savedpos + 4;
1222 blanks[nblanks].type = PKTLOG_OMIT;
1223 ssh_pkt_getstring(pkt, &str, &slen);
1225 blanks[nblanks].len = slen;
1229 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1230 ssh1_pkt_type(pkt->type),
1231 pkt->body, pkt->length, nblanks, blanks, NULL,
1235 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1238 struct logblank_t blanks[4];
1243 * For outgoing packets, pkt->length represents the length of the
1244 * whole packet starting at pkt->data (including some header), and
1245 * pkt->body refers to the point within that where the log-worthy
1246 * payload begins. However, incoming packets expect pkt->length to
1247 * represent only the payload length (that is, it's measured from
1248 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1249 * packet to conform to the incoming-packet semantics, so that we
1250 * can analyse it with the ssh_pkt_get functions.
1252 pkt->length -= (pkt->body - pkt->data);
1255 if (ssh->logomitdata &&
1256 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1257 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1258 /* "Session data" packets - omit the data string. */
1259 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1260 ssh_pkt_getuint32(pkt); /* skip channel id */
1261 blanks[nblanks].offset = pkt->savedpos + 4;
1262 blanks[nblanks].type = PKTLOG_OMIT;
1263 ssh_pkt_getstring(pkt, &str, &slen);
1265 blanks[nblanks].len = slen;
1270 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1271 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1272 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1273 conf_get_int(ssh->conf, CONF_logomitpass)) {
1274 /* If this is a password or similar packet, blank the password(s). */
1275 blanks[nblanks].offset = 0;
1276 blanks[nblanks].len = pkt->length;
1277 blanks[nblanks].type = PKTLOG_BLANK;
1279 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1280 conf_get_int(ssh->conf, CONF_logomitpass)) {
1282 * If this is an X forwarding request packet, blank the fake
1285 * Note that while we blank the X authentication data here, we
1286 * don't take any special action to blank the start of an X11
1287 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1288 * an X connection without having session blanking enabled is
1289 * likely to leak your cookie into the log.
1292 ssh_pkt_getstring(pkt, &str, &slen);
1293 blanks[nblanks].offset = pkt->savedpos;
1294 blanks[nblanks].type = PKTLOG_BLANK;
1295 ssh_pkt_getstring(pkt, &str, &slen);
1297 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1302 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1303 ssh1_pkt_type(pkt->data[12]),
1304 pkt->body, pkt->length,
1305 nblanks, blanks, NULL, 0, NULL);
1308 * Undo the above adjustment of pkt->length, to put the packet
1309 * back in the state we found it.
1311 pkt->length += (pkt->body - pkt->data);
1315 * Collect incoming data in the incoming packet buffer.
1316 * Decipher and verify the packet when it is completely read.
1317 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1318 * Update the *data and *datalen variables.
1319 * Return a Packet structure when a packet is completed.
1321 static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
1324 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1326 crBegin(ssh->ssh1_rdpkt_crstate);
1328 st->pktin = ssh_new_packet();
1330 st->pktin->type = 0;
1331 st->pktin->length = 0;
1333 for (st->i = st->len = 0; st->i < 4; st->i++) {
1334 while ((*datalen) == 0)
1336 st->len = (st->len << 8) + **data;
1337 (*data)++, (*datalen)--;
1340 st->pad = 8 - (st->len % 8);
1341 st->biglen = st->len + st->pad;
1342 st->pktin->length = st->len - 5;
1344 if (st->biglen < 0) {
1345 bombout(("Extremely large packet length from server suggests"
1346 " data stream corruption"));
1347 ssh_free_packet(st->pktin);
1351 st->pktin->maxlen = st->biglen;
1352 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1354 st->to_read = st->biglen;
1355 st->p = st->pktin->data;
1356 while (st->to_read > 0) {
1357 st->chunk = st->to_read;
1358 while ((*datalen) == 0)
1360 if (st->chunk > (*datalen))
1361 st->chunk = (*datalen);
1362 memcpy(st->p, *data, st->chunk);
1364 *datalen -= st->chunk;
1366 st->to_read -= st->chunk;
1369 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1370 st->biglen, NULL)) {
1371 bombout(("Network attack (CRC compensation) detected!"));
1372 ssh_free_packet(st->pktin);
1377 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1379 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1380 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1381 if (st->gotcrc != st->realcrc) {
1382 bombout(("Incorrect CRC received on packet"));
1383 ssh_free_packet(st->pktin);
1387 st->pktin->body = st->pktin->data + st->pad + 1;
1389 if (ssh->v1_compressing) {
1390 unsigned char *decompblk;
1392 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1393 st->pktin->body - 1, st->pktin->length + 1,
1394 &decompblk, &decomplen)) {
1395 bombout(("Zlib decompression encountered invalid data"));
1396 ssh_free_packet(st->pktin);
1400 if (st->pktin->maxlen < st->pad + decomplen) {
1401 st->pktin->maxlen = st->pad + decomplen;
1402 st->pktin->data = sresize(st->pktin->data,
1403 st->pktin->maxlen + APIEXTRA,
1405 st->pktin->body = st->pktin->data + st->pad + 1;
1408 memcpy(st->pktin->body - 1, decompblk, decomplen);
1410 st->pktin->length = decomplen - 1;
1413 st->pktin->type = st->pktin->body[-1];
1416 * Now pktin->body and pktin->length identify the semantic content
1417 * of the packet, excluding the initial type byte.
1421 ssh1_log_incoming_packet(ssh, st->pktin);
1423 st->pktin->savedpos = 0;
1425 crFinish(st->pktin);
1428 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1431 struct logblank_t blanks[4];
1437 if (ssh->logomitdata &&
1438 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1439 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1440 /* "Session data" packets - omit the data string. */
1441 ssh_pkt_getuint32(pkt); /* skip channel id */
1442 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1443 ssh_pkt_getuint32(pkt); /* skip extended data type */
1444 blanks[nblanks].offset = pkt->savedpos + 4;
1445 blanks[nblanks].type = PKTLOG_OMIT;
1446 ssh_pkt_getstring(pkt, &str, &slen);
1448 blanks[nblanks].len = slen;
1453 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1454 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1455 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1459 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1462 struct logblank_t blanks[4];
1467 * For outgoing packets, pkt->length represents the length of the
1468 * whole packet starting at pkt->data (including some header), and
1469 * pkt->body refers to the point within that where the log-worthy
1470 * payload begins. However, incoming packets expect pkt->length to
1471 * represent only the payload length (that is, it's measured from
1472 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1473 * packet to conform to the incoming-packet semantics, so that we
1474 * can analyse it with the ssh_pkt_get functions.
1476 pkt->length -= (pkt->body - pkt->data);
1479 if (ssh->logomitdata &&
1480 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1481 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1482 /* "Session data" packets - omit the data string. */
1483 ssh_pkt_getuint32(pkt); /* skip channel id */
1484 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1485 ssh_pkt_getuint32(pkt); /* skip extended data type */
1486 blanks[nblanks].offset = pkt->savedpos + 4;
1487 blanks[nblanks].type = PKTLOG_OMIT;
1488 ssh_pkt_getstring(pkt, &str, &slen);
1490 blanks[nblanks].len = slen;
1495 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1496 conf_get_int(ssh->conf, CONF_logomitpass)) {
1497 /* If this is a password packet, blank the password(s). */
1499 ssh_pkt_getstring(pkt, &str, &slen);
1500 ssh_pkt_getstring(pkt, &str, &slen);
1501 ssh_pkt_getstring(pkt, &str, &slen);
1502 if (slen == 8 && !memcmp(str, "password", 8)) {
1503 ssh2_pkt_getbool(pkt);
1504 /* Blank the password field. */
1505 blanks[nblanks].offset = pkt->savedpos;
1506 blanks[nblanks].type = PKTLOG_BLANK;
1507 ssh_pkt_getstring(pkt, &str, &slen);
1509 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1511 /* If there's another password field beyond it (change of
1512 * password), blank that too. */
1513 ssh_pkt_getstring(pkt, &str, &slen);
1515 blanks[nblanks-1].len =
1516 pkt->savedpos - blanks[nblanks].offset;
1519 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1520 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1521 conf_get_int(ssh->conf, CONF_logomitpass)) {
1522 /* If this is a keyboard-interactive response packet, blank
1525 ssh_pkt_getuint32(pkt);
1526 blanks[nblanks].offset = pkt->savedpos;
1527 blanks[nblanks].type = PKTLOG_BLANK;
1529 ssh_pkt_getstring(pkt, &str, &slen);
1533 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1535 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1536 conf_get_int(ssh->conf, CONF_logomitpass)) {
1538 * If this is an X forwarding request packet, blank the fake
1541 * Note that while we blank the X authentication data here, we
1542 * don't take any special action to blank the start of an X11
1543 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1544 * an X connection without having session blanking enabled is
1545 * likely to leak your cookie into the log.
1548 ssh_pkt_getuint32(pkt);
1549 ssh_pkt_getstring(pkt, &str, &slen);
1550 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1551 ssh2_pkt_getbool(pkt);
1552 ssh2_pkt_getbool(pkt);
1553 ssh_pkt_getstring(pkt, &str, &slen);
1554 blanks[nblanks].offset = pkt->savedpos;
1555 blanks[nblanks].type = PKTLOG_BLANK;
1556 ssh_pkt_getstring(pkt, &str, &slen);
1558 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1564 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1565 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1566 pkt->body, pkt->length, nblanks, blanks,
1567 &ssh->v2_outgoing_sequence,
1568 pkt->downstream_id, pkt->additional_log_text);
1571 * Undo the above adjustment of pkt->length, to put the packet
1572 * back in the state we found it.
1574 pkt->length += (pkt->body - pkt->data);
1577 static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
1580 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1582 crBegin(ssh->ssh2_rdpkt_crstate);
1584 st->pktin = ssh_new_packet();
1586 st->pktin->type = 0;
1587 st->pktin->length = 0;
1589 st->cipherblk = ssh->sccipher->blksize;
1592 if (st->cipherblk < 8)
1594 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1596 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1597 ssh->scmac && !ssh->scmac_etm) {
1599 * When dealing with a CBC-mode cipher, we want to avoid the
1600 * possibility of an attacker's tweaking the ciphertext stream
1601 * so as to cause us to feed the same block to the block
1602 * cipher more than once and thus leak information
1603 * (VU#958563). The way we do this is not to take any
1604 * decisions on the basis of anything we've decrypted until
1605 * we've verified it with a MAC. That includes the packet
1606 * length, so we just read data and check the MAC repeatedly,
1607 * and when the MAC passes, see if the length we've got is
1610 * This defence is unnecessary in OpenSSH ETM mode, because
1611 * the whole point of ETM mode is that the attacker can't
1612 * tweak the ciphertext stream at all without the MAC
1613 * detecting it before we decrypt anything.
1616 /* May as well allocate the whole lot now. */
1617 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1620 /* Read an amount corresponding to the MAC. */
1621 for (st->i = 0; st->i < st->maclen; st->i++) {
1622 while ((*datalen) == 0)
1624 st->pktin->data[st->i] = *(*data)++;
1630 unsigned char seq[4];
1631 ssh->scmac->start(ssh->sc_mac_ctx);
1632 PUT_32BIT(seq, st->incoming_sequence);
1633 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1636 for (;;) { /* Once around this loop per cipher block. */
1637 /* Read another cipher-block's worth, and tack it onto the end. */
1638 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1639 while ((*datalen) == 0)
1641 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1644 /* Decrypt one more block (a little further back in the stream). */
1645 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1646 st->pktin->data + st->packetlen,
1648 /* Feed that block to the MAC. */
1649 ssh->scmac->bytes(ssh->sc_mac_ctx,
1650 st->pktin->data + st->packetlen, st->cipherblk);
1651 st->packetlen += st->cipherblk;
1652 /* See if that gives us a valid packet. */
1653 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1654 st->pktin->data + st->packetlen) &&
1655 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1658 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1659 bombout(("No valid incoming packet found"));
1660 ssh_free_packet(st->pktin);
1664 st->pktin->maxlen = st->packetlen + st->maclen;
1665 st->pktin->data = sresize(st->pktin->data,
1666 st->pktin->maxlen + APIEXTRA,
1668 } else if (ssh->scmac && ssh->scmac_etm) {
1669 st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1672 * OpenSSH encrypt-then-MAC mode: the packet length is
1673 * unencrypted, unless the cipher supports length encryption.
1675 for (st->i = st->len = 0; st->i < 4; st->i++) {
1676 while ((*datalen) == 0)
1678 st->pktin->data[st->i] = *(*data)++;
1681 /* Cipher supports length decryption, so do it */
1682 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
1683 /* Keep the packet the same though, so the MAC passes */
1684 unsigned char len[4];
1685 memcpy(len, st->pktin->data, 4);
1686 ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
1687 st->len = toint(GET_32BIT(len));
1689 st->len = toint(GET_32BIT(st->pktin->data));
1693 * _Completely_ silly lengths should be stomped on before they
1694 * do us any more damage.
1696 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1697 st->len % st->cipherblk != 0) {
1698 bombout(("Incoming packet length field was garbled"));
1699 ssh_free_packet(st->pktin);
1704 * So now we can work out the total packet length.
1706 st->packetlen = st->len + 4;
1709 * Allocate memory for the rest of the packet.
1711 st->pktin->maxlen = st->packetlen + st->maclen;
1712 st->pktin->data = sresize(st->pktin->data,
1713 st->pktin->maxlen + APIEXTRA,
1717 * Read the remainder of the packet.
1719 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1720 while ((*datalen) == 0)
1722 st->pktin->data[st->i] = *(*data)++;
1730 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1731 st->len + 4, st->incoming_sequence)) {
1732 bombout(("Incorrect MAC received on packet"));
1733 ssh_free_packet(st->pktin);
1737 /* Decrypt everything between the length field and the MAC. */
1739 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1740 st->pktin->data + 4,
1743 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1746 * Acquire and decrypt the first block of the packet. This will
1747 * contain the length and padding details.
1749 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1750 while ((*datalen) == 0)
1752 st->pktin->data[st->i] = *(*data)++;
1757 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1758 st->pktin->data, st->cipherblk);
1761 * Now get the length figure.
1763 st->len = toint(GET_32BIT(st->pktin->data));
1766 * _Completely_ silly lengths should be stomped on before they
1767 * do us any more damage.
1769 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1770 (st->len + 4) % st->cipherblk != 0) {
1771 bombout(("Incoming packet was garbled on decryption"));
1772 ssh_free_packet(st->pktin);
1777 * So now we can work out the total packet length.
1779 st->packetlen = st->len + 4;
1782 * Allocate memory for the rest of the packet.
1784 st->pktin->maxlen = st->packetlen + st->maclen;
1785 st->pktin->data = sresize(st->pktin->data,
1786 st->pktin->maxlen + APIEXTRA,
1790 * Read and decrypt the remainder of the packet.
1792 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1794 while ((*datalen) == 0)
1796 st->pktin->data[st->i] = *(*data)++;
1799 /* Decrypt everything _except_ the MAC. */
1801 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1802 st->pktin->data + st->cipherblk,
1803 st->packetlen - st->cipherblk);
1809 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1810 st->len + 4, st->incoming_sequence)) {
1811 bombout(("Incorrect MAC received on packet"));
1812 ssh_free_packet(st->pktin);
1816 /* Get and sanity-check the amount of random padding. */
1817 st->pad = st->pktin->data[4];
1818 if (st->pad < 4 || st->len - st->pad < 1) {
1819 bombout(("Invalid padding length on received packet"));
1820 ssh_free_packet(st->pktin);
1824 * This enables us to deduce the payload length.
1826 st->payload = st->len - st->pad - 1;
1828 st->pktin->length = st->payload + 5;
1829 st->pktin->encrypted_len = st->packetlen;
1831 st->pktin->sequence = st->incoming_sequence++;
1833 st->pktin->length = st->packetlen - st->pad;
1834 assert(st->pktin->length >= 0);
1837 * Decompress packet payload.
1840 unsigned char *newpayload;
1843 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1844 st->pktin->data + 5, st->pktin->length - 5,
1845 &newpayload, &newlen)) {
1846 if (st->pktin->maxlen < newlen + 5) {
1847 st->pktin->maxlen = newlen + 5;
1848 st->pktin->data = sresize(st->pktin->data,
1849 st->pktin->maxlen + APIEXTRA,
1852 st->pktin->length = 5 + newlen;
1853 memcpy(st->pktin->data + 5, newpayload, newlen);
1859 * RFC 4253 doesn't explicitly say that completely empty packets
1860 * with no type byte are forbidden, so treat them as deserving
1861 * an SSH_MSG_UNIMPLEMENTED.
1863 if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */
1864 ssh2_msg_something_unimplemented(ssh, st->pktin);
1868 * pktin->body and pktin->length should identify the semantic
1869 * content of the packet, excluding the initial type byte.
1871 st->pktin->type = st->pktin->data[5];
1872 st->pktin->body = st->pktin->data + 6;
1873 st->pktin->length -= 6;
1874 assert(st->pktin->length >= 0); /* one last double-check */
1877 ssh2_log_incoming_packet(ssh, st->pktin);
1879 st->pktin->savedpos = 0;
1881 crFinish(st->pktin);
1884 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
1885 const unsigned char **data,
1888 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1890 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1893 * Read the packet length field.
1895 for (st->i = 0; st->i < 4; st->i++) {
1896 while ((*datalen) == 0)
1898 st->length[st->i] = *(*data)++;
1902 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1903 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1904 bombout(("Invalid packet length received"));
1908 st->pktin = ssh_new_packet();
1909 st->pktin->data = snewn(st->packetlen, unsigned char);
1911 st->pktin->encrypted_len = st->packetlen;
1913 st->pktin->sequence = st->incoming_sequence++;
1916 * Read the remainder of the packet.
1918 for (st->i = 0; st->i < st->packetlen; st->i++) {
1919 while ((*datalen) == 0)
1921 st->pktin->data[st->i] = *(*data)++;
1926 * pktin->body and pktin->length should identify the semantic
1927 * content of the packet, excluding the initial type byte.
1929 st->pktin->type = st->pktin->data[0];
1930 st->pktin->body = st->pktin->data + 1;
1931 st->pktin->length = st->packetlen - 1;
1934 * Log incoming packet, possibly omitting sensitive fields.
1937 ssh2_log_incoming_packet(ssh, st->pktin);
1939 st->pktin->savedpos = 0;
1941 crFinish(st->pktin);
1944 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1946 int pad, biglen, i, pktoffs;
1950 * XXX various versions of SC (including 8.8.4) screw up the
1951 * register allocation in this function and use the same register
1952 * (D6) for len and as a temporary, with predictable results. The
1953 * following sledgehammer prevents this.
1960 ssh1_log_outgoing_packet(ssh, pkt);
1962 if (ssh->v1_compressing) {
1963 unsigned char *compblk;
1965 zlib_compress_block(ssh->cs_comp_ctx,
1966 pkt->data + 12, pkt->length - 12,
1967 &compblk, &complen);
1968 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1969 memcpy(pkt->data + 12, compblk, complen);
1971 pkt->length = complen + 12;
1974 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1976 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1977 pad = 8 - (len % 8);
1979 biglen = len + pad; /* len(padding+type+data+CRC) */
1981 for (i = pktoffs; i < 4+8; i++)
1982 pkt->data[i] = random_byte();
1983 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1984 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1985 PUT_32BIT(pkt->data + pktoffs, len);
1988 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1989 pkt->data + pktoffs + 4, biglen);
1991 if (offset_p) *offset_p = pktoffs;
1992 return biglen + 4; /* len(length+padding+type+data+CRC) */
1995 static int s_write(Ssh ssh, void *data, int len)
1998 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1999 0, NULL, NULL, 0, NULL);
2002 return sk_write(ssh->s, (char *)data, len);
2005 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
2007 int len, backlog, offset;
2008 len = s_wrpkt_prepare(ssh, pkt, &offset);
2009 backlog = s_write(ssh, pkt->data + offset, len);
2010 if (backlog > SSH_MAX_BACKLOG)
2011 ssh_throttle_all(ssh, 1, backlog);
2012 ssh_free_packet(pkt);
2015 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
2018 len = s_wrpkt_prepare(ssh, pkt, &offset);
2019 if (ssh->deferred_len + len > ssh->deferred_size) {
2020 ssh->deferred_size = ssh->deferred_len + len + 128;
2021 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2025 memcpy(ssh->deferred_send_data + ssh->deferred_len,
2026 pkt->data + offset, len);
2027 ssh->deferred_len += len;
2028 ssh_free_packet(pkt);
2032 * Construct a SSH-1 packet with the specified contents.
2033 * (This all-at-once interface used to be the only one, but now SSH-1
2034 * packets can also be constructed incrementally.)
2036 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
2042 pkt = ssh1_pkt_init(pkttype);
2044 while ((argtype = va_arg(ap, int)) != PKT_END) {
2045 unsigned char *argp, argchar;
2047 unsigned long argint;
2050 /* Actual fields in the packet */
2052 argint = va_arg(ap, int);
2053 ssh_pkt_adduint32(pkt, argint);
2056 argchar = (unsigned char) va_arg(ap, int);
2057 ssh_pkt_addbyte(pkt, argchar);
2060 argp = va_arg(ap, unsigned char *);
2061 arglen = va_arg(ap, int);
2062 ssh_pkt_adddata(pkt, argp, arglen);
2065 sargp = va_arg(ap, char *);
2066 ssh_pkt_addstring(pkt, sargp);
2069 bn = va_arg(ap, Bignum);
2070 ssh1_pkt_addmp(pkt, bn);
2078 static void send_packet(Ssh ssh, int pkttype, ...)
2082 va_start(ap, pkttype);
2083 pkt = construct_packet(ssh, pkttype, ap);
2088 static void defer_packet(Ssh ssh, int pkttype, ...)
2092 va_start(ap, pkttype);
2093 pkt = construct_packet(ssh, pkttype, ap);
2095 s_wrpkt_defer(ssh, pkt);
2098 static int ssh_versioncmp(const char *a, const char *b)
2101 unsigned long av, bv;
2103 av = strtoul(a, &ae, 10);
2104 bv = strtoul(b, &be, 10);
2106 return (av < bv ? -1 : +1);
2111 av = strtoul(ae, &ae, 10);
2112 bv = strtoul(be, &be, 10);
2114 return (av < bv ? -1 : +1);
2119 * Utility routines for putting an SSH-protocol `string' and
2120 * `uint32' into a hash state.
2122 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2124 unsigned char lenblk[4];
2125 PUT_32BIT(lenblk, len);
2126 h->bytes(s, lenblk, 4);
2127 h->bytes(s, str, len);
2130 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2132 unsigned char intblk[4];
2133 PUT_32BIT(intblk, i);
2134 h->bytes(s, intblk, 4);
2138 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2140 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2142 if (pkt->maxlen < length) {
2143 unsigned char *body = pkt->body;
2144 int offset = body ? body - pkt->data : 0;
2145 pkt->maxlen = length + 256;
2146 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2147 if (body) pkt->body = pkt->data + offset;
2150 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2153 ssh_pkt_ensure(pkt, pkt->length);
2154 memcpy(pkt->data + pkt->length - len, data, len);
2156 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2158 ssh_pkt_adddata(pkt, &byte, 1);
2160 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2162 ssh_pkt_adddata(pkt, &value, 1);
2164 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2167 PUT_32BIT(x, value);
2168 ssh_pkt_adddata(pkt, x, 4);
2170 static void ssh_pkt_addstring_start(struct Packet *pkt)
2172 ssh_pkt_adduint32(pkt, 0);
2173 pkt->savedpos = pkt->length;
2175 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2178 ssh_pkt_adddata(pkt, data, len);
2179 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2181 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2183 ssh_pkt_addstring_data(pkt, data, strlen(data));
2185 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2187 ssh_pkt_addstring_start(pkt);
2188 ssh_pkt_addstring_str(pkt, data);
2190 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2192 int len = ssh1_bignum_length(b);
2193 unsigned char *data = snewn(len, unsigned char);
2194 (void) ssh1_write_bignum(data, b);
2195 ssh_pkt_adddata(pkt, data, len);
2198 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2201 int i, n = (bignum_bitcount(b) + 7) / 8;
2202 p = snewn(n + 1, unsigned char);
2204 for (i = 1; i <= n; i++)
2205 p[i] = bignum_byte(b, n - i);
2207 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2209 memmove(p, p + i, n + 1 - i);
2213 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2217 p = ssh2_mpint_fmt(b, &len);
2218 ssh_pkt_addstring_start(pkt);
2219 ssh_pkt_addstring_data(pkt, (char *)p, len);
2223 static struct Packet *ssh1_pkt_init(int pkt_type)
2225 struct Packet *pkt = ssh_new_packet();
2226 pkt->length = 4 + 8; /* space for length + max padding */
2227 ssh_pkt_addbyte(pkt, pkt_type);
2228 pkt->body = pkt->data + pkt->length;
2229 pkt->type = pkt_type;
2230 pkt->downstream_id = 0;
2231 pkt->additional_log_text = NULL;
2235 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2236 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2237 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2238 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2239 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2240 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2241 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2242 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2243 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2245 static struct Packet *ssh2_pkt_init(int pkt_type)
2247 struct Packet *pkt = ssh_new_packet();
2248 pkt->length = 5; /* space for packet length + padding length */
2250 pkt->type = pkt_type;
2251 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2252 pkt->body = pkt->data + pkt->length; /* after packet type */
2253 pkt->downstream_id = 0;
2254 pkt->additional_log_text = NULL;
2259 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2260 * put the MAC on it. Final packet, ready to be sent, is stored in
2261 * pkt->data. Total length is returned.
2263 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2265 int cipherblk, maclen, padding, unencrypted_prefix, i;
2268 ssh2_log_outgoing_packet(ssh, pkt);
2270 if (ssh->bare_connection) {
2272 * Trivial packet construction for the bare connection
2275 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2276 pkt->body = pkt->data + 1;
2277 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2278 return pkt->length - 1;
2282 * Compress packet payload.
2285 unsigned char *newpayload;
2288 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2290 &newpayload, &newlen)) {
2292 ssh2_pkt_adddata(pkt, newpayload, newlen);
2298 * Add padding. At least four bytes, and must also bring total
2299 * length (minus MAC) up to a multiple of the block size.
2300 * If pkt->forcepad is set, make sure the packet is at least that size
2303 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2304 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2306 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2307 if (pkt->length + padding < pkt->forcepad)
2308 padding = pkt->forcepad - pkt->length;
2310 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2312 assert(padding <= 255);
2313 maclen = ssh->csmac ? ssh->csmac->len : 0;
2314 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2315 pkt->data[4] = padding;
2316 for (i = 0; i < padding; i++)
2317 pkt->data[pkt->length + i] = random_byte();
2318 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2320 /* Encrypt length if the scheme requires it */
2321 if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
2322 ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
2323 ssh->v2_outgoing_sequence);
2326 if (ssh->csmac && ssh->csmac_etm) {
2328 * OpenSSH-defined encrypt-then-MAC protocol.
2331 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2332 pkt->data + 4, pkt->length + padding - 4);
2333 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2334 pkt->length + padding,
2335 ssh->v2_outgoing_sequence);
2338 * SSH-2 standard protocol.
2341 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2342 pkt->length + padding,
2343 ssh->v2_outgoing_sequence);
2345 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2346 pkt->data, pkt->length + padding);
2349 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2350 pkt->encrypted_len = pkt->length + padding;
2352 /* Ready-to-send packet starts at pkt->data. We return length. */
2353 pkt->body = pkt->data;
2354 return pkt->length + padding + maclen;
2358 * Routines called from the main SSH code to send packets. There
2359 * are quite a few of these, because we have two separate
2360 * mechanisms for delaying the sending of packets:
2362 * - In order to send an IGNORE message and a password message in
2363 * a single fixed-length blob, we require the ability to
2364 * concatenate the encrypted forms of those two packets _into_ a
2365 * single blob and then pass it to our <network.h> transport
2366 * layer in one go. Hence, there's a deferment mechanism which
2367 * works after packet encryption.
2369 * - In order to avoid sending any connection-layer messages
2370 * during repeat key exchange, we have to queue up any such
2371 * outgoing messages _before_ they are encrypted (and in
2372 * particular before they're allocated sequence numbers), and
2373 * then send them once we've finished.
2375 * I call these mechanisms `defer' and `queue' respectively, so as
2376 * to distinguish them reasonably easily.
2378 * The functions send_noqueue() and defer_noqueue() free the packet
2379 * structure they are passed. Every outgoing packet goes through
2380 * precisely one of these functions in its life; packets passed to
2381 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2382 * these or get queued, and then when the queue is later emptied
2383 * the packets are all passed to defer_noqueue().
2385 * When using a CBC-mode cipher, it's necessary to ensure that an
2386 * attacker can't provide data to be encrypted using an IV that they
2387 * know. We ensure this by prefixing each packet that might contain
2388 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2389 * mechanism, so in this case send_noqueue() ends up redirecting to
2390 * defer_noqueue(). If you don't like this inefficiency, don't use
2394 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2395 static void ssh_pkt_defersend(Ssh);
2398 * Send an SSH-2 packet immediately, without queuing or deferring.
2400 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2404 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2405 /* We need to send two packets, so use the deferral mechanism. */
2406 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2407 ssh_pkt_defersend(ssh);
2410 len = ssh2_pkt_construct(ssh, pkt);
2411 backlog = s_write(ssh, pkt->body, len);
2412 if (backlog > SSH_MAX_BACKLOG)
2413 ssh_throttle_all(ssh, 1, backlog);
2415 ssh->outgoing_data_size += pkt->encrypted_len;
2416 if (!ssh->kex_in_progress &&
2417 !ssh->bare_connection &&
2418 ssh->max_data_size != 0 &&
2419 ssh->outgoing_data_size > ssh->max_data_size)
2420 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2422 ssh_free_packet(pkt);
2426 * Defer an SSH-2 packet.
2428 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2431 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2432 ssh->deferred_len == 0 && !noignore &&
2433 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2435 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2436 * get encrypted with a known IV.
2438 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2439 ssh2_pkt_addstring_start(ipkt);
2440 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2442 len = ssh2_pkt_construct(ssh, pkt);
2443 if (ssh->deferred_len + len > ssh->deferred_size) {
2444 ssh->deferred_size = ssh->deferred_len + len + 128;
2445 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2449 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2450 ssh->deferred_len += len;
2451 ssh->deferred_data_size += pkt->encrypted_len;
2452 ssh_free_packet(pkt);
2456 * Queue an SSH-2 packet.
2458 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2460 assert(ssh->queueing);
2462 if (ssh->queuelen >= ssh->queuesize) {
2463 ssh->queuesize = ssh->queuelen + 32;
2464 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2467 ssh->queue[ssh->queuelen++] = pkt;
2471 * Either queue or send a packet, depending on whether queueing is
2474 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2477 ssh2_pkt_queue(ssh, pkt);
2479 ssh2_pkt_send_noqueue(ssh, pkt);
2483 * Either queue or defer a packet, depending on whether queueing is
2486 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2489 ssh2_pkt_queue(ssh, pkt);
2491 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2495 * Send the whole deferred data block constructed by
2496 * ssh2_pkt_defer() or SSH-1's defer_packet().
2498 * The expected use of the defer mechanism is that you call
2499 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2500 * not currently queueing, this simply sets up deferred_send_data
2501 * and then sends it. If we _are_ currently queueing, the calls to
2502 * ssh2_pkt_defer() put the deferred packets on to the queue
2503 * instead, and therefore ssh_pkt_defersend() has no deferred data
2504 * to send. Hence, there's no need to make it conditional on
2507 static void ssh_pkt_defersend(Ssh ssh)
2510 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2511 ssh->deferred_len = ssh->deferred_size = 0;
2512 sfree(ssh->deferred_send_data);
2513 ssh->deferred_send_data = NULL;
2514 if (backlog > SSH_MAX_BACKLOG)
2515 ssh_throttle_all(ssh, 1, backlog);
2517 ssh->outgoing_data_size += ssh->deferred_data_size;
2518 if (!ssh->kex_in_progress &&
2519 !ssh->bare_connection &&
2520 ssh->max_data_size != 0 &&
2521 ssh->outgoing_data_size > ssh->max_data_size)
2522 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2523 ssh->deferred_data_size = 0;
2527 * Send a packet whose length needs to be disguised (typically
2528 * passwords or keyboard-interactive responses).
2530 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2536 * The simplest way to do this is to adjust the
2537 * variable-length padding field in the outgoing packet.
2539 * Currently compiled out, because some Cisco SSH servers
2540 * don't like excessively padded packets (bah, why's it
2543 pkt->forcepad = padsize;
2544 ssh2_pkt_send(ssh, pkt);
2549 * If we can't do that, however, an alternative approach is
2550 * to use the pkt_defer mechanism to bundle the packet
2551 * tightly together with an SSH_MSG_IGNORE such that their
2552 * combined length is a constant. So first we construct the
2553 * final form of this packet and defer its sending.
2555 ssh2_pkt_defer(ssh, pkt);
2558 * Now construct an SSH_MSG_IGNORE which includes a string
2559 * that's an exact multiple of the cipher block size. (If
2560 * the cipher is NULL so that the block size is
2561 * unavailable, we don't do this trick at all, because we
2562 * gain nothing by it.)
2564 if (ssh->cscipher &&
2565 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2568 stringlen = (256 - ssh->deferred_len);
2569 stringlen += ssh->cscipher->blksize - 1;
2570 stringlen -= (stringlen % ssh->cscipher->blksize);
2573 * Temporarily disable actual compression, so we
2574 * can guarantee to get this string exactly the
2575 * length we want it. The compression-disabling
2576 * routine should return an integer indicating how
2577 * many bytes we should adjust our string length
2581 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2583 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2584 ssh2_pkt_addstring_start(pkt);
2585 for (i = 0; i < stringlen; i++) {
2586 char c = (char) random_byte();
2587 ssh2_pkt_addstring_data(pkt, &c, 1);
2589 ssh2_pkt_defer(ssh, pkt);
2591 ssh_pkt_defersend(ssh);
2596 * Send all queued SSH-2 packets. We send them by means of
2597 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2598 * packets that needed to be lumped together.
2600 static void ssh2_pkt_queuesend(Ssh ssh)
2604 assert(!ssh->queueing);
2606 for (i = 0; i < ssh->queuelen; i++)
2607 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2610 ssh_pkt_defersend(ssh);
2614 void bndebug(char *string, Bignum b)
2618 p = ssh2_mpint_fmt(b, &len);
2619 debug(("%s", string));
2620 for (i = 0; i < len; i++)
2621 debug((" %02x", p[i]));
2627 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2631 p = ssh2_mpint_fmt(b, &len);
2632 hash_string(h, s, p, len);
2637 * Packet decode functions for both SSH-1 and SSH-2.
2639 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2641 unsigned long value;
2642 if (pkt->length - pkt->savedpos < 4)
2643 return 0; /* arrgh, no way to decline (FIXME?) */
2644 value = GET_32BIT(pkt->body + pkt->savedpos);
2648 static int ssh2_pkt_getbool(struct Packet *pkt)
2650 unsigned long value;
2651 if (pkt->length - pkt->savedpos < 1)
2652 return 0; /* arrgh, no way to decline (FIXME?) */
2653 value = pkt->body[pkt->savedpos] != 0;
2657 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2662 if (pkt->length - pkt->savedpos < 4)
2664 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2669 if (pkt->length - pkt->savedpos < *length)
2671 *p = (char *)(pkt->body + pkt->savedpos);
2672 pkt->savedpos += *length;
2674 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2676 if (pkt->length - pkt->savedpos < length)
2678 pkt->savedpos += length;
2679 return pkt->body + (pkt->savedpos - length);
2681 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2682 const unsigned char **keystr)
2686 j = makekey(pkt->body + pkt->savedpos,
2687 pkt->length - pkt->savedpos,
2694 assert(pkt->savedpos < pkt->length);
2698 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2703 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2704 pkt->length - pkt->savedpos, &b);
2712 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2718 ssh_pkt_getstring(pkt, &p, &length);
2723 b = bignum_from_bytes((unsigned char *)p, length);
2728 * Helper function to add an SSH-2 signature blob to a packet.
2729 * Expects to be shown the public key blob as well as the signature
2730 * blob. Normally works just like ssh2_pkt_addstring, but will
2731 * fiddle with the signature packet if necessary for
2732 * BUG_SSH2_RSA_PADDING.
2734 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2735 void *pkblob_v, int pkblob_len,
2736 void *sigblob_v, int sigblob_len)
2738 unsigned char *pkblob = (unsigned char *)pkblob_v;
2739 unsigned char *sigblob = (unsigned char *)sigblob_v;
2741 /* dmemdump(pkblob, pkblob_len); */
2742 /* dmemdump(sigblob, sigblob_len); */
2745 * See if this is in fact an ssh-rsa signature and a buggy
2746 * server; otherwise we can just do this the easy way.
2748 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2749 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2750 int pos, len, siglen;
2753 * Find the byte length of the modulus.
2756 pos = 4+7; /* skip over "ssh-rsa" */
2757 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2758 if (len < 0 || len > pkblob_len - pos - 4)
2760 pos += 4 + len; /* skip over exponent */
2761 if (pkblob_len - pos < 4)
2763 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2764 if (len < 0 || len > pkblob_len - pos - 4)
2766 pos += 4; /* find modulus itself */
2767 while (len > 0 && pkblob[pos] == 0)
2769 /* debug(("modulus length is %d\n", len)); */
2772 * Now find the signature integer.
2774 pos = 4+7; /* skip over "ssh-rsa" */
2775 if (sigblob_len < pos+4)
2777 siglen = toint(GET_32BIT(sigblob+pos));
2778 if (siglen != sigblob_len - pos - 4)
2780 /* debug(("signature length is %d\n", siglen)); */
2782 if (len != siglen) {
2783 unsigned char newlen[4];
2784 ssh2_pkt_addstring_start(pkt);
2785 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2786 /* dmemdump(sigblob, pos); */
2787 pos += 4; /* point to start of actual sig */
2788 PUT_32BIT(newlen, len);
2789 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2790 /* dmemdump(newlen, 4); */
2792 while (len-- > siglen) {
2793 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2794 /* dmemdump(newlen, 1); */
2796 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2797 /* dmemdump(sigblob+pos, siglen); */
2801 /* Otherwise fall through and do it the easy way. We also come
2802 * here as a fallback if we discover above that the key blob
2803 * is misformatted in some way. */
2807 ssh2_pkt_addstring_start(pkt);
2808 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2812 * Examine the remote side's version string and compare it against
2813 * a list of known buggy implementations.
2815 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2817 char *imp; /* pointer to implementation part */
2819 imp += strcspn(imp, "-");
2821 imp += strcspn(imp, "-");
2824 ssh->remote_bugs = 0;
2827 * General notes on server version strings:
2828 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2829 * here -- in particular, we've heard of one that's perfectly happy
2830 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2831 * so we can't distinguish them.
2833 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2834 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2835 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2836 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2837 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2838 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2840 * These versions don't support SSH1_MSG_IGNORE, so we have
2841 * to use a different defence against password length
2844 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2845 logevent("We believe remote version has SSH-1 ignore bug");
2848 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2849 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2850 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2852 * These versions need a plain password sent; they can't
2853 * handle having a null and a random length of data after
2856 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2857 logevent("We believe remote version needs a plain SSH-1 password");
2860 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2861 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2862 (!strcmp(imp, "Cisco-1.25")))) {
2864 * These versions apparently have no clue whatever about
2865 * RSA authentication and will panic and die if they see
2866 * an AUTH_RSA message.
2868 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2869 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2872 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2873 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2874 !wc_match("* VShell", imp) &&
2875 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2876 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2877 wc_match("2.1 *", imp)))) {
2879 * These versions have the HMAC bug.
2881 ssh->remote_bugs |= BUG_SSH2_HMAC;
2882 logevent("We believe remote version has SSH-2 HMAC bug");
2885 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2886 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2887 !wc_match("* VShell", imp) &&
2888 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2890 * These versions have the key-derivation bug (failing to
2891 * include the literal shared secret in the hashes that
2892 * generate the keys).
2894 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2895 logevent("We believe remote version has SSH-2 key-derivation bug");
2898 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2899 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2900 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2901 wc_match("OpenSSH_3.[0-2]*", imp) ||
2902 wc_match("mod_sftp/0.[0-8]*", imp) ||
2903 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2905 * These versions have the SSH-2 RSA padding bug.
2907 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2908 logevent("We believe remote version has SSH-2 RSA padding bug");
2911 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2912 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2913 wc_match("OpenSSH_2.[0-2]*", imp))) {
2915 * These versions have the SSH-2 session-ID bug in
2916 * public-key authentication.
2918 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2919 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2922 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2923 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2924 (wc_match("DigiSSH_2.0", imp) ||
2925 wc_match("OpenSSH_2.[0-4]*", imp) ||
2926 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2927 wc_match("Sun_SSH_1.0", imp) ||
2928 wc_match("Sun_SSH_1.0.1", imp) ||
2929 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2930 wc_match("WeOnlyDo-*", imp)))) {
2932 * These versions have the SSH-2 rekey bug.
2934 ssh->remote_bugs |= BUG_SSH2_REKEY;
2935 logevent("We believe remote version has SSH-2 rekey bug");
2938 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2939 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2940 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2941 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2943 * This version ignores our makpkt and needs to be throttled.
2945 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2946 logevent("We believe remote version ignores SSH-2 maximum packet size");
2949 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2951 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2952 * none detected automatically.
2954 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2955 logevent("We believe remote version has SSH-2 ignore bug");
2958 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2959 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2960 (wc_match("OpenSSH_2.[235]*", imp)))) {
2962 * These versions only support the original (pre-RFC4419)
2963 * SSH-2 GEX request, and disconnect with a protocol error if
2964 * we use the newer version.
2966 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2967 logevent("We believe remote version has outdated SSH-2 GEX");
2970 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2972 * Servers that don't support our winadj request for one
2973 * reason or another. Currently, none detected automatically.
2975 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2976 logevent("We believe remote version has winadj bug");
2979 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
2980 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
2981 (wc_match("OpenSSH_[2-5].*", imp) ||
2982 wc_match("OpenSSH_6.[0-6]*", imp) ||
2983 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
2984 wc_match("dropbear_0.5[01]*", imp)))) {
2986 * These versions have the SSH-2 channel request bug.
2987 * OpenSSH 6.7 and above do not:
2988 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
2989 * dropbear_0.52 and above do not:
2990 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
2992 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
2993 logevent("We believe remote version has SSH-2 channel request bug");
2998 * The `software version' part of an SSH version string is required
2999 * to contain no spaces or minus signs.
3001 static void ssh_fix_verstring(char *str)
3003 /* Eat "<protoversion>-". */
3004 while (*str && *str != '-') str++;
3005 assert(*str == '-'); str++;
3007 /* Convert minus signs and spaces in the remaining string into
3010 if (*str == '-' || *str == ' ')
3017 * Send an appropriate SSH version string.
3019 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
3023 if (ssh->version == 2) {
3025 * Construct a v2 version string.
3027 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
3030 * Construct a v1 version string.
3032 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
3033 verstring = dupprintf("SSH-%s-%s\012",
3034 (ssh_versioncmp(svers, "1.5") <= 0 ?
3039 ssh_fix_verstring(verstring + strlen(protoname));
3041 /* FUZZING make PuTTY insecure, so make live use difficult. */
3045 if (ssh->version == 2) {
3048 * Record our version string.
3050 len = strcspn(verstring, "\015\012");
3051 ssh->v_c = snewn(len + 1, char);
3052 memcpy(ssh->v_c, verstring, len);
3056 logeventf(ssh, "We claim version: %.*s",
3057 strcspn(verstring, "\015\012"), verstring);
3058 s_write(ssh, verstring, strlen(verstring));
3062 static int do_ssh_init(Ssh ssh, unsigned char c)
3064 static const char protoname[] = "SSH-";
3066 struct do_ssh_init_state {
3075 crState(do_ssh_init_state);
3079 /* Search for a line beginning with the protocol name prefix in
3082 for (s->i = 0; protoname[s->i]; s->i++) {
3083 if ((char)c != protoname[s->i]) goto no;
3093 ssh->session_started = TRUE;
3095 s->vstrsize = sizeof(protoname) + 16;
3096 s->vstring = snewn(s->vstrsize, char);
3097 strcpy(s->vstring, protoname);
3098 s->vslen = strlen(protoname);
3101 if (s->vslen >= s->vstrsize - 1) {
3103 s->vstring = sresize(s->vstring, s->vstrsize, char);
3105 s->vstring[s->vslen++] = c;
3108 s->version[s->i] = '\0';
3110 } else if (s->i < sizeof(s->version) - 1)
3111 s->version[s->i++] = c;
3112 } else if (c == '\012')
3114 crReturn(1); /* get another char */
3117 ssh->agentfwd_enabled = FALSE;
3118 ssh->rdpkt2_state.incoming_sequence = 0;
3120 s->vstring[s->vslen] = 0;
3121 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3122 logeventf(ssh, "Server version: %s", s->vstring);
3123 ssh_detect_bugs(ssh, s->vstring);
3126 * Decide which SSH protocol version to support.
3129 /* Anything strictly below "2.0" means protocol 1 is supported. */
3130 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3131 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3132 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3134 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
3135 bombout(("SSH protocol version 1 required by configuration but "
3136 "not provided by server"));
3139 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
3140 bombout(("SSH protocol version 2 required by configuration but "
3141 "not provided by server"));
3145 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3150 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3152 /* Send the version string, if we haven't already */
3153 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3154 ssh_send_verstring(ssh, protoname, s->version);
3156 if (ssh->version == 2) {
3159 * Record their version string.
3161 len = strcspn(s->vstring, "\015\012");
3162 ssh->v_s = snewn(len + 1, char);
3163 memcpy(ssh->v_s, s->vstring, len);
3167 * Initialise SSH-2 protocol.
3169 ssh->protocol = ssh2_protocol;
3170 ssh2_protocol_setup(ssh);
3171 ssh->s_rdpkt = ssh2_rdpkt;
3174 * Initialise SSH-1 protocol.
3176 ssh->protocol = ssh1_protocol;
3177 ssh1_protocol_setup(ssh);
3178 ssh->s_rdpkt = ssh1_rdpkt;
3180 if (ssh->version == 2)
3181 do_ssh2_transport(ssh, NULL, -1, NULL);
3183 update_specials_menu(ssh->frontend);
3184 ssh->state = SSH_STATE_BEFORE_SIZE;
3185 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3192 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3195 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3196 * the ssh-connection part, extracted and given a trivial binary
3197 * packet protocol, so we replace 'SSH-' at the start with a new
3198 * name. In proper SSH style (though of course this part of the
3199 * proper SSH protocol _isn't_ subject to this kind of
3200 * DNS-domain-based extension), we define the new name in our
3203 static const char protoname[] =
3204 "SSHCONNECTION@putty.projects.tartarus.org-";
3206 struct do_ssh_connection_init_state {
3214 crState(do_ssh_connection_init_state);
3218 /* Search for a line beginning with the protocol name prefix in
3221 for (s->i = 0; protoname[s->i]; s->i++) {
3222 if ((char)c != protoname[s->i]) goto no;
3232 s->vstrsize = sizeof(protoname) + 16;
3233 s->vstring = snewn(s->vstrsize, char);
3234 strcpy(s->vstring, protoname);
3235 s->vslen = strlen(protoname);
3238 if (s->vslen >= s->vstrsize - 1) {
3240 s->vstring = sresize(s->vstring, s->vstrsize, char);
3242 s->vstring[s->vslen++] = c;
3245 s->version[s->i] = '\0';
3247 } else if (s->i < sizeof(s->version) - 1)
3248 s->version[s->i++] = c;
3249 } else if (c == '\012')
3251 crReturn(1); /* get another char */
3254 ssh->agentfwd_enabled = FALSE;
3255 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3257 s->vstring[s->vslen] = 0;
3258 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3259 logeventf(ssh, "Server version: %s", s->vstring);
3260 ssh_detect_bugs(ssh, s->vstring);
3263 * Decide which SSH protocol version to support. This is easy in
3264 * bare ssh-connection mode: only 2.0 is legal.
3266 if (ssh_versioncmp(s->version, "2.0") < 0) {
3267 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3270 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3271 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3277 logeventf(ssh, "Using bare ssh-connection protocol");
3279 /* Send the version string, if we haven't already */
3280 ssh_send_verstring(ssh, protoname, s->version);
3283 * Initialise bare connection protocol.
3285 ssh->protocol = ssh2_bare_connection_protocol;
3286 ssh2_bare_connection_protocol_setup(ssh);
3287 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3289 update_specials_menu(ssh->frontend);
3290 ssh->state = SSH_STATE_BEFORE_SIZE;
3291 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3294 * Get authconn (really just conn) under way.
3296 do_ssh2_authconn(ssh, NULL, 0, NULL);
3303 static void ssh_process_incoming_data(Ssh ssh,
3304 const unsigned char **data, int *datalen)
3306 struct Packet *pktin;
3308 pktin = ssh->s_rdpkt(ssh, data, datalen);
3310 ssh->protocol(ssh, NULL, 0, pktin);
3311 ssh_free_packet(pktin);
3315 static void ssh_queue_incoming_data(Ssh ssh,
3316 const unsigned char **data, int *datalen)
3318 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3323 static void ssh_process_queued_incoming_data(Ssh ssh)
3326 const unsigned char *data;
3329 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3330 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3334 while (!ssh->frozen && len > 0)
3335 ssh_process_incoming_data(ssh, &data, &len);
3338 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3342 static void ssh_set_frozen(Ssh ssh, int frozen)
3345 sk_set_frozen(ssh->s, frozen);
3346 ssh->frozen = frozen;
3349 static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
3351 /* Log raw data, if we're in that mode. */
3353 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3354 0, NULL, NULL, 0, NULL);
3356 crBegin(ssh->ssh_gotdata_crstate);
3359 * To begin with, feed the characters one by one to the
3360 * protocol initialisation / selection function do_ssh_init().
3361 * When that returns 0, we're done with the initial greeting
3362 * exchange and can move on to packet discipline.
3365 int ret; /* need not be kept across crReturn */
3367 crReturnV; /* more data please */
3368 ret = ssh->do_ssh_init(ssh, *data);
3376 * We emerge from that loop when the initial negotiation is
3377 * over and we have selected an s_rdpkt function. Now pass
3378 * everything to s_rdpkt, and then pass the resulting packets
3379 * to the proper protocol handler.
3383 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3385 ssh_queue_incoming_data(ssh, &data, &datalen);
3386 /* This uses up all data and cannot cause anything interesting
3387 * to happen; indeed, for anything to happen at all, we must
3388 * return, so break out. */
3390 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3391 /* This uses up some or all data, and may freeze the
3393 ssh_process_queued_incoming_data(ssh);
3395 /* This uses up some or all data, and may freeze the
3397 ssh_process_incoming_data(ssh, &data, &datalen);
3399 /* FIXME this is probably EBW. */
3400 if (ssh->state == SSH_STATE_CLOSED)
3403 /* We're out of data. Go and get some more. */
3409 static int ssh_do_close(Ssh ssh, int notify_exit)
3412 struct ssh_channel *c;
3414 ssh->state = SSH_STATE_CLOSED;
3415 expire_timer_context(ssh);
3420 notify_remote_exit(ssh->frontend);
3425 * Now we must shut down any port- and X-forwarded channels going
3426 * through this connection.
3428 if (ssh->channels) {
3429 while (NULL != (c = index234(ssh->channels, 0))) {
3432 x11_close(c->u.x11.xconn);
3435 case CHAN_SOCKDATA_DORMANT:
3436 pfd_close(c->u.pfd.pf);
3439 del234(ssh->channels, c); /* moving next one to index 0 */
3440 if (ssh->version == 2)
3441 bufchain_clear(&c->v.v2.outbuffer);
3446 * Go through port-forwardings, and close any associated
3447 * listening sockets.
3449 if (ssh->portfwds) {
3450 struct ssh_portfwd *pf;
3451 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3452 /* Dispose of any listening socket. */
3454 pfl_terminate(pf->local);
3455 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3458 freetree234(ssh->portfwds);
3459 ssh->portfwds = NULL;
3463 * Also stop attempting to connection-share.
3465 if (ssh->connshare) {
3466 sharestate_free(ssh->connshare);
3467 ssh->connshare = NULL;
3473 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3474 const char *error_msg, int error_code)
3476 Ssh ssh = (Ssh) plug;
3479 * While we're attempting connection sharing, don't loudly log
3480 * everything that happens. Real TCP connections need to be logged
3481 * when we _start_ trying to connect, because it might be ages
3482 * before they respond if something goes wrong; but connection
3483 * sharing is local and quick to respond, and it's sufficient to
3484 * simply wait and see whether it worked afterwards.
3487 if (!ssh->attempting_connshare)
3488 backend_socket_log(ssh->frontend, type, addr, port,
3489 error_msg, error_code, ssh->conf,
3490 ssh->session_started);
3493 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3494 const char *ds_err, const char *us_err)
3496 if (event == SHARE_NONE) {
3497 /* In this case, 'logtext' is an error message indicating a
3498 * reason why connection sharing couldn't be set up _at all_.
3499 * Failing that, ds_err and us_err indicate why we couldn't be
3500 * a downstream and an upstream respectively. */
3502 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3505 logeventf(ssh, "Could not set up connection sharing"
3506 " as downstream: %s", ds_err);
3508 logeventf(ssh, "Could not set up connection sharing"
3509 " as upstream: %s", us_err);
3511 } else if (event == SHARE_DOWNSTREAM) {
3512 /* In this case, 'logtext' is a local endpoint address */
3513 logeventf(ssh, "Using existing shared connection at %s", logtext);
3514 /* Also we should mention this in the console window to avoid
3515 * confusing users as to why this window doesn't behave the
3517 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3518 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3520 } else if (event == SHARE_UPSTREAM) {
3521 /* In this case, 'logtext' is a local endpoint address too */
3522 logeventf(ssh, "Sharing this connection at %s", logtext);
3526 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3529 Ssh ssh = (Ssh) plug;
3530 int need_notify = ssh_do_close(ssh, FALSE);
3533 if (!ssh->close_expected)
3534 error_msg = "Server unexpectedly closed network connection";
3536 error_msg = "Server closed network connection";
3539 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3543 notify_remote_exit(ssh->frontend);
3546 logevent(error_msg);
3547 if (!ssh->close_expected || !ssh->clean_exit)
3548 connection_fatal(ssh->frontend, "%s", error_msg);
3552 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3554 Ssh ssh = (Ssh) plug;
3555 ssh_gotdata(ssh, (unsigned char *)data, len);
3556 if (ssh->state == SSH_STATE_CLOSED) {
3557 ssh_do_close(ssh, TRUE);
3563 static void ssh_sent(Plug plug, int bufsize)
3565 Ssh ssh = (Ssh) plug;
3567 * If the send backlog on the SSH socket itself clears, we
3568 * should unthrottle the whole world if it was throttled.
3570 if (bufsize < SSH_MAX_BACKLOG)
3571 ssh_throttle_all(ssh, 0, bufsize);
3574 static void ssh_hostport_setup(const char *host, int port, Conf *conf,
3575 char **savedhost, int *savedport,
3578 char *loghost = conf_get_str(conf, CONF_loghost);
3580 *loghost_ret = loghost;
3586 tmphost = dupstr(loghost);
3587 *savedport = 22; /* default ssh port */
3590 * A colon suffix on the hostname string also lets us affect
3591 * savedport. (Unless there are multiple colons, in which case
3592 * we assume this is an unbracketed IPv6 literal.)
3594 colon = host_strrchr(tmphost, ':');
3595 if (colon && colon == host_strchr(tmphost, ':')) {
3598 *savedport = atoi(colon);
3601 *savedhost = host_strduptrim(tmphost);
3604 *savedhost = host_strduptrim(host);
3606 port = 22; /* default ssh port */
3611 static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
3617 random_ref(); /* platform may need this to determine share socket name */
3618 ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
3619 ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
3627 * Connect to specified host and port.
3628 * Returns an error message, or NULL on success.
3629 * Also places the canonical host name into `realhost'. It must be
3630 * freed by the caller.
3632 static const char *connect_to_host(Ssh ssh, const char *host, int port,
3633 char **realhost, int nodelay, int keepalive)
3635 static const struct plug_function_table fn_table = {
3646 int addressfamily, sshprot;
3648 ssh_hostport_setup(host, port, ssh->conf,
3649 &ssh->savedhost, &ssh->savedport, &loghost);
3651 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3654 * Try connection-sharing, in case that means we don't open a
3655 * socket after all. ssh_connection_sharing_init will connect to a
3656 * previously established upstream if it can, and failing that,
3657 * establish a listening socket for _us_ to be the upstream. In
3658 * the latter case it will return NULL just as if it had done
3659 * nothing, because here we only need to care if we're a
3660 * downstream and need to do our connection setup differently.
3662 ssh->connshare = NULL;
3663 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3664 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3665 ssh->conf, ssh, &ssh->connshare);
3666 ssh->attempting_connshare = FALSE;
3667 if (ssh->s != NULL) {
3669 * We are a downstream.
3671 ssh->bare_connection = TRUE;
3672 ssh->do_ssh_init = do_ssh_connection_init;
3673 ssh->fullhostname = NULL;
3674 *realhost = dupstr(host); /* best we can do */
3677 * We're not a downstream, so open a normal socket.
3679 ssh->do_ssh_init = do_ssh_init;
3684 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3685 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
3686 ssh->frontend, "SSH connection");
3687 if ((err = sk_addr_error(addr)) != NULL) {
3691 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3693 ssh->s = new_connection(addr, *realhost, port,
3694 0, 1, nodelay, keepalive,
3695 (Plug) ssh, ssh->conf);
3696 if ((err = sk_socket_error(ssh->s)) != NULL) {
3698 notify_remote_exit(ssh->frontend);
3704 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3705 * send the version string too.
3707 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3710 if (sshprot == 3 && !ssh->bare_connection) {
3712 ssh_send_verstring(ssh, "SSH-", NULL);
3716 * loghost, if configured, overrides realhost.
3720 *realhost = dupstr(loghost);
3727 * Throttle or unthrottle the SSH connection.
3729 static void ssh_throttle_conn(Ssh ssh, int adjust)
3731 int old_count = ssh->conn_throttle_count;
3732 ssh->conn_throttle_count += adjust;
3733 assert(ssh->conn_throttle_count >= 0);
3734 if (ssh->conn_throttle_count && !old_count) {
3735 ssh_set_frozen(ssh, 1);
3736 } else if (!ssh->conn_throttle_count && old_count) {
3737 ssh_set_frozen(ssh, 0);
3742 * Throttle or unthrottle _all_ local data streams (for when sends
3743 * on the SSH connection itself back up).
3745 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3748 struct ssh_channel *c;
3750 if (enable == ssh->throttled_all)
3752 ssh->throttled_all = enable;
3753 ssh->overall_bufsize = bufsize;
3756 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3758 case CHAN_MAINSESSION:
3760 * This is treated separately, outside the switch.
3764 x11_override_throttle(c->u.x11.xconn, enable);
3767 /* Agent channels require no buffer management. */
3770 pfd_override_throttle(c->u.pfd.pf, enable);
3776 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3778 Ssh ssh = (Ssh) sshv;
3780 ssh->agent_response = reply;
3781 ssh->agent_response_len = replylen;
3783 if (ssh->version == 1)
3784 do_ssh1_login(ssh, NULL, -1, NULL);
3786 do_ssh2_authconn(ssh, NULL, -1, NULL);
3789 static void ssh_dialog_callback(void *sshv, int ret)
3791 Ssh ssh = (Ssh) sshv;
3793 ssh->user_response = ret;
3795 if (ssh->version == 1)
3796 do_ssh1_login(ssh, NULL, -1, NULL);
3798 do_ssh2_transport(ssh, NULL, -1, NULL);
3801 * This may have unfrozen the SSH connection, so do a
3804 ssh_process_queued_incoming_data(ssh);
3807 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3809 struct ssh_channel *c = (struct ssh_channel *)cv;
3811 const void *sentreply = reply;
3813 c->u.a.outstanding_requests--;
3815 /* Fake SSH_AGENT_FAILURE. */
3816 sentreply = "\0\0\0\1\5";
3819 if (ssh->version == 2) {
3820 ssh2_add_channel_data(c, sentreply, replylen);
3823 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3824 PKT_INT, c->remoteid,
3826 PKT_DATA, sentreply, replylen,
3832 * If we've already seen an incoming EOF but haven't sent an
3833 * outgoing one, this may be the moment to send it.
3835 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3836 sshfwd_write_eof(c);
3840 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3841 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3842 * => log `wire_reason'.
3844 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3845 const char *wire_reason,
3846 int code, int clean_exit)
3850 client_reason = wire_reason;
3852 error = dupprintf("Disconnected: %s", client_reason);
3854 error = dupstr("Disconnected");
3856 if (ssh->version == 1) {
3857 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3859 } else if (ssh->version == 2) {
3860 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3861 ssh2_pkt_adduint32(pktout, code);
3862 ssh2_pkt_addstring(pktout, wire_reason);
3863 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3864 ssh2_pkt_send_noqueue(ssh, pktout);
3867 ssh->close_expected = TRUE;
3868 ssh->clean_exit = clean_exit;
3869 ssh_closing((Plug)ssh, error, 0, 0);
3873 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3874 const struct ssh_signkey *ssh2keytype,
3877 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3878 return -1; /* no manual keys configured */
3883 * The fingerprint string we've been given will have things
3884 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3885 * narrow down to just the colon-separated hex block at the
3886 * end of the string.
3888 const char *p = strrchr(fingerprint, ' ');
3889 fingerprint = p ? p+1 : fingerprint;
3890 /* Quick sanity checks, including making sure it's in lowercase */
3891 assert(strlen(fingerprint) == 16*3 - 1);
3892 assert(fingerprint[2] == ':');
3893 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3895 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3897 return 1; /* success */
3902 * Construct the base64-encoded public key blob and see if
3905 unsigned char *binblob;
3907 int binlen, atoms, i;
3908 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3909 atoms = (binlen + 2) / 3;
3910 base64blob = snewn(atoms * 4 + 1, char);
3911 for (i = 0; i < atoms; i++)
3912 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3913 base64blob[atoms * 4] = '\0';
3915 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3918 return 1; /* success */
3927 * Handle the key exchange and user authentication phases.
3929 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
3930 struct Packet *pktin)
3933 unsigned char cookie[8], *ptr;
3934 struct MD5Context md5c;
3935 struct do_ssh1_login_state {
3938 unsigned char *rsabuf;
3939 const unsigned char *keystr1, *keystr2;
3940 unsigned long supported_ciphers_mask, supported_auths_mask;
3941 int tried_publickey, tried_agent;
3942 int tis_auth_refused, ccard_auth_refused;
3943 unsigned char session_id[16];
3945 void *publickey_blob;
3946 int publickey_bloblen;
3947 char *publickey_comment;
3948 int privatekey_available, privatekey_encrypted;
3949 prompts_t *cur_prompt;
3952 unsigned char request[5], *response, *p;
3962 struct RSAKey servkey, hostkey;
3964 crState(do_ssh1_login_state);
3971 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3972 bombout(("Public key packet not received"));
3976 logevent("Received public keys");
3978 ptr = ssh_pkt_getdata(pktin, 8);
3980 bombout(("SSH-1 public key packet stopped before random cookie"));
3983 memcpy(cookie, ptr, 8);
3985 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
3986 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
3987 bombout(("Failed to read SSH-1 public keys from public key packet"));
3992 * Log the host key fingerprint.
3996 logevent("Host key fingerprint is:");
3997 strcpy(logmsg, " ");
3998 s->hostkey.comment = NULL;
3999 rsa_fingerprint(logmsg + strlen(logmsg),
4000 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
4004 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
4005 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
4006 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
4007 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
4008 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
4010 ssh->v1_local_protoflags =
4011 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
4012 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
4015 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
4016 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
4017 MD5Update(&md5c, cookie, 8);
4018 MD5Final(s->session_id, &md5c);
4020 for (i = 0; i < 32; i++)
4021 ssh->session_key[i] = random_byte();
4024 * Verify that the `bits' and `bytes' parameters match.
4026 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
4027 s->servkey.bits > s->servkey.bytes * 8) {
4028 bombout(("SSH-1 public keys were badly formatted"));
4032 s->len = (s->hostkey.bytes > s->servkey.bytes ?
4033 s->hostkey.bytes : s->servkey.bytes);
4035 s->rsabuf = snewn(s->len, unsigned char);
4038 * Verify the host key.
4042 * First format the key into a string.
4044 int len = rsastr_len(&s->hostkey);
4045 char fingerprint[100];
4046 char *keystr = snewn(len, char);
4047 rsastr_fmt(keystr, &s->hostkey);
4048 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4050 /* First check against manually configured host keys. */
4051 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4052 if (s->dlgret == 0) { /* did not match */
4053 bombout(("Host key did not appear in manually configured list"));
4056 } else if (s->dlgret < 0) { /* none configured; use standard handling */
4057 ssh_set_frozen(ssh, 1);
4058 s->dlgret = verify_ssh_host_key(ssh->frontend,
4059 ssh->savedhost, ssh->savedport,
4060 "rsa", keystr, fingerprint,
4061 ssh_dialog_callback, ssh);
4066 if (s->dlgret < 0) {
4070 bombout(("Unexpected data from server while waiting"
4071 " for user host key response"));
4074 } while (pktin || inlen > 0);
4075 s->dlgret = ssh->user_response;
4077 ssh_set_frozen(ssh, 0);
4079 if (s->dlgret == 0) {
4080 ssh_disconnect(ssh, "User aborted at host key verification",
4089 for (i = 0; i < 32; i++) {
4090 s->rsabuf[i] = ssh->session_key[i];
4092 s->rsabuf[i] ^= s->session_id[i];
4095 if (s->hostkey.bytes > s->servkey.bytes) {
4096 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4098 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4100 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4102 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4105 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4109 logevent("Encrypted session key");
4112 int cipher_chosen = 0, warn = 0;
4113 const char *cipher_string = NULL;
4115 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4116 int next_cipher = conf_get_int_int(ssh->conf,
4117 CONF_ssh_cipherlist, i);
4118 if (next_cipher == CIPHER_WARN) {
4119 /* If/when we choose a cipher, warn about it */
4121 } else if (next_cipher == CIPHER_AES) {
4122 /* XXX Probably don't need to mention this. */
4123 logevent("AES not supported in SSH-1, skipping");
4125 switch (next_cipher) {
4126 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4127 cipher_string = "3DES"; break;
4128 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4129 cipher_string = "Blowfish"; break;
4130 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4131 cipher_string = "single-DES"; break;
4133 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4137 if (!cipher_chosen) {
4138 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4139 bombout(("Server violates SSH-1 protocol by not "
4140 "supporting 3DES encryption"));
4142 /* shouldn't happen */
4143 bombout(("No supported ciphers found"));
4147 /* Warn about chosen cipher if necessary. */
4149 ssh_set_frozen(ssh, 1);
4150 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4151 ssh_dialog_callback, ssh);
4152 if (s->dlgret < 0) {
4156 bombout(("Unexpected data from server while waiting"
4157 " for user response"));
4160 } while (pktin || inlen > 0);
4161 s->dlgret = ssh->user_response;
4163 ssh_set_frozen(ssh, 0);
4164 if (s->dlgret == 0) {
4165 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4172 switch (s->cipher_type) {
4173 case SSH_CIPHER_3DES:
4174 logevent("Using 3DES encryption");
4176 case SSH_CIPHER_DES:
4177 logevent("Using single-DES encryption");
4179 case SSH_CIPHER_BLOWFISH:
4180 logevent("Using Blowfish encryption");
4184 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4185 PKT_CHAR, s->cipher_type,
4186 PKT_DATA, cookie, 8,
4187 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4188 PKT_DATA, s->rsabuf, s->len,
4189 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4191 logevent("Trying to enable encryption...");
4195 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4196 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4198 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4199 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4200 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4202 ssh->crcda_ctx = crcda_make_context();
4203 logevent("Installing CRC compensation attack detector");
4205 if (s->servkey.modulus) {
4206 sfree(s->servkey.modulus);
4207 s->servkey.modulus = NULL;
4209 if (s->servkey.exponent) {
4210 sfree(s->servkey.exponent);
4211 s->servkey.exponent = NULL;
4213 if (s->hostkey.modulus) {
4214 sfree(s->hostkey.modulus);
4215 s->hostkey.modulus = NULL;
4217 if (s->hostkey.exponent) {
4218 sfree(s->hostkey.exponent);
4219 s->hostkey.exponent = NULL;
4223 if (pktin->type != SSH1_SMSG_SUCCESS) {
4224 bombout(("Encryption not successfully enabled"));
4228 logevent("Successfully started encryption");
4230 fflush(stdout); /* FIXME eh? */
4232 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4233 int ret; /* need not be kept over crReturn */
4234 s->cur_prompt = new_prompts(ssh->frontend);
4235 s->cur_prompt->to_server = TRUE;
4236 s->cur_prompt->name = dupstr("SSH login name");
4237 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4238 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4241 crWaitUntil(!pktin);
4242 ret = get_userpass_input(s->cur_prompt, in, inlen);
4247 * Failed to get a username. Terminate.
4249 free_prompts(s->cur_prompt);
4250 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4253 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4254 free_prompts(s->cur_prompt);
4257 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4259 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4261 if (flags & FLAG_INTERACTIVE &&
4262 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4263 c_write_str(ssh, userlog);
4264 c_write_str(ssh, "\r\n");
4272 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4273 /* We must not attempt PK auth. Pretend we've already tried it. */
4274 s->tried_publickey = s->tried_agent = 1;
4276 s->tried_publickey = s->tried_agent = 0;
4278 s->tis_auth_refused = s->ccard_auth_refused = 0;
4280 * Load the public half of any configured keyfile for later use.
4282 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4283 if (!filename_is_null(s->keyfile)) {
4285 logeventf(ssh, "Reading key file \"%.150s\"",
4286 filename_to_str(s->keyfile));
4287 keytype = key_type(s->keyfile);
4288 if (keytype == SSH_KEYTYPE_SSH1 ||
4289 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4291 if (rsakey_pubblob(s->keyfile,
4292 &s->publickey_blob, &s->publickey_bloblen,
4293 &s->publickey_comment, &error)) {
4294 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4295 if (!s->privatekey_available)
4296 logeventf(ssh, "Key file contains public key only");
4297 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4301 logeventf(ssh, "Unable to load key (%s)", error);
4302 msgbuf = dupprintf("Unable to load key file "
4303 "\"%.150s\" (%s)\r\n",
4304 filename_to_str(s->keyfile),
4306 c_write_str(ssh, msgbuf);
4308 s->publickey_blob = NULL;
4312 logeventf(ssh, "Unable to use this key file (%s)",
4313 key_type_to_str(keytype));
4314 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4316 filename_to_str(s->keyfile),
4317 key_type_to_str(keytype));
4318 c_write_str(ssh, msgbuf);
4320 s->publickey_blob = NULL;
4323 s->publickey_blob = NULL;
4325 while (pktin->type == SSH1_SMSG_FAILURE) {
4326 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4328 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4330 * Attempt RSA authentication using Pageant.
4336 logevent("Pageant is running. Requesting keys.");
4338 /* Request the keys held by the agent. */
4339 PUT_32BIT(s->request, 1);
4340 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4341 if (!agent_query(s->request, 5, &r, &s->responselen,
4342 ssh_agent_callback, ssh)) {
4346 bombout(("Unexpected data from server while waiting"
4347 " for agent response"));
4350 } while (pktin || inlen > 0);
4351 r = ssh->agent_response;
4352 s->responselen = ssh->agent_response_len;
4354 s->response = (unsigned char *) r;
4355 if (s->response && s->responselen >= 5 &&
4356 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4357 s->p = s->response + 5;
4358 s->nkeys = toint(GET_32BIT(s->p));
4360 logeventf(ssh, "Pageant reported negative key count %d",
4365 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4366 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4367 unsigned char *pkblob = s->p;
4371 do { /* do while (0) to make breaking easy */
4372 n = ssh1_read_bignum
4373 (s->p, toint(s->responselen-(s->p-s->response)),
4378 n = ssh1_read_bignum
4379 (s->p, toint(s->responselen-(s->p-s->response)),
4384 if (s->responselen - (s->p-s->response) < 4)
4386 s->commentlen = toint(GET_32BIT(s->p));
4388 if (s->commentlen < 0 ||
4389 toint(s->responselen - (s->p-s->response)) <
4392 s->commentp = (char *)s->p;
4393 s->p += s->commentlen;
4397 logevent("Pageant key list packet was truncated");
4401 if (s->publickey_blob) {
4402 if (!memcmp(pkblob, s->publickey_blob,
4403 s->publickey_bloblen)) {
4404 logeventf(ssh, "Pageant key #%d matches "
4405 "configured key file", s->keyi);
4406 s->tried_publickey = 1;
4408 /* Skip non-configured key */
4411 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4412 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4413 PKT_BIGNUM, s->key.modulus, PKT_END);
4415 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4416 logevent("Key refused");
4419 logevent("Received RSA challenge");
4420 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4421 bombout(("Server's RSA challenge was badly formatted"));
4426 char *agentreq, *q, *ret;
4429 len = 1 + 4; /* message type, bit count */
4430 len += ssh1_bignum_length(s->key.exponent);
4431 len += ssh1_bignum_length(s->key.modulus);
4432 len += ssh1_bignum_length(s->challenge);
4433 len += 16; /* session id */
4434 len += 4; /* response format */
4435 agentreq = snewn(4 + len, char);
4436 PUT_32BIT(agentreq, len);
4438 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4439 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4441 q += ssh1_write_bignum(q, s->key.exponent);
4442 q += ssh1_write_bignum(q, s->key.modulus);
4443 q += ssh1_write_bignum(q, s->challenge);
4444 memcpy(q, s->session_id, 16);
4446 PUT_32BIT(q, 1); /* response format */
4447 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4448 ssh_agent_callback, ssh)) {
4453 bombout(("Unexpected data from server"
4454 " while waiting for agent"
4458 } while (pktin || inlen > 0);
4459 vret = ssh->agent_response;
4460 retlen = ssh->agent_response_len;
4465 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4466 logevent("Sending Pageant's response");
4467 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4468 PKT_DATA, ret + 5, 16,
4472 if (pktin->type == SSH1_SMSG_SUCCESS) {
4474 ("Pageant's response accepted");
4475 if (flags & FLAG_VERBOSE) {
4476 c_write_str(ssh, "Authenticated using"
4478 c_write(ssh, s->commentp,
4480 c_write_str(ssh, "\" from agent\r\n");
4485 ("Pageant's response not accepted");
4488 ("Pageant failed to answer challenge");
4492 logevent("No reply received from Pageant");
4495 freebn(s->key.exponent);
4496 freebn(s->key.modulus);
4497 freebn(s->challenge);
4502 if (s->publickey_blob && !s->tried_publickey)
4503 logevent("Configured key file not in Pageant");
4505 logevent("Failed to get reply from Pageant");
4510 if (s->publickey_blob && s->privatekey_available &&
4511 !s->tried_publickey) {
4513 * Try public key authentication with the specified
4516 int got_passphrase; /* need not be kept over crReturn */
4517 if (flags & FLAG_VERBOSE)
4518 c_write_str(ssh, "Trying public key authentication.\r\n");
4519 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4520 logeventf(ssh, "Trying public key \"%s\"",
4521 filename_to_str(s->keyfile));
4522 s->tried_publickey = 1;
4523 got_passphrase = FALSE;
4524 while (!got_passphrase) {
4526 * Get a passphrase, if necessary.
4528 char *passphrase = NULL; /* only written after crReturn */
4530 if (!s->privatekey_encrypted) {
4531 if (flags & FLAG_VERBOSE)
4532 c_write_str(ssh, "No passphrase required.\r\n");
4535 int ret; /* need not be kept over crReturn */
4536 s->cur_prompt = new_prompts(ssh->frontend);
4537 s->cur_prompt->to_server = FALSE;
4538 s->cur_prompt->name = dupstr("SSH key passphrase");
4539 add_prompt(s->cur_prompt,
4540 dupprintf("Passphrase for key \"%.100s\": ",
4541 s->publickey_comment), FALSE);
4542 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4545 crWaitUntil(!pktin);
4546 ret = get_userpass_input(s->cur_prompt, in, inlen);
4550 /* Failed to get a passphrase. Terminate. */
4551 free_prompts(s->cur_prompt);
4552 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4556 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4557 free_prompts(s->cur_prompt);
4560 * Try decrypting key with passphrase.
4562 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4563 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4566 smemclr(passphrase, strlen(passphrase));
4570 /* Correct passphrase. */
4571 got_passphrase = TRUE;
4572 } else if (ret == 0) {
4573 c_write_str(ssh, "Couldn't load private key from ");
4574 c_write_str(ssh, filename_to_str(s->keyfile));
4575 c_write_str(ssh, " (");
4576 c_write_str(ssh, error);
4577 c_write_str(ssh, ").\r\n");
4578 got_passphrase = FALSE;
4579 break; /* go and try something else */
4580 } else if (ret == -1) {
4581 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4582 got_passphrase = FALSE;
4585 assert(0 && "unexpected return from loadrsakey()");
4586 got_passphrase = FALSE; /* placate optimisers */
4590 if (got_passphrase) {
4593 * Send a public key attempt.
4595 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4596 PKT_BIGNUM, s->key.modulus, PKT_END);
4599 if (pktin->type == SSH1_SMSG_FAILURE) {
4600 c_write_str(ssh, "Server refused our public key.\r\n");
4601 continue; /* go and try something else */
4603 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4604 bombout(("Bizarre response to offer of public key"));
4610 unsigned char buffer[32];
4611 Bignum challenge, response;
4613 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4614 bombout(("Server's RSA challenge was badly formatted"));
4617 response = rsadecrypt(challenge, &s->key);
4618 freebn(s->key.private_exponent);/* burn the evidence */
4620 for (i = 0; i < 32; i++) {
4621 buffer[i] = bignum_byte(response, 31 - i);
4625 MD5Update(&md5c, buffer, 32);
4626 MD5Update(&md5c, s->session_id, 16);
4627 MD5Final(buffer, &md5c);
4629 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4630 PKT_DATA, buffer, 16, PKT_END);
4637 if (pktin->type == SSH1_SMSG_FAILURE) {
4638 if (flags & FLAG_VERBOSE)
4639 c_write_str(ssh, "Failed to authenticate with"
4640 " our public key.\r\n");
4641 continue; /* go and try something else */
4642 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4643 bombout(("Bizarre response to RSA authentication response"));
4647 break; /* we're through! */
4653 * Otherwise, try various forms of password-like authentication.
4655 s->cur_prompt = new_prompts(ssh->frontend);
4657 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4658 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4659 !s->tis_auth_refused) {
4660 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4661 logevent("Requested TIS authentication");
4662 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4664 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4665 logevent("TIS authentication declined");
4666 if (flags & FLAG_INTERACTIVE)
4667 c_write_str(ssh, "TIS authentication refused.\r\n");
4668 s->tis_auth_refused = 1;
4673 char *instr_suf, *prompt;
4675 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4677 bombout(("TIS challenge packet was badly formed"));
4680 logevent("Received TIS challenge");
4681 s->cur_prompt->to_server = TRUE;
4682 s->cur_prompt->name = dupstr("SSH TIS authentication");
4683 /* Prompt heuristic comes from OpenSSH */
4684 if (memchr(challenge, '\n', challengelen)) {
4685 instr_suf = dupstr("");
4686 prompt = dupprintf("%.*s", challengelen, challenge);
4688 instr_suf = dupprintf("%.*s", challengelen, challenge);
4689 prompt = dupstr("Response: ");
4691 s->cur_prompt->instruction =
4692 dupprintf("Using TIS authentication.%s%s",
4693 (*instr_suf) ? "\n" : "",
4695 s->cur_prompt->instr_reqd = TRUE;
4696 add_prompt(s->cur_prompt, prompt, FALSE);
4700 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4701 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4702 !s->ccard_auth_refused) {
4703 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4704 logevent("Requested CryptoCard authentication");
4705 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4707 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4708 logevent("CryptoCard authentication declined");
4709 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4710 s->ccard_auth_refused = 1;
4715 char *instr_suf, *prompt;
4717 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4719 bombout(("CryptoCard challenge packet was badly formed"));
4722 logevent("Received CryptoCard challenge");
4723 s->cur_prompt->to_server = TRUE;
4724 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4725 s->cur_prompt->name_reqd = FALSE;
4726 /* Prompt heuristic comes from OpenSSH */
4727 if (memchr(challenge, '\n', challengelen)) {
4728 instr_suf = dupstr("");
4729 prompt = dupprintf("%.*s", challengelen, challenge);
4731 instr_suf = dupprintf("%.*s", challengelen, challenge);
4732 prompt = dupstr("Response: ");
4734 s->cur_prompt->instruction =
4735 dupprintf("Using CryptoCard authentication.%s%s",
4736 (*instr_suf) ? "\n" : "",
4738 s->cur_prompt->instr_reqd = TRUE;
4739 add_prompt(s->cur_prompt, prompt, FALSE);
4743 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4744 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4745 bombout(("No supported authentication methods available"));
4748 s->cur_prompt->to_server = TRUE;
4749 s->cur_prompt->name = dupstr("SSH password");
4750 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4751 ssh->username, ssh->savedhost),
4756 * Show password prompt, having first obtained it via a TIS
4757 * or CryptoCard exchange if we're doing TIS or CryptoCard
4761 int ret; /* need not be kept over crReturn */
4762 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4765 crWaitUntil(!pktin);
4766 ret = get_userpass_input(s->cur_prompt, in, inlen);
4771 * Failed to get a password (for example
4772 * because one was supplied on the command line
4773 * which has already failed to work). Terminate.
4775 free_prompts(s->cur_prompt);
4776 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4781 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4783 * Defence against traffic analysis: we send a
4784 * whole bunch of packets containing strings of
4785 * different lengths. One of these strings is the
4786 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4787 * The others are all random data in
4788 * SSH1_MSG_IGNORE packets. This way a passive
4789 * listener can't tell which is the password, and
4790 * hence can't deduce the password length.
4792 * Anybody with a password length greater than 16
4793 * bytes is going to have enough entropy in their
4794 * password that a listener won't find it _that_
4795 * much help to know how long it is. So what we'll
4798 * - if password length < 16, we send 15 packets
4799 * containing string lengths 1 through 15
4801 * - otherwise, we let N be the nearest multiple
4802 * of 8 below the password length, and send 8
4803 * packets containing string lengths N through
4804 * N+7. This won't obscure the order of
4805 * magnitude of the password length, but it will
4806 * introduce a bit of extra uncertainty.
4808 * A few servers can't deal with SSH1_MSG_IGNORE, at
4809 * least in this context. For these servers, we need
4810 * an alternative defence. We make use of the fact
4811 * that the password is interpreted as a C string:
4812 * so we can append a NUL, then some random data.
4814 * A few servers can deal with neither SSH1_MSG_IGNORE
4815 * here _nor_ a padded password string.
4816 * For these servers we are left with no defences
4817 * against password length sniffing.
4819 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4820 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4822 * The server can deal with SSH1_MSG_IGNORE, so
4823 * we can use the primary defence.
4825 int bottom, top, pwlen, i;
4828 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4830 bottom = 0; /* zero length passwords are OK! :-) */
4833 bottom = pwlen & ~7;
4837 assert(pwlen >= bottom && pwlen <= top);
4839 randomstr = snewn(top + 1, char);
4841 for (i = bottom; i <= top; i++) {
4843 defer_packet(ssh, s->pwpkt_type,
4844 PKT_STR,s->cur_prompt->prompts[0]->result,
4847 for (j = 0; j < i; j++) {
4849 randomstr[j] = random_byte();
4850 } while (randomstr[j] == '\0');
4852 randomstr[i] = '\0';
4853 defer_packet(ssh, SSH1_MSG_IGNORE,
4854 PKT_STR, randomstr, PKT_END);
4857 logevent("Sending password with camouflage packets");
4858 ssh_pkt_defersend(ssh);
4861 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4863 * The server can't deal with SSH1_MSG_IGNORE
4864 * but can deal with padded passwords, so we
4865 * can use the secondary defence.
4871 len = strlen(s->cur_prompt->prompts[0]->result);
4872 if (len < sizeof(string)) {
4874 strcpy(string, s->cur_prompt->prompts[0]->result);
4875 len++; /* cover the zero byte */
4876 while (len < sizeof(string)) {
4877 string[len++] = (char) random_byte();
4880 ss = s->cur_prompt->prompts[0]->result;
4882 logevent("Sending length-padded password");
4883 send_packet(ssh, s->pwpkt_type,
4884 PKT_INT, len, PKT_DATA, ss, len,
4888 * The server is believed unable to cope with
4889 * any of our password camouflage methods.
4892 len = strlen(s->cur_prompt->prompts[0]->result);
4893 logevent("Sending unpadded password");
4894 send_packet(ssh, s->pwpkt_type,
4896 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4900 send_packet(ssh, s->pwpkt_type,
4901 PKT_STR, s->cur_prompt->prompts[0]->result,
4904 logevent("Sent password");
4905 free_prompts(s->cur_prompt);
4907 if (pktin->type == SSH1_SMSG_FAILURE) {
4908 if (flags & FLAG_VERBOSE)
4909 c_write_str(ssh, "Access denied\r\n");
4910 logevent("Authentication refused");
4911 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4912 bombout(("Strange packet received, type %d", pktin->type));
4918 if (s->publickey_blob) {
4919 sfree(s->publickey_blob);
4920 sfree(s->publickey_comment);
4923 logevent("Authentication successful");
4928 static void ssh_channel_try_eof(struct ssh_channel *c)
4931 assert(c->pending_eof); /* precondition for calling us */
4933 return; /* can't close: not even opened yet */
4934 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4935 return; /* can't send EOF: pending outgoing data */
4937 c->pending_eof = FALSE; /* we're about to send it */
4938 if (ssh->version == 1) {
4939 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4941 c->closes |= CLOSES_SENT_EOF;
4943 struct Packet *pktout;
4944 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4945 ssh2_pkt_adduint32(pktout, c->remoteid);
4946 ssh2_pkt_send(ssh, pktout);
4947 c->closes |= CLOSES_SENT_EOF;
4948 ssh2_channel_check_close(c);
4952 Conf *sshfwd_get_conf(struct ssh_channel *c)
4958 void sshfwd_write_eof(struct ssh_channel *c)
4962 if (ssh->state == SSH_STATE_CLOSED)
4965 if (c->closes & CLOSES_SENT_EOF)
4968 c->pending_eof = TRUE;
4969 ssh_channel_try_eof(c);
4972 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4976 if (ssh->state == SSH_STATE_CLOSED)
4981 x11_close(c->u.x11.xconn);
4982 logeventf(ssh, "Forwarded X11 connection terminated due to local "
4986 case CHAN_SOCKDATA_DORMANT:
4987 pfd_close(c->u.pfd.pf);
4988 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
4991 c->type = CHAN_ZOMBIE;
4992 c->pending_eof = FALSE; /* this will confuse a zombie channel */
4994 ssh2_channel_check_close(c);
4997 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
5001 if (ssh->state == SSH_STATE_CLOSED)
5004 if (ssh->version == 1) {
5005 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
5006 PKT_INT, c->remoteid,
5007 PKT_INT, len, PKT_DATA, buf, len,
5010 * In SSH-1 we can return 0 here - implying that forwarded
5011 * connections are never individually throttled - because
5012 * the only circumstance that can cause throttling will be
5013 * the whole SSH connection backing up, in which case
5014 * _everything_ will be throttled as a whole.
5018 ssh2_add_channel_data(c, buf, len);
5019 return ssh2_try_send(c);
5023 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
5028 if (ssh->state == SSH_STATE_CLOSED)
5031 if (ssh->version == 1) {
5032 buflimit = SSH1_BUFFER_LIMIT;
5034 buflimit = c->v.v2.locmaxwin;
5035 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
5037 if (c->throttling_conn && bufsize <= buflimit) {
5038 c->throttling_conn = 0;
5039 ssh_throttle_conn(ssh, -1);
5043 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
5045 struct queued_handler *qh = ssh->qhead;
5049 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5052 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5053 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5056 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5057 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5061 ssh->qhead = qh->next;
5063 if (ssh->qhead->msg1 > 0) {
5064 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5065 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5067 if (ssh->qhead->msg2 > 0) {
5068 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5069 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5072 ssh->qhead = ssh->qtail = NULL;
5075 qh->handler(ssh, pktin, qh->ctx);
5080 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5081 chandler_fn_t handler, void *ctx)
5083 struct queued_handler *qh;
5085 qh = snew(struct queued_handler);
5088 qh->handler = handler;
5092 if (ssh->qtail == NULL) {
5096 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5097 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5100 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5101 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5104 ssh->qtail->next = qh;
5109 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5111 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5113 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5114 SSH2_MSG_REQUEST_SUCCESS)) {
5115 logeventf(ssh, "Remote port forwarding from %s enabled",
5118 logeventf(ssh, "Remote port forwarding from %s refused",
5121 rpf = del234(ssh->rportfwds, pf);
5123 pf->pfrec->remote = NULL;
5128 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5131 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5134 pf->share_ctx = share_ctx;
5135 pf->shost = dupstr(shost);
5137 pf->sportdesc = NULL;
5138 if (!ssh->rportfwds) {
5139 assert(ssh->version == 2);
5140 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5142 if (add234(ssh->rportfwds, pf) != pf) {
5150 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5153 share_got_pkt_from_server(ctx, pktin->type,
5154 pktin->body, pktin->length);
5157 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5159 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5160 ssh_sharing_global_request_response, share_ctx);
5163 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5165 struct ssh_portfwd *epf;
5169 if (!ssh->portfwds) {
5170 ssh->portfwds = newtree234(ssh_portcmp);
5173 * Go through the existing port forwardings and tag them
5174 * with status==DESTROY. Any that we want to keep will be
5175 * re-enabled (status==KEEP) as we go through the
5176 * configuration and find out which bits are the same as
5179 struct ssh_portfwd *epf;
5181 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5182 epf->status = DESTROY;
5185 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5187 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5188 char *kp, *kp2, *vp, *vp2;
5189 char address_family, type;
5190 int sport,dport,sserv,dserv;
5191 char *sports, *dports, *saddr, *host;
5195 address_family = 'A';
5197 if (*kp == 'A' || *kp == '4' || *kp == '6')
5198 address_family = *kp++;
5199 if (*kp == 'L' || *kp == 'R')
5202 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5204 * There's a colon in the middle of the source port
5205 * string, which means that the part before it is
5206 * actually a source address.
5208 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5209 saddr = host_strduptrim(saddr_tmp);
5216 sport = atoi(sports);
5220 sport = net_service_lookup(sports);
5222 logeventf(ssh, "Service lookup failed for source"
5223 " port \"%s\"", sports);
5227 if (type == 'L' && !strcmp(val, "D")) {
5228 /* dynamic forwarding */
5235 /* ordinary forwarding */
5237 vp2 = vp + host_strcspn(vp, ":");
5238 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5242 dport = atoi(dports);
5246 dport = net_service_lookup(dports);
5248 logeventf(ssh, "Service lookup failed for destination"
5249 " port \"%s\"", dports);
5254 if (sport && dport) {
5255 /* Set up a description of the source port. */
5256 struct ssh_portfwd *pfrec, *epfrec;
5258 pfrec = snew(struct ssh_portfwd);
5260 pfrec->saddr = saddr;
5261 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5262 pfrec->sport = sport;
5263 pfrec->daddr = host;
5264 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5265 pfrec->dport = dport;
5266 pfrec->local = NULL;
5267 pfrec->remote = NULL;
5268 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5269 address_family == '6' ? ADDRTYPE_IPV6 :
5272 epfrec = add234(ssh->portfwds, pfrec);
5273 if (epfrec != pfrec) {
5274 if (epfrec->status == DESTROY) {
5276 * We already have a port forwarding up and running
5277 * with precisely these parameters. Hence, no need
5278 * to do anything; simply re-tag the existing one
5281 epfrec->status = KEEP;
5284 * Anything else indicates that there was a duplicate
5285 * in our input, which we'll silently ignore.
5287 free_portfwd(pfrec);
5289 pfrec->status = CREATE;
5298 * Now go through and destroy any port forwardings which were
5301 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5302 if (epf->status == DESTROY) {
5305 message = dupprintf("%s port forwarding from %s%s%d",
5306 epf->type == 'L' ? "local" :
5307 epf->type == 'R' ? "remote" : "dynamic",
5308 epf->saddr ? epf->saddr : "",
5309 epf->saddr ? ":" : "",
5312 if (epf->type != 'D') {
5313 char *msg2 = dupprintf("%s to %s:%d", message,
5314 epf->daddr, epf->dport);
5319 logeventf(ssh, "Cancelling %s", message);
5322 /* epf->remote or epf->local may be NULL if setting up a
5323 * forwarding failed. */
5325 struct ssh_rportfwd *rpf = epf->remote;
5326 struct Packet *pktout;
5329 * Cancel the port forwarding at the server
5332 if (ssh->version == 1) {
5334 * We cannot cancel listening ports on the
5335 * server side in SSH-1! There's no message
5336 * to support it. Instead, we simply remove
5337 * the rportfwd record from the local end
5338 * so that any connections the server tries
5339 * to make on it are rejected.
5342 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5343 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5344 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5346 ssh2_pkt_addstring(pktout, epf->saddr);
5347 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5348 /* XXX: rport_acceptall may not represent
5349 * what was used to open the original connection,
5350 * since it's reconfigurable. */
5351 ssh2_pkt_addstring(pktout, "");
5353 ssh2_pkt_addstring(pktout, "localhost");
5355 ssh2_pkt_adduint32(pktout, epf->sport);
5356 ssh2_pkt_send(ssh, pktout);
5359 del234(ssh->rportfwds, rpf);
5361 } else if (epf->local) {
5362 pfl_terminate(epf->local);
5365 delpos234(ssh->portfwds, i);
5367 i--; /* so we don't skip one in the list */
5371 * And finally, set up any new port forwardings (status==CREATE).
5373 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5374 if (epf->status == CREATE) {
5375 char *sportdesc, *dportdesc;
5376 sportdesc = dupprintf("%s%s%s%s%d%s",
5377 epf->saddr ? epf->saddr : "",
5378 epf->saddr ? ":" : "",
5379 epf->sserv ? epf->sserv : "",
5380 epf->sserv ? "(" : "",
5382 epf->sserv ? ")" : "");
5383 if (epf->type == 'D') {
5386 dportdesc = dupprintf("%s:%s%s%d%s",
5388 epf->dserv ? epf->dserv : "",
5389 epf->dserv ? "(" : "",
5391 epf->dserv ? ")" : "");
5394 if (epf->type == 'L') {
5395 char *err = pfl_listen(epf->daddr, epf->dport,
5396 epf->saddr, epf->sport,
5397 ssh, conf, &epf->local,
5398 epf->addressfamily);
5400 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5401 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5402 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5403 sportdesc, dportdesc,
5404 err ? " failed: " : "", err ? err : "");
5407 } else if (epf->type == 'D') {
5408 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5409 ssh, conf, &epf->local,
5410 epf->addressfamily);
5412 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5413 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5414 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5416 err ? " failed: " : "", err ? err : "");
5421 struct ssh_rportfwd *pf;
5424 * Ensure the remote port forwardings tree exists.
5426 if (!ssh->rportfwds) {
5427 if (ssh->version == 1)
5428 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5430 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5433 pf = snew(struct ssh_rportfwd);
5434 pf->share_ctx = NULL;
5435 pf->dhost = dupstr(epf->daddr);
5436 pf->dport = epf->dport;
5438 pf->shost = dupstr(epf->saddr);
5439 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5440 pf->shost = dupstr("");
5442 pf->shost = dupstr("localhost");
5444 pf->sport = epf->sport;
5445 if (add234(ssh->rportfwds, pf) != pf) {
5446 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5447 epf->daddr, epf->dport);
5450 logeventf(ssh, "Requesting remote port %s"
5451 " forward to %s", sportdesc, dportdesc);
5453 pf->sportdesc = sportdesc;
5458 if (ssh->version == 1) {
5459 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5460 PKT_INT, epf->sport,
5461 PKT_STR, epf->daddr,
5462 PKT_INT, epf->dport,
5464 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5466 ssh_rportfwd_succfail, pf);
5468 struct Packet *pktout;
5469 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5470 ssh2_pkt_addstring(pktout, "tcpip-forward");
5471 ssh2_pkt_addbool(pktout, 1);/* want reply */
5472 ssh2_pkt_addstring(pktout, pf->shost);
5473 ssh2_pkt_adduint32(pktout, pf->sport);
5474 ssh2_pkt_send(ssh, pktout);
5476 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5477 SSH2_MSG_REQUEST_FAILURE,
5478 ssh_rportfwd_succfail, pf);
5487 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5490 int stringlen, bufsize;
5492 ssh_pkt_getstring(pktin, &string, &stringlen);
5493 if (string == NULL) {
5494 bombout(("Incoming terminal data packet was badly formed"));
5498 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5500 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5501 ssh->v1_stdout_throttling = 1;
5502 ssh_throttle_conn(ssh, +1);
5506 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5508 /* Remote side is trying to open a channel to talk to our
5509 * X-Server. Give them back a local channel number. */
5510 struct ssh_channel *c;
5511 int remoteid = ssh_pkt_getuint32(pktin);
5513 logevent("Received X11 connect request");
5514 /* Refuse if X11 forwarding is disabled. */
5515 if (!ssh->X11_fwd_enabled) {
5516 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5517 PKT_INT, remoteid, PKT_END);
5518 logevent("Rejected X11 connect request");
5520 c = snew(struct ssh_channel);
5523 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5524 c->remoteid = remoteid;
5525 c->halfopen = FALSE;
5526 c->localid = alloc_channel_id(ssh);
5528 c->pending_eof = FALSE;
5529 c->throttling_conn = 0;
5530 c->type = CHAN_X11; /* identify channel type */
5531 add234(ssh->channels, c);
5532 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5533 PKT_INT, c->remoteid, PKT_INT,
5534 c->localid, PKT_END);
5535 logevent("Opened X11 forward channel");
5539 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5541 /* Remote side is trying to open a channel to talk to our
5542 * agent. Give them back a local channel number. */
5543 struct ssh_channel *c;
5544 int remoteid = ssh_pkt_getuint32(pktin);
5546 /* Refuse if agent forwarding is disabled. */
5547 if (!ssh->agentfwd_enabled) {
5548 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5549 PKT_INT, remoteid, PKT_END);
5551 c = snew(struct ssh_channel);
5553 c->remoteid = remoteid;
5554 c->halfopen = FALSE;
5555 c->localid = alloc_channel_id(ssh);
5557 c->pending_eof = FALSE;
5558 c->throttling_conn = 0;
5559 c->type = CHAN_AGENT; /* identify channel type */
5560 c->u.a.lensofar = 0;
5561 c->u.a.message = NULL;
5562 c->u.a.outstanding_requests = 0;
5563 add234(ssh->channels, c);
5564 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5565 PKT_INT, c->remoteid, PKT_INT, c->localid,
5570 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5572 /* Remote side is trying to open a channel to talk to a
5573 * forwarded port. Give them back a local channel number. */
5574 struct ssh_rportfwd pf, *pfp;
5580 remoteid = ssh_pkt_getuint32(pktin);
5581 ssh_pkt_getstring(pktin, &host, &hostsize);
5582 port = ssh_pkt_getuint32(pktin);
5584 pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
5586 pfp = find234(ssh->rportfwds, &pf, NULL);
5589 logeventf(ssh, "Rejected remote port open request for %s:%d",
5591 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5592 PKT_INT, remoteid, PKT_END);
5594 struct ssh_channel *c = snew(struct ssh_channel);
5597 logeventf(ssh, "Received remote port open request for %s:%d",
5599 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5600 c, ssh->conf, pfp->pfrec->addressfamily);
5602 logeventf(ssh, "Port open failed: %s", err);
5605 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5606 PKT_INT, remoteid, PKT_END);
5608 c->remoteid = remoteid;
5609 c->halfopen = FALSE;
5610 c->localid = alloc_channel_id(ssh);
5612 c->pending_eof = FALSE;
5613 c->throttling_conn = 0;
5614 c->type = CHAN_SOCKDATA; /* identify channel type */
5615 add234(ssh->channels, c);
5616 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5617 PKT_INT, c->remoteid, PKT_INT,
5618 c->localid, PKT_END);
5619 logevent("Forwarded port opened successfully");
5626 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5628 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5629 unsigned int localid = ssh_pkt_getuint32(pktin);
5630 struct ssh_channel *c;
5632 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5633 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5634 c->remoteid = localid;
5635 c->halfopen = FALSE;
5636 c->type = CHAN_SOCKDATA;
5637 c->throttling_conn = 0;
5638 pfd_confirm(c->u.pfd.pf);
5641 if (c && c->pending_eof) {
5643 * We have a pending close on this channel,
5644 * which we decided on before the server acked
5645 * the channel open. So now we know the
5646 * remoteid, we can close it again.
5648 ssh_channel_try_eof(c);
5652 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5654 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5655 struct ssh_channel *c;
5657 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5658 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5659 logevent("Forwarded connection refused by server");
5660 pfd_close(c->u.pfd.pf);
5661 del234(ssh->channels, c);
5666 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5668 /* Remote side closes a channel. */
5669 unsigned i = ssh_pkt_getuint32(pktin);
5670 struct ssh_channel *c;
5671 c = find234(ssh->channels, &i, ssh_channelfind);
5672 if (c && !c->halfopen) {
5674 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5675 !(c->closes & CLOSES_RCVD_EOF)) {
5677 * Received CHANNEL_CLOSE, which we translate into
5680 int send_close = FALSE;
5682 c->closes |= CLOSES_RCVD_EOF;
5687 x11_send_eof(c->u.x11.xconn);
5693 pfd_send_eof(c->u.pfd.pf);
5702 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5703 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5705 c->closes |= CLOSES_SENT_EOF;
5709 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5710 !(c->closes & CLOSES_RCVD_CLOSE)) {
5712 if (!(c->closes & CLOSES_SENT_EOF)) {
5713 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5714 " for which we never sent CHANNEL_CLOSE\n", i));
5717 c->closes |= CLOSES_RCVD_CLOSE;
5720 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5721 !(c->closes & CLOSES_SENT_CLOSE)) {
5722 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5723 PKT_INT, c->remoteid, PKT_END);
5724 c->closes |= CLOSES_SENT_CLOSE;
5727 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5728 ssh_channel_destroy(c);
5730 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5731 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5732 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5737 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5739 /* Data sent down one of our channels. */
5740 int i = ssh_pkt_getuint32(pktin);
5743 struct ssh_channel *c;
5745 ssh_pkt_getstring(pktin, &p, &len);
5747 c = find234(ssh->channels, &i, ssh_channelfind);
5752 bufsize = x11_send(c->u.x11.xconn, p, len);
5755 bufsize = pfd_send(c->u.pfd.pf, p, len);
5758 /* Data for an agent message. Buffer it. */
5760 if (c->u.a.lensofar < 4) {
5761 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
5762 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5766 c->u.a.lensofar += l;
5768 if (c->u.a.lensofar == 4) {
5770 4 + GET_32BIT(c->u.a.msglen);
5771 c->u.a.message = snewn(c->u.a.totallen,
5773 memcpy(c->u.a.message, c->u.a.msglen, 4);
5775 if (c->u.a.lensofar >= 4 && len > 0) {
5777 min(c->u.a.totallen - c->u.a.lensofar,
5779 memcpy(c->u.a.message + c->u.a.lensofar, p,
5783 c->u.a.lensofar += l;
5785 if (c->u.a.lensofar == c->u.a.totallen) {
5788 c->u.a.outstanding_requests++;
5789 if (agent_query(c->u.a.message,
5792 ssh_agentf_callback, c))
5793 ssh_agentf_callback(c, reply, replylen);
5794 sfree(c->u.a.message);
5795 c->u.a.lensofar = 0;
5798 bufsize = 0; /* agent channels never back up */
5801 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5802 c->throttling_conn = 1;
5803 ssh_throttle_conn(ssh, +1);
5808 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5810 ssh->exitcode = ssh_pkt_getuint32(pktin);
5811 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5812 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5814 * In case `helpful' firewalls or proxies tack
5815 * extra human-readable text on the end of the
5816 * session which we might mistake for another
5817 * encrypted packet, we close the session once
5818 * we've sent EXIT_CONFIRMATION.
5820 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5823 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5824 static void ssh1_send_ttymode(void *data, char *mode, char *val)
5826 struct Packet *pktout = (struct Packet *)data;
5828 unsigned int arg = 0;
5829 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5830 if (i == lenof(ssh_ttymodes)) return;
5831 switch (ssh_ttymodes[i].type) {
5833 arg = ssh_tty_parse_specchar(val);
5836 arg = ssh_tty_parse_boolean(val);
5839 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5840 ssh2_pkt_addbyte(pktout, arg);
5843 int ssh_agent_forwarding_permitted(Ssh ssh)
5845 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5848 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5849 struct Packet *pktin)
5851 crBegin(ssh->do_ssh1_connection_crstate);
5853 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5854 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5855 ssh1_smsg_stdout_stderr_data;
5857 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5858 ssh1_msg_channel_open_confirmation;
5859 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5860 ssh1_msg_channel_open_failure;
5861 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5862 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5863 ssh1_msg_channel_close;
5864 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5865 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5867 if (ssh_agent_forwarding_permitted(ssh)) {
5868 logevent("Requesting agent forwarding");
5869 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5873 if (pktin->type != SSH1_SMSG_SUCCESS
5874 && pktin->type != SSH1_SMSG_FAILURE) {
5875 bombout(("Protocol confusion"));
5877 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5878 logevent("Agent forwarding refused");
5880 logevent("Agent forwarding enabled");
5881 ssh->agentfwd_enabled = TRUE;
5882 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5886 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5888 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5890 if (!ssh->x11disp) {
5891 /* FIXME: return an error message from x11_setup_display */
5892 logevent("X11 forwarding not enabled: unable to"
5893 " initialise X display");
5895 ssh->x11auth = x11_invent_fake_auth
5896 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5897 ssh->x11auth->disp = ssh->x11disp;
5899 logevent("Requesting X11 forwarding");
5900 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5901 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5902 PKT_STR, ssh->x11auth->protoname,
5903 PKT_STR, ssh->x11auth->datastring,
5904 PKT_INT, ssh->x11disp->screennum,
5907 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5908 PKT_STR, ssh->x11auth->protoname,
5909 PKT_STR, ssh->x11auth->datastring,
5915 if (pktin->type != SSH1_SMSG_SUCCESS
5916 && pktin->type != SSH1_SMSG_FAILURE) {
5917 bombout(("Protocol confusion"));
5919 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5920 logevent("X11 forwarding refused");
5922 logevent("X11 forwarding enabled");
5923 ssh->X11_fwd_enabled = TRUE;
5924 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5929 ssh_setup_portfwd(ssh, ssh->conf);
5930 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5932 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5934 /* Unpick the terminal-speed string. */
5935 /* XXX perhaps we should allow no speeds to be sent. */
5936 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5937 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5938 /* Send the pty request. */
5939 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5940 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5941 ssh_pkt_adduint32(pkt, ssh->term_height);
5942 ssh_pkt_adduint32(pkt, ssh->term_width);
5943 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5944 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5945 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5946 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5947 ssh_pkt_adduint32(pkt, ssh->ispeed);
5948 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5949 ssh_pkt_adduint32(pkt, ssh->ospeed);
5950 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5952 ssh->state = SSH_STATE_INTERMED;
5956 if (pktin->type != SSH1_SMSG_SUCCESS
5957 && pktin->type != SSH1_SMSG_FAILURE) {
5958 bombout(("Protocol confusion"));
5960 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5961 c_write_str(ssh, "Server refused to allocate pty\r\n");
5962 ssh->editing = ssh->echoing = 1;
5964 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5965 ssh->ospeed, ssh->ispeed);
5966 ssh->got_pty = TRUE;
5969 ssh->editing = ssh->echoing = 1;
5972 if (conf_get_int(ssh->conf, CONF_compression)) {
5973 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5977 if (pktin->type != SSH1_SMSG_SUCCESS
5978 && pktin->type != SSH1_SMSG_FAILURE) {
5979 bombout(("Protocol confusion"));
5981 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5982 c_write_str(ssh, "Server refused to compress\r\n");
5984 logevent("Started compression");
5985 ssh->v1_compressing = TRUE;
5986 ssh->cs_comp_ctx = zlib_compress_init();
5987 logevent("Initialised zlib (RFC1950) compression");
5988 ssh->sc_comp_ctx = zlib_decompress_init();
5989 logevent("Initialised zlib (RFC1950) decompression");
5993 * Start the shell or command.
5995 * Special case: if the first-choice command is an SSH-2
5996 * subsystem (hence not usable here) and the second choice
5997 * exists, we fall straight back to that.
6000 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
6002 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
6003 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
6004 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
6005 ssh->fallback_cmd = TRUE;
6008 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
6010 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
6011 logevent("Started session");
6014 ssh->state = SSH_STATE_SESSION;
6015 if (ssh->size_needed)
6016 ssh_size(ssh, ssh->term_width, ssh->term_height);
6017 if (ssh->eof_needed)
6018 ssh_special(ssh, TS_EOF);
6021 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
6023 ssh->channels = newtree234(ssh_channelcmp);
6027 * By this point, most incoming packets are already being
6028 * handled by the dispatch table, and we need only pay
6029 * attention to the unusual ones.
6034 if (pktin->type == SSH1_SMSG_SUCCESS) {
6035 /* may be from EXEC_SHELL on some servers */
6036 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6037 /* may be from EXEC_SHELL on some servers
6038 * if no pty is available or in other odd cases. Ignore */
6040 bombout(("Strange packet received: type %d", pktin->type));
6045 int len = min(inlen, 512);
6046 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
6047 PKT_INT, len, PKT_DATA, in, len,
6059 * Handle the top-level SSH-2 protocol.
6061 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6066 ssh_pkt_getstring(pktin, &msg, &msglen);
6067 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
6070 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6072 /* log reason code in disconnect message */
6076 ssh_pkt_getstring(pktin, &msg, &msglen);
6077 bombout(("Server sent disconnect message:\n\"%.*s\"",
6078 msglen, NULLTOEMPTY(msg)));
6081 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6083 /* Do nothing, because we're ignoring it! Duhh. */
6086 static void ssh1_protocol_setup(Ssh ssh)
6091 * Most messages are handled by the coroutines.
6093 for (i = 0; i < 256; i++)
6094 ssh->packet_dispatch[i] = NULL;
6097 * These special message types we install handlers for.
6099 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6100 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6101 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6104 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6105 struct Packet *pktin)
6107 const unsigned char *in = (const unsigned char *)vin;
6108 if (ssh->state == SSH_STATE_CLOSED)
6111 if (pktin && ssh->packet_dispatch[pktin->type]) {
6112 ssh->packet_dispatch[pktin->type](ssh, pktin);
6116 if (!ssh->protocol_initial_phase_done) {
6117 if (do_ssh1_login(ssh, in, inlen, pktin))
6118 ssh->protocol_initial_phase_done = TRUE;
6123 do_ssh1_connection(ssh, in, inlen, pktin);
6127 * Utility routines for decoding comma-separated strings in KEXINIT.
6129 static int first_in_commasep_string(char const *needle, char const *haystack,
6133 if (!needle || !haystack) /* protect against null pointers */
6135 needlen = strlen(needle);
6137 if (haylen >= needlen && /* haystack is long enough */
6138 !memcmp(needle, haystack, needlen) && /* initial match */
6139 (haylen == needlen || haystack[needlen] == ',')
6140 /* either , or EOS follows */
6146 static int in_commasep_string(char const *needle, char const *haystack,
6151 if (!needle || !haystack) /* protect against null pointers */
6154 * Is it at the start of the string?
6156 if (first_in_commasep_string(needle, haystack, haylen))
6159 * If not, search for the next comma and resume after that.
6160 * If no comma found, terminate.
6162 p = memchr(haystack, ',', haylen);
6164 /* + 1 to skip over comma */
6165 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6169 * Add a value to the comma-separated string at the end of the packet.
6171 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6173 if (pkt->length - pkt->savedpos > 0)
6174 ssh_pkt_addstring_str(pkt, ",");
6175 ssh_pkt_addstring_str(pkt, data);
6180 * SSH-2 key derivation (RFC 4253 section 7.2).
6182 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6183 char chr, int keylen)
6185 const struct ssh_hash *h = ssh->kex->hash;
6193 /* Round up to the next multiple of hash length. */
6194 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6196 key = snewn(keylen_padded, unsigned char);
6198 /* First hlen bytes. */
6200 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6201 hash_mpint(h, s, K);
6202 h->bytes(s, H, h->hlen);
6203 h->bytes(s, &chr, 1);
6204 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6207 /* Subsequent blocks of hlen bytes. */
6208 if (keylen_padded > h->hlen) {
6212 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6213 hash_mpint(h, s, K);
6214 h->bytes(s, H, h->hlen);
6216 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6217 h->bytes(s, key + offset - h->hlen, h->hlen);
6219 h->final(s2, key + offset);
6225 /* Now clear any extra bytes of key material beyond the length
6226 * we're officially returning, because the caller won't know to
6228 if (keylen_padded > keylen)
6229 smemclr(key + keylen, keylen_padded - keylen);
6235 * Structure for constructing KEXINIT algorithm lists.
6237 #define MAXKEXLIST 16
6238 struct kexinit_algorithm {
6242 const struct ssh_kex *kex;
6245 const struct ssh_signkey *hostkey;
6247 const struct ssh2_cipher *cipher;
6251 const struct ssh_mac *mac;
6254 const struct ssh_compress *comp;
6259 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6260 * If the algorithm is already in the list, return a pointer to its
6261 * entry, otherwise return an entry from the end of the list.
6262 * This assumes that every time a particular name is passed in, it
6263 * comes from the same string constant. If this isn't true, this
6264 * function may need to be rewritten to use strcmp() instead.
6266 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6267 *list, const char *name)
6271 for (i = 0; i < MAXKEXLIST; i++)
6272 if (list[i].name == NULL || list[i].name == name) {
6273 list[i].name = name;
6276 assert(!"No space in KEXINIT list");
6281 * Handle the SSH-2 transport layer.
6283 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6284 struct Packet *pktin)
6286 const unsigned char *in = (const unsigned char *)vin;
6288 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6289 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6292 const char * kexlist_descr[NKEXLIST] = {
6293 "key exchange algorithm", "host key algorithm",
6294 "client-to-server cipher", "server-to-client cipher",
6295 "client-to-server MAC", "server-to-client MAC",
6296 "client-to-server compression method",
6297 "server-to-client compression method" };
6298 struct do_ssh2_transport_state {
6300 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
6301 Bignum p, g, e, f, K;
6304 int kex_init_value, kex_reply_value;
6305 const struct ssh_mac **maclist;
6307 const struct ssh2_cipher *cscipher_tobe;
6308 const struct ssh2_cipher *sccipher_tobe;
6309 const struct ssh_mac *csmac_tobe;
6310 const struct ssh_mac *scmac_tobe;
6311 int csmac_etm_tobe, scmac_etm_tobe;
6312 const struct ssh_compress *cscomp_tobe;
6313 const struct ssh_compress *sccomp_tobe;
6314 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6315 int hostkeylen, siglen, rsakeylen;
6316 void *hkey; /* actual host key */
6317 void *rsakey; /* for RSA kex */
6318 void *eckey; /* for ECDH kex */
6319 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6320 int n_preferred_kex;
6321 const struct ssh_kexes *preferred_kex[KEX_MAX];
6322 int n_preferred_ciphers;
6323 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6324 const struct ssh_compress *preferred_comp;
6325 int userauth_succeeded; /* for delayed compression */
6326 int pending_compression;
6327 int got_session_id, activated_authconn;
6328 struct Packet *pktout;
6332 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6334 crState(do_ssh2_transport_state);
6336 assert(!ssh->bare_connection);
6340 s->cscipher_tobe = s->sccipher_tobe = NULL;
6341 s->csmac_tobe = s->scmac_tobe = NULL;
6342 s->cscomp_tobe = s->sccomp_tobe = NULL;
6344 s->got_session_id = s->activated_authconn = FALSE;
6345 s->userauth_succeeded = FALSE;
6346 s->pending_compression = FALSE;
6349 * Be prepared to work around the buggy MAC problem.
6351 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6352 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6354 s->maclist = macs, s->nmacs = lenof(macs);
6357 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6360 struct kexinit_algorithm *alg;
6363 * Set up the preferred key exchange. (NULL => warn below here)
6365 s->n_preferred_kex = 0;
6366 for (i = 0; i < KEX_MAX; i++) {
6367 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6369 s->preferred_kex[s->n_preferred_kex++] =
6370 &ssh_diffiehellman_gex;
6373 s->preferred_kex[s->n_preferred_kex++] =
6374 &ssh_diffiehellman_group14;
6377 s->preferred_kex[s->n_preferred_kex++] =
6378 &ssh_diffiehellman_group1;
6381 s->preferred_kex[s->n_preferred_kex++] =
6385 s->preferred_kex[s->n_preferred_kex++] =
6389 /* Flag for later. Don't bother if it's the last in
6391 if (i < KEX_MAX - 1) {
6392 s->preferred_kex[s->n_preferred_kex++] = NULL;
6399 * Set up the preferred ciphers. (NULL => warn below here)
6401 s->n_preferred_ciphers = 0;
6402 for (i = 0; i < CIPHER_MAX; i++) {
6403 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6404 case CIPHER_BLOWFISH:
6405 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6408 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6409 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6413 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6416 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6418 case CIPHER_ARCFOUR:
6419 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6421 case CIPHER_CHACHA20:
6422 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6425 /* Flag for later. Don't bother if it's the last in
6427 if (i < CIPHER_MAX - 1) {
6428 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6435 * Set up preferred compression.
6437 if (conf_get_int(ssh->conf, CONF_compression))
6438 s->preferred_comp = &ssh_zlib;
6440 s->preferred_comp = &ssh_comp_none;
6443 * Enable queueing of outgoing auth- or connection-layer
6444 * packets while we are in the middle of a key exchange.
6446 ssh->queueing = TRUE;
6449 * Flag that KEX is in progress.
6451 ssh->kex_in_progress = TRUE;
6453 for (i = 0; i < NKEXLIST; i++)
6454 for (j = 0; j < MAXKEXLIST; j++)
6455 s->kexlists[i][j].name = NULL;
6456 /* List key exchange algorithms. */
6458 for (i = 0; i < s->n_preferred_kex; i++) {
6459 const struct ssh_kexes *k = s->preferred_kex[i];
6460 if (!k) warn = TRUE;
6461 else for (j = 0; j < k->nkexes; j++) {
6462 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6464 alg->u.kex.kex = k->list[j];
6465 alg->u.kex.warn = warn;
6468 /* List server host key algorithms. */
6469 if (!s->got_session_id) {
6471 * In the first key exchange, we list all the algorithms
6472 * we're prepared to cope with, but prefer those algorithms
6473 * for which we have a host key for this host.
6475 for (i = 0; i < lenof(hostkey_algs); i++) {
6476 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6477 hostkey_algs[i]->keytype)) {
6478 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6479 hostkey_algs[i]->name);
6480 alg->u.hostkey = hostkey_algs[i];
6483 for (i = 0; i < lenof(hostkey_algs); i++) {
6484 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6485 hostkey_algs[i]->name);
6486 alg->u.hostkey = hostkey_algs[i];
6490 * In subsequent key exchanges, we list only the kex
6491 * algorithm that was selected in the first key exchange,
6492 * so that we keep getting the same host key and hence
6493 * don't have to interrupt the user's session to ask for
6497 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6498 ssh->hostkey->name);
6499 alg->u.hostkey = ssh->hostkey;
6501 /* List encryption algorithms (client->server then server->client). */
6502 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6505 alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6506 alg->u.cipher.cipher = NULL;
6507 alg->u.cipher.warn = warn;
6508 #endif /* FUZZING */
6509 for (i = 0; i < s->n_preferred_ciphers; i++) {
6510 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6511 if (!c) warn = TRUE;
6512 else for (j = 0; j < c->nciphers; j++) {
6513 alg = ssh2_kexinit_addalg(s->kexlists[k],
6515 alg->u.cipher.cipher = c->list[j];
6516 alg->u.cipher.warn = warn;
6520 /* List MAC algorithms (client->server then server->client). */
6521 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6523 alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6524 alg->u.mac.mac = NULL;
6525 alg->u.mac.etm = FALSE;
6526 #endif /* FUZZING */
6527 for (i = 0; i < s->nmacs; i++) {
6528 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6529 alg->u.mac.mac = s->maclist[i];
6530 alg->u.mac.etm = FALSE;
6532 for (i = 0; i < s->nmacs; i++)
6533 /* For each MAC, there may also be an ETM version,
6534 * which we list second. */
6535 if (s->maclist[i]->etm_name) {
6536 alg = ssh2_kexinit_addalg(s->kexlists[j],
6537 s->maclist[i]->etm_name);
6538 alg->u.mac.mac = s->maclist[i];
6539 alg->u.mac.etm = TRUE;
6542 /* List client->server compression algorithms,
6543 * then server->client compression algorithms. (We use the
6544 * same set twice.) */
6545 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6546 assert(lenof(compressions) > 1);
6547 /* Prefer non-delayed versions */
6548 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6549 alg->u.comp = s->preferred_comp;
6550 /* We don't even list delayed versions of algorithms until
6551 * they're allowed to be used, to avoid a race. See the end of
6553 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6554 alg = ssh2_kexinit_addalg(s->kexlists[j],
6555 s->preferred_comp->delayed_name);
6556 alg->u.comp = s->preferred_comp;
6558 for (i = 0; i < lenof(compressions); i++) {
6559 const struct ssh_compress *c = compressions[i];
6560 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6562 if (s->userauth_succeeded && c->delayed_name) {
6563 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6569 * Construct and send our key exchange packet.
6571 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6572 for (i = 0; i < 16; i++)
6573 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6574 for (i = 0; i < NKEXLIST; i++) {
6575 ssh2_pkt_addstring_start(s->pktout);
6576 for (j = 0; j < MAXKEXLIST; j++) {
6577 if (s->kexlists[i][j].name == NULL) break;
6578 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6581 /* List client->server languages. Empty list. */
6582 ssh2_pkt_addstring_start(s->pktout);
6583 /* List server->client languages. Empty list. */
6584 ssh2_pkt_addstring_start(s->pktout);
6585 /* First KEX packet does _not_ follow, because we're not that brave. */
6586 ssh2_pkt_addbool(s->pktout, FALSE);
6588 ssh2_pkt_adduint32(s->pktout, 0);
6591 s->our_kexinitlen = s->pktout->length - 5;
6592 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6593 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6595 ssh2_pkt_send_noqueue(ssh, s->pktout);
6598 crWaitUntilV(pktin);
6601 * Now examine the other side's KEXINIT to see what we're up
6608 if (pktin->type != SSH2_MSG_KEXINIT) {
6609 bombout(("expected key exchange packet from server"));
6613 ssh->hostkey = NULL;
6614 s->cscipher_tobe = NULL;
6615 s->sccipher_tobe = NULL;
6616 s->csmac_tobe = NULL;
6617 s->scmac_tobe = NULL;
6618 s->cscomp_tobe = NULL;
6619 s->sccomp_tobe = NULL;
6620 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
6622 pktin->savedpos += 16; /* skip garbage cookie */
6625 for (i = 0; i < NKEXLIST; i++) {
6626 ssh_pkt_getstring(pktin, &str, &len);
6628 bombout(("KEXINIT packet was incomplete"));
6632 /* If we've already selected a cipher which requires a
6633 * particular MAC, then just select that, and don't even
6634 * bother looking through the server's KEXINIT string for
6636 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6637 s->cscipher_tobe->required_mac) {
6638 s->csmac_tobe = s->cscipher_tobe->required_mac;
6639 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6642 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6643 s->sccipher_tobe->required_mac) {
6644 s->scmac_tobe = s->sccipher_tobe->required_mac;
6645 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6649 for (j = 0; j < MAXKEXLIST; j++) {
6650 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6651 if (alg->name == NULL) break;
6652 if (in_commasep_string(alg->name, str, len)) {
6653 /* We've found a matching algorithm. */
6654 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6655 /* Check if we might need to ignore first kex pkt */
6657 !first_in_commasep_string(alg->name, str, len))
6660 if (i == KEXLIST_KEX) {
6661 ssh->kex = alg->u.kex.kex;
6662 s->warn_kex = alg->u.kex.warn;
6663 } else if (i == KEXLIST_HOSTKEY) {
6664 ssh->hostkey = alg->u.hostkey;
6665 } else if (i == KEXLIST_CSCIPHER) {
6666 s->cscipher_tobe = alg->u.cipher.cipher;
6667 s->warn_cscipher = alg->u.cipher.warn;
6668 } else if (i == KEXLIST_SCCIPHER) {
6669 s->sccipher_tobe = alg->u.cipher.cipher;
6670 s->warn_sccipher = alg->u.cipher.warn;
6671 } else if (i == KEXLIST_CSMAC) {
6672 s->csmac_tobe = alg->u.mac.mac;
6673 s->csmac_etm_tobe = alg->u.mac.etm;
6674 } else if (i == KEXLIST_SCMAC) {
6675 s->scmac_tobe = alg->u.mac.mac;
6676 s->scmac_etm_tobe = alg->u.mac.etm;
6677 } else if (i == KEXLIST_CSCOMP) {
6678 s->cscomp_tobe = alg->u.comp;
6679 } else if (i == KEXLIST_SCCOMP) {
6680 s->sccomp_tobe = alg->u.comp;
6684 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6685 in_commasep_string(alg->u.comp->delayed_name, str, len))
6686 s->pending_compression = TRUE; /* try this later */
6688 bombout(("Couldn't agree a %s ((available: %.*s)",
6689 kexlist_descr[i], len, str));
6693 if (i == KEXLIST_HOSTKEY) {
6697 * In addition to deciding which host key we're
6698 * actually going to use, we should make a list of the
6699 * host keys offered by the server which we _don't_
6700 * have cached. These will be offered as cross-
6701 * certification options by ssh_get_specials.
6703 ssh->n_uncert_hostkeys = 0;
6705 for (j = 0; j < lenof(hostkey_algs); j++) {
6706 if (in_commasep_string(hostkey_algs[j]->name, str, len) &&
6707 !have_ssh_host_key(ssh->savedhost, ssh->savedport,
6708 hostkey_algs[j]->keytype)) {
6709 ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
6715 if (s->pending_compression) {
6716 logevent("Server supports delayed compression; "
6717 "will try this later");
6719 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6720 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6721 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6723 ssh->exhash = ssh->kex->hash->init();
6724 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6725 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6726 hash_string(ssh->kex->hash, ssh->exhash,
6727 s->our_kexinit, s->our_kexinitlen);
6728 sfree(s->our_kexinit);
6729 /* Include the type byte in the hash of server's KEXINIT */
6730 hash_string(ssh->kex->hash, ssh->exhash,
6731 pktin->body - 1, pktin->length + 1);
6734 ssh_set_frozen(ssh, 1);
6735 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6737 ssh_dialog_callback, ssh);
6738 if (s->dlgret < 0) {
6742 bombout(("Unexpected data from server while"
6743 " waiting for user response"));
6746 } while (pktin || inlen > 0);
6747 s->dlgret = ssh->user_response;
6749 ssh_set_frozen(ssh, 0);
6750 if (s->dlgret == 0) {
6751 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6757 if (s->warn_cscipher) {
6758 ssh_set_frozen(ssh, 1);
6759 s->dlgret = askalg(ssh->frontend,
6760 "client-to-server cipher",
6761 s->cscipher_tobe->name,
6762 ssh_dialog_callback, ssh);
6763 if (s->dlgret < 0) {
6767 bombout(("Unexpected data from server while"
6768 " waiting for user response"));
6771 } while (pktin || inlen > 0);
6772 s->dlgret = ssh->user_response;
6774 ssh_set_frozen(ssh, 0);
6775 if (s->dlgret == 0) {
6776 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6782 if (s->warn_sccipher) {
6783 ssh_set_frozen(ssh, 1);
6784 s->dlgret = askalg(ssh->frontend,
6785 "server-to-client cipher",
6786 s->sccipher_tobe->name,
6787 ssh_dialog_callback, ssh);
6788 if (s->dlgret < 0) {
6792 bombout(("Unexpected data from server while"
6793 " waiting for user response"));
6796 } while (pktin || inlen > 0);
6797 s->dlgret = ssh->user_response;
6799 ssh_set_frozen(ssh, 0);
6800 if (s->dlgret == 0) {
6801 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6807 if (s->ignorepkt) /* first_kex_packet_follows */
6808 crWaitUntilV(pktin); /* Ignore packet */
6811 if (ssh->kex->main_type == KEXTYPE_DH) {
6813 * Work out the number of bits of key we will need from the
6814 * key exchange. We start with the maximum key length of
6820 csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6821 scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6822 s->nbits = (csbits > scbits ? csbits : scbits);
6824 /* The keys only have hlen-bit entropy, since they're based on
6825 * a hash. So cap the key size at hlen bits. */
6826 if (s->nbits > ssh->kex->hash->hlen * 8)
6827 s->nbits = ssh->kex->hash->hlen * 8;
6830 * If we're doing Diffie-Hellman group exchange, start by
6831 * requesting a group.
6833 if (dh_is_gex(ssh->kex)) {
6834 logevent("Doing Diffie-Hellman group exchange");
6835 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6837 * Work out how big a DH group we will need to allow that
6840 s->pbits = 512 << ((s->nbits - 1) / 64);
6841 if (s->pbits < DH_MIN_SIZE)
6842 s->pbits = DH_MIN_SIZE;
6843 if (s->pbits > DH_MAX_SIZE)
6844 s->pbits = DH_MAX_SIZE;
6845 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6846 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6847 ssh2_pkt_adduint32(s->pktout, s->pbits);
6849 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6850 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6851 ssh2_pkt_adduint32(s->pktout, s->pbits);
6852 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6854 ssh2_pkt_send_noqueue(ssh, s->pktout);
6856 crWaitUntilV(pktin);
6857 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6858 bombout(("expected key exchange group packet from server"));
6861 s->p = ssh2_pkt_getmp(pktin);
6862 s->g = ssh2_pkt_getmp(pktin);
6863 if (!s->p || !s->g) {
6864 bombout(("unable to read mp-ints from incoming group packet"));
6867 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6868 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6869 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6871 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6872 ssh->kex_ctx = dh_setup_group(ssh->kex);
6873 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6874 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6875 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6876 ssh->kex->groupname);
6879 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6880 ssh->kex->hash->text_name);
6882 * Now generate and send e for Diffie-Hellman.
6884 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6885 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6886 s->pktout = ssh2_pkt_init(s->kex_init_value);
6887 ssh2_pkt_addmp(s->pktout, s->e);
6888 ssh2_pkt_send_noqueue(ssh, s->pktout);
6890 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6891 crWaitUntilV(pktin);
6892 if (pktin->type != s->kex_reply_value) {
6893 bombout(("expected key exchange reply packet from server"));
6896 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6897 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6898 if (!s->hostkeydata) {
6899 bombout(("unable to parse key exchange reply packet"));
6902 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6903 s->hostkeydata, s->hostkeylen);
6904 s->f = ssh2_pkt_getmp(pktin);
6906 bombout(("unable to parse key exchange reply packet"));
6909 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6911 bombout(("unable to parse key exchange reply packet"));
6916 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
6918 bombout(("key exchange reply failed validation: %s", err));
6922 s->K = dh_find_K(ssh->kex_ctx, s->f);
6924 /* We assume everything from now on will be quick, and it might
6925 * involve user interaction. */
6926 set_busy_status(ssh->frontend, BUSY_NOT);
6928 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6929 if (dh_is_gex(ssh->kex)) {
6930 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6931 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
6932 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6933 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6934 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
6935 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6936 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6938 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6939 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6941 dh_cleanup(ssh->kex_ctx);
6943 if (dh_is_gex(ssh->kex)) {
6947 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
6949 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
6950 ssh_ecdhkex_curve_textname(ssh->kex),
6951 ssh->kex->hash->text_name);
6952 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
6954 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
6956 bombout(("Unable to generate key for ECDH"));
6962 int publicPointLength;
6963 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6965 ssh_ecdhkex_freekey(s->eckey);
6966 bombout(("Unable to encode public key for ECDH"));
6969 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
6970 ssh2_pkt_addstring_start(s->pktout);
6971 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
6975 ssh2_pkt_send_noqueue(ssh, s->pktout);
6977 crWaitUntilV(pktin);
6978 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
6979 ssh_ecdhkex_freekey(s->eckey);
6980 bombout(("expected ECDH reply packet from server"));
6984 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6985 if (!s->hostkeydata) {
6986 bombout(("unable to parse ECDH reply packet"));
6989 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6990 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6991 s->hostkeydata, s->hostkeylen);
6995 int publicPointLength;
6996 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
6998 ssh_ecdhkex_freekey(s->eckey);
6999 bombout(("Unable to encode public key for ECDH hash"));
7002 hash_string(ssh->kex->hash, ssh->exhash,
7003 publicPoint, publicPointLength);
7010 ssh_pkt_getstring(pktin, &keydata, &keylen);
7012 bombout(("unable to parse ECDH reply packet"));
7015 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
7016 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
7018 ssh_ecdhkex_freekey(s->eckey);
7019 bombout(("point received in ECDH was not valid"));
7024 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7026 bombout(("unable to parse key exchange reply packet"));
7030 ssh_ecdhkex_freekey(s->eckey);
7032 logeventf(ssh, "Doing RSA key exchange with hash %s",
7033 ssh->kex->hash->text_name);
7034 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7036 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7039 crWaitUntilV(pktin);
7040 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7041 bombout(("expected RSA public key packet from server"));
7045 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7046 if (!s->hostkeydata) {
7047 bombout(("unable to parse RSA public key packet"));
7050 hash_string(ssh->kex->hash, ssh->exhash,
7051 s->hostkeydata, s->hostkeylen);
7052 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7053 s->hostkeydata, s->hostkeylen);
7057 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7059 bombout(("unable to parse RSA public key packet"));
7062 s->rsakeydata = snewn(s->rsakeylen, char);
7063 memcpy(s->rsakeydata, keydata, s->rsakeylen);
7066 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7068 sfree(s->rsakeydata);
7069 bombout(("unable to parse RSA public key from server"));
7073 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7076 * Next, set up a shared secret K, of precisely KLEN -
7077 * 2*HLEN - 49 bits, where KLEN is the bit length of the
7078 * RSA key modulus and HLEN is the bit length of the hash
7082 int klen = ssh_rsakex_klen(s->rsakey);
7083 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7085 unsigned char *kstr1, *kstr2, *outstr;
7086 int kstr1len, kstr2len, outstrlen;
7088 s->K = bn_power_2(nbits - 1);
7090 for (i = 0; i < nbits; i++) {
7092 byte = random_byte();
7094 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7098 * Encode this as an mpint.
7100 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7101 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7102 PUT_32BIT(kstr2, kstr1len);
7103 memcpy(kstr2 + 4, kstr1, kstr1len);
7106 * Encrypt it with the given RSA key.
7108 outstrlen = (klen + 7) / 8;
7109 outstr = snewn(outstrlen, unsigned char);
7110 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7111 outstr, outstrlen, s->rsakey);
7114 * And send it off in a return packet.
7116 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7117 ssh2_pkt_addstring_start(s->pktout);
7118 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7119 ssh2_pkt_send_noqueue(ssh, s->pktout);
7121 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7128 ssh_rsakex_freekey(s->rsakey);
7130 crWaitUntilV(pktin);
7131 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7132 sfree(s->rsakeydata);
7133 bombout(("expected signature packet from server"));
7137 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7139 bombout(("unable to parse signature packet"));
7143 sfree(s->rsakeydata);
7146 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7147 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7148 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7150 ssh->kex_ctx = NULL;
7153 debug(("Exchange hash is:\n"));
7154 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7158 bombout(("Server's host key is invalid"));
7162 if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7163 (char *)s->exchange_hash,
7164 ssh->kex->hash->hlen)) {
7166 bombout(("Server's host key did not match the signature supplied"));
7171 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7172 if (!s->got_session_id) {
7174 * Authenticate remote host: verify host key. (We've already
7175 * checked the signature of the exchange hash.)
7177 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7178 logevent("Host key fingerprint is:");
7179 logevent(s->fingerprint);
7180 /* First check against manually configured host keys. */
7181 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7182 ssh->hostkey, s->hkey);
7183 if (s->dlgret == 0) { /* did not match */
7184 bombout(("Host key did not appear in manually configured list"));
7186 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7187 ssh_set_frozen(ssh, 1);
7188 s->dlgret = verify_ssh_host_key(ssh->frontend,
7189 ssh->savedhost, ssh->savedport,
7190 ssh->hostkey->keytype, s->keystr,
7192 ssh_dialog_callback, ssh);
7196 if (s->dlgret < 0) {
7200 bombout(("Unexpected data from server while waiting"
7201 " for user host key response"));
7204 } while (pktin || inlen > 0);
7205 s->dlgret = ssh->user_response;
7207 ssh_set_frozen(ssh, 0);
7208 if (s->dlgret == 0) {
7209 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7214 sfree(s->fingerprint);
7216 * Save this host key, to check against the one presented in
7217 * subsequent rekeys.
7219 ssh->hostkey_str = s->keystr;
7220 } else if (ssh->cross_certifying) {
7221 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7222 logevent("Storing additional host key for this host:");
7223 logevent(s->fingerprint);
7224 store_host_key(ssh->savedhost, ssh->savedport,
7225 ssh->hostkey->keytype, s->keystr);
7226 ssh->cross_certifying = FALSE;
7228 * Don't forget to store the new key as the one we'll be
7229 * re-checking in future normal rekeys.
7231 ssh->hostkey_str = s->keystr;
7234 * In a rekey, we never present an interactive host key
7235 * verification request to the user. Instead, we simply
7236 * enforce that the key we're seeing this time is identical to
7237 * the one we saw before.
7239 if (strcmp(ssh->hostkey_str, s->keystr)) {
7241 bombout(("Host key was different in repeat key exchange"));
7247 ssh->hostkey->freekey(s->hkey);
7250 * The exchange hash from the very first key exchange is also
7251 * the session id, used in session key construction and
7254 if (!s->got_session_id) {
7255 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7256 memcpy(ssh->v2_session_id, s->exchange_hash,
7257 sizeof(s->exchange_hash));
7258 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7259 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7260 s->got_session_id = TRUE;
7264 * Send SSH2_MSG_NEWKEYS.
7266 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7267 ssh2_pkt_send_noqueue(ssh, s->pktout);
7268 ssh->outgoing_data_size = 0; /* start counting from here */
7271 * We've sent client NEWKEYS, so create and initialise
7272 * client-to-server session keys.
7274 if (ssh->cs_cipher_ctx)
7275 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7276 ssh->cscipher = s->cscipher_tobe;
7277 if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7279 if (ssh->cs_mac_ctx)
7280 ssh->csmac->free_context(ssh->cs_mac_ctx);
7281 ssh->csmac = s->csmac_tobe;
7282 ssh->csmac_etm = s->csmac_etm_tobe;
7284 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7286 if (ssh->cs_comp_ctx)
7287 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7288 ssh->cscomp = s->cscomp_tobe;
7289 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7292 * Set IVs on client-to-server keys. Here we use the exchange
7293 * hash from the _first_ key exchange.
7295 if (ssh->cscipher) {
7298 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7299 ssh->cscipher->padded_keybytes);
7300 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7301 smemclr(key, ssh->cscipher->padded_keybytes);
7304 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7305 ssh->cscipher->blksize);
7306 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7307 smemclr(key, ssh->cscipher->blksize);
7313 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7314 ssh->csmac->keylen);
7315 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7316 smemclr(key, ssh->csmac->keylen);
7321 logeventf(ssh, "Initialised %.200s client->server encryption",
7322 ssh->cscipher->text_name);
7324 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7325 ssh->csmac->text_name,
7326 ssh->csmac_etm ? " (in ETM mode)" : "",
7327 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7328 if (ssh->cscomp->text_name)
7329 logeventf(ssh, "Initialised %s compression",
7330 ssh->cscomp->text_name);
7333 * Now our end of the key exchange is complete, we can send all
7334 * our queued higher-layer packets.
7336 ssh->queueing = FALSE;
7337 ssh2_pkt_queuesend(ssh);
7340 * Expect SSH2_MSG_NEWKEYS from server.
7342 crWaitUntilV(pktin);
7343 if (pktin->type != SSH2_MSG_NEWKEYS) {
7344 bombout(("expected new-keys packet from server"));
7347 ssh->incoming_data_size = 0; /* start counting from here */
7350 * We've seen server NEWKEYS, so create and initialise
7351 * server-to-client session keys.
7353 if (ssh->sc_cipher_ctx)
7354 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7355 if (s->sccipher_tobe) {
7356 ssh->sccipher = s->sccipher_tobe;
7357 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7360 if (ssh->sc_mac_ctx)
7361 ssh->scmac->free_context(ssh->sc_mac_ctx);
7362 if (s->scmac_tobe) {
7363 ssh->scmac = s->scmac_tobe;
7364 ssh->scmac_etm = s->scmac_etm_tobe;
7365 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7368 if (ssh->sc_comp_ctx)
7369 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7370 ssh->sccomp = s->sccomp_tobe;
7371 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7374 * Set IVs on server-to-client keys. Here we use the exchange
7375 * hash from the _first_ key exchange.
7377 if (ssh->sccipher) {
7380 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7381 ssh->sccipher->padded_keybytes);
7382 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7383 smemclr(key, ssh->sccipher->padded_keybytes);
7386 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7387 ssh->sccipher->blksize);
7388 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7389 smemclr(key, ssh->sccipher->blksize);
7395 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7396 ssh->scmac->keylen);
7397 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7398 smemclr(key, ssh->scmac->keylen);
7402 logeventf(ssh, "Initialised %.200s server->client encryption",
7403 ssh->sccipher->text_name);
7405 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7406 ssh->scmac->text_name,
7407 ssh->scmac_etm ? " (in ETM mode)" : "",
7408 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7409 if (ssh->sccomp->text_name)
7410 logeventf(ssh, "Initialised %s decompression",
7411 ssh->sccomp->text_name);
7414 * Free shared secret.
7419 * Key exchange is over. Loop straight back round if we have a
7420 * deferred rekey reason.
7422 if (ssh->deferred_rekey_reason) {
7423 logevent(ssh->deferred_rekey_reason);
7425 ssh->deferred_rekey_reason = NULL;
7426 goto begin_key_exchange;
7430 * Otherwise, schedule a timer for our next rekey.
7432 ssh->kex_in_progress = FALSE;
7433 ssh->last_rekey = GETTICKCOUNT();
7434 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7435 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7439 * Now we're encrypting. Begin returning 1 to the protocol main
7440 * function so that other things can run on top of the
7441 * transport. If we ever see a KEXINIT, we must go back to the
7444 * We _also_ go back to the start if we see pktin==NULL and
7445 * inlen negative, because this is a special signal meaning
7446 * `initiate client-driven rekey', and `in' contains a message
7447 * giving the reason for the rekey.
7449 * inlen==-1 means always initiate a rekey;
7450 * inlen==-2 means that userauth has completed successfully and
7451 * we should consider rekeying (for delayed compression).
7453 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7454 (!pktin && inlen < 0))) {
7456 if (!ssh->protocol_initial_phase_done) {
7457 ssh->protocol_initial_phase_done = TRUE;
7459 * Allow authconn to initialise itself.
7461 do_ssh2_authconn(ssh, NULL, 0, NULL);
7466 logevent("Server initiated key re-exchange");
7470 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7471 * delayed compression, if it's available.
7473 * draft-miller-secsh-compression-delayed-00 says that you
7474 * negotiate delayed compression in the first key exchange, and
7475 * both sides start compressing when the server has sent
7476 * USERAUTH_SUCCESS. This has a race condition -- the server
7477 * can't know when the client has seen it, and thus which incoming
7478 * packets it should treat as compressed.
7480 * Instead, we do the initial key exchange without offering the
7481 * delayed methods, but note if the server offers them; when we
7482 * get here, if a delayed method was available that was higher
7483 * on our list than what we got, we initiate a rekey in which we
7484 * _do_ list the delayed methods (and hopefully get it as a
7485 * result). Subsequent rekeys will do the same.
7487 assert(!s->userauth_succeeded); /* should only happen once */
7488 s->userauth_succeeded = TRUE;
7489 if (!s->pending_compression)
7490 /* Can't see any point rekeying. */
7491 goto wait_for_rekey; /* this is utterly horrid */
7492 /* else fall through to rekey... */
7493 s->pending_compression = FALSE;
7496 * Now we've decided to rekey.
7498 * Special case: if the server bug is set that doesn't
7499 * allow rekeying, we give a different log message and
7500 * continue waiting. (If such a server _initiates_ a rekey,
7501 * we process it anyway!)
7503 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7504 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7506 /* Reset the counters, so that at least this message doesn't
7507 * hit the event log _too_ often. */
7508 ssh->outgoing_data_size = 0;
7509 ssh->incoming_data_size = 0;
7510 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7512 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7515 goto wait_for_rekey; /* this is still utterly horrid */
7517 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7520 goto begin_key_exchange;
7526 * Add data to an SSH-2 channel output buffer.
7528 static void ssh2_add_channel_data(struct ssh_channel *c, const char *buf,
7531 bufchain_add(&c->v.v2.outbuffer, buf, len);
7535 * Attempt to send data on an SSH-2 channel.
7537 static int ssh2_try_send(struct ssh_channel *c)
7540 struct Packet *pktout;
7543 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7546 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7547 if ((unsigned)len > c->v.v2.remwindow)
7548 len = c->v.v2.remwindow;
7549 if ((unsigned)len > c->v.v2.remmaxpkt)
7550 len = c->v.v2.remmaxpkt;
7551 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7552 ssh2_pkt_adduint32(pktout, c->remoteid);
7553 ssh2_pkt_addstring_start(pktout);
7554 ssh2_pkt_addstring_data(pktout, data, len);
7555 ssh2_pkt_send(ssh, pktout);
7556 bufchain_consume(&c->v.v2.outbuffer, len);
7557 c->v.v2.remwindow -= len;
7561 * After having sent as much data as we can, return the amount
7564 ret = bufchain_size(&c->v.v2.outbuffer);
7567 * And if there's no data pending but we need to send an EOF, send
7570 if (!ret && c->pending_eof)
7571 ssh_channel_try_eof(c);
7576 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7579 if (c->closes & CLOSES_SENT_EOF)
7580 return; /* don't send on channels we've EOFed */
7581 bufsize = ssh2_try_send(c);
7584 case CHAN_MAINSESSION:
7585 /* stdin need not receive an unthrottle
7586 * notification since it will be polled */
7589 x11_unthrottle(c->u.x11.xconn);
7592 /* agent sockets are request/response and need no
7593 * buffer management */
7596 pfd_unthrottle(c->u.pfd.pf);
7602 static int ssh_is_simple(Ssh ssh)
7605 * We use the 'simple' variant of the SSH protocol if we're asked
7606 * to, except not if we're also doing connection-sharing (either
7607 * tunnelling our packets over an upstream or expecting to be
7608 * tunnelled over ourselves), since then the assumption that we
7609 * have only one channel to worry about is not true after all.
7611 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7612 !ssh->bare_connection && !ssh->connshare);
7616 * Set up most of a new ssh_channel for SSH-2.
7618 static void ssh2_channel_init(struct ssh_channel *c)
7621 c->localid = alloc_channel_id(ssh);
7623 c->pending_eof = FALSE;
7624 c->throttling_conn = FALSE;
7625 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7626 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7627 c->v.v2.chanreq_head = NULL;
7628 c->v.v2.throttle_state = UNTHROTTLED;
7629 bufchain_init(&c->v.v2.outbuffer);
7633 * Construct the common parts of a CHANNEL_OPEN.
7635 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7638 struct Packet *pktout;
7640 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7641 ssh2_pkt_addstring(pktout, type);
7642 ssh2_pkt_adduint32(pktout, c->localid);
7643 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7644 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7649 * CHANNEL_FAILURE doesn't come with any indication of what message
7650 * caused it, so we have to keep track of the outstanding
7651 * CHANNEL_REQUESTs ourselves.
7653 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7654 cchandler_fn_t handler, void *ctx)
7656 struct outstanding_channel_request *ocr =
7657 snew(struct outstanding_channel_request);
7659 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7660 ocr->handler = handler;
7663 if (!c->v.v2.chanreq_head)
7664 c->v.v2.chanreq_head = ocr;
7666 c->v.v2.chanreq_tail->next = ocr;
7667 c->v.v2.chanreq_tail = ocr;
7671 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7672 * NULL then a reply will be requested and the handler will be called
7673 * when it arrives. The returned packet is ready to have any
7674 * request-specific data added and be sent. Note that if a handler is
7675 * provided, it's essential that the request actually be sent.
7677 * The handler will usually be passed the response packet in pktin. If
7678 * pktin is NULL, this means that no reply will ever be forthcoming
7679 * (e.g. because the entire connection is being destroyed, or because
7680 * the server initiated channel closure before we saw the response)
7681 * and the handler should free any storage it's holding.
7683 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7685 cchandler_fn_t handler, void *ctx)
7687 struct Packet *pktout;
7689 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7690 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7691 ssh2_pkt_adduint32(pktout, c->remoteid);
7692 ssh2_pkt_addstring(pktout, type);
7693 ssh2_pkt_addbool(pktout, handler != NULL);
7694 if (handler != NULL)
7695 ssh2_queue_chanreq_handler(c, handler, ctx);
7700 * Potentially enlarge the window on an SSH-2 channel.
7702 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7704 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7709 * Never send WINDOW_ADJUST for a channel that the remote side has
7710 * already sent EOF on; there's no point, since it won't be
7711 * sending any more data anyway. Ditto if _we've_ already sent
7714 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7718 * Also, never widen the window for an X11 channel when we're
7719 * still waiting to see its initial auth and may yet hand it off
7722 if (c->type == CHAN_X11 && c->u.x11.initial)
7726 * If the remote end has a habit of ignoring maxpkt, limit the
7727 * window so that it has no choice (assuming it doesn't ignore the
7730 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7731 newwin = OUR_V2_MAXPKT;
7734 * Only send a WINDOW_ADJUST if there's significantly more window
7735 * available than the other end thinks there is. This saves us
7736 * sending a WINDOW_ADJUST for every character in a shell session.
7738 * "Significant" is arbitrarily defined as half the window size.
7740 if (newwin / 2 >= c->v.v2.locwindow) {
7741 struct Packet *pktout;
7745 * In order to keep track of how much window the client
7746 * actually has available, we'd like it to acknowledge each
7747 * WINDOW_ADJUST. We can't do that directly, so we accompany
7748 * it with a CHANNEL_REQUEST that has to be acknowledged.
7750 * This is only necessary if we're opening the window wide.
7751 * If we're not, then throughput is being constrained by
7752 * something other than the maximum window size anyway.
7754 if (newwin == c->v.v2.locmaxwin &&
7755 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7756 up = snew(unsigned);
7757 *up = newwin - c->v.v2.locwindow;
7758 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7759 ssh2_handle_winadj_response, up);
7760 ssh2_pkt_send(ssh, pktout);
7762 if (c->v.v2.throttle_state != UNTHROTTLED)
7763 c->v.v2.throttle_state = UNTHROTTLING;
7765 /* Pretend the WINDOW_ADJUST was acked immediately. */
7766 c->v.v2.remlocwin = newwin;
7767 c->v.v2.throttle_state = THROTTLED;
7769 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7770 ssh2_pkt_adduint32(pktout, c->remoteid);
7771 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7772 ssh2_pkt_send(ssh, pktout);
7773 c->v.v2.locwindow = newwin;
7778 * Find the channel associated with a message. If there's no channel,
7779 * or it's not properly open, make a noise about it and return NULL.
7781 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7783 unsigned localid = ssh_pkt_getuint32(pktin);
7784 struct ssh_channel *c;
7786 c = find234(ssh->channels, &localid, ssh_channelfind);
7788 (c->type != CHAN_SHARING && c->halfopen &&
7789 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7790 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7791 char *buf = dupprintf("Received %s for %s channel %u",
7792 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7794 c ? "half-open" : "nonexistent", localid);
7795 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7802 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7803 struct Packet *pktin, void *ctx)
7805 unsigned *sizep = ctx;
7808 * Winadj responses should always be failures. However, at least
7809 * one server ("boks_sshd") is known to return SUCCESS for channel
7810 * requests it's never heard of, such as "winadj@putty". Raised
7811 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7812 * life, we don't worry about what kind of response we got.
7815 c->v.v2.remlocwin += *sizep;
7818 * winadj messages are only sent when the window is fully open, so
7819 * if we get an ack of one, we know any pending unthrottle is
7822 if (c->v.v2.throttle_state == UNTHROTTLING)
7823 c->v.v2.throttle_state = UNTHROTTLED;
7826 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
7828 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
7829 struct outstanding_channel_request *ocr;
7832 if (c->type == CHAN_SHARING) {
7833 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7834 pktin->body, pktin->length);
7837 ocr = c->v.v2.chanreq_head;
7839 ssh2_msg_unexpected(ssh, pktin);
7842 ocr->handler(c, pktin, ocr->ctx);
7843 c->v.v2.chanreq_head = ocr->next;
7846 * We may now initiate channel-closing procedures, if that
7847 * CHANNEL_REQUEST was the last thing outstanding before we send
7850 ssh2_channel_check_close(c);
7853 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
7855 struct ssh_channel *c;
7856 c = ssh2_channel_msg(ssh, pktin);
7859 if (c->type == CHAN_SHARING) {
7860 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7861 pktin->body, pktin->length);
7864 if (!(c->closes & CLOSES_SENT_EOF)) {
7865 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
7866 ssh2_try_send_and_unthrottle(ssh, c);
7870 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
7874 struct ssh_channel *c;
7875 c = ssh2_channel_msg(ssh, pktin);
7878 if (c->type == CHAN_SHARING) {
7879 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7880 pktin->body, pktin->length);
7883 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
7884 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
7885 return; /* extended but not stderr */
7886 ssh_pkt_getstring(pktin, &data, &length);
7889 c->v.v2.locwindow -= length;
7890 c->v.v2.remlocwin -= length;
7892 case CHAN_MAINSESSION:
7894 from_backend(ssh->frontend, pktin->type ==
7895 SSH2_MSG_CHANNEL_EXTENDED_DATA,
7899 bufsize = x11_send(c->u.x11.xconn, data, length);
7902 bufsize = pfd_send(c->u.pfd.pf, data, length);
7905 while (length > 0) {
7906 if (c->u.a.lensofar < 4) {
7907 unsigned int l = min(4 - c->u.a.lensofar,
7909 memcpy(c->u.a.msglen + c->u.a.lensofar,
7913 c->u.a.lensofar += l;
7915 if (c->u.a.lensofar == 4) {
7917 4 + GET_32BIT(c->u.a.msglen);
7918 c->u.a.message = snewn(c->u.a.totallen,
7920 memcpy(c->u.a.message, c->u.a.msglen, 4);
7922 if (c->u.a.lensofar >= 4 && length > 0) {
7924 min(c->u.a.totallen - c->u.a.lensofar,
7926 memcpy(c->u.a.message + c->u.a.lensofar,
7930 c->u.a.lensofar += l;
7932 if (c->u.a.lensofar == c->u.a.totallen) {
7935 c->u.a.outstanding_requests++;
7936 if (agent_query(c->u.a.message,
7939 ssh_agentf_callback, c))
7940 ssh_agentf_callback(c, reply, replylen);
7941 sfree(c->u.a.message);
7942 c->u.a.message = NULL;
7943 c->u.a.lensofar = 0;
7950 * If it looks like the remote end hit the end of its window,
7951 * and we didn't want it to do that, think about using a
7954 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
7955 c->v.v2.locmaxwin < 0x40000000)
7956 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
7958 * If we are not buffering too much data,
7959 * enlarge the window again at the remote side.
7960 * If we are buffering too much, we may still
7961 * need to adjust the window if the server's
7964 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
7965 c->v.v2.locmaxwin - bufsize : 0);
7967 * If we're either buffering way too much data, or if we're
7968 * buffering anything at all and we're in "simple" mode,
7969 * throttle the whole channel.
7971 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
7972 && !c->throttling_conn) {
7973 c->throttling_conn = 1;
7974 ssh_throttle_conn(ssh, +1);
7979 static void ssh_check_termination(Ssh ssh)
7981 if (ssh->version == 2 &&
7982 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
7983 (ssh->channels && count234(ssh->channels) == 0) &&
7984 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
7986 * We used to send SSH_MSG_DISCONNECT here, because I'd
7987 * believed that _every_ conforming SSH-2 connection had to
7988 * end with a disconnect being sent by at least one side;
7989 * apparently I was wrong and it's perfectly OK to
7990 * unceremoniously slam the connection shut when you're done,
7991 * and indeed OpenSSH feels this is more polite than sending a
7992 * DISCONNECT. So now we don't.
7994 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
7998 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
7999 const char *peerinfo)
8002 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
8005 logeventf(ssh, "Connection sharing downstream #%u connected", id);
8008 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
8010 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
8011 ssh_check_termination(ssh);
8014 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
8019 va_start(ap, logfmt);
8020 buf = dupvprintf(logfmt, ap);
8023 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
8025 logeventf(ssh, "Connection sharing: %s", buf);
8029 static void ssh_channel_destroy(struct ssh_channel *c)
8034 case CHAN_MAINSESSION:
8035 ssh->mainchan = NULL;
8036 update_specials_menu(ssh->frontend);
8039 if (c->u.x11.xconn != NULL)
8040 x11_close(c->u.x11.xconn);
8041 logevent("Forwarded X11 connection terminated");
8044 sfree(c->u.a.message);
8047 if (c->u.pfd.pf != NULL)
8048 pfd_close(c->u.pfd.pf);
8049 logevent("Forwarded port closed");
8053 del234(ssh->channels, c);
8054 if (ssh->version == 2) {
8055 bufchain_clear(&c->v.v2.outbuffer);
8056 assert(c->v.v2.chanreq_head == NULL);
8061 * If that was the last channel left open, we might need to
8064 ssh_check_termination(ssh);
8067 static void ssh2_channel_check_close(struct ssh_channel *c)
8070 struct Packet *pktout;
8074 * If we've sent out our own CHANNEL_OPEN but not yet seen
8075 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8076 * it's too early to be sending close messages of any kind.
8081 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8082 c->type == CHAN_ZOMBIE) &&
8083 !c->v.v2.chanreq_head &&
8084 !(c->closes & CLOSES_SENT_CLOSE)) {
8086 * We have both sent and received EOF (or the channel is a
8087 * zombie), and we have no outstanding channel requests, which
8088 * means the channel is in final wind-up. But we haven't sent
8089 * CLOSE, so let's do so now.
8091 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8092 ssh2_pkt_adduint32(pktout, c->remoteid);
8093 ssh2_pkt_send(ssh, pktout);
8094 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8097 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8098 assert(c->v.v2.chanreq_head == NULL);
8100 * We have both sent and received CLOSE, which means we're
8101 * completely done with the channel.
8103 ssh_channel_destroy(c);
8107 static void ssh2_channel_got_eof(struct ssh_channel *c)
8109 if (c->closes & CLOSES_RCVD_EOF)
8110 return; /* already seen EOF */
8111 c->closes |= CLOSES_RCVD_EOF;
8113 if (c->type == CHAN_X11) {
8114 x11_send_eof(c->u.x11.xconn);
8115 } else if (c->type == CHAN_AGENT) {
8116 if (c->u.a.outstanding_requests == 0) {
8117 /* Manufacture an outgoing EOF in response to the incoming one. */
8118 sshfwd_write_eof(c);
8120 } else if (c->type == CHAN_SOCKDATA) {
8121 pfd_send_eof(c->u.pfd.pf);
8122 } else if (c->type == CHAN_MAINSESSION) {
8125 if (!ssh->sent_console_eof &&
8126 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8128 * Either from_backend_eof told us that the front end
8129 * wants us to close the outgoing side of the connection
8130 * as soon as we see EOF from the far end, or else we've
8131 * unilaterally decided to do that because we've allocated
8132 * a remote pty and hence EOF isn't a particularly
8133 * meaningful concept.
8135 sshfwd_write_eof(c);
8137 ssh->sent_console_eof = TRUE;
8140 ssh2_channel_check_close(c);
8143 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8145 struct ssh_channel *c;
8147 c = ssh2_channel_msg(ssh, pktin);
8150 if (c->type == CHAN_SHARING) {
8151 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8152 pktin->body, pktin->length);
8155 ssh2_channel_got_eof(c);
8158 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8160 struct ssh_channel *c;
8162 c = ssh2_channel_msg(ssh, pktin);
8165 if (c->type == CHAN_SHARING) {
8166 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8167 pktin->body, pktin->length);
8172 * When we receive CLOSE on a channel, we assume it comes with an
8173 * implied EOF if we haven't seen EOF yet.
8175 ssh2_channel_got_eof(c);
8177 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8179 * It also means we stop expecting to see replies to any
8180 * outstanding channel requests, so clean those up too.
8181 * (ssh_chanreq_init will enforce by assertion that we don't
8182 * subsequently put anything back on this list.)
8184 while (c->v.v2.chanreq_head) {
8185 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8186 ocr->handler(c, NULL, ocr->ctx);
8187 c->v.v2.chanreq_head = ocr->next;
8193 * And we also send an outgoing EOF, if we haven't already, on the
8194 * assumption that CLOSE is a pretty forceful announcement that
8195 * the remote side is doing away with the entire channel. (If it
8196 * had wanted to send us EOF and continue receiving data from us,
8197 * it would have just sent CHANNEL_EOF.)
8199 if (!(c->closes & CLOSES_SENT_EOF)) {
8201 * Make sure we don't read any more from whatever our local
8202 * data source is for this channel.
8205 case CHAN_MAINSESSION:
8206 ssh->send_ok = 0; /* stop trying to read from stdin */
8209 x11_override_throttle(c->u.x11.xconn, 1);
8212 pfd_override_throttle(c->u.pfd.pf, 1);
8217 * Abandon any buffered data we still wanted to send to this
8218 * channel. Receiving a CHANNEL_CLOSE is an indication that
8219 * the server really wants to get on and _destroy_ this
8220 * channel, and it isn't going to send us any further
8221 * WINDOW_ADJUSTs to permit us to send pending stuff.
8223 bufchain_clear(&c->v.v2.outbuffer);
8226 * Send outgoing EOF.
8228 sshfwd_write_eof(c);
8232 * Now process the actual close.
8234 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8235 c->closes |= CLOSES_RCVD_CLOSE;
8236 ssh2_channel_check_close(c);
8240 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8242 struct ssh_channel *c;
8244 c = ssh2_channel_msg(ssh, pktin);
8247 if (c->type == CHAN_SHARING) {
8248 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8249 pktin->body, pktin->length);
8252 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8253 c->remoteid = ssh_pkt_getuint32(pktin);
8254 c->halfopen = FALSE;
8255 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8256 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8258 if (c->type == CHAN_SOCKDATA_DORMANT) {
8259 c->type = CHAN_SOCKDATA;
8261 pfd_confirm(c->u.pfd.pf);
8262 } else if (c->type == CHAN_ZOMBIE) {
8264 * This case can occur if a local socket error occurred
8265 * between us sending out CHANNEL_OPEN and receiving
8266 * OPEN_CONFIRMATION. In this case, all we can do is
8267 * immediately initiate close proceedings now that we know the
8268 * server's id to put in the close message.
8270 ssh2_channel_check_close(c);
8273 * We never expect to receive OPEN_CONFIRMATION for any
8274 * *other* channel type (since only local-to-remote port
8275 * forwardings cause us to send CHANNEL_OPEN after the main
8276 * channel is live - all other auxiliary channel types are
8277 * initiated from the server end). It's safe to enforce this
8278 * by assertion rather than by ssh_disconnect, because the
8279 * real point is that we never constructed a half-open channel
8280 * structure in the first place with any type other than the
8283 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8287 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8290 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8292 static const char *const reasons[] = {
8293 "<unknown reason code>",
8294 "Administratively prohibited",
8296 "Unknown channel type",
8297 "Resource shortage",
8299 unsigned reason_code;
8300 char *reason_string;
8302 struct ssh_channel *c;
8304 c = ssh2_channel_msg(ssh, pktin);
8307 if (c->type == CHAN_SHARING) {
8308 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8309 pktin->body, pktin->length);
8312 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8314 if (c->type == CHAN_SOCKDATA_DORMANT) {
8315 reason_code = ssh_pkt_getuint32(pktin);
8316 if (reason_code >= lenof(reasons))
8317 reason_code = 0; /* ensure reasons[reason_code] in range */
8318 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8319 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8320 reasons[reason_code], reason_length,
8321 NULLTOEMPTY(reason_string));
8323 pfd_close(c->u.pfd.pf);
8324 } else if (c->type == CHAN_ZOMBIE) {
8326 * This case can occur if a local socket error occurred
8327 * between us sending out CHANNEL_OPEN and receiving
8328 * OPEN_FAILURE. In this case, we need do nothing except allow
8329 * the code below to throw the half-open channel away.
8333 * We never expect to receive OPEN_FAILURE for any *other*
8334 * channel type (since only local-to-remote port forwardings
8335 * cause us to send CHANNEL_OPEN after the main channel is
8336 * live - all other auxiliary channel types are initiated from
8337 * the server end). It's safe to enforce this by assertion
8338 * rather than by ssh_disconnect, because the real point is
8339 * that we never constructed a half-open channel structure in
8340 * the first place with any type other than the above.
8342 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8345 del234(ssh->channels, c);
8349 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8352 int typelen, want_reply;
8353 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8354 struct ssh_channel *c;
8355 struct Packet *pktout;
8357 c = ssh2_channel_msg(ssh, pktin);
8360 if (c->type == CHAN_SHARING) {
8361 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8362 pktin->body, pktin->length);
8365 ssh_pkt_getstring(pktin, &type, &typelen);
8366 want_reply = ssh2_pkt_getbool(pktin);
8368 if (c->closes & CLOSES_SENT_CLOSE) {
8370 * We don't reply to channel requests after we've sent
8371 * CHANNEL_CLOSE for the channel, because our reply might
8372 * cross in the network with the other side's CHANNEL_CLOSE
8373 * and arrive after they have wound the channel up completely.
8379 * Having got the channel number, we now look at
8380 * the request type string to see if it's something
8383 if (c == ssh->mainchan) {
8385 * We recognise "exit-status" and "exit-signal" on
8386 * the primary channel.
8388 if (typelen == 11 &&
8389 !memcmp(type, "exit-status", 11)) {
8391 ssh->exitcode = ssh_pkt_getuint32(pktin);
8392 logeventf(ssh, "Server sent command exit status %d",
8394 reply = SSH2_MSG_CHANNEL_SUCCESS;
8396 } else if (typelen == 11 &&
8397 !memcmp(type, "exit-signal", 11)) {
8399 int is_plausible = TRUE, is_int = FALSE;
8400 char *fmt_sig = NULL, *fmt_msg = NULL;
8402 int msglen = 0, core = FALSE;
8403 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8404 * provide an `int' for the signal, despite its
8405 * having been a `string' in the drafts of RFC 4254 since at
8406 * least 2001. (Fixed in session.c 1.147.) Try to
8407 * infer which we can safely parse it as. */
8409 unsigned char *p = pktin->body +
8411 long len = pktin->length - pktin->savedpos;
8412 unsigned long num = GET_32BIT(p); /* what is it? */
8413 /* If it's 0, it hardly matters; assume string */
8417 int maybe_int = FALSE, maybe_str = FALSE;
8418 #define CHECK_HYPOTHESIS(offset, result) \
8421 int q = toint(offset); \
8422 if (q >= 0 && q+4 <= len) { \
8423 q = toint(q + 4 + GET_32BIT(p+q)); \
8424 if (q >= 0 && q+4 <= len && \
8425 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8430 CHECK_HYPOTHESIS(4+1, maybe_int);
8431 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8432 #undef CHECK_HYPOTHESIS
8433 if (maybe_int && !maybe_str)
8435 else if (!maybe_int && maybe_str)
8438 /* Crikey. Either or neither. Panic. */
8439 is_plausible = FALSE;
8442 ssh->exitcode = 128; /* means `unknown signal' */
8445 /* Old non-standard OpenSSH. */
8446 int signum = ssh_pkt_getuint32(pktin);
8447 fmt_sig = dupprintf(" %d", signum);
8448 ssh->exitcode = 128 + signum;
8450 /* As per RFC 4254. */
8453 ssh_pkt_getstring(pktin, &sig, &siglen);
8454 /* Signal name isn't supposed to be blank, but
8455 * let's cope gracefully if it is. */
8457 fmt_sig = dupprintf(" \"%.*s\"",
8462 * Really hideous method of translating the
8463 * signal description back into a locally
8464 * meaningful number.
8469 #define TRANSLATE_SIGNAL(s) \
8470 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8471 ssh->exitcode = 128 + SIG ## s
8473 TRANSLATE_SIGNAL(ABRT);
8476 TRANSLATE_SIGNAL(ALRM);
8479 TRANSLATE_SIGNAL(FPE);
8482 TRANSLATE_SIGNAL(HUP);
8485 TRANSLATE_SIGNAL(ILL);
8488 TRANSLATE_SIGNAL(INT);
8491 TRANSLATE_SIGNAL(KILL);
8494 TRANSLATE_SIGNAL(PIPE);
8497 TRANSLATE_SIGNAL(QUIT);
8500 TRANSLATE_SIGNAL(SEGV);
8503 TRANSLATE_SIGNAL(TERM);
8506 TRANSLATE_SIGNAL(USR1);
8509 TRANSLATE_SIGNAL(USR2);
8511 #undef TRANSLATE_SIGNAL
8513 ssh->exitcode = 128;
8515 core = ssh2_pkt_getbool(pktin);
8516 ssh_pkt_getstring(pktin, &msg, &msglen);
8518 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8520 /* ignore lang tag */
8521 } /* else don't attempt to parse */
8522 logeventf(ssh, "Server exited on signal%s%s%s",
8523 fmt_sig ? fmt_sig : "",
8524 core ? " (core dumped)" : "",
8525 fmt_msg ? fmt_msg : "");
8528 reply = SSH2_MSG_CHANNEL_SUCCESS;
8533 * This is a channel request we don't know
8534 * about, so we now either ignore the request
8535 * or respond with CHANNEL_FAILURE, depending
8538 reply = SSH2_MSG_CHANNEL_FAILURE;
8541 pktout = ssh2_pkt_init(reply);
8542 ssh2_pkt_adduint32(pktout, c->remoteid);
8543 ssh2_pkt_send(ssh, pktout);
8547 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8550 int typelen, want_reply;
8551 struct Packet *pktout;
8553 ssh_pkt_getstring(pktin, &type, &typelen);
8554 want_reply = ssh2_pkt_getbool(pktin);
8557 * We currently don't support any global requests
8558 * at all, so we either ignore the request or
8559 * respond with REQUEST_FAILURE, depending on
8563 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8564 ssh2_pkt_send(ssh, pktout);
8568 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8572 struct X11FakeAuth *auth;
8575 * Make up a new set of fake X11 auth data, and add it to the tree
8576 * of currently valid ones with an indication of the sharing
8577 * context that it's relevant to.
8579 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8580 auth->share_cs = share_cs;
8581 auth->share_chan = share_chan;
8586 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8588 del234(ssh->x11authtree, auth);
8589 x11_free_fake_auth(auth);
8592 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8599 const char *error = NULL;
8600 struct ssh_channel *c;
8601 unsigned remid, winsize, pktsize;
8602 unsigned our_winsize_override = 0;
8603 struct Packet *pktout;
8605 ssh_pkt_getstring(pktin, &type, &typelen);
8606 c = snew(struct ssh_channel);
8609 remid = ssh_pkt_getuint32(pktin);
8610 winsize = ssh_pkt_getuint32(pktin);
8611 pktsize = ssh_pkt_getuint32(pktin);
8613 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8616 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8617 addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
8618 peerport = ssh_pkt_getuint32(pktin);
8620 logeventf(ssh, "Received X11 connect request from %s:%d",
8623 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8624 error = "X11 forwarding is not enabled";
8626 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8629 c->u.x11.initial = TRUE;
8632 * If we are a connection-sharing upstream, then we should
8633 * initially present a very small window, adequate to take
8634 * the X11 initial authorisation packet but not much more.
8635 * Downstream will then present us a larger window (by
8636 * fiat of the connection-sharing protocol) and we can
8637 * guarantee to send a positive-valued WINDOW_ADJUST.
8640 our_winsize_override = 128;
8642 logevent("Opened X11 forward channel");
8646 } else if (typelen == 15 &&
8647 !memcmp(type, "forwarded-tcpip", 15)) {
8648 struct ssh_rportfwd pf, *realpf;
8651 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8652 pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
8653 pf.sport = ssh_pkt_getuint32(pktin);
8654 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8655 peerport = ssh_pkt_getuint32(pktin);
8656 realpf = find234(ssh->rportfwds, &pf, NULL);
8657 logeventf(ssh, "Received remote port %s:%d open request "
8658 "from %.*s:%d", pf.shost, pf.sport,
8659 peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
8662 if (realpf == NULL) {
8663 error = "Remote port is not recognised";
8667 if (realpf->share_ctx) {
8669 * This port forwarding is on behalf of a
8670 * connection-sharing downstream, so abandon our own
8671 * channel-open procedure and just pass the message on
8674 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8675 pktin->body, pktin->length);
8680 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8681 c, ssh->conf, realpf->pfrec->addressfamily);
8682 logeventf(ssh, "Attempting to forward remote port to "
8683 "%s:%d", realpf->dhost, realpf->dport);
8685 logeventf(ssh, "Port open failed: %s", err);
8687 error = "Port open failed";
8689 logevent("Forwarded port opened successfully");
8690 c->type = CHAN_SOCKDATA;
8693 } else if (typelen == 22 &&
8694 !memcmp(type, "auth-agent@openssh.com", 22)) {
8695 if (!ssh->agentfwd_enabled)
8696 error = "Agent forwarding is not enabled";
8698 c->type = CHAN_AGENT; /* identify channel type */
8699 c->u.a.lensofar = 0;
8700 c->u.a.message = NULL;
8701 c->u.a.outstanding_requests = 0;
8704 error = "Unsupported channel type requested";
8707 c->remoteid = remid;
8708 c->halfopen = FALSE;
8710 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8711 ssh2_pkt_adduint32(pktout, c->remoteid);
8712 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8713 ssh2_pkt_addstring(pktout, error);
8714 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8715 ssh2_pkt_send(ssh, pktout);
8716 logeventf(ssh, "Rejected channel open: %s", error);
8719 ssh2_channel_init(c);
8720 c->v.v2.remwindow = winsize;
8721 c->v.v2.remmaxpkt = pktsize;
8722 if (our_winsize_override) {
8723 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8724 our_winsize_override;
8726 add234(ssh->channels, c);
8727 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8728 ssh2_pkt_adduint32(pktout, c->remoteid);
8729 ssh2_pkt_adduint32(pktout, c->localid);
8730 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8731 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8732 ssh2_pkt_send(ssh, pktout);
8736 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8737 void *share_cs, void *share_chan,
8738 const char *peer_addr, int peer_port,
8739 int endian, int protomajor, int protominor,
8740 const void *initial_data, int initial_len)
8743 * This function is called when we've just discovered that an X
8744 * forwarding channel on which we'd been handling the initial auth
8745 * ourselves turns out to be destined for a connection-sharing
8746 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8747 * that we completely stop tracking windows and buffering data and
8748 * just pass more or less unmodified SSH messages back and forth.
8750 c->type = CHAN_SHARING;
8751 c->u.sharing.ctx = share_cs;
8752 share_setup_x11_channel(share_cs, share_chan,
8753 c->localid, c->remoteid, c->v.v2.remwindow,
8754 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8755 peer_addr, peer_port, endian,
8756 protomajor, protominor,
8757 initial_data, initial_len);
8760 void sshfwd_x11_is_local(struct ssh_channel *c)
8763 * This function is called when we've just discovered that an X
8764 * forwarding channel is _not_ destined for a connection-sharing
8765 * downstream but we're going to handle it ourselves. We stop
8766 * presenting a cautiously small window and go into ordinary data
8769 c->u.x11.initial = FALSE;
8770 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8774 * Buffer banner messages for later display at some convenient point,
8775 * if we're going to display them.
8777 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8779 /* Arbitrary limit to prevent unbounded inflation of buffer */
8780 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8781 bufchain_size(&ssh->banner) <= 131072) {
8782 char *banner = NULL;
8784 ssh_pkt_getstring(pktin, &banner, &size);
8786 bufchain_add(&ssh->banner, banner, size);
8790 /* Helper function to deal with sending tty modes for "pty-req" */
8791 static void ssh2_send_ttymode(void *data, char *mode, char *val)
8793 struct Packet *pktout = (struct Packet *)data;
8795 unsigned int arg = 0;
8796 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
8797 if (i == lenof(ssh_ttymodes)) return;
8798 switch (ssh_ttymodes[i].type) {
8800 arg = ssh_tty_parse_specchar(val);
8803 arg = ssh_tty_parse_boolean(val);
8806 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
8807 ssh2_pkt_adduint32(pktout, arg);
8810 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8813 struct ssh2_setup_x11_state {
8817 struct Packet *pktout;
8818 crStateP(ssh2_setup_x11_state, ctx);
8822 logevent("Requesting X11 forwarding");
8823 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8825 ssh2_pkt_addbool(pktout, 0); /* many connections */
8826 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8827 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8828 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8829 ssh2_pkt_send(ssh, pktout);
8831 /* Wait to be called back with either a response packet, or NULL
8832 * meaning clean up and free our data */
8836 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8837 logevent("X11 forwarding enabled");
8838 ssh->X11_fwd_enabled = TRUE;
8840 logevent("X11 forwarding refused");
8846 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8849 struct ssh2_setup_agent_state {
8853 struct Packet *pktout;
8854 crStateP(ssh2_setup_agent_state, ctx);
8858 logevent("Requesting OpenSSH-style agent forwarding");
8859 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8860 ssh2_setup_agent, s);
8861 ssh2_pkt_send(ssh, pktout);
8863 /* Wait to be called back with either a response packet, or NULL
8864 * meaning clean up and free our data */
8868 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8869 logevent("Agent forwarding enabled");
8870 ssh->agentfwd_enabled = TRUE;
8872 logevent("Agent forwarding refused");
8878 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8881 struct ssh2_setup_pty_state {
8885 struct Packet *pktout;
8886 crStateP(ssh2_setup_pty_state, ctx);
8890 /* Unpick the terminal-speed string. */
8891 /* XXX perhaps we should allow no speeds to be sent. */
8892 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8893 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8894 /* Build the pty request. */
8895 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
8897 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
8898 ssh2_pkt_adduint32(pktout, ssh->term_width);
8899 ssh2_pkt_adduint32(pktout, ssh->term_height);
8900 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
8901 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
8902 ssh2_pkt_addstring_start(pktout);
8903 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
8904 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
8905 ssh2_pkt_adduint32(pktout, ssh->ispeed);
8906 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
8907 ssh2_pkt_adduint32(pktout, ssh->ospeed);
8908 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
8909 ssh2_pkt_send(ssh, pktout);
8910 ssh->state = SSH_STATE_INTERMED;
8912 /* Wait to be called back with either a response packet, or NULL
8913 * meaning clean up and free our data */
8917 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8918 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
8919 ssh->ospeed, ssh->ispeed);
8920 ssh->got_pty = TRUE;
8922 c_write_str(ssh, "Server refused to allocate pty\r\n");
8923 ssh->editing = ssh->echoing = 1;
8930 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
8933 struct ssh2_setup_env_state {
8935 int num_env, env_left, env_ok;
8938 struct Packet *pktout;
8939 crStateP(ssh2_setup_env_state, ctx);
8944 * Send environment variables.
8946 * Simplest thing here is to send all the requests at once, and
8947 * then wait for a whole bunch of successes or failures.
8953 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
8955 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
8956 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
8957 ssh2_pkt_addstring(pktout, key);
8958 ssh2_pkt_addstring(pktout, val);
8959 ssh2_pkt_send(ssh, pktout);
8964 logeventf(ssh, "Sent %d environment variables", s->num_env);
8969 s->env_left = s->num_env;
8971 while (s->env_left > 0) {
8972 /* Wait to be called back with either a response packet,
8973 * or NULL meaning clean up and free our data */
8975 if (!pktin) goto out;
8976 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
8981 if (s->env_ok == s->num_env) {
8982 logevent("All environment variables successfully set");
8983 } else if (s->env_ok == 0) {
8984 logevent("All environment variables refused");
8985 c_write_str(ssh, "Server refused to set environment variables\r\n");
8987 logeventf(ssh, "%d environment variables refused",
8988 s->num_env - s->env_ok);
8989 c_write_str(ssh, "Server refused to set all environment variables\r\n");
8997 * Handle the SSH-2 userauth and connection layers.
8999 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
9001 do_ssh2_authconn(ssh, NULL, 0, pktin);
9004 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
9008 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
9011 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
9012 struct Packet *pktin)
9014 struct do_ssh2_authconn_state {
9018 AUTH_TYPE_PUBLICKEY,
9019 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
9020 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
9022 AUTH_TYPE_GSSAPI, /* always QUIET */
9023 AUTH_TYPE_KEYBOARD_INTERACTIVE,
9024 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
9026 int done_service_req;
9027 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
9028 int tried_pubkey_config, done_agent;
9033 int kbd_inter_refused;
9034 int we_are_in, userauth_success;
9035 prompts_t *cur_prompt;
9040 void *publickey_blob;
9041 int publickey_bloblen;
9042 int privatekey_available, privatekey_encrypted;
9043 char *publickey_algorithm;
9044 char *publickey_comment;
9045 unsigned char agent_request[5], *agent_response, *agentp;
9046 int agent_responselen;
9047 unsigned char *pkblob_in_agent;
9049 char *pkblob, *alg, *commentp;
9050 int pklen, alglen, commentlen;
9051 int siglen, retlen, len;
9052 char *q, *agentreq, *ret;
9054 struct Packet *pktout;
9057 struct ssh_gss_library *gsslib;
9058 Ssh_gss_ctx gss_ctx;
9059 Ssh_gss_buf gss_buf;
9060 Ssh_gss_buf gss_rcvtok, gss_sndtok;
9061 Ssh_gss_name gss_srv_name;
9062 Ssh_gss_stat gss_stat;
9065 crState(do_ssh2_authconn_state);
9069 /* Register as a handler for all the messages this coroutine handles. */
9070 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9071 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9072 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9073 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9074 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9075 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9076 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9077 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9078 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9079 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9080 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9081 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9082 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9083 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9084 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9085 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9086 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9087 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9088 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9089 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9091 s->done_service_req = FALSE;
9092 s->we_are_in = s->userauth_success = FALSE;
9093 s->agent_response = NULL;
9095 s->tried_gssapi = FALSE;
9098 if (!ssh->bare_connection) {
9099 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9101 * Request userauth protocol, and await a response to it.
9103 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9104 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9105 ssh2_pkt_send(ssh, s->pktout);
9106 crWaitUntilV(pktin);
9107 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9108 s->done_service_req = TRUE;
9110 if (!s->done_service_req) {
9112 * Request connection protocol directly, without authentication.
9114 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9115 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9116 ssh2_pkt_send(ssh, s->pktout);
9117 crWaitUntilV(pktin);
9118 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9119 s->we_are_in = TRUE; /* no auth required */
9121 bombout(("Server refused service request"));
9126 s->we_are_in = TRUE;
9129 /* Arrange to be able to deal with any BANNERs that come in.
9130 * (We do this now as packets may come in during the next bit.) */
9131 bufchain_init(&ssh->banner);
9132 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9133 ssh2_msg_userauth_banner;
9136 * Misc one-time setup for authentication.
9138 s->publickey_blob = NULL;
9139 if (!s->we_are_in) {
9142 * Load the public half of any configured public key file
9145 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9146 if (!filename_is_null(s->keyfile)) {
9148 logeventf(ssh, "Reading key file \"%.150s\"",
9149 filename_to_str(s->keyfile));
9150 keytype = key_type(s->keyfile);
9151 if (keytype == SSH_KEYTYPE_SSH2 ||
9152 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9153 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9156 ssh2_userkey_loadpub(s->keyfile,
9157 &s->publickey_algorithm,
9158 &s->publickey_bloblen,
9159 &s->publickey_comment, &error);
9160 if (s->publickey_blob) {
9161 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9162 if (!s->privatekey_available)
9163 logeventf(ssh, "Key file contains public key only");
9164 s->privatekey_encrypted =
9165 ssh2_userkey_encrypted(s->keyfile, NULL);
9168 logeventf(ssh, "Unable to load key (%s)",
9170 msgbuf = dupprintf("Unable to load key file "
9171 "\"%.150s\" (%s)\r\n",
9172 filename_to_str(s->keyfile),
9174 c_write_str(ssh, msgbuf);
9179 logeventf(ssh, "Unable to use this key file (%s)",
9180 key_type_to_str(keytype));
9181 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9183 filename_to_str(s->keyfile),
9184 key_type_to_str(keytype));
9185 c_write_str(ssh, msgbuf);
9187 s->publickey_blob = NULL;
9192 * Find out about any keys Pageant has (but if there's a
9193 * public key configured, filter out all others).
9196 s->agent_response = NULL;
9197 s->pkblob_in_agent = NULL;
9198 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9202 logevent("Pageant is running. Requesting keys.");
9204 /* Request the keys held by the agent. */
9205 PUT_32BIT(s->agent_request, 1);
9206 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9207 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9208 ssh_agent_callback, ssh)) {
9212 bombout(("Unexpected data from server while"
9213 " waiting for agent response"));
9216 } while (pktin || inlen > 0);
9217 r = ssh->agent_response;
9218 s->agent_responselen = ssh->agent_response_len;
9220 s->agent_response = (unsigned char *) r;
9221 if (s->agent_response && s->agent_responselen >= 5 &&
9222 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9225 p = s->agent_response + 5;
9226 s->nkeys = toint(GET_32BIT(p));
9229 * Vet the Pageant response to ensure that the key
9230 * count and blob lengths make sense.
9233 logeventf(ssh, "Pageant response contained a negative"
9234 " key count %d", s->nkeys);
9236 goto done_agent_query;
9238 unsigned char *q = p + 4;
9239 int lenleft = s->agent_responselen - 5 - 4;
9241 for (keyi = 0; keyi < s->nkeys; keyi++) {
9242 int bloblen, commentlen;
9244 logeventf(ssh, "Pageant response was truncated");
9246 goto done_agent_query;
9248 bloblen = toint(GET_32BIT(q));
9249 if (bloblen < 0 || bloblen > lenleft) {
9250 logeventf(ssh, "Pageant response was truncated");
9252 goto done_agent_query;
9254 lenleft -= 4 + bloblen;
9256 commentlen = toint(GET_32BIT(q));
9257 if (commentlen < 0 || commentlen > lenleft) {
9258 logeventf(ssh, "Pageant response was truncated");
9260 goto done_agent_query;
9262 lenleft -= 4 + commentlen;
9263 q += 4 + commentlen;
9268 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9269 if (s->publickey_blob) {
9270 /* See if configured key is in agent. */
9271 for (keyi = 0; keyi < s->nkeys; keyi++) {
9272 s->pklen = toint(GET_32BIT(p));
9273 if (s->pklen == s->publickey_bloblen &&
9274 !memcmp(p+4, s->publickey_blob,
9275 s->publickey_bloblen)) {
9276 logeventf(ssh, "Pageant key #%d matches "
9277 "configured key file", keyi);
9279 s->pkblob_in_agent = p;
9283 p += toint(GET_32BIT(p)) + 4; /* comment */
9285 if (!s->pkblob_in_agent) {
9286 logevent("Configured key file not in Pageant");
9291 logevent("Failed to get reply from Pageant");
9299 * We repeat this whole loop, including the username prompt,
9300 * until we manage a successful authentication. If the user
9301 * types the wrong _password_, they can be sent back to the
9302 * beginning to try another username, if this is configured on.
9303 * (If they specify a username in the config, they are never
9304 * asked, even if they do give a wrong password.)
9306 * I think this best serves the needs of
9308 * - the people who have no configuration, no keys, and just
9309 * want to try repeated (username,password) pairs until they
9310 * type both correctly
9312 * - people who have keys and configuration but occasionally
9313 * need to fall back to passwords
9315 * - people with a key held in Pageant, who might not have
9316 * logged in to a particular machine before; so they want to
9317 * type a username, and then _either_ their key will be
9318 * accepted, _or_ they will type a password. If they mistype
9319 * the username they will want to be able to get back and
9322 s->got_username = FALSE;
9323 while (!s->we_are_in) {
9327 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9329 * We got a username last time round this loop, and
9330 * with change_username turned off we don't try to get
9333 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9334 int ret; /* need not be kept over crReturn */
9335 s->cur_prompt = new_prompts(ssh->frontend);
9336 s->cur_prompt->to_server = TRUE;
9337 s->cur_prompt->name = dupstr("SSH login name");
9338 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9339 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9342 crWaitUntilV(!pktin);
9343 ret = get_userpass_input(s->cur_prompt, in, inlen);
9348 * get_userpass_input() failed to get a username.
9351 free_prompts(s->cur_prompt);
9352 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9355 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9356 free_prompts(s->cur_prompt);
9359 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9360 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9361 c_write_str(ssh, stuff);
9365 s->got_username = TRUE;
9368 * Send an authentication request using method "none": (a)
9369 * just in case it succeeds, and (b) so that we know what
9370 * authentication methods we can usefully try next.
9372 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9374 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9375 ssh2_pkt_addstring(s->pktout, ssh->username);
9376 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9377 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9378 ssh2_pkt_send(ssh, s->pktout);
9379 s->type = AUTH_TYPE_NONE;
9381 s->we_are_in = FALSE;
9383 s->tried_pubkey_config = FALSE;
9384 s->kbd_inter_refused = FALSE;
9386 /* Reset agent request state. */
9387 s->done_agent = FALSE;
9388 if (s->agent_response) {
9389 if (s->pkblob_in_agent) {
9390 s->agentp = s->pkblob_in_agent;
9392 s->agentp = s->agent_response + 5 + 4;
9398 char *methods = NULL;
9402 * Wait for the result of the last authentication request.
9405 crWaitUntilV(pktin);
9407 * Now is a convenient point to spew any banner material
9408 * that we've accumulated. (This should ensure that when
9409 * we exit the auth loop, we haven't any left to deal
9413 int size = bufchain_size(&ssh->banner);
9415 * Don't show the banner if we're operating in
9416 * non-verbose non-interactive mode. (It's probably
9417 * a script, which means nobody will read the
9418 * banner _anyway_, and moreover the printing of
9419 * the banner will screw up processing on the
9420 * output of (say) plink.)
9422 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9423 char *banner = snewn(size, char);
9424 bufchain_fetch(&ssh->banner, banner, size);
9425 c_write_untrusted(ssh, banner, size);
9428 bufchain_clear(&ssh->banner);
9430 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9431 logevent("Access granted");
9432 s->we_are_in = s->userauth_success = TRUE;
9436 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9437 bombout(("Strange packet received during authentication: "
9438 "type %d", pktin->type));
9445 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9446 * we can look at the string in it and know what we can
9447 * helpfully try next.
9449 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9450 ssh_pkt_getstring(pktin, &methods, &methlen);
9451 if (!ssh2_pkt_getbool(pktin)) {
9453 * We have received an unequivocal Access
9454 * Denied. This can translate to a variety of
9455 * messages, or no message at all.
9457 * For forms of authentication which are attempted
9458 * implicitly, by which I mean without printing
9459 * anything in the window indicating that we're
9460 * trying them, we should never print 'Access
9463 * If we do print a message saying that we're
9464 * attempting some kind of authentication, it's OK
9465 * to print a followup message saying it failed -
9466 * but the message may sometimes be more specific
9467 * than simply 'Access denied'.
9469 * Additionally, if we'd just tried password
9470 * authentication, we should break out of this
9471 * whole loop so as to go back to the username
9472 * prompt (iff we're configured to allow
9473 * username change attempts).
9475 if (s->type == AUTH_TYPE_NONE) {
9477 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9478 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9479 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9480 c_write_str(ssh, "Server refused our key\r\n");
9481 logevent("Server refused our key");
9482 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9483 /* This _shouldn't_ happen except by a
9484 * protocol bug causing client and server to
9485 * disagree on what is a correct signature. */
9486 c_write_str(ssh, "Server refused public-key signature"
9487 " despite accepting key!\r\n");
9488 logevent("Server refused public-key signature"
9489 " despite accepting key!");
9490 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9491 /* quiet, so no c_write */
9492 logevent("Server refused keyboard-interactive authentication");
9493 } else if (s->type==AUTH_TYPE_GSSAPI) {
9494 /* always quiet, so no c_write */
9495 /* also, the code down in the GSSAPI block has
9496 * already logged this in the Event Log */
9497 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9498 logevent("Keyboard-interactive authentication failed");
9499 c_write_str(ssh, "Access denied\r\n");
9501 assert(s->type == AUTH_TYPE_PASSWORD);
9502 logevent("Password authentication failed");
9503 c_write_str(ssh, "Access denied\r\n");
9505 if (conf_get_int(ssh->conf, CONF_change_username)) {
9506 /* XXX perhaps we should allow
9507 * keyboard-interactive to do this too? */
9508 s->we_are_in = FALSE;
9513 c_write_str(ssh, "Further authentication required\r\n");
9514 logevent("Further authentication required");
9518 in_commasep_string("publickey", methods, methlen);
9520 in_commasep_string("password", methods, methlen);
9521 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9522 in_commasep_string("keyboard-interactive", methods, methlen);
9524 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9525 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9526 /* Try loading the GSS libraries and see if we
9529 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9530 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9532 /* No point in even bothering to try to load the
9533 * GSS libraries, if the user configuration and
9534 * server aren't both prepared to attempt GSSAPI
9535 * auth in the first place. */
9536 s->can_gssapi = FALSE;
9541 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9543 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9546 * Attempt public-key authentication using a key from Pageant.
9549 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9551 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9553 /* Unpack key from agent response */
9554 s->pklen = toint(GET_32BIT(s->agentp));
9556 s->pkblob = (char *)s->agentp;
9557 s->agentp += s->pklen;
9558 s->alglen = toint(GET_32BIT(s->pkblob));
9559 s->alg = s->pkblob + 4;
9560 s->commentlen = toint(GET_32BIT(s->agentp));
9562 s->commentp = (char *)s->agentp;
9563 s->agentp += s->commentlen;
9564 /* s->agentp now points at next key, if any */
9566 /* See if server will accept it */
9567 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9568 ssh2_pkt_addstring(s->pktout, ssh->username);
9569 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9570 /* service requested */
9571 ssh2_pkt_addstring(s->pktout, "publickey");
9573 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9574 ssh2_pkt_addstring_start(s->pktout);
9575 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9576 ssh2_pkt_addstring_start(s->pktout);
9577 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9578 ssh2_pkt_send(ssh, s->pktout);
9579 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9581 crWaitUntilV(pktin);
9582 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9584 /* Offer of key refused. */
9591 if (flags & FLAG_VERBOSE) {
9592 c_write_str(ssh, "Authenticating with "
9594 c_write(ssh, s->commentp, s->commentlen);
9595 c_write_str(ssh, "\" from agent\r\n");
9599 * Server is willing to accept the key.
9600 * Construct a SIGN_REQUEST.
9602 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9603 ssh2_pkt_addstring(s->pktout, ssh->username);
9604 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9605 /* service requested */
9606 ssh2_pkt_addstring(s->pktout, "publickey");
9608 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9609 ssh2_pkt_addstring_start(s->pktout);
9610 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9611 ssh2_pkt_addstring_start(s->pktout);
9612 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9614 /* Ask agent for signature. */
9615 s->siglen = s->pktout->length - 5 + 4 +
9616 ssh->v2_session_id_len;
9617 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9619 s->len = 1; /* message type */
9620 s->len += 4 + s->pklen; /* key blob */
9621 s->len += 4 + s->siglen; /* data to sign */
9622 s->len += 4; /* flags */
9623 s->agentreq = snewn(4 + s->len, char);
9624 PUT_32BIT(s->agentreq, s->len);
9625 s->q = s->agentreq + 4;
9626 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9627 PUT_32BIT(s->q, s->pklen);
9629 memcpy(s->q, s->pkblob, s->pklen);
9631 PUT_32BIT(s->q, s->siglen);
9633 /* Now the data to be signed... */
9634 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9635 PUT_32BIT(s->q, ssh->v2_session_id_len);
9638 memcpy(s->q, ssh->v2_session_id,
9639 ssh->v2_session_id_len);
9640 s->q += ssh->v2_session_id_len;
9641 memcpy(s->q, s->pktout->data + 5,
9642 s->pktout->length - 5);
9643 s->q += s->pktout->length - 5;
9644 /* And finally the (zero) flags word. */
9646 if (!agent_query(s->agentreq, s->len + 4,
9648 ssh_agent_callback, ssh)) {
9652 bombout(("Unexpected data from server"
9653 " while waiting for agent"
9657 } while (pktin || inlen > 0);
9658 vret = ssh->agent_response;
9659 s->retlen = ssh->agent_response_len;
9664 if (s->retlen >= 9 &&
9665 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9666 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9667 logevent("Sending Pageant's response");
9668 ssh2_add_sigblob(ssh, s->pktout,
9669 s->pkblob, s->pklen,
9671 GET_32BIT(s->ret + 5));
9672 ssh2_pkt_send(ssh, s->pktout);
9673 s->type = AUTH_TYPE_PUBLICKEY;
9675 /* FIXME: less drastic response */
9676 bombout(("Pageant failed to answer challenge"));
9682 /* Do we have any keys left to try? */
9683 if (s->pkblob_in_agent) {
9684 s->done_agent = TRUE;
9685 s->tried_pubkey_config = TRUE;
9688 if (s->keyi >= s->nkeys)
9689 s->done_agent = TRUE;
9692 } else if (s->can_pubkey && s->publickey_blob &&
9693 s->privatekey_available && !s->tried_pubkey_config) {
9695 struct ssh2_userkey *key; /* not live over crReturn */
9696 char *passphrase; /* not live over crReturn */
9698 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9700 s->tried_pubkey_config = TRUE;
9703 * Try the public key supplied in the configuration.
9705 * First, offer the public blob to see if the server is
9706 * willing to accept it.
9708 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9709 ssh2_pkt_addstring(s->pktout, ssh->username);
9710 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9711 /* service requested */
9712 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9713 ssh2_pkt_addbool(s->pktout, FALSE);
9714 /* no signature included */
9715 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9716 ssh2_pkt_addstring_start(s->pktout);
9717 ssh2_pkt_addstring_data(s->pktout,
9718 (char *)s->publickey_blob,
9719 s->publickey_bloblen);
9720 ssh2_pkt_send(ssh, s->pktout);
9721 logevent("Offered public key");
9723 crWaitUntilV(pktin);
9724 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9725 /* Key refused. Give up. */
9726 s->gotit = TRUE; /* reconsider message next loop */
9727 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9728 continue; /* process this new message */
9730 logevent("Offer of public key accepted");
9733 * Actually attempt a serious authentication using
9736 if (flags & FLAG_VERBOSE) {
9737 c_write_str(ssh, "Authenticating with public key \"");
9738 c_write_str(ssh, s->publickey_comment);
9739 c_write_str(ssh, "\"\r\n");
9743 const char *error; /* not live over crReturn */
9744 if (s->privatekey_encrypted) {
9746 * Get a passphrase from the user.
9748 int ret; /* need not be kept over crReturn */
9749 s->cur_prompt = new_prompts(ssh->frontend);
9750 s->cur_prompt->to_server = FALSE;
9751 s->cur_prompt->name = dupstr("SSH key passphrase");
9752 add_prompt(s->cur_prompt,
9753 dupprintf("Passphrase for key \"%.100s\": ",
9754 s->publickey_comment),
9756 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9759 crWaitUntilV(!pktin);
9760 ret = get_userpass_input(s->cur_prompt,
9765 /* Failed to get a passphrase. Terminate. */
9766 free_prompts(s->cur_prompt);
9767 ssh_disconnect(ssh, NULL,
9768 "Unable to authenticate",
9769 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9774 dupstr(s->cur_prompt->prompts[0]->result);
9775 free_prompts(s->cur_prompt);
9777 passphrase = NULL; /* no passphrase needed */
9781 * Try decrypting the key.
9783 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9784 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9786 /* burn the evidence */
9787 smemclr(passphrase, strlen(passphrase));
9790 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9792 (key == SSH2_WRONG_PASSPHRASE)) {
9793 c_write_str(ssh, "Wrong passphrase\r\n");
9795 /* and loop again */
9797 c_write_str(ssh, "Unable to load private key (");
9798 c_write_str(ssh, error);
9799 c_write_str(ssh, ")\r\n");
9801 break; /* try something else */
9807 unsigned char *pkblob, *sigblob, *sigdata;
9808 int pkblob_len, sigblob_len, sigdata_len;
9812 * We have loaded the private key and the server
9813 * has announced that it's willing to accept it.
9814 * Hallelujah. Generate a signature and send it.
9816 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9817 ssh2_pkt_addstring(s->pktout, ssh->username);
9818 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9819 /* service requested */
9820 ssh2_pkt_addstring(s->pktout, "publickey");
9822 ssh2_pkt_addbool(s->pktout, TRUE);
9823 /* signature follows */
9824 ssh2_pkt_addstring(s->pktout, key->alg->name);
9825 pkblob = key->alg->public_blob(key->data,
9827 ssh2_pkt_addstring_start(s->pktout);
9828 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9832 * The data to be signed is:
9836 * followed by everything so far placed in the
9839 sigdata_len = s->pktout->length - 5 + 4 +
9840 ssh->v2_session_id_len;
9841 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9843 sigdata = snewn(sigdata_len, unsigned char);
9845 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9846 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9849 memcpy(sigdata+p, ssh->v2_session_id,
9850 ssh->v2_session_id_len);
9851 p += ssh->v2_session_id_len;
9852 memcpy(sigdata+p, s->pktout->data + 5,
9853 s->pktout->length - 5);
9854 p += s->pktout->length - 5;
9855 assert(p == sigdata_len);
9856 sigblob = key->alg->sign(key->data, (char *)sigdata,
9857 sigdata_len, &sigblob_len);
9858 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9859 sigblob, sigblob_len);
9864 ssh2_pkt_send(ssh, s->pktout);
9865 logevent("Sent public key signature");
9866 s->type = AUTH_TYPE_PUBLICKEY;
9867 key->alg->freekey(key->data);
9868 sfree(key->comment);
9873 } else if (s->can_gssapi && !s->tried_gssapi) {
9875 /* GSSAPI Authentication */
9880 s->type = AUTH_TYPE_GSSAPI;
9881 s->tried_gssapi = TRUE;
9883 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9886 * Pick the highest GSS library on the preference
9892 for (i = 0; i < ngsslibs; i++) {
9893 int want_id = conf_get_int_int(ssh->conf,
9894 CONF_ssh_gsslist, i);
9895 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
9896 if (ssh->gsslibs->libraries[j].id == want_id) {
9897 s->gsslib = &ssh->gsslibs->libraries[j];
9898 goto got_gsslib; /* double break */
9903 * We always expect to have found something in
9904 * the above loop: we only came here if there
9905 * was at least one viable GSS library, and the
9906 * preference list should always mention
9907 * everything and only change the order.
9912 if (s->gsslib->gsslogmsg)
9913 logevent(s->gsslib->gsslogmsg);
9915 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
9916 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9917 ssh2_pkt_addstring(s->pktout, ssh->username);
9918 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9919 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
9920 logevent("Attempting GSSAPI authentication");
9922 /* add mechanism info */
9923 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
9925 /* number of GSSAPI mechanisms */
9926 ssh2_pkt_adduint32(s->pktout,1);
9928 /* length of OID + 2 */
9929 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
9930 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
9933 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
9935 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
9937 ssh2_pkt_send(ssh, s->pktout);
9938 crWaitUntilV(pktin);
9939 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
9940 logevent("GSSAPI authentication request refused");
9944 /* check returned packet ... */
9946 ssh_pkt_getstring(pktin, &data, &len);
9947 s->gss_rcvtok.value = data;
9948 s->gss_rcvtok.length = len;
9949 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
9950 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
9951 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
9952 memcmp((char *)s->gss_rcvtok.value + 2,
9953 s->gss_buf.value,s->gss_buf.length) ) {
9954 logevent("GSSAPI authentication - wrong response from server");
9958 /* now start running */
9959 s->gss_stat = s->gsslib->import_name(s->gsslib,
9962 if (s->gss_stat != SSH_GSS_OK) {
9963 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
9964 logevent("GSSAPI import name failed - Bad service name");
9966 logevent("GSSAPI import name failed");
9970 /* fetch TGT into GSS engine */
9971 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
9973 if (s->gss_stat != SSH_GSS_OK) {
9974 logevent("GSSAPI authentication failed to get credentials");
9975 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
9979 /* initial tokens are empty */
9980 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
9981 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
9983 /* now enter the loop */
9985 s->gss_stat = s->gsslib->init_sec_context
9989 conf_get_int(ssh->conf, CONF_gssapifwd),
9993 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
9994 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
9995 logevent("GSSAPI authentication initialisation failed");
9997 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
9998 &s->gss_buf) == SSH_GSS_OK) {
9999 logevent(s->gss_buf.value);
10000 sfree(s->gss_buf.value);
10005 logevent("GSSAPI authentication initialised");
10007 /* Client and server now exchange tokens until GSSAPI
10008 * no longer says CONTINUE_NEEDED */
10010 if (s->gss_sndtok.length != 0) {
10011 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
10012 ssh_pkt_addstring_start(s->pktout);
10013 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
10014 ssh2_pkt_send(ssh, s->pktout);
10015 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
10018 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
10019 crWaitUntilV(pktin);
10020 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
10021 logevent("GSSAPI authentication - bad server response");
10022 s->gss_stat = SSH_GSS_FAILURE;
10025 ssh_pkt_getstring(pktin, &data, &len);
10026 s->gss_rcvtok.value = data;
10027 s->gss_rcvtok.length = len;
10029 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
10031 if (s->gss_stat != SSH_GSS_OK) {
10032 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10033 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10036 logevent("GSSAPI authentication loop finished OK");
10038 /* Now send the MIC */
10040 s->pktout = ssh2_pkt_init(0);
10041 micoffset = s->pktout->length;
10042 ssh_pkt_addstring_start(s->pktout);
10043 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10044 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10045 ssh_pkt_addstring(s->pktout, ssh->username);
10046 ssh_pkt_addstring(s->pktout, "ssh-connection");
10047 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10049 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10050 s->gss_buf.length = s->pktout->length - micoffset;
10052 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10053 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10054 ssh_pkt_addstring_start(s->pktout);
10055 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10056 ssh2_pkt_send(ssh, s->pktout);
10057 s->gsslib->free_mic(s->gsslib, &mic);
10061 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10062 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10065 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10068 * Keyboard-interactive authentication.
10071 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10073 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10075 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10076 ssh2_pkt_addstring(s->pktout, ssh->username);
10077 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10078 /* service requested */
10079 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10081 ssh2_pkt_addstring(s->pktout, ""); /* lang */
10082 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
10083 ssh2_pkt_send(ssh, s->pktout);
10085 logevent("Attempting keyboard-interactive authentication");
10087 crWaitUntilV(pktin);
10088 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10089 /* Server is not willing to do keyboard-interactive
10090 * at all (or, bizarrely but legally, accepts the
10091 * user without actually issuing any prompts).
10092 * Give up on it entirely. */
10094 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10095 s->kbd_inter_refused = TRUE; /* don't try it again */
10100 * Loop while the server continues to send INFO_REQUESTs.
10102 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10104 char *name, *inst, *lang;
10105 int name_len, inst_len, lang_len;
10109 * We've got a fresh USERAUTH_INFO_REQUEST.
10110 * Get the preamble and start building a prompt.
10112 ssh_pkt_getstring(pktin, &name, &name_len);
10113 ssh_pkt_getstring(pktin, &inst, &inst_len);
10114 ssh_pkt_getstring(pktin, &lang, &lang_len);
10115 s->cur_prompt = new_prompts(ssh->frontend);
10116 s->cur_prompt->to_server = TRUE;
10119 * Get any prompt(s) from the packet.
10121 s->num_prompts = ssh_pkt_getuint32(pktin);
10122 for (i = 0; i < s->num_prompts; i++) {
10126 static char noprompt[] =
10127 "<server failed to send prompt>: ";
10129 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10130 echo = ssh2_pkt_getbool(pktin);
10133 prompt_len = lenof(noprompt)-1;
10135 add_prompt(s->cur_prompt,
10136 dupprintf("%.*s", prompt_len, prompt),
10141 /* FIXME: better prefix to distinguish from
10142 * local prompts? */
10143 s->cur_prompt->name =
10144 dupprintf("SSH server: %.*s", name_len, name);
10145 s->cur_prompt->name_reqd = TRUE;
10147 s->cur_prompt->name =
10148 dupstr("SSH server authentication");
10149 s->cur_prompt->name_reqd = FALSE;
10151 /* We add a prefix to try to make it clear that a prompt
10152 * has come from the server.
10153 * FIXME: ugly to print "Using..." in prompt _every_
10154 * time round. Can this be done more subtly? */
10155 /* Special case: for reasons best known to themselves,
10156 * some servers send k-i requests with no prompts and
10157 * nothing to display. Keep quiet in this case. */
10158 if (s->num_prompts || name_len || inst_len) {
10159 s->cur_prompt->instruction =
10160 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10161 inst_len ? "\n" : "", inst_len, inst);
10162 s->cur_prompt->instr_reqd = TRUE;
10164 s->cur_prompt->instr_reqd = FALSE;
10168 * Display any instructions, and get the user's
10172 int ret; /* not live over crReturn */
10173 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10176 crWaitUntilV(!pktin);
10177 ret = get_userpass_input(s->cur_prompt, in, inlen);
10182 * Failed to get responses. Terminate.
10184 free_prompts(s->cur_prompt);
10185 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10186 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10193 * Send the response(s) to the server.
10195 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10196 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10197 for (i=0; i < s->num_prompts; i++) {
10198 ssh2_pkt_addstring(s->pktout,
10199 s->cur_prompt->prompts[i]->result);
10201 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10204 * Free the prompts structure from this iteration.
10205 * If there's another, a new one will be allocated
10206 * when we return to the top of this while loop.
10208 free_prompts(s->cur_prompt);
10211 * Get the next packet in case it's another
10214 crWaitUntilV(pktin);
10219 * We should have SUCCESS or FAILURE now.
10223 } else if (s->can_passwd) {
10226 * Plain old password authentication.
10228 int ret; /* not live over crReturn */
10229 int changereq_first_time; /* not live over crReturn */
10231 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10233 s->cur_prompt = new_prompts(ssh->frontend);
10234 s->cur_prompt->to_server = TRUE;
10235 s->cur_prompt->name = dupstr("SSH password");
10236 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10241 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10244 crWaitUntilV(!pktin);
10245 ret = get_userpass_input(s->cur_prompt, in, inlen);
10250 * Failed to get responses. Terminate.
10252 free_prompts(s->cur_prompt);
10253 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10254 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10259 * Squirrel away the password. (We may need it later if
10260 * asked to change it.)
10262 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10263 free_prompts(s->cur_prompt);
10266 * Send the password packet.
10268 * We pad out the password packet to 256 bytes to make
10269 * it harder for an attacker to find the length of the
10272 * Anyone using a password longer than 256 bytes
10273 * probably doesn't have much to worry about from
10274 * people who find out how long their password is!
10276 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10277 ssh2_pkt_addstring(s->pktout, ssh->username);
10278 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10279 /* service requested */
10280 ssh2_pkt_addstring(s->pktout, "password");
10281 ssh2_pkt_addbool(s->pktout, FALSE);
10282 ssh2_pkt_addstring(s->pktout, s->password);
10283 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10284 logevent("Sent password");
10285 s->type = AUTH_TYPE_PASSWORD;
10288 * Wait for next packet, in case it's a password change
10291 crWaitUntilV(pktin);
10292 changereq_first_time = TRUE;
10294 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10297 * We're being asked for a new password
10298 * (perhaps not for the first time).
10299 * Loop until the server accepts it.
10302 int got_new = FALSE; /* not live over crReturn */
10303 char *prompt; /* not live over crReturn */
10304 int prompt_len; /* not live over crReturn */
10308 if (changereq_first_time)
10309 msg = "Server requested password change";
10311 msg = "Server rejected new password";
10313 c_write_str(ssh, msg);
10314 c_write_str(ssh, "\r\n");
10317 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10319 s->cur_prompt = new_prompts(ssh->frontend);
10320 s->cur_prompt->to_server = TRUE;
10321 s->cur_prompt->name = dupstr("New SSH password");
10322 s->cur_prompt->instruction =
10323 dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
10324 s->cur_prompt->instr_reqd = TRUE;
10326 * There's no explicit requirement in the protocol
10327 * for the "old" passwords in the original and
10328 * password-change messages to be the same, and
10329 * apparently some Cisco kit supports password change
10330 * by the user entering a blank password originally
10331 * and the real password subsequently, so,
10332 * reluctantly, we prompt for the old password again.
10334 * (On the other hand, some servers don't even bother
10335 * to check this field.)
10337 add_prompt(s->cur_prompt,
10338 dupstr("Current password (blank for previously entered password): "),
10340 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10342 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10346 * Loop until the user manages to enter the same
10351 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10354 crWaitUntilV(!pktin);
10355 ret = get_userpass_input(s->cur_prompt, in, inlen);
10360 * Failed to get responses. Terminate.
10362 /* burn the evidence */
10363 free_prompts(s->cur_prompt);
10364 smemclr(s->password, strlen(s->password));
10365 sfree(s->password);
10366 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10367 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10373 * If the user specified a new original password
10374 * (IYSWIM), overwrite any previously specified
10376 * (A side effect is that the user doesn't have to
10377 * re-enter it if they louse up the new password.)
10379 if (s->cur_prompt->prompts[0]->result[0]) {
10380 smemclr(s->password, strlen(s->password));
10381 /* burn the evidence */
10382 sfree(s->password);
10384 dupstr(s->cur_prompt->prompts[0]->result);
10388 * Check the two new passwords match.
10390 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10391 s->cur_prompt->prompts[2]->result)
10394 /* They don't. Silly user. */
10395 c_write_str(ssh, "Passwords do not match\r\n");
10400 * Send the new password (along with the old one).
10401 * (see above for padding rationale)
10403 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10404 ssh2_pkt_addstring(s->pktout, ssh->username);
10405 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10406 /* service requested */
10407 ssh2_pkt_addstring(s->pktout, "password");
10408 ssh2_pkt_addbool(s->pktout, TRUE);
10409 ssh2_pkt_addstring(s->pktout, s->password);
10410 ssh2_pkt_addstring(s->pktout,
10411 s->cur_prompt->prompts[1]->result);
10412 free_prompts(s->cur_prompt);
10413 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10414 logevent("Sent new password");
10417 * Now see what the server has to say about it.
10418 * (If it's CHANGEREQ again, it's not happy with the
10421 crWaitUntilV(pktin);
10422 changereq_first_time = FALSE;
10427 * We need to reexamine the current pktin at the top
10428 * of the loop. Either:
10429 * - we weren't asked to change password at all, in
10430 * which case it's a SUCCESS or FAILURE with the
10432 * - we sent a new password, and the server was
10433 * either OK with it (SUCCESS or FAILURE w/partial
10434 * success) or unhappy with the _old_ password
10435 * (FAILURE w/o partial success)
10436 * In any of these cases, we go back to the top of
10437 * the loop and start again.
10442 * We don't need the old password any more, in any
10443 * case. Burn the evidence.
10445 smemclr(s->password, strlen(s->password));
10446 sfree(s->password);
10449 char *str = dupprintf("No supported authentication methods available"
10450 " (server sent: %.*s)",
10453 ssh_disconnect(ssh, str,
10454 "No supported authentication methods available",
10455 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10465 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10467 /* Clear up various bits and pieces from authentication. */
10468 if (s->publickey_blob) {
10469 sfree(s->publickey_algorithm);
10470 sfree(s->publickey_blob);
10471 sfree(s->publickey_comment);
10473 if (s->agent_response)
10474 sfree(s->agent_response);
10476 if (s->userauth_success && !ssh->bare_connection) {
10478 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10479 * packets since. Signal the transport layer to consider enacting
10480 * delayed compression.
10482 * (Relying on we_are_in is not sufficient, as
10483 * draft-miller-secsh-compression-delayed is quite clear that it
10484 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10485 * become set for other reasons.)
10487 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10490 ssh->channels = newtree234(ssh_channelcmp);
10493 * Set up handlers for some connection protocol messages, so we
10494 * don't have to handle them repeatedly in this coroutine.
10496 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10497 ssh2_msg_channel_window_adjust;
10498 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10499 ssh2_msg_global_request;
10502 * Create the main session channel.
10504 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10505 ssh->mainchan = NULL;
10507 ssh->mainchan = snew(struct ssh_channel);
10508 ssh->mainchan->ssh = ssh;
10509 ssh2_channel_init(ssh->mainchan);
10511 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10513 * Just start a direct-tcpip channel and use it as the main
10516 ssh_send_port_open(ssh->mainchan,
10517 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10518 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10520 ssh->ncmode = TRUE;
10522 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10523 logevent("Opening session as main channel");
10524 ssh2_pkt_send(ssh, s->pktout);
10525 ssh->ncmode = FALSE;
10527 crWaitUntilV(pktin);
10528 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10529 bombout(("Server refused to open channel"));
10531 /* FIXME: error data comes back in FAILURE packet */
10533 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10534 bombout(("Server's channel confirmation cited wrong channel"));
10537 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10538 ssh->mainchan->halfopen = FALSE;
10539 ssh->mainchan->type = CHAN_MAINSESSION;
10540 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10541 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10542 add234(ssh->channels, ssh->mainchan);
10543 update_specials_menu(ssh->frontend);
10544 logevent("Opened main channel");
10548 * Now we have a channel, make dispatch table entries for
10549 * general channel-based messages.
10551 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10552 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10553 ssh2_msg_channel_data;
10554 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10555 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10556 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10557 ssh2_msg_channel_open_confirmation;
10558 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10559 ssh2_msg_channel_open_failure;
10560 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10561 ssh2_msg_channel_request;
10562 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10563 ssh2_msg_channel_open;
10564 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10565 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10568 * Now the connection protocol is properly up and running, with
10569 * all those dispatch table entries, so it's safe to let
10570 * downstreams start trying to open extra channels through us.
10572 if (ssh->connshare)
10573 share_activate(ssh->connshare, ssh->v_s);
10575 if (ssh->mainchan && ssh_is_simple(ssh)) {
10577 * This message indicates to the server that we promise
10578 * not to try to run any other channel in parallel with
10579 * this one, so it's safe for it to advertise a very large
10580 * window and leave the flow control to TCP.
10582 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10583 "simple@putty.projects.tartarus.org",
10585 ssh2_pkt_send(ssh, s->pktout);
10589 * Enable port forwardings.
10591 ssh_setup_portfwd(ssh, ssh->conf);
10593 if (ssh->mainchan && !ssh->ncmode) {
10595 * Send the CHANNEL_REQUESTS for the main session channel.
10596 * Each one is handled by its own little asynchronous
10600 /* Potentially enable X11 forwarding. */
10601 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10603 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10605 if (!ssh->x11disp) {
10606 /* FIXME: return an error message from x11_setup_display */
10607 logevent("X11 forwarding not enabled: unable to"
10608 " initialise X display");
10610 ssh->x11auth = x11_invent_fake_auth
10611 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10612 ssh->x11auth->disp = ssh->x11disp;
10614 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10618 /* Potentially enable agent forwarding. */
10619 if (ssh_agent_forwarding_permitted(ssh))
10620 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10622 /* Now allocate a pty for the session. */
10623 if (!conf_get_int(ssh->conf, CONF_nopty))
10624 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10626 /* Send environment variables. */
10627 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10630 * Start a shell or a remote command. We may have to attempt
10631 * this twice if the config data has provided a second choice
10638 if (ssh->fallback_cmd) {
10639 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10640 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10642 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10643 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10647 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10648 ssh2_response_authconn, NULL);
10649 ssh2_pkt_addstring(s->pktout, cmd);
10651 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10652 ssh2_response_authconn, NULL);
10653 ssh2_pkt_addstring(s->pktout, cmd);
10655 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10656 ssh2_response_authconn, NULL);
10658 ssh2_pkt_send(ssh, s->pktout);
10660 crWaitUntilV(pktin);
10662 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10663 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10664 bombout(("Unexpected response to shell/command request:"
10665 " packet type %d", pktin->type));
10669 * We failed to start the command. If this is the
10670 * fallback command, we really are finished; if it's
10671 * not, and if the fallback command exists, try falling
10672 * back to it before complaining.
10674 if (!ssh->fallback_cmd &&
10675 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10676 logevent("Primary command failed; attempting fallback");
10677 ssh->fallback_cmd = TRUE;
10680 bombout(("Server refused to start a shell/command"));
10683 logevent("Started a shell/command");
10688 ssh->editing = ssh->echoing = TRUE;
10691 ssh->state = SSH_STATE_SESSION;
10692 if (ssh->size_needed)
10693 ssh_size(ssh, ssh->term_width, ssh->term_height);
10694 if (ssh->eof_needed)
10695 ssh_special(ssh, TS_EOF);
10701 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10706 s->try_send = FALSE;
10710 * _All_ the connection-layer packets we expect to
10711 * receive are now handled by the dispatch table.
10712 * Anything that reaches here must be bogus.
10715 bombout(("Strange packet received: type %d", pktin->type));
10717 } else if (ssh->mainchan) {
10719 * We have spare data. Add it to the channel buffer.
10721 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
10722 s->try_send = TRUE;
10726 struct ssh_channel *c;
10728 * Try to send data on all channels if we can.
10730 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
10731 if (c->type != CHAN_SHARING)
10732 ssh2_try_send_and_unthrottle(ssh, c);
10740 * Handlers for SSH-2 messages that might arrive at any moment.
10742 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10744 /* log reason code in disconnect message */
10746 int reason, msglen;
10748 reason = ssh_pkt_getuint32(pktin);
10749 ssh_pkt_getstring(pktin, &msg, &msglen);
10751 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10752 buf = dupprintf("Received disconnect message (%s)",
10753 ssh2_disconnect_reasons[reason]);
10755 buf = dupprintf("Received disconnect message (unknown"
10756 " type %d)", reason);
10760 buf = dupprintf("Disconnection message text: %.*s",
10761 msglen, NULLTOEMPTY(msg));
10763 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10765 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10766 ssh2_disconnect_reasons[reason] : "unknown",
10767 msglen, NULLTOEMPTY(msg)));
10771 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10773 /* log the debug message */
10777 /* XXX maybe we should actually take notice of the return value */
10778 ssh2_pkt_getbool(pktin);
10779 ssh_pkt_getstring(pktin, &msg, &msglen);
10781 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
10784 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10786 do_ssh2_transport(ssh, NULL, 0, pktin);
10790 * Called if we receive a packet that isn't allowed by the protocol.
10791 * This only applies to packets whose meaning PuTTY understands.
10792 * Entirely unknown packets are handled below.
10794 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10796 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10797 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10799 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10803 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10805 struct Packet *pktout;
10806 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10807 ssh2_pkt_adduint32(pktout, pktin->sequence);
10809 * UNIMPLEMENTED messages MUST appear in the same order as the
10810 * messages they respond to. Hence, never queue them.
10812 ssh2_pkt_send_noqueue(ssh, pktout);
10816 * Handle the top-level SSH-2 protocol.
10818 static void ssh2_protocol_setup(Ssh ssh)
10823 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10825 for (i = 0; i < 256; i++)
10826 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10829 * Initially, we only accept transport messages (and a few generic
10830 * ones). do_ssh2_authconn will add more when it starts.
10831 * Messages that are understood but not currently acceptable go to
10832 * ssh2_msg_unexpected.
10834 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10835 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10836 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10837 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10838 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10839 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10840 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10841 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10842 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10843 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10844 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10845 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10846 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10847 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10848 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10849 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10850 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10851 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10852 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10853 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10854 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10855 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10856 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10857 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10858 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10859 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10860 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10861 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10862 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10863 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10864 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10865 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10866 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10869 * These messages have a special handler from the start.
10871 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10872 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10873 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10876 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10881 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10883 for (i = 0; i < 256; i++)
10884 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10887 * Initially, we set all ssh-connection messages to 'unexpected';
10888 * do_ssh2_authconn will fill things in properly. We also handle a
10889 * couple of messages from the transport protocol which aren't
10890 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10893 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10894 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10895 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10896 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10897 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10898 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10899 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10900 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10901 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10902 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10903 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10904 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10905 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10906 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10908 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10911 * These messages have a special handler from the start.
10913 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10914 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
10915 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10918 static void ssh2_timer(void *ctx, unsigned long now)
10920 Ssh ssh = (Ssh)ctx;
10922 if (ssh->state == SSH_STATE_CLOSED)
10925 if (!ssh->kex_in_progress && !ssh->bare_connection &&
10926 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
10927 now == ssh->next_rekey) {
10928 do_ssh2_transport(ssh, "timeout", -1, NULL);
10932 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
10933 struct Packet *pktin)
10935 const unsigned char *in = (const unsigned char *)vin;
10936 if (ssh->state == SSH_STATE_CLOSED)
10940 ssh->incoming_data_size += pktin->encrypted_len;
10941 if (!ssh->kex_in_progress &&
10942 ssh->max_data_size != 0 &&
10943 ssh->incoming_data_size > ssh->max_data_size)
10944 do_ssh2_transport(ssh, "too much data received", -1, NULL);
10948 ssh->packet_dispatch[pktin->type](ssh, pktin);
10949 else if (!ssh->protocol_initial_phase_done)
10950 do_ssh2_transport(ssh, in, inlen, pktin);
10952 do_ssh2_authconn(ssh, in, inlen, pktin);
10955 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
10956 struct Packet *pktin)
10958 const unsigned char *in = (const unsigned char *)vin;
10959 if (ssh->state == SSH_STATE_CLOSED)
10963 ssh->packet_dispatch[pktin->type](ssh, pktin);
10965 do_ssh2_authconn(ssh, in, inlen, pktin);
10968 static void ssh_cache_conf_values(Ssh ssh)
10970 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
10974 * Called to set up the connection.
10976 * Returns an error message, or NULL on success.
10978 static const char *ssh_init(void *frontend_handle, void **backend_handle,
10980 const char *host, int port, char **realhost,
10981 int nodelay, int keepalive)
10986 ssh = snew(struct ssh_tag);
10987 ssh->conf = conf_copy(conf);
10988 ssh_cache_conf_values(ssh);
10989 ssh->version = 0; /* when not ready yet */
10991 ssh->cipher = NULL;
10992 ssh->v1_cipher_ctx = NULL;
10993 ssh->crcda_ctx = NULL;
10994 ssh->cscipher = NULL;
10995 ssh->cs_cipher_ctx = NULL;
10996 ssh->sccipher = NULL;
10997 ssh->sc_cipher_ctx = NULL;
10999 ssh->cs_mac_ctx = NULL;
11001 ssh->sc_mac_ctx = NULL;
11002 ssh->cscomp = NULL;
11003 ssh->cs_comp_ctx = NULL;
11004 ssh->sccomp = NULL;
11005 ssh->sc_comp_ctx = NULL;
11007 ssh->kex_ctx = NULL;
11008 ssh->hostkey = NULL;
11009 ssh->hostkey_str = NULL;
11010 ssh->exitcode = -1;
11011 ssh->close_expected = FALSE;
11012 ssh->clean_exit = FALSE;
11013 ssh->state = SSH_STATE_PREPACKET;
11014 ssh->size_needed = FALSE;
11015 ssh->eof_needed = FALSE;
11017 ssh->logctx = NULL;
11018 ssh->deferred_send_data = NULL;
11019 ssh->deferred_len = 0;
11020 ssh->deferred_size = 0;
11021 ssh->fallback_cmd = 0;
11022 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
11023 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
11024 ssh->x11disp = NULL;
11025 ssh->x11auth = NULL;
11026 ssh->x11authtree = newtree234(x11_authcmp);
11027 ssh->v1_compressing = FALSE;
11028 ssh->v2_outgoing_sequence = 0;
11029 ssh->ssh1_rdpkt_crstate = 0;
11030 ssh->ssh2_rdpkt_crstate = 0;
11031 ssh->ssh2_bare_rdpkt_crstate = 0;
11032 ssh->ssh_gotdata_crstate = 0;
11033 ssh->do_ssh1_connection_crstate = 0;
11034 ssh->do_ssh_init_state = NULL;
11035 ssh->do_ssh_connection_init_state = NULL;
11036 ssh->do_ssh1_login_state = NULL;
11037 ssh->do_ssh2_transport_state = NULL;
11038 ssh->do_ssh2_authconn_state = NULL;
11041 ssh->mainchan = NULL;
11042 ssh->throttled_all = 0;
11043 ssh->v1_stdout_throttling = 0;
11045 ssh->queuelen = ssh->queuesize = 0;
11046 ssh->queueing = FALSE;
11047 ssh->qhead = ssh->qtail = NULL;
11048 ssh->deferred_rekey_reason = NULL;
11049 bufchain_init(&ssh->queued_incoming_data);
11050 ssh->frozen = FALSE;
11051 ssh->username = NULL;
11052 ssh->sent_console_eof = FALSE;
11053 ssh->got_pty = FALSE;
11054 ssh->bare_connection = FALSE;
11055 ssh->X11_fwd_enabled = FALSE;
11056 ssh->connshare = NULL;
11057 ssh->attempting_connshare = FALSE;
11058 ssh->session_started = FALSE;
11059 ssh->specials = NULL;
11060 ssh->n_uncert_hostkeys = 0;
11061 ssh->cross_certifying = FALSE;
11063 *backend_handle = ssh;
11066 if (crypto_startup() == 0)
11067 return "Microsoft high encryption pack not installed!";
11070 ssh->frontend = frontend_handle;
11071 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11072 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11074 ssh->channels = NULL;
11075 ssh->rportfwds = NULL;
11076 ssh->portfwds = NULL;
11081 ssh->conn_throttle_count = 0;
11082 ssh->overall_bufsize = 0;
11083 ssh->fallback_cmd = 0;
11085 ssh->protocol = NULL;
11087 ssh->protocol_initial_phase_done = FALSE;
11089 ssh->pinger = NULL;
11091 ssh->incoming_data_size = ssh->outgoing_data_size =
11092 ssh->deferred_data_size = 0L;
11093 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11094 CONF_ssh_rekey_data));
11095 ssh->kex_in_progress = FALSE;
11098 ssh->gsslibs = NULL;
11101 random_ref(); /* do this now - may be needed by sharing setup code */
11103 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11112 static void ssh_free(void *handle)
11114 Ssh ssh = (Ssh) handle;
11115 struct ssh_channel *c;
11116 struct ssh_rportfwd *pf;
11117 struct X11FakeAuth *auth;
11119 if (ssh->v1_cipher_ctx)
11120 ssh->cipher->free_context(ssh->v1_cipher_ctx);
11121 if (ssh->cs_cipher_ctx)
11122 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11123 if (ssh->sc_cipher_ctx)
11124 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11125 if (ssh->cs_mac_ctx)
11126 ssh->csmac->free_context(ssh->cs_mac_ctx);
11127 if (ssh->sc_mac_ctx)
11128 ssh->scmac->free_context(ssh->sc_mac_ctx);
11129 if (ssh->cs_comp_ctx) {
11131 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11133 zlib_compress_cleanup(ssh->cs_comp_ctx);
11135 if (ssh->sc_comp_ctx) {
11137 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11139 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11142 dh_cleanup(ssh->kex_ctx);
11143 sfree(ssh->savedhost);
11145 while (ssh->queuelen-- > 0)
11146 ssh_free_packet(ssh->queue[ssh->queuelen]);
11149 while (ssh->qhead) {
11150 struct queued_handler *qh = ssh->qhead;
11151 ssh->qhead = qh->next;
11154 ssh->qhead = ssh->qtail = NULL;
11156 if (ssh->channels) {
11157 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11160 if (c->u.x11.xconn != NULL)
11161 x11_close(c->u.x11.xconn);
11163 case CHAN_SOCKDATA:
11164 case CHAN_SOCKDATA_DORMANT:
11165 if (c->u.pfd.pf != NULL)
11166 pfd_close(c->u.pfd.pf);
11169 if (ssh->version == 2) {
11170 struct outstanding_channel_request *ocr, *nocr;
11171 ocr = c->v.v2.chanreq_head;
11173 ocr->handler(c, NULL, ocr->ctx);
11178 bufchain_clear(&c->v.v2.outbuffer);
11182 freetree234(ssh->channels);
11183 ssh->channels = NULL;
11186 if (ssh->connshare)
11187 sharestate_free(ssh->connshare);
11189 if (ssh->rportfwds) {
11190 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11192 freetree234(ssh->rportfwds);
11193 ssh->rportfwds = NULL;
11195 sfree(ssh->deferred_send_data);
11197 x11_free_display(ssh->x11disp);
11198 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11199 x11_free_fake_auth(auth);
11200 freetree234(ssh->x11authtree);
11201 sfree(ssh->do_ssh_init_state);
11202 sfree(ssh->do_ssh1_login_state);
11203 sfree(ssh->do_ssh2_transport_state);
11204 sfree(ssh->do_ssh2_authconn_state);
11207 sfree(ssh->fullhostname);
11208 sfree(ssh->hostkey_str);
11209 sfree(ssh->specials);
11210 if (ssh->crcda_ctx) {
11211 crcda_free_context(ssh->crcda_ctx);
11212 ssh->crcda_ctx = NULL;
11215 ssh_do_close(ssh, TRUE);
11216 expire_timer_context(ssh);
11218 pinger_free(ssh->pinger);
11219 bufchain_clear(&ssh->queued_incoming_data);
11220 sfree(ssh->username);
11221 conf_free(ssh->conf);
11224 ssh_gss_cleanup(ssh->gsslibs);
11232 * Reconfigure the SSH backend.
11234 static void ssh_reconfig(void *handle, Conf *conf)
11236 Ssh ssh = (Ssh) handle;
11237 const char *rekeying = NULL;
11238 int rekey_mandatory = FALSE;
11239 unsigned long old_max_data_size;
11242 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11244 ssh_setup_portfwd(ssh, conf);
11246 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11247 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11249 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11250 unsigned long now = GETTICKCOUNT();
11252 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11253 rekeying = "timeout shortened";
11255 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11259 old_max_data_size = ssh->max_data_size;
11260 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11261 CONF_ssh_rekey_data));
11262 if (old_max_data_size != ssh->max_data_size &&
11263 ssh->max_data_size != 0) {
11264 if (ssh->outgoing_data_size > ssh->max_data_size ||
11265 ssh->incoming_data_size > ssh->max_data_size)
11266 rekeying = "data limit lowered";
11269 if (conf_get_int(ssh->conf, CONF_compression) !=
11270 conf_get_int(conf, CONF_compression)) {
11271 rekeying = "compression setting changed";
11272 rekey_mandatory = TRUE;
11275 for (i = 0; i < CIPHER_MAX; i++)
11276 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11277 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11278 rekeying = "cipher settings changed";
11279 rekey_mandatory = TRUE;
11281 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11282 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11283 rekeying = "cipher settings changed";
11284 rekey_mandatory = TRUE;
11287 conf_free(ssh->conf);
11288 ssh->conf = conf_copy(conf);
11289 ssh_cache_conf_values(ssh);
11291 if (!ssh->bare_connection && rekeying) {
11292 if (!ssh->kex_in_progress) {
11293 do_ssh2_transport(ssh, rekeying, -1, NULL);
11294 } else if (rekey_mandatory) {
11295 ssh->deferred_rekey_reason = rekeying;
11301 * Called to send data down the SSH connection.
11303 static int ssh_send(void *handle, const char *buf, int len)
11305 Ssh ssh = (Ssh) handle;
11307 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11310 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11312 return ssh_sendbuffer(ssh);
11316 * Called to query the current amount of buffered stdin data.
11318 static int ssh_sendbuffer(void *handle)
11320 Ssh ssh = (Ssh) handle;
11321 int override_value;
11323 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11327 * If the SSH socket itself has backed up, add the total backup
11328 * size on that to any individual buffer on the stdin channel.
11330 override_value = 0;
11331 if (ssh->throttled_all)
11332 override_value = ssh->overall_bufsize;
11334 if (ssh->version == 1) {
11335 return override_value;
11336 } else if (ssh->version == 2) {
11337 if (!ssh->mainchan)
11338 return override_value;
11340 return (override_value +
11341 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11348 * Called to set the size of the window from SSH's POV.
11350 static void ssh_size(void *handle, int width, int height)
11352 Ssh ssh = (Ssh) handle;
11353 struct Packet *pktout;
11355 ssh->term_width = width;
11356 ssh->term_height = height;
11358 switch (ssh->state) {
11359 case SSH_STATE_BEFORE_SIZE:
11360 case SSH_STATE_PREPACKET:
11361 case SSH_STATE_CLOSED:
11362 break; /* do nothing */
11363 case SSH_STATE_INTERMED:
11364 ssh->size_needed = TRUE; /* buffer for later */
11366 case SSH_STATE_SESSION:
11367 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11368 if (ssh->version == 1) {
11369 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11370 PKT_INT, ssh->term_height,
11371 PKT_INT, ssh->term_width,
11372 PKT_INT, 0, PKT_INT, 0, PKT_END);
11373 } else if (ssh->mainchan) {
11374 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11376 ssh2_pkt_adduint32(pktout, ssh->term_width);
11377 ssh2_pkt_adduint32(pktout, ssh->term_height);
11378 ssh2_pkt_adduint32(pktout, 0);
11379 ssh2_pkt_adduint32(pktout, 0);
11380 ssh2_pkt_send(ssh, pktout);
11388 * Return a list of the special codes that make sense in this
11391 static const struct telnet_special *ssh_get_specials(void *handle)
11393 static const struct telnet_special ssh1_ignore_special[] = {
11394 {"IGNORE message", TS_NOP}
11396 static const struct telnet_special ssh2_ignore_special[] = {
11397 {"IGNORE message", TS_NOP},
11399 static const struct telnet_special ssh2_rekey_special[] = {
11400 {"Repeat key exchange", TS_REKEY},
11402 static const struct telnet_special ssh2_session_specials[] = {
11405 /* These are the signal names defined by RFC 4254.
11406 * They include all the ISO C signals, but are a subset of the POSIX
11407 * required signals. */
11408 {"SIGINT (Interrupt)", TS_SIGINT},
11409 {"SIGTERM (Terminate)", TS_SIGTERM},
11410 {"SIGKILL (Kill)", TS_SIGKILL},
11411 {"SIGQUIT (Quit)", TS_SIGQUIT},
11412 {"SIGHUP (Hangup)", TS_SIGHUP},
11413 {"More signals", TS_SUBMENU},
11414 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11415 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11416 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11417 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11418 {NULL, TS_EXITMENU}
11420 static const struct telnet_special specials_end[] = {
11421 {NULL, TS_EXITMENU}
11424 struct telnet_special *specials = NULL;
11425 int nspecials = 0, specialsize = 0;
11427 Ssh ssh = (Ssh) handle;
11429 sfree(ssh->specials);
11431 #define ADD_SPECIALS(name) do \
11433 int len = lenof(name); \
11434 if (nspecials + len > specialsize) { \
11435 specialsize = (nspecials + len) * 5 / 4 + 32; \
11436 specials = sresize(specials, specialsize, struct telnet_special); \
11438 memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
11439 nspecials += len; \
11442 if (ssh->version == 1) {
11443 /* Don't bother offering IGNORE if we've decided the remote
11444 * won't cope with it, since we wouldn't bother sending it if
11446 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11447 ADD_SPECIALS(ssh1_ignore_special);
11448 } else if (ssh->version == 2) {
11449 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11450 ADD_SPECIALS(ssh2_ignore_special);
11451 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11452 ADD_SPECIALS(ssh2_rekey_special);
11454 ADD_SPECIALS(ssh2_session_specials);
11456 if (ssh->n_uncert_hostkeys) {
11457 static const struct telnet_special uncert_start[] = {
11459 {"Cache new host key type", TS_SUBMENU},
11461 static const struct telnet_special uncert_end[] = {
11462 {NULL, TS_EXITMENU},
11466 ADD_SPECIALS(uncert_start);
11467 for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
11468 struct telnet_special uncert[1];
11469 const struct ssh_signkey *alg =
11470 hostkey_algs[ssh->uncert_hostkeys[i]];
11471 uncert[0].name = alg->name;
11472 uncert[0].code = TS_LOCALSTART + i;
11473 ADD_SPECIALS(uncert);
11475 ADD_SPECIALS(uncert_end);
11477 } /* else we're not ready yet */
11480 ADD_SPECIALS(specials_end);
11482 ssh->specials = specials;
11489 #undef ADD_SPECIALS
11493 * Send special codes. TS_EOF is useful for `plink', so you
11494 * can send an EOF and collect resulting output (e.g. `plink
11497 static void ssh_special(void *handle, Telnet_Special code)
11499 Ssh ssh = (Ssh) handle;
11500 struct Packet *pktout;
11502 if (code == TS_EOF) {
11503 if (ssh->state != SSH_STATE_SESSION) {
11505 * Buffer the EOF in case we are pre-SESSION, so we can
11506 * send it as soon as we reach SESSION.
11508 if (code == TS_EOF)
11509 ssh->eof_needed = TRUE;
11512 if (ssh->version == 1) {
11513 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11514 } else if (ssh->mainchan) {
11515 sshfwd_write_eof(ssh->mainchan);
11516 ssh->send_ok = 0; /* now stop trying to read from stdin */
11518 logevent("Sent EOF message");
11519 } else if (code == TS_PING || code == TS_NOP) {
11520 if (ssh->state == SSH_STATE_CLOSED
11521 || ssh->state == SSH_STATE_PREPACKET) return;
11522 if (ssh->version == 1) {
11523 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11524 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11526 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11527 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11528 ssh2_pkt_addstring_start(pktout);
11529 ssh2_pkt_send_noqueue(ssh, pktout);
11532 } else if (code == TS_REKEY) {
11533 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11534 ssh->version == 2) {
11535 do_ssh2_transport(ssh, "at user request", -1, NULL);
11537 } else if (code >= TS_LOCALSTART) {
11538 ssh->hostkey = hostkey_algs[code - TS_LOCALSTART];
11539 ssh->cross_certifying = TRUE;
11540 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11541 ssh->version == 2) {
11542 do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
11544 } else if (code == TS_BRK) {
11545 if (ssh->state == SSH_STATE_CLOSED
11546 || ssh->state == SSH_STATE_PREPACKET) return;
11547 if (ssh->version == 1) {
11548 logevent("Unable to send BREAK signal in SSH-1");
11549 } else if (ssh->mainchan) {
11550 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11551 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11552 ssh2_pkt_send(ssh, pktout);
11555 /* Is is a POSIX signal? */
11556 const char *signame = NULL;
11557 if (code == TS_SIGABRT) signame = "ABRT";
11558 if (code == TS_SIGALRM) signame = "ALRM";
11559 if (code == TS_SIGFPE) signame = "FPE";
11560 if (code == TS_SIGHUP) signame = "HUP";
11561 if (code == TS_SIGILL) signame = "ILL";
11562 if (code == TS_SIGINT) signame = "INT";
11563 if (code == TS_SIGKILL) signame = "KILL";
11564 if (code == TS_SIGPIPE) signame = "PIPE";
11565 if (code == TS_SIGQUIT) signame = "QUIT";
11566 if (code == TS_SIGSEGV) signame = "SEGV";
11567 if (code == TS_SIGTERM) signame = "TERM";
11568 if (code == TS_SIGUSR1) signame = "USR1";
11569 if (code == TS_SIGUSR2) signame = "USR2";
11570 /* The SSH-2 protocol does in principle support arbitrary named
11571 * signals, including signame@domain, but we don't support those. */
11573 /* It's a signal. */
11574 if (ssh->version == 2 && ssh->mainchan) {
11575 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11576 ssh2_pkt_addstring(pktout, signame);
11577 ssh2_pkt_send(ssh, pktout);
11578 logeventf(ssh, "Sent signal SIG%s", signame);
11581 /* Never heard of it. Do nothing */
11586 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11588 Ssh ssh = (Ssh) handle;
11589 struct ssh_channel *c;
11590 c = snew(struct ssh_channel);
11593 ssh2_channel_init(c);
11594 c->halfopen = TRUE;
11595 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11597 add234(ssh->channels, c);
11601 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11603 struct ssh_channel *c;
11604 c = snew(struct ssh_channel);
11607 ssh2_channel_init(c);
11608 c->type = CHAN_SHARING;
11609 c->u.sharing.ctx = sharing_ctx;
11610 add234(ssh->channels, c);
11614 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11616 struct ssh_channel *c;
11618 c = find234(ssh->channels, &localid, ssh_channelfind);
11620 ssh_channel_destroy(c);
11623 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11624 const void *data, int datalen,
11625 const char *additional_log_text)
11627 struct Packet *pkt;
11629 pkt = ssh2_pkt_init(type);
11630 pkt->downstream_id = id;
11631 pkt->additional_log_text = additional_log_text;
11632 ssh2_pkt_adddata(pkt, data, datalen);
11633 ssh2_pkt_send(ssh, pkt);
11637 * This is called when stdout/stderr (the entity to which
11638 * from_backend sends data) manages to clear some backlog.
11640 static void ssh_unthrottle(void *handle, int bufsize)
11642 Ssh ssh = (Ssh) handle;
11645 if (ssh->version == 1) {
11646 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11647 ssh->v1_stdout_throttling = 0;
11648 ssh_throttle_conn(ssh, -1);
11651 if (ssh->mainchan) {
11652 ssh2_set_window(ssh->mainchan,
11653 bufsize < ssh->mainchan->v.v2.locmaxwin ?
11654 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11655 if (ssh_is_simple(ssh))
11658 buflimit = ssh->mainchan->v.v2.locmaxwin;
11659 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11660 ssh->mainchan->throttling_conn = 0;
11661 ssh_throttle_conn(ssh, -1);
11667 * Now process any SSH connection data that was stashed in our
11668 * queue while we were frozen.
11670 ssh_process_queued_incoming_data(ssh);
11673 void ssh_send_port_open(void *channel, const char *hostname, int port,
11676 struct ssh_channel *c = (struct ssh_channel *)channel;
11678 struct Packet *pktout;
11680 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11682 if (ssh->version == 1) {
11683 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11684 PKT_INT, c->localid,
11687 /* PKT_STR, <org:orgport>, */
11690 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11692 char *trimmed_host = host_strduptrim(hostname);
11693 ssh2_pkt_addstring(pktout, trimmed_host);
11694 sfree(trimmed_host);
11696 ssh2_pkt_adduint32(pktout, port);
11698 * We make up values for the originator data; partly it's
11699 * too much hassle to keep track, and partly I'm not
11700 * convinced the server should be told details like that
11701 * about my local network configuration.
11702 * The "originator IP address" is syntactically a numeric
11703 * IP address, and some servers (e.g., Tectia) get upset
11704 * if it doesn't match this syntax.
11706 ssh2_pkt_addstring(pktout, "0.0.0.0");
11707 ssh2_pkt_adduint32(pktout, 0);
11708 ssh2_pkt_send(ssh, pktout);
11712 static int ssh_connected(void *handle)
11714 Ssh ssh = (Ssh) handle;
11715 return ssh->s != NULL;
11718 static int ssh_sendok(void *handle)
11720 Ssh ssh = (Ssh) handle;
11721 return ssh->send_ok;
11724 static int ssh_ldisc(void *handle, int option)
11726 Ssh ssh = (Ssh) handle;
11727 if (option == LD_ECHO)
11728 return ssh->echoing;
11729 if (option == LD_EDIT)
11730 return ssh->editing;
11734 static void ssh_provide_ldisc(void *handle, void *ldisc)
11736 Ssh ssh = (Ssh) handle;
11737 ssh->ldisc = ldisc;
11740 static void ssh_provide_logctx(void *handle, void *logctx)
11742 Ssh ssh = (Ssh) handle;
11743 ssh->logctx = logctx;
11746 static int ssh_return_exitcode(void *handle)
11748 Ssh ssh = (Ssh) handle;
11749 if (ssh->s != NULL)
11752 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11756 * cfg_info for SSH is the protocol running in this session.
11757 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11758 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11760 static int ssh_cfg_info(void *handle)
11762 Ssh ssh = (Ssh) handle;
11763 if (ssh->version == 0)
11764 return 0; /* don't know yet */
11765 else if (ssh->bare_connection)
11768 return ssh->version;
11772 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11773 * that fails. This variable is the means by which scp.c can reach
11774 * into the SSH code and find out which one it got.
11776 extern int ssh_fallback_cmd(void *handle)
11778 Ssh ssh = (Ssh) handle;
11779 return ssh->fallback_cmd;
11782 Backend ssh_backend = {
11792 ssh_return_exitcode,
11796 ssh_provide_logctx,
11799 ssh_test_for_upstream,