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
92 static const struct ssh_ttymode {
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 { "IUTF8", 42, TTY_OP_BOOL },
129 { "ISIG", 50, TTY_OP_BOOL },
130 { "ICANON", 51, TTY_OP_BOOL },
131 { "XCASE", 52, TTY_OP_BOOL },
132 { "ECHO", 53, TTY_OP_BOOL },
133 { "ECHOE", 54, TTY_OP_BOOL },
134 { "ECHOK", 55, TTY_OP_BOOL },
135 { "ECHONL", 56, TTY_OP_BOOL },
136 { "NOFLSH", 57, TTY_OP_BOOL },
137 { "TOSTOP", 58, TTY_OP_BOOL },
138 { "IEXTEN", 59, TTY_OP_BOOL },
139 { "ECHOCTL", 60, TTY_OP_BOOL },
140 { "ECHOKE", 61, TTY_OP_BOOL },
141 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
142 { "OPOST", 70, TTY_OP_BOOL },
143 { "OLCUC", 71, TTY_OP_BOOL },
144 { "ONLCR", 72, TTY_OP_BOOL },
145 { "OCRNL", 73, TTY_OP_BOOL },
146 { "ONOCR", 74, TTY_OP_BOOL },
147 { "ONLRET", 75, TTY_OP_BOOL },
148 { "CS7", 90, TTY_OP_BOOL },
149 { "CS8", 91, TTY_OP_BOOL },
150 { "PARENB", 92, TTY_OP_BOOL },
151 { "PARODD", 93, TTY_OP_BOOL }
154 /* Miscellaneous other tty-related constants. */
155 #define SSH_TTY_OP_END 0
156 /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
157 #define SSH1_TTY_OP_ISPEED 192
158 #define SSH1_TTY_OP_OSPEED 193
159 #define SSH2_TTY_OP_ISPEED 128
160 #define SSH2_TTY_OP_OSPEED 129
162 /* Helper functions for parsing tty-related config. */
163 static unsigned int ssh_tty_parse_specchar(char *s)
168 ret = ctrlparse(s, &next);
169 if (!next) ret = s[0];
171 ret = 255; /* special value meaning "don't set" */
175 static unsigned int ssh_tty_parse_boolean(char *s)
177 if (stricmp(s, "yes") == 0 ||
178 stricmp(s, "on") == 0 ||
179 stricmp(s, "true") == 0 ||
180 stricmp(s, "+") == 0)
182 else if (stricmp(s, "no") == 0 ||
183 stricmp(s, "off") == 0 ||
184 stricmp(s, "false") == 0 ||
185 stricmp(s, "-") == 0)
186 return 0; /* false */
188 return (atoi(s) != 0);
191 #define translate(x) if (type == x) return #x
192 #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
193 #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
194 static const char *ssh1_pkt_type(int type)
196 translate(SSH1_MSG_DISCONNECT);
197 translate(SSH1_SMSG_PUBLIC_KEY);
198 translate(SSH1_CMSG_SESSION_KEY);
199 translate(SSH1_CMSG_USER);
200 translate(SSH1_CMSG_AUTH_RSA);
201 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
202 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
203 translate(SSH1_CMSG_AUTH_PASSWORD);
204 translate(SSH1_CMSG_REQUEST_PTY);
205 translate(SSH1_CMSG_WINDOW_SIZE);
206 translate(SSH1_CMSG_EXEC_SHELL);
207 translate(SSH1_CMSG_EXEC_CMD);
208 translate(SSH1_SMSG_SUCCESS);
209 translate(SSH1_SMSG_FAILURE);
210 translate(SSH1_CMSG_STDIN_DATA);
211 translate(SSH1_SMSG_STDOUT_DATA);
212 translate(SSH1_SMSG_STDERR_DATA);
213 translate(SSH1_CMSG_EOF);
214 translate(SSH1_SMSG_EXIT_STATUS);
215 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
216 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
217 translate(SSH1_MSG_CHANNEL_DATA);
218 translate(SSH1_MSG_CHANNEL_CLOSE);
219 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
220 translate(SSH1_SMSG_X11_OPEN);
221 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
222 translate(SSH1_MSG_PORT_OPEN);
223 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
224 translate(SSH1_SMSG_AGENT_OPEN);
225 translate(SSH1_MSG_IGNORE);
226 translate(SSH1_CMSG_EXIT_CONFIRMATION);
227 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
228 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
229 translate(SSH1_MSG_DEBUG);
230 translate(SSH1_CMSG_REQUEST_COMPRESSION);
231 translate(SSH1_CMSG_AUTH_TIS);
232 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
233 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
234 translate(SSH1_CMSG_AUTH_CCARD);
235 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
236 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
239 static const char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx,
242 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
243 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
244 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
245 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
246 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
247 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
248 translate(SSH2_MSG_DISCONNECT);
249 translate(SSH2_MSG_IGNORE);
250 translate(SSH2_MSG_UNIMPLEMENTED);
251 translate(SSH2_MSG_DEBUG);
252 translate(SSH2_MSG_SERVICE_REQUEST);
253 translate(SSH2_MSG_SERVICE_ACCEPT);
254 translate(SSH2_MSG_KEXINIT);
255 translate(SSH2_MSG_NEWKEYS);
256 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
257 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
258 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD, SSH2_PKTCTX_DHGEX);
259 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
260 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
261 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
262 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
263 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
264 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
265 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
266 translatek(SSH2_MSG_KEX_ECDH_INIT, SSH2_PKTCTX_ECDHKEX);
267 translatek(SSH2_MSG_KEX_ECDH_REPLY, SSH2_PKTCTX_ECDHKEX);
268 translate(SSH2_MSG_USERAUTH_REQUEST);
269 translate(SSH2_MSG_USERAUTH_FAILURE);
270 translate(SSH2_MSG_USERAUTH_SUCCESS);
271 translate(SSH2_MSG_USERAUTH_BANNER);
272 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
273 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
274 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
275 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
276 translate(SSH2_MSG_GLOBAL_REQUEST);
277 translate(SSH2_MSG_REQUEST_SUCCESS);
278 translate(SSH2_MSG_REQUEST_FAILURE);
279 translate(SSH2_MSG_CHANNEL_OPEN);
280 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
281 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
282 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
283 translate(SSH2_MSG_CHANNEL_DATA);
284 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
285 translate(SSH2_MSG_CHANNEL_EOF);
286 translate(SSH2_MSG_CHANNEL_CLOSE);
287 translate(SSH2_MSG_CHANNEL_REQUEST);
288 translate(SSH2_MSG_CHANNEL_SUCCESS);
289 translate(SSH2_MSG_CHANNEL_FAILURE);
295 /* Enumeration values for fields in SSH-1 packets */
297 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
301 * Coroutine mechanics for the sillier bits of the code. If these
302 * macros look impenetrable to you, you might find it helpful to
305 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
307 * which explains the theory behind these macros.
309 * In particular, if you are getting `case expression not constant'
310 * errors when building with MS Visual Studio, this is because MS's
311 * Edit and Continue debugging feature causes their compiler to
312 * violate ANSI C. To disable Edit and Continue debugging:
314 * - right-click ssh.c in the FileView
316 * - select the C/C++ tab and the General category
317 * - under `Debug info:', select anything _other_ than `Program
318 * Database for Edit and Continue'.
320 #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
321 #define crBeginState crBegin(s->crLine)
322 #define crStateP(t, v) \
324 if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
326 #define crState(t) crStateP(t, ssh->t)
327 #define crFinish(z) } *crLine = 0; return (z); }
328 #define crFinishV } *crLine = 0; return; }
329 #define crFinishFree(z) } sfree(s); return (z); }
330 #define crFinishFreeV } sfree(s); return; }
331 #define crReturn(z) \
333 *crLine =__LINE__; return (z); case __LINE__:;\
337 *crLine=__LINE__; return; case __LINE__:;\
339 #define crStop(z) do{ *crLine = 0; return (z); }while(0)
340 #define crStopV do{ *crLine = 0; return; }while(0)
341 #define crWaitUntil(c) do { crReturn(0); } while (!(c))
342 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
346 static struct Packet *ssh1_pkt_init(int pkt_type);
347 static struct Packet *ssh2_pkt_init(int pkt_type);
348 static void ssh_pkt_ensure(struct Packet *, int length);
349 static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
350 static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
351 static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
352 static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
353 static void ssh_pkt_addstring_start(struct Packet *);
354 static void ssh_pkt_addstring_str(struct Packet *, const char *data);
355 static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
356 static void ssh_pkt_addstring(struct Packet *, const char *data);
357 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
358 static void ssh1_pkt_addmp(struct Packet *, Bignum b);
359 static void ssh2_pkt_addmp(struct Packet *, Bignum b);
360 static int ssh2_pkt_construct(Ssh, struct Packet *);
361 static void ssh2_pkt_send(Ssh, struct Packet *);
362 static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
363 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
364 struct Packet *pktin);
365 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
366 struct Packet *pktin);
367 static void ssh2_channel_check_close(struct ssh_channel *c);
368 static void ssh_channel_destroy(struct ssh_channel *c);
369 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin);
372 * Buffer management constants. There are several of these for
373 * various different purposes:
375 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
376 * on a local data stream before we throttle the whole SSH
377 * connection (in SSH-1 only). Throttling the whole connection is
378 * pretty drastic so we set this high in the hope it won't
381 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
382 * on the SSH connection itself before we defensively throttle
383 * _all_ local data streams. This is pretty drastic too (though
384 * thankfully unlikely in SSH-2 since the window mechanism should
385 * ensure that the server never has any need to throttle its end
386 * of the connection), so we set this high as well.
388 * - OUR_V2_WINSIZE is the default window size we present on SSH-2
391 * - OUR_V2_BIGWIN is the window size we advertise for the only
392 * channel in a simple connection. It must be <= INT_MAX.
394 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
395 * to the remote side. This actually has nothing to do with the
396 * size of the _packet_, but is instead a limit on the amount
397 * of data we're willing to receive in a single SSH2 channel
400 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
401 * _packet_ we're prepared to cope with. It must be a multiple
402 * of the cipher block size, and must be at least 35000.
405 #define SSH1_BUFFER_LIMIT 32768
406 #define SSH_MAX_BACKLOG 32768
407 #define OUR_V2_WINSIZE 16384
408 #define OUR_V2_BIGWIN 0x7fffffff
409 #define OUR_V2_MAXPKT 0x4000UL
410 #define OUR_V2_PACKETLIMIT 0x9000UL
412 struct ssh_signkey_with_user_pref_id {
413 const struct ssh_signkey *alg;
416 const static struct ssh_signkey_with_user_pref_id hostkey_algs[] = {
417 { &ssh_ecdsa_ed25519, HK_ED25519 },
418 { &ssh_ecdsa_nistp256, HK_ECDSA },
419 { &ssh_ecdsa_nistp384, HK_ECDSA },
420 { &ssh_ecdsa_nistp521, HK_ECDSA },
421 { &ssh_dss, HK_DSA },
422 { &ssh_rsa, HK_RSA },
425 const static struct ssh_mac *const macs[] = {
426 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
428 const static struct ssh_mac *const buggymacs[] = {
429 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
432 static void *ssh_comp_none_init(void)
436 static void ssh_comp_none_cleanup(void *handle)
439 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
440 unsigned char **outblock, int *outlen)
444 static int ssh_comp_none_disable(void *handle)
448 const static struct ssh_compress ssh_comp_none = {
450 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
451 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
452 ssh_comp_none_disable, NULL
454 extern const struct ssh_compress ssh_zlib;
455 const static struct ssh_compress *const compressions[] = {
456 &ssh_zlib, &ssh_comp_none
459 enum { /* channel types */
464 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
466 * CHAN_SHARING indicates a channel which is tracked here on
467 * behalf of a connection-sharing downstream. We do almost nothing
468 * with these channels ourselves: all messages relating to them
469 * get thrown straight to sshshare.c and passed on almost
470 * unmodified to downstream.
474 * CHAN_ZOMBIE is used to indicate a channel for which we've
475 * already destroyed the local data source: for instance, if a
476 * forwarded port experiences a socket error on the local side, we
477 * immediately destroy its local socket and turn the SSH channel
483 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
484 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
485 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
488 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
491 struct outstanding_channel_request {
492 cchandler_fn_t handler;
494 struct outstanding_channel_request *next;
498 * 2-3-4 tree storing channels.
501 Ssh ssh; /* pointer back to main context */
502 unsigned remoteid, localid;
504 /* True if we opened this channel but server hasn't confirmed. */
507 * In SSH-1, this value contains four bits:
509 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
510 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
511 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
512 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
514 * A channel is completely finished with when all four bits are set.
516 * In SSH-2, the four bits mean:
518 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
519 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
520 * 4 We have received SSH2_MSG_CHANNEL_EOF.
521 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
523 * A channel is completely finished with when we have both sent
524 * and received CLOSE.
526 * The symbolic constants below use the SSH-2 terminology, which
527 * is a bit confusing in SSH-1, but we have to use _something_.
529 #define CLOSES_SENT_EOF 1
530 #define CLOSES_SENT_CLOSE 2
531 #define CLOSES_RCVD_EOF 4
532 #define CLOSES_RCVD_CLOSE 8
536 * This flag indicates that an EOF is pending on the outgoing side
537 * of the channel: that is, wherever we're getting the data for
538 * this channel has sent us some data followed by EOF. We can't
539 * actually send the EOF until we've finished sending the data, so
540 * we set this flag instead to remind us to do so once our buffer
546 * True if this channel is causing the underlying connection to be
551 struct ssh2_data_channel {
553 unsigned remwindow, remmaxpkt;
554 /* locwindow is signed so we can cope with excess data. */
555 int locwindow, locmaxwin;
557 * remlocwin is the amount of local window that we think
558 * the remote end had available to it after it sent the
559 * last data packet or window adjust ack.
563 * These store the list of channel requests that haven't
566 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
567 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
571 struct ssh_agent_channel {
572 unsigned char *message;
573 unsigned char msglen[4];
574 unsigned lensofar, totallen;
575 int outstanding_requests;
577 struct ssh_x11_channel {
578 struct X11Connection *xconn;
581 struct ssh_pfd_channel {
582 struct PortForwarding *pf;
584 struct ssh_sharing_channel {
591 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
592 * use this structure in different ways, reflecting SSH-2's
593 * altogether saner approach to port forwarding.
595 * In SSH-1, you arrange a remote forwarding by sending the server
596 * the remote port number, and the local destination host:port.
597 * When a connection comes in, the server sends you back that
598 * host:port pair, and you connect to it. This is a ready-made
599 * security hole if you're not on the ball: a malicious server
600 * could send you back _any_ host:port pair, so if you trustingly
601 * connect to the address it gives you then you've just opened the
602 * entire inside of your corporate network just by connecting
603 * through it to a dodgy SSH server. Hence, we must store a list of
604 * host:port pairs we _are_ trying to forward to, and reject a
605 * connection request from the server if it's not in the list.
607 * In SSH-2, each side of the connection minds its own business and
608 * doesn't send unnecessary information to the other. You arrange a
609 * remote forwarding by sending the server just the remote port
610 * number. When a connection comes in, the server tells you which
611 * of its ports was connected to; and _you_ have to remember what
612 * local host:port pair went with that port number.
614 * Hence, in SSH-1 this structure is indexed by destination
615 * host:port pair, whereas in SSH-2 it is indexed by source port.
617 struct ssh_portfwd; /* forward declaration */
619 struct ssh_rportfwd {
620 unsigned sport, dport;
624 struct ssh_portfwd *pfrec;
627 static void free_rportfwd(struct ssh_rportfwd *pf)
630 sfree(pf->sportdesc);
638 * Separately to the rportfwd tree (which is for looking up port
639 * open requests from the server), a tree of _these_ structures is
640 * used to keep track of all the currently open port forwardings,
641 * so that we can reconfigure in mid-session if the user requests
645 enum { DESTROY, KEEP, CREATE } status;
647 unsigned sport, dport;
650 struct ssh_rportfwd *remote;
652 struct PortListener *local;
654 #define free_portfwd(pf) ( \
655 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
656 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
659 long length; /* length of packet: see below */
660 long forcepad; /* SSH-2: force padding to at least this length */
661 int type; /* only used for incoming packets */
662 unsigned long sequence; /* SSH-2 incoming sequence number */
663 unsigned char *data; /* allocated storage */
664 unsigned char *body; /* offset of payload within `data' */
665 long savedpos; /* dual-purpose saved packet position: see below */
666 long maxlen; /* amount of storage allocated for `data' */
667 long encrypted_len; /* for SSH-2 total-size counting */
670 * A note on the 'length' and 'savedpos' fields above.
672 * Incoming packets are set up so that pkt->length is measured
673 * relative to pkt->body, which itself points to a few bytes after
674 * pkt->data (skipping some uninteresting header fields including
675 * the packet type code). The ssh_pkt_get* functions all expect
676 * this setup, and they also use pkt->savedpos to indicate how far
677 * through the packet being decoded they've got - and that, too,
678 * is an offset from pkt->body rather than pkt->data.
680 * During construction of an outgoing packet, however, pkt->length
681 * is measured relative to the base pointer pkt->data, and
682 * pkt->body is not really used for anything until the packet is
683 * ready for sending. In this mode, pkt->savedpos is reused as a
684 * temporary variable by the addstring functions, which write out
685 * a string length field and then keep going back and updating it
686 * as more data is appended to the subsequent string data field;
687 * pkt->savedpos stores the offset (again relative to pkt->data)
688 * of the start of the string data field.
691 /* Extra metadata used in SSH packet logging mode, allowing us to
692 * log in the packet header line that the packet came from a
693 * connection-sharing downstream and what if anything unusual was
694 * done to it. The additional_log_text field is expected to be a
695 * static string - it will not be freed. */
696 unsigned downstream_id;
697 const char *additional_log_text;
700 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
701 struct Packet *pktin);
702 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
703 struct Packet *pktin);
704 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
705 struct Packet *pktin);
706 static void ssh1_protocol_setup(Ssh ssh);
707 static void ssh2_protocol_setup(Ssh ssh);
708 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
709 static void ssh_size(void *handle, int width, int height);
710 static void ssh_special(void *handle, Telnet_Special);
711 static int ssh2_try_send(struct ssh_channel *c);
712 static int ssh_send_channel_data(struct ssh_channel *c,
713 const char *buf, int len);
714 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
715 static void ssh2_set_window(struct ssh_channel *c, int newwin);
716 static int ssh_sendbuffer(void *handle);
717 static int ssh_do_close(Ssh ssh, int notify_exit);
718 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
719 static int ssh2_pkt_getbool(struct Packet *pkt);
720 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
721 static void ssh2_timer(void *ctx, unsigned long now);
722 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
723 struct Packet *pktin);
724 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
726 struct rdpkt1_state_tag {
727 long len, pad, biglen, to_read;
728 unsigned long realcrc, gotcrc;
732 struct Packet *pktin;
735 struct rdpkt2_state_tag {
736 long len, pad, payload, packetlen, maclen;
739 unsigned long incoming_sequence;
740 struct Packet *pktin;
743 struct rdpkt2_bare_state_tag {
747 unsigned long incoming_sequence;
748 struct Packet *pktin;
751 struct queued_handler;
752 struct queued_handler {
754 chandler_fn_t handler;
756 struct queued_handler *next;
760 const struct plug_function_table *fn;
761 /* the above field _must_ be first in the structure */
771 unsigned char session_key[32];
773 int v1_remote_protoflags;
774 int v1_local_protoflags;
775 int agentfwd_enabled;
778 const struct ssh_cipher *cipher;
781 const struct ssh2_cipher *cscipher, *sccipher;
782 void *cs_cipher_ctx, *sc_cipher_ctx;
783 const struct ssh_mac *csmac, *scmac;
784 int csmac_etm, scmac_etm;
785 void *cs_mac_ctx, *sc_mac_ctx;
786 const struct ssh_compress *cscomp, *sccomp;
787 void *cs_comp_ctx, *sc_comp_ctx;
788 const struct ssh_kex *kex;
789 const struct ssh_signkey *hostkey;
790 char *hostkey_str; /* string representation, for easy checking in rekeys */
791 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
792 int v2_session_id_len;
796 int attempting_connshare;
802 int echoing, editing;
807 int ospeed, ispeed; /* temporaries */
808 int term_width, term_height;
810 tree234 *channels; /* indexed by local id */
811 struct ssh_channel *mainchan; /* primary session channel */
812 int ncmode; /* is primary channel direct-tcpip? */
817 tree234 *rportfwds, *portfwds;
821 SSH_STATE_BEFORE_SIZE,
827 int size_needed, eof_needed;
828 int sent_console_eof;
829 int got_pty; /* affects EOF behaviour on main channel */
831 struct Packet **queue;
832 int queuelen, queuesize;
834 unsigned char *deferred_send_data;
835 int deferred_len, deferred_size;
838 * Gross hack: pscp will try to start SFTP but fall back to
839 * scp1 if that fails. This variable is the means by which
840 * scp.c can reach into the SSH code and find out which one it
845 bufchain banner; /* accumulates banners during do_ssh2_authconn */
850 struct X11Display *x11disp;
851 struct X11FakeAuth *x11auth;
852 tree234 *x11authtree;
855 int conn_throttle_count;
858 int v1_stdout_throttling;
859 unsigned long v2_outgoing_sequence;
861 int ssh1_rdpkt_crstate;
862 int ssh2_rdpkt_crstate;
863 int ssh2_bare_rdpkt_crstate;
864 int ssh_gotdata_crstate;
865 int do_ssh1_connection_crstate;
867 void *do_ssh_init_state;
868 void *do_ssh1_login_state;
869 void *do_ssh2_transport_state;
870 void *do_ssh2_authconn_state;
871 void *do_ssh_connection_init_state;
873 struct rdpkt1_state_tag rdpkt1_state;
874 struct rdpkt2_state_tag rdpkt2_state;
875 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
877 /* SSH-1 and SSH-2 use this for different things, but both use it */
878 int protocol_initial_phase_done;
880 void (*protocol) (Ssh ssh, const void *vin, int inlen,
882 struct Packet *(*s_rdpkt) (Ssh ssh, const unsigned char **data,
884 int (*do_ssh_init)(Ssh ssh, unsigned char c);
887 * We maintain our own copy of a Conf structure here. That way,
888 * when we're passed a new one for reconfiguration, we can check
889 * the differences and potentially reconfigure port forwardings
890 * etc in mid-session.
895 * Values cached out of conf so as to avoid the tree234 lookup
896 * cost every time they're used.
901 * Dynamically allocated username string created during SSH
902 * login. Stored in here rather than in the coroutine state so
903 * that it'll be reliably freed if we shut down the SSH session
904 * at some unexpected moment.
909 * Used to transfer data back from async callbacks.
911 void *agent_response;
912 int agent_response_len;
916 * The SSH connection can be set as `frozen', meaning we are
917 * not currently accepting incoming data from the network. This
918 * is slightly more serious than setting the _socket_ as
919 * frozen, because we may already have had data passed to us
920 * from the network which we need to delay processing until
921 * after the freeze is lifted, so we also need a bufchain to
925 bufchain queued_incoming_data;
928 * Dispatch table for packet types that we may have to deal
931 handler_fn_t packet_dispatch[256];
934 * Queues of one-off handler functions for success/failure
935 * indications from a request.
937 struct queued_handler *qhead, *qtail;
938 handler_fn_t q_saved_handler1, q_saved_handler2;
941 * This module deals with sending keepalives.
946 * Track incoming and outgoing data sizes and time, for
949 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
950 unsigned long max_data_size;
952 unsigned long next_rekey, last_rekey;
953 const char *deferred_rekey_reason;
956 * Fully qualified host name, which we need if doing GSSAPI.
962 * GSSAPI libraries for this session.
964 struct ssh_gss_liblist *gsslibs;
968 * The last list returned from get_specials.
970 struct telnet_special *specials;
973 * List of host key algorithms for which we _don't_ have a stored
974 * host key. These are indices into the main hostkey_algs[] array
976 int uncert_hostkeys[lenof(hostkey_algs)];
977 int n_uncert_hostkeys;
980 * Flag indicating that the current rekey is intended to finish
981 * with a newly cross-certified host key.
983 int cross_certifying;
986 #define logevent(s) logevent(ssh->frontend, s)
988 /* logevent, only printf-formatted. */
989 static void logeventf(Ssh ssh, const char *fmt, ...)
995 buf = dupvprintf(fmt, ap);
1001 static void bomb_out(Ssh ssh, char *text)
1003 ssh_do_close(ssh, FALSE);
1005 connection_fatal(ssh->frontend, "%s", text);
1009 #define bombout(msg) bomb_out(ssh, dupprintf msg)
1011 /* Helper function for common bits of parsing ttymodes. */
1012 static void parse_ttymodes(Ssh ssh,
1013 void (*do_mode)(void *data,
1014 const struct ssh_ttymode *mode,
1019 const struct ssh_ttymode *mode;
1021 char default_val[2];
1023 strcpy(default_val, "A");
1025 for (i = 0; i < lenof(ssh_ttymodes); i++) {
1026 mode = ssh_ttymodes + i;
1027 val = conf_get_str_str_opt(ssh->conf, CONF_ttymodes, mode->mode);
1032 * val[0] is either 'V', indicating that an explicit value
1033 * follows it, or 'A' indicating that we should pass the
1034 * value through from the local environment via get_ttymode.
1036 if (val[0] == 'A') {
1037 val = get_ttymode(ssh->frontend, mode->mode);
1039 do_mode(data, mode, val);
1043 do_mode(data, mode, val + 1); /* skip the 'V' */
1047 static int ssh_channelcmp(void *av, void *bv)
1049 struct ssh_channel *a = (struct ssh_channel *) av;
1050 struct ssh_channel *b = (struct ssh_channel *) bv;
1051 if (a->localid < b->localid)
1053 if (a->localid > b->localid)
1057 static int ssh_channelfind(void *av, void *bv)
1059 unsigned *a = (unsigned *) av;
1060 struct ssh_channel *b = (struct ssh_channel *) bv;
1061 if (*a < b->localid)
1063 if (*a > b->localid)
1068 static int ssh_rportcmp_ssh1(void *av, void *bv)
1070 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1071 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1073 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1074 return i < 0 ? -1 : +1;
1075 if (a->dport > b->dport)
1077 if (a->dport < b->dport)
1082 static int ssh_rportcmp_ssh2(void *av, void *bv)
1084 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1085 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1087 if ( (i = strcmp(a->shost, b->shost)) != 0)
1088 return i < 0 ? -1 : +1;
1089 if (a->sport > b->sport)
1091 if (a->sport < b->sport)
1097 * Special form of strcmp which can cope with NULL inputs. NULL is
1098 * defined to sort before even the empty string.
1100 static int nullstrcmp(const char *a, const char *b)
1102 if (a == NULL && b == NULL)
1108 return strcmp(a, b);
1111 static int ssh_portcmp(void *av, void *bv)
1113 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1114 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1116 if (a->type > b->type)
1118 if (a->type < b->type)
1120 if (a->addressfamily > b->addressfamily)
1122 if (a->addressfamily < b->addressfamily)
1124 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1125 return i < 0 ? -1 : +1;
1126 if (a->sport > b->sport)
1128 if (a->sport < b->sport)
1130 if (a->type != 'D') {
1131 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1132 return i < 0 ? -1 : +1;
1133 if (a->dport > b->dport)
1135 if (a->dport < b->dport)
1141 static int alloc_channel_id(Ssh ssh)
1143 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1144 unsigned low, high, mid;
1146 struct ssh_channel *c;
1149 * First-fit allocation of channel numbers: always pick the
1150 * lowest unused one. To do this, binary-search using the
1151 * counted B-tree to find the largest channel ID which is in a
1152 * contiguous sequence from the beginning. (Precisely
1153 * everything in that sequence must have ID equal to its tree
1154 * index plus CHANNEL_NUMBER_OFFSET.)
1156 tsize = count234(ssh->channels);
1160 while (high - low > 1) {
1161 mid = (high + low) / 2;
1162 c = index234(ssh->channels, mid);
1163 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1164 low = mid; /* this one is fine */
1166 high = mid; /* this one is past it */
1169 * Now low points to either -1, or the tree index of the
1170 * largest ID in the initial sequence.
1173 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1174 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1176 return low + 1 + CHANNEL_NUMBER_OFFSET;
1179 static void c_write_stderr(int trusted, const char *buf, int len)
1182 for (i = 0; i < len; i++)
1183 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1184 fputc(buf[i], stderr);
1187 static void c_write(Ssh ssh, const char *buf, int len)
1189 if (flags & FLAG_STDERR)
1190 c_write_stderr(1, buf, len);
1192 from_backend(ssh->frontend, 1, buf, len);
1195 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1197 if (flags & FLAG_STDERR)
1198 c_write_stderr(0, buf, len);
1200 from_backend_untrusted(ssh->frontend, buf, len);
1203 static void c_write_str(Ssh ssh, const char *buf)
1205 c_write(ssh, buf, strlen(buf));
1208 static void ssh_free_packet(struct Packet *pkt)
1213 static struct Packet *ssh_new_packet(void)
1215 struct Packet *pkt = snew(struct Packet);
1217 pkt->body = pkt->data = NULL;
1223 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1226 struct logblank_t blanks[4];
1232 if (ssh->logomitdata &&
1233 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1234 pkt->type == SSH1_SMSG_STDERR_DATA ||
1235 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1236 /* "Session data" packets - omit the data string. */
1237 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1238 ssh_pkt_getuint32(pkt); /* skip channel id */
1239 blanks[nblanks].offset = pkt->savedpos + 4;
1240 blanks[nblanks].type = PKTLOG_OMIT;
1241 ssh_pkt_getstring(pkt, &str, &slen);
1243 blanks[nblanks].len = slen;
1247 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1248 ssh1_pkt_type(pkt->type),
1249 pkt->body, pkt->length, nblanks, blanks, NULL,
1253 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1256 struct logblank_t blanks[4];
1261 * For outgoing packets, pkt->length represents the length of the
1262 * whole packet starting at pkt->data (including some header), and
1263 * pkt->body refers to the point within that where the log-worthy
1264 * payload begins. However, incoming packets expect pkt->length to
1265 * represent only the payload length (that is, it's measured from
1266 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1267 * packet to conform to the incoming-packet semantics, so that we
1268 * can analyse it with the ssh_pkt_get functions.
1270 pkt->length -= (pkt->body - pkt->data);
1273 if (ssh->logomitdata &&
1274 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1275 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1276 /* "Session data" packets - omit the data string. */
1277 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1278 ssh_pkt_getuint32(pkt); /* skip channel id */
1279 blanks[nblanks].offset = pkt->savedpos + 4;
1280 blanks[nblanks].type = PKTLOG_OMIT;
1281 ssh_pkt_getstring(pkt, &str, &slen);
1283 blanks[nblanks].len = slen;
1288 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1289 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1290 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1291 conf_get_int(ssh->conf, CONF_logomitpass)) {
1292 /* If this is a password or similar packet, blank the password(s). */
1293 blanks[nblanks].offset = 0;
1294 blanks[nblanks].len = pkt->length;
1295 blanks[nblanks].type = PKTLOG_BLANK;
1297 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1298 conf_get_int(ssh->conf, CONF_logomitpass)) {
1300 * If this is an X forwarding request packet, blank the fake
1303 * Note that while we blank the X authentication data here, we
1304 * don't take any special action to blank the start of an X11
1305 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1306 * an X connection without having session blanking enabled is
1307 * likely to leak your cookie into the log.
1310 ssh_pkt_getstring(pkt, &str, &slen);
1311 blanks[nblanks].offset = pkt->savedpos;
1312 blanks[nblanks].type = PKTLOG_BLANK;
1313 ssh_pkt_getstring(pkt, &str, &slen);
1315 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1320 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1321 ssh1_pkt_type(pkt->data[12]),
1322 pkt->body, pkt->length,
1323 nblanks, blanks, NULL, 0, NULL);
1326 * Undo the above adjustment of pkt->length, to put the packet
1327 * back in the state we found it.
1329 pkt->length += (pkt->body - pkt->data);
1333 * Collect incoming data in the incoming packet buffer.
1334 * Decipher and verify the packet when it is completely read.
1335 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1336 * Update the *data and *datalen variables.
1337 * Return a Packet structure when a packet is completed.
1339 static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
1342 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1344 crBegin(ssh->ssh1_rdpkt_crstate);
1346 st->pktin = ssh_new_packet();
1348 st->pktin->type = 0;
1349 st->pktin->length = 0;
1351 for (st->i = st->len = 0; st->i < 4; st->i++) {
1352 while ((*datalen) == 0)
1354 st->len = (st->len << 8) + **data;
1355 (*data)++, (*datalen)--;
1358 st->pad = 8 - (st->len % 8);
1359 st->biglen = st->len + st->pad;
1360 st->pktin->length = st->len - 5;
1362 if (st->biglen < 0) {
1363 bombout(("Extremely large packet length from server suggests"
1364 " data stream corruption"));
1365 ssh_free_packet(st->pktin);
1369 st->pktin->maxlen = st->biglen;
1370 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1372 st->to_read = st->biglen;
1373 st->p = st->pktin->data;
1374 while (st->to_read > 0) {
1375 st->chunk = st->to_read;
1376 while ((*datalen) == 0)
1378 if (st->chunk > (*datalen))
1379 st->chunk = (*datalen);
1380 memcpy(st->p, *data, st->chunk);
1382 *datalen -= st->chunk;
1384 st->to_read -= st->chunk;
1387 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1388 st->biglen, NULL)) {
1389 bombout(("Network attack (CRC compensation) detected!"));
1390 ssh_free_packet(st->pktin);
1395 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1397 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1398 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1399 if (st->gotcrc != st->realcrc) {
1400 bombout(("Incorrect CRC received on packet"));
1401 ssh_free_packet(st->pktin);
1405 st->pktin->body = st->pktin->data + st->pad + 1;
1407 if (ssh->v1_compressing) {
1408 unsigned char *decompblk;
1410 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1411 st->pktin->body - 1, st->pktin->length + 1,
1412 &decompblk, &decomplen)) {
1413 bombout(("Zlib decompression encountered invalid data"));
1414 ssh_free_packet(st->pktin);
1418 if (st->pktin->maxlen < st->pad + decomplen) {
1419 st->pktin->maxlen = st->pad + decomplen;
1420 st->pktin->data = sresize(st->pktin->data,
1421 st->pktin->maxlen + APIEXTRA,
1423 st->pktin->body = st->pktin->data + st->pad + 1;
1426 memcpy(st->pktin->body - 1, decompblk, decomplen);
1428 st->pktin->length = decomplen - 1;
1431 st->pktin->type = st->pktin->body[-1];
1434 * Now pktin->body and pktin->length identify the semantic content
1435 * of the packet, excluding the initial type byte.
1439 ssh1_log_incoming_packet(ssh, st->pktin);
1441 st->pktin->savedpos = 0;
1443 crFinish(st->pktin);
1446 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1449 struct logblank_t blanks[4];
1455 if (ssh->logomitdata &&
1456 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1457 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1458 /* "Session data" packets - omit the data string. */
1459 ssh_pkt_getuint32(pkt); /* skip channel id */
1460 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1461 ssh_pkt_getuint32(pkt); /* skip extended data type */
1462 blanks[nblanks].offset = pkt->savedpos + 4;
1463 blanks[nblanks].type = PKTLOG_OMIT;
1464 ssh_pkt_getstring(pkt, &str, &slen);
1466 blanks[nblanks].len = slen;
1471 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1472 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1473 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1477 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1480 struct logblank_t blanks[4];
1485 * For outgoing packets, pkt->length represents the length of the
1486 * whole packet starting at pkt->data (including some header), and
1487 * pkt->body refers to the point within that where the log-worthy
1488 * payload begins. However, incoming packets expect pkt->length to
1489 * represent only the payload length (that is, it's measured from
1490 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1491 * packet to conform to the incoming-packet semantics, so that we
1492 * can analyse it with the ssh_pkt_get functions.
1494 pkt->length -= (pkt->body - pkt->data);
1497 if (ssh->logomitdata &&
1498 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1499 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1500 /* "Session data" packets - omit the data string. */
1501 ssh_pkt_getuint32(pkt); /* skip channel id */
1502 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1503 ssh_pkt_getuint32(pkt); /* skip extended data type */
1504 blanks[nblanks].offset = pkt->savedpos + 4;
1505 blanks[nblanks].type = PKTLOG_OMIT;
1506 ssh_pkt_getstring(pkt, &str, &slen);
1508 blanks[nblanks].len = slen;
1513 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1514 conf_get_int(ssh->conf, CONF_logomitpass)) {
1515 /* If this is a password packet, blank the password(s). */
1517 ssh_pkt_getstring(pkt, &str, &slen);
1518 ssh_pkt_getstring(pkt, &str, &slen);
1519 ssh_pkt_getstring(pkt, &str, &slen);
1520 if (slen == 8 && !memcmp(str, "password", 8)) {
1521 ssh2_pkt_getbool(pkt);
1522 /* Blank the password field. */
1523 blanks[nblanks].offset = pkt->savedpos;
1524 blanks[nblanks].type = PKTLOG_BLANK;
1525 ssh_pkt_getstring(pkt, &str, &slen);
1527 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1529 /* If there's another password field beyond it (change of
1530 * password), blank that too. */
1531 ssh_pkt_getstring(pkt, &str, &slen);
1533 blanks[nblanks-1].len =
1534 pkt->savedpos - blanks[nblanks].offset;
1537 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1538 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1539 conf_get_int(ssh->conf, CONF_logomitpass)) {
1540 /* If this is a keyboard-interactive response packet, blank
1543 ssh_pkt_getuint32(pkt);
1544 blanks[nblanks].offset = pkt->savedpos;
1545 blanks[nblanks].type = PKTLOG_BLANK;
1547 ssh_pkt_getstring(pkt, &str, &slen);
1551 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1553 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1554 conf_get_int(ssh->conf, CONF_logomitpass)) {
1556 * If this is an X forwarding request packet, blank the fake
1559 * Note that while we blank the X authentication data here, we
1560 * don't take any special action to blank the start of an X11
1561 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1562 * an X connection without having session blanking enabled is
1563 * likely to leak your cookie into the log.
1566 ssh_pkt_getuint32(pkt);
1567 ssh_pkt_getstring(pkt, &str, &slen);
1568 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1569 ssh2_pkt_getbool(pkt);
1570 ssh2_pkt_getbool(pkt);
1571 ssh_pkt_getstring(pkt, &str, &slen);
1572 blanks[nblanks].offset = pkt->savedpos;
1573 blanks[nblanks].type = PKTLOG_BLANK;
1574 ssh_pkt_getstring(pkt, &str, &slen);
1576 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1582 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1583 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1584 pkt->body, pkt->length, nblanks, blanks,
1585 &ssh->v2_outgoing_sequence,
1586 pkt->downstream_id, pkt->additional_log_text);
1589 * Undo the above adjustment of pkt->length, to put the packet
1590 * back in the state we found it.
1592 pkt->length += (pkt->body - pkt->data);
1595 static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
1598 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1600 crBegin(ssh->ssh2_rdpkt_crstate);
1602 st->pktin = ssh_new_packet();
1604 st->pktin->type = 0;
1605 st->pktin->length = 0;
1607 st->cipherblk = ssh->sccipher->blksize;
1610 if (st->cipherblk < 8)
1612 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1614 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1615 ssh->scmac && !ssh->scmac_etm) {
1617 * When dealing with a CBC-mode cipher, we want to avoid the
1618 * possibility of an attacker's tweaking the ciphertext stream
1619 * so as to cause us to feed the same block to the block
1620 * cipher more than once and thus leak information
1621 * (VU#958563). The way we do this is not to take any
1622 * decisions on the basis of anything we've decrypted until
1623 * we've verified it with a MAC. That includes the packet
1624 * length, so we just read data and check the MAC repeatedly,
1625 * and when the MAC passes, see if the length we've got is
1628 * This defence is unnecessary in OpenSSH ETM mode, because
1629 * the whole point of ETM mode is that the attacker can't
1630 * tweak the ciphertext stream at all without the MAC
1631 * detecting it before we decrypt anything.
1634 /* May as well allocate the whole lot now. */
1635 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1638 /* Read an amount corresponding to the MAC. */
1639 for (st->i = 0; st->i < st->maclen; st->i++) {
1640 while ((*datalen) == 0)
1642 st->pktin->data[st->i] = *(*data)++;
1648 unsigned char seq[4];
1649 ssh->scmac->start(ssh->sc_mac_ctx);
1650 PUT_32BIT(seq, st->incoming_sequence);
1651 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1654 for (;;) { /* Once around this loop per cipher block. */
1655 /* Read another cipher-block's worth, and tack it onto the end. */
1656 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1657 while ((*datalen) == 0)
1659 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1662 /* Decrypt one more block (a little further back in the stream). */
1663 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1664 st->pktin->data + st->packetlen,
1666 /* Feed that block to the MAC. */
1667 ssh->scmac->bytes(ssh->sc_mac_ctx,
1668 st->pktin->data + st->packetlen, st->cipherblk);
1669 st->packetlen += st->cipherblk;
1670 /* See if that gives us a valid packet. */
1671 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1672 st->pktin->data + st->packetlen) &&
1673 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1676 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1677 bombout(("No valid incoming packet found"));
1678 ssh_free_packet(st->pktin);
1682 st->pktin->maxlen = st->packetlen + st->maclen;
1683 st->pktin->data = sresize(st->pktin->data,
1684 st->pktin->maxlen + APIEXTRA,
1686 } else if (ssh->scmac && ssh->scmac_etm) {
1687 st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1690 * OpenSSH encrypt-then-MAC mode: the packet length is
1691 * unencrypted, unless the cipher supports length encryption.
1693 for (st->i = st->len = 0; st->i < 4; st->i++) {
1694 while ((*datalen) == 0)
1696 st->pktin->data[st->i] = *(*data)++;
1699 /* Cipher supports length decryption, so do it */
1700 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
1701 /* Keep the packet the same though, so the MAC passes */
1702 unsigned char len[4];
1703 memcpy(len, st->pktin->data, 4);
1704 ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
1705 st->len = toint(GET_32BIT(len));
1707 st->len = toint(GET_32BIT(st->pktin->data));
1711 * _Completely_ silly lengths should be stomped on before they
1712 * do us any more damage.
1714 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1715 st->len % st->cipherblk != 0) {
1716 bombout(("Incoming packet length field was garbled"));
1717 ssh_free_packet(st->pktin);
1722 * So now we can work out the total packet length.
1724 st->packetlen = st->len + 4;
1727 * Allocate memory for the rest of the packet.
1729 st->pktin->maxlen = st->packetlen + st->maclen;
1730 st->pktin->data = sresize(st->pktin->data,
1731 st->pktin->maxlen + APIEXTRA,
1735 * Read the remainder of the packet.
1737 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1738 while ((*datalen) == 0)
1740 st->pktin->data[st->i] = *(*data)++;
1748 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1749 st->len + 4, st->incoming_sequence)) {
1750 bombout(("Incorrect MAC received on packet"));
1751 ssh_free_packet(st->pktin);
1755 /* Decrypt everything between the length field and the MAC. */
1757 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1758 st->pktin->data + 4,
1761 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1764 * Acquire and decrypt the first block of the packet. This will
1765 * contain the length and padding details.
1767 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1768 while ((*datalen) == 0)
1770 st->pktin->data[st->i] = *(*data)++;
1775 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1776 st->pktin->data, st->cipherblk);
1779 * Now get the length figure.
1781 st->len = toint(GET_32BIT(st->pktin->data));
1784 * _Completely_ silly lengths should be stomped on before they
1785 * do us any more damage.
1787 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1788 (st->len + 4) % st->cipherblk != 0) {
1789 bombout(("Incoming packet was garbled on decryption"));
1790 ssh_free_packet(st->pktin);
1795 * So now we can work out the total packet length.
1797 st->packetlen = st->len + 4;
1800 * Allocate memory for the rest of the packet.
1802 st->pktin->maxlen = st->packetlen + st->maclen;
1803 st->pktin->data = sresize(st->pktin->data,
1804 st->pktin->maxlen + APIEXTRA,
1808 * Read and decrypt the remainder of the packet.
1810 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1812 while ((*datalen) == 0)
1814 st->pktin->data[st->i] = *(*data)++;
1817 /* Decrypt everything _except_ the MAC. */
1819 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1820 st->pktin->data + st->cipherblk,
1821 st->packetlen - st->cipherblk);
1827 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1828 st->len + 4, st->incoming_sequence)) {
1829 bombout(("Incorrect MAC received on packet"));
1830 ssh_free_packet(st->pktin);
1834 /* Get and sanity-check the amount of random padding. */
1835 st->pad = st->pktin->data[4];
1836 if (st->pad < 4 || st->len - st->pad < 1) {
1837 bombout(("Invalid padding length on received packet"));
1838 ssh_free_packet(st->pktin);
1842 * This enables us to deduce the payload length.
1844 st->payload = st->len - st->pad - 1;
1846 st->pktin->length = st->payload + 5;
1847 st->pktin->encrypted_len = st->packetlen;
1849 st->pktin->sequence = st->incoming_sequence++;
1851 st->pktin->length = st->packetlen - st->pad;
1852 assert(st->pktin->length >= 0);
1855 * Decompress packet payload.
1858 unsigned char *newpayload;
1861 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1862 st->pktin->data + 5, st->pktin->length - 5,
1863 &newpayload, &newlen)) {
1864 if (st->pktin->maxlen < newlen + 5) {
1865 st->pktin->maxlen = newlen + 5;
1866 st->pktin->data = sresize(st->pktin->data,
1867 st->pktin->maxlen + APIEXTRA,
1870 st->pktin->length = 5 + newlen;
1871 memcpy(st->pktin->data + 5, newpayload, newlen);
1877 * RFC 4253 doesn't explicitly say that completely empty packets
1878 * with no type byte are forbidden, so treat them as deserving
1879 * an SSH_MSG_UNIMPLEMENTED.
1881 if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */
1882 ssh2_msg_something_unimplemented(ssh, st->pktin);
1886 * pktin->body and pktin->length should identify the semantic
1887 * content of the packet, excluding the initial type byte.
1889 st->pktin->type = st->pktin->data[5];
1890 st->pktin->body = st->pktin->data + 6;
1891 st->pktin->length -= 6;
1892 assert(st->pktin->length >= 0); /* one last double-check */
1895 ssh2_log_incoming_packet(ssh, st->pktin);
1897 st->pktin->savedpos = 0;
1899 crFinish(st->pktin);
1902 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
1903 const unsigned char **data,
1906 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1908 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1911 * Read the packet length field.
1913 for (st->i = 0; st->i < 4; st->i++) {
1914 while ((*datalen) == 0)
1916 st->length[st->i] = *(*data)++;
1920 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1921 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1922 bombout(("Invalid packet length received"));
1926 st->pktin = ssh_new_packet();
1927 st->pktin->data = snewn(st->packetlen, unsigned char);
1929 st->pktin->encrypted_len = st->packetlen;
1931 st->pktin->sequence = st->incoming_sequence++;
1934 * Read the remainder of the packet.
1936 for (st->i = 0; st->i < st->packetlen; st->i++) {
1937 while ((*datalen) == 0)
1939 st->pktin->data[st->i] = *(*data)++;
1944 * pktin->body and pktin->length should identify the semantic
1945 * content of the packet, excluding the initial type byte.
1947 st->pktin->type = st->pktin->data[0];
1948 st->pktin->body = st->pktin->data + 1;
1949 st->pktin->length = st->packetlen - 1;
1952 * Log incoming packet, possibly omitting sensitive fields.
1955 ssh2_log_incoming_packet(ssh, st->pktin);
1957 st->pktin->savedpos = 0;
1959 crFinish(st->pktin);
1962 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1964 int pad, biglen, i, pktoffs;
1968 * XXX various versions of SC (including 8.8.4) screw up the
1969 * register allocation in this function and use the same register
1970 * (D6) for len and as a temporary, with predictable results. The
1971 * following sledgehammer prevents this.
1978 ssh1_log_outgoing_packet(ssh, pkt);
1980 if (ssh->v1_compressing) {
1981 unsigned char *compblk;
1983 zlib_compress_block(ssh->cs_comp_ctx,
1984 pkt->data + 12, pkt->length - 12,
1985 &compblk, &complen);
1986 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1987 memcpy(pkt->data + 12, compblk, complen);
1989 pkt->length = complen + 12;
1992 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1994 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
1995 pad = 8 - (len % 8);
1997 biglen = len + pad; /* len(padding+type+data+CRC) */
1999 for (i = pktoffs; i < 4+8; i++)
2000 pkt->data[i] = random_byte();
2001 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
2002 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
2003 PUT_32BIT(pkt->data + pktoffs, len);
2006 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
2007 pkt->data + pktoffs + 4, biglen);
2009 if (offset_p) *offset_p = pktoffs;
2010 return biglen + 4; /* len(length+padding+type+data+CRC) */
2013 static int s_write(Ssh ssh, void *data, int len)
2016 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
2017 0, NULL, NULL, 0, NULL);
2020 return sk_write(ssh->s, (char *)data, len);
2023 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
2025 int len, backlog, offset;
2026 len = s_wrpkt_prepare(ssh, pkt, &offset);
2027 backlog = s_write(ssh, pkt->data + offset, len);
2028 if (backlog > SSH_MAX_BACKLOG)
2029 ssh_throttle_all(ssh, 1, backlog);
2030 ssh_free_packet(pkt);
2033 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
2036 len = s_wrpkt_prepare(ssh, pkt, &offset);
2037 if (ssh->deferred_len + len > ssh->deferred_size) {
2038 ssh->deferred_size = ssh->deferred_len + len + 128;
2039 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2043 memcpy(ssh->deferred_send_data + ssh->deferred_len,
2044 pkt->data + offset, len);
2045 ssh->deferred_len += len;
2046 ssh_free_packet(pkt);
2050 * Construct a SSH-1 packet with the specified contents.
2051 * (This all-at-once interface used to be the only one, but now SSH-1
2052 * packets can also be constructed incrementally.)
2054 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
2060 pkt = ssh1_pkt_init(pkttype);
2062 while ((argtype = va_arg(ap, int)) != PKT_END) {
2063 unsigned char *argp, argchar;
2065 unsigned long argint;
2068 /* Actual fields in the packet */
2070 argint = va_arg(ap, int);
2071 ssh_pkt_adduint32(pkt, argint);
2074 argchar = (unsigned char) va_arg(ap, int);
2075 ssh_pkt_addbyte(pkt, argchar);
2078 argp = va_arg(ap, unsigned char *);
2079 arglen = va_arg(ap, int);
2080 ssh_pkt_adddata(pkt, argp, arglen);
2083 sargp = va_arg(ap, char *);
2084 ssh_pkt_addstring(pkt, sargp);
2087 bn = va_arg(ap, Bignum);
2088 ssh1_pkt_addmp(pkt, bn);
2096 static void send_packet(Ssh ssh, int pkttype, ...)
2100 va_start(ap, pkttype);
2101 pkt = construct_packet(ssh, pkttype, ap);
2106 static void defer_packet(Ssh ssh, int pkttype, ...)
2110 va_start(ap, pkttype);
2111 pkt = construct_packet(ssh, pkttype, ap);
2113 s_wrpkt_defer(ssh, pkt);
2116 static int ssh_versioncmp(const char *a, const char *b)
2119 unsigned long av, bv;
2121 av = strtoul(a, &ae, 10);
2122 bv = strtoul(b, &be, 10);
2124 return (av < bv ? -1 : +1);
2129 av = strtoul(ae, &ae, 10);
2130 bv = strtoul(be, &be, 10);
2132 return (av < bv ? -1 : +1);
2137 * Utility routines for putting an SSH-protocol `string' and
2138 * `uint32' into a hash state.
2140 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2142 unsigned char lenblk[4];
2143 PUT_32BIT(lenblk, len);
2144 h->bytes(s, lenblk, 4);
2145 h->bytes(s, str, len);
2148 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2150 unsigned char intblk[4];
2151 PUT_32BIT(intblk, i);
2152 h->bytes(s, intblk, 4);
2156 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2158 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2160 if (pkt->maxlen < length) {
2161 unsigned char *body = pkt->body;
2162 int offset = body ? body - pkt->data : 0;
2163 pkt->maxlen = length + 256;
2164 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2165 if (body) pkt->body = pkt->data + offset;
2168 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2171 ssh_pkt_ensure(pkt, pkt->length);
2172 memcpy(pkt->data + pkt->length - len, data, len);
2174 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2176 ssh_pkt_adddata(pkt, &byte, 1);
2178 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2180 ssh_pkt_adddata(pkt, &value, 1);
2182 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2185 PUT_32BIT(x, value);
2186 ssh_pkt_adddata(pkt, x, 4);
2188 static void ssh_pkt_addstring_start(struct Packet *pkt)
2190 ssh_pkt_adduint32(pkt, 0);
2191 pkt->savedpos = pkt->length;
2193 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2196 ssh_pkt_adddata(pkt, data, len);
2197 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2199 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2201 ssh_pkt_addstring_data(pkt, data, strlen(data));
2203 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2205 ssh_pkt_addstring_start(pkt);
2206 ssh_pkt_addstring_str(pkt, data);
2208 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2210 int len = ssh1_bignum_length(b);
2211 unsigned char *data = snewn(len, unsigned char);
2212 (void) ssh1_write_bignum(data, b);
2213 ssh_pkt_adddata(pkt, data, len);
2216 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2219 int i, n = (bignum_bitcount(b) + 7) / 8;
2220 p = snewn(n + 1, unsigned char);
2222 for (i = 1; i <= n; i++)
2223 p[i] = bignum_byte(b, n - i);
2225 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2227 memmove(p, p + i, n + 1 - i);
2231 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2235 p = ssh2_mpint_fmt(b, &len);
2236 ssh_pkt_addstring_start(pkt);
2237 ssh_pkt_addstring_data(pkt, (char *)p, len);
2241 static struct Packet *ssh1_pkt_init(int pkt_type)
2243 struct Packet *pkt = ssh_new_packet();
2244 pkt->length = 4 + 8; /* space for length + max padding */
2245 ssh_pkt_addbyte(pkt, pkt_type);
2246 pkt->body = pkt->data + pkt->length;
2247 pkt->type = pkt_type;
2248 pkt->downstream_id = 0;
2249 pkt->additional_log_text = NULL;
2253 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2254 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2255 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2256 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2257 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2258 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2259 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2260 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2261 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2263 static struct Packet *ssh2_pkt_init(int pkt_type)
2265 struct Packet *pkt = ssh_new_packet();
2266 pkt->length = 5; /* space for packet length + padding length */
2268 pkt->type = pkt_type;
2269 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2270 pkt->body = pkt->data + pkt->length; /* after packet type */
2271 pkt->downstream_id = 0;
2272 pkt->additional_log_text = NULL;
2277 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2278 * put the MAC on it. Final packet, ready to be sent, is stored in
2279 * pkt->data. Total length is returned.
2281 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2283 int cipherblk, maclen, padding, unencrypted_prefix, i;
2286 ssh2_log_outgoing_packet(ssh, pkt);
2288 if (ssh->bare_connection) {
2290 * Trivial packet construction for the bare connection
2293 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2294 pkt->body = pkt->data + 1;
2295 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2296 return pkt->length - 1;
2300 * Compress packet payload.
2303 unsigned char *newpayload;
2306 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2308 &newpayload, &newlen)) {
2310 ssh2_pkt_adddata(pkt, newpayload, newlen);
2316 * Add padding. At least four bytes, and must also bring total
2317 * length (minus MAC) up to a multiple of the block size.
2318 * If pkt->forcepad is set, make sure the packet is at least that size
2321 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2322 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2324 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2325 if (pkt->length + padding < pkt->forcepad)
2326 padding = pkt->forcepad - pkt->length;
2328 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2330 assert(padding <= 255);
2331 maclen = ssh->csmac ? ssh->csmac->len : 0;
2332 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2333 pkt->data[4] = padding;
2334 for (i = 0; i < padding; i++)
2335 pkt->data[pkt->length + i] = random_byte();
2336 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2338 /* Encrypt length if the scheme requires it */
2339 if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
2340 ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
2341 ssh->v2_outgoing_sequence);
2344 if (ssh->csmac && ssh->csmac_etm) {
2346 * OpenSSH-defined encrypt-then-MAC protocol.
2349 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2350 pkt->data + 4, pkt->length + padding - 4);
2351 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2352 pkt->length + padding,
2353 ssh->v2_outgoing_sequence);
2356 * SSH-2 standard protocol.
2359 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2360 pkt->length + padding,
2361 ssh->v2_outgoing_sequence);
2363 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2364 pkt->data, pkt->length + padding);
2367 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2368 pkt->encrypted_len = pkt->length + padding;
2370 /* Ready-to-send packet starts at pkt->data. We return length. */
2371 pkt->body = pkt->data;
2372 return pkt->length + padding + maclen;
2376 * Routines called from the main SSH code to send packets. There
2377 * are quite a few of these, because we have two separate
2378 * mechanisms for delaying the sending of packets:
2380 * - In order to send an IGNORE message and a password message in
2381 * a single fixed-length blob, we require the ability to
2382 * concatenate the encrypted forms of those two packets _into_ a
2383 * single blob and then pass it to our <network.h> transport
2384 * layer in one go. Hence, there's a deferment mechanism which
2385 * works after packet encryption.
2387 * - In order to avoid sending any connection-layer messages
2388 * during repeat key exchange, we have to queue up any such
2389 * outgoing messages _before_ they are encrypted (and in
2390 * particular before they're allocated sequence numbers), and
2391 * then send them once we've finished.
2393 * I call these mechanisms `defer' and `queue' respectively, so as
2394 * to distinguish them reasonably easily.
2396 * The functions send_noqueue() and defer_noqueue() free the packet
2397 * structure they are passed. Every outgoing packet goes through
2398 * precisely one of these functions in its life; packets passed to
2399 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2400 * these or get queued, and then when the queue is later emptied
2401 * the packets are all passed to defer_noqueue().
2403 * When using a CBC-mode cipher, it's necessary to ensure that an
2404 * attacker can't provide data to be encrypted using an IV that they
2405 * know. We ensure this by prefixing each packet that might contain
2406 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2407 * mechanism, so in this case send_noqueue() ends up redirecting to
2408 * defer_noqueue(). If you don't like this inefficiency, don't use
2412 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2413 static void ssh_pkt_defersend(Ssh);
2416 * Send an SSH-2 packet immediately, without queuing or deferring.
2418 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2422 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2423 /* We need to send two packets, so use the deferral mechanism. */
2424 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2425 ssh_pkt_defersend(ssh);
2428 len = ssh2_pkt_construct(ssh, pkt);
2429 backlog = s_write(ssh, pkt->body, len);
2430 if (backlog > SSH_MAX_BACKLOG)
2431 ssh_throttle_all(ssh, 1, backlog);
2433 ssh->outgoing_data_size += pkt->encrypted_len;
2434 if (!ssh->kex_in_progress &&
2435 !ssh->bare_connection &&
2436 ssh->max_data_size != 0 &&
2437 ssh->outgoing_data_size > ssh->max_data_size)
2438 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2440 ssh_free_packet(pkt);
2444 * Defer an SSH-2 packet.
2446 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2449 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2450 ssh->deferred_len == 0 && !noignore &&
2451 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2453 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2454 * get encrypted with a known IV.
2456 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2457 ssh2_pkt_addstring_start(ipkt);
2458 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2460 len = ssh2_pkt_construct(ssh, pkt);
2461 if (ssh->deferred_len + len > ssh->deferred_size) {
2462 ssh->deferred_size = ssh->deferred_len + len + 128;
2463 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2467 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2468 ssh->deferred_len += len;
2469 ssh->deferred_data_size += pkt->encrypted_len;
2470 ssh_free_packet(pkt);
2474 * Queue an SSH-2 packet.
2476 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2478 assert(ssh->queueing);
2480 if (ssh->queuelen >= ssh->queuesize) {
2481 ssh->queuesize = ssh->queuelen + 32;
2482 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2485 ssh->queue[ssh->queuelen++] = pkt;
2489 * Either queue or send a packet, depending on whether queueing is
2492 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2495 ssh2_pkt_queue(ssh, pkt);
2497 ssh2_pkt_send_noqueue(ssh, pkt);
2501 * Either queue or defer a packet, depending on whether queueing is
2504 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2507 ssh2_pkt_queue(ssh, pkt);
2509 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2513 * Send the whole deferred data block constructed by
2514 * ssh2_pkt_defer() or SSH-1's defer_packet().
2516 * The expected use of the defer mechanism is that you call
2517 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2518 * not currently queueing, this simply sets up deferred_send_data
2519 * and then sends it. If we _are_ currently queueing, the calls to
2520 * ssh2_pkt_defer() put the deferred packets on to the queue
2521 * instead, and therefore ssh_pkt_defersend() has no deferred data
2522 * to send. Hence, there's no need to make it conditional on
2525 static void ssh_pkt_defersend(Ssh ssh)
2528 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2529 ssh->deferred_len = ssh->deferred_size = 0;
2530 sfree(ssh->deferred_send_data);
2531 ssh->deferred_send_data = NULL;
2532 if (backlog > SSH_MAX_BACKLOG)
2533 ssh_throttle_all(ssh, 1, backlog);
2535 if (ssh->version == 2) {
2536 ssh->outgoing_data_size += ssh->deferred_data_size;
2537 ssh->deferred_data_size = 0;
2538 if (!ssh->kex_in_progress &&
2539 !ssh->bare_connection &&
2540 ssh->max_data_size != 0 &&
2541 ssh->outgoing_data_size > ssh->max_data_size)
2542 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2547 * Send a packet whose length needs to be disguised (typically
2548 * passwords or keyboard-interactive responses).
2550 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2556 * The simplest way to do this is to adjust the
2557 * variable-length padding field in the outgoing packet.
2559 * Currently compiled out, because some Cisco SSH servers
2560 * don't like excessively padded packets (bah, why's it
2563 pkt->forcepad = padsize;
2564 ssh2_pkt_send(ssh, pkt);
2569 * If we can't do that, however, an alternative approach is
2570 * to use the pkt_defer mechanism to bundle the packet
2571 * tightly together with an SSH_MSG_IGNORE such that their
2572 * combined length is a constant. So first we construct the
2573 * final form of this packet and defer its sending.
2575 ssh2_pkt_defer(ssh, pkt);
2578 * Now construct an SSH_MSG_IGNORE which includes a string
2579 * that's an exact multiple of the cipher block size. (If
2580 * the cipher is NULL so that the block size is
2581 * unavailable, we don't do this trick at all, because we
2582 * gain nothing by it.)
2584 if (ssh->cscipher &&
2585 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2588 stringlen = (256 - ssh->deferred_len);
2589 stringlen += ssh->cscipher->blksize - 1;
2590 stringlen -= (stringlen % ssh->cscipher->blksize);
2593 * Temporarily disable actual compression, so we
2594 * can guarantee to get this string exactly the
2595 * length we want it. The compression-disabling
2596 * routine should return an integer indicating how
2597 * many bytes we should adjust our string length
2601 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2603 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2604 ssh2_pkt_addstring_start(pkt);
2605 for (i = 0; i < stringlen; i++) {
2606 char c = (char) random_byte();
2607 ssh2_pkt_addstring_data(pkt, &c, 1);
2609 ssh2_pkt_defer(ssh, pkt);
2611 ssh_pkt_defersend(ssh);
2616 * Send all queued SSH-2 packets. We send them by means of
2617 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2618 * packets that needed to be lumped together.
2620 static void ssh2_pkt_queuesend(Ssh ssh)
2624 assert(!ssh->queueing);
2626 for (i = 0; i < ssh->queuelen; i++)
2627 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2630 ssh_pkt_defersend(ssh);
2634 void bndebug(char *string, Bignum b)
2638 p = ssh2_mpint_fmt(b, &len);
2639 debug(("%s", string));
2640 for (i = 0; i < len; i++)
2641 debug((" %02x", p[i]));
2647 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2651 p = ssh2_mpint_fmt(b, &len);
2652 hash_string(h, s, p, len);
2657 * Packet decode functions for both SSH-1 and SSH-2.
2659 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2661 unsigned long value;
2662 if (pkt->length - pkt->savedpos < 4)
2663 return 0; /* arrgh, no way to decline (FIXME?) */
2664 value = GET_32BIT(pkt->body + pkt->savedpos);
2668 static int ssh2_pkt_getbool(struct Packet *pkt)
2670 unsigned long value;
2671 if (pkt->length - pkt->savedpos < 1)
2672 return 0; /* arrgh, no way to decline (FIXME?) */
2673 value = pkt->body[pkt->savedpos] != 0;
2677 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2682 if (pkt->length - pkt->savedpos < 4)
2684 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2689 if (pkt->length - pkt->savedpos < *length)
2691 *p = (char *)(pkt->body + pkt->savedpos);
2692 pkt->savedpos += *length;
2694 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2696 if (pkt->length - pkt->savedpos < length)
2698 pkt->savedpos += length;
2699 return pkt->body + (pkt->savedpos - length);
2701 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2702 const unsigned char **keystr)
2706 j = makekey(pkt->body + pkt->savedpos,
2707 pkt->length - pkt->savedpos,
2714 assert(pkt->savedpos < pkt->length);
2718 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2723 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2724 pkt->length - pkt->savedpos, &b);
2732 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2738 ssh_pkt_getstring(pkt, &p, &length);
2743 b = bignum_from_bytes((unsigned char *)p, length);
2748 * Helper function to add an SSH-2 signature blob to a packet.
2749 * Expects to be shown the public key blob as well as the signature
2750 * blob. Normally works just like ssh2_pkt_addstring, but will
2751 * fiddle with the signature packet if necessary for
2752 * BUG_SSH2_RSA_PADDING.
2754 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2755 void *pkblob_v, int pkblob_len,
2756 void *sigblob_v, int sigblob_len)
2758 unsigned char *pkblob = (unsigned char *)pkblob_v;
2759 unsigned char *sigblob = (unsigned char *)sigblob_v;
2761 /* dmemdump(pkblob, pkblob_len); */
2762 /* dmemdump(sigblob, sigblob_len); */
2765 * See if this is in fact an ssh-rsa signature and a buggy
2766 * server; otherwise we can just do this the easy way.
2768 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2769 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2770 int pos, len, siglen;
2773 * Find the byte length of the modulus.
2776 pos = 4+7; /* skip over "ssh-rsa" */
2777 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2778 if (len < 0 || len > pkblob_len - pos - 4)
2780 pos += 4 + len; /* skip over exponent */
2781 if (pkblob_len - pos < 4)
2783 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2784 if (len < 0 || len > pkblob_len - pos - 4)
2786 pos += 4; /* find modulus itself */
2787 while (len > 0 && pkblob[pos] == 0)
2789 /* debug(("modulus length is %d\n", len)); */
2792 * Now find the signature integer.
2794 pos = 4+7; /* skip over "ssh-rsa" */
2795 if (sigblob_len < pos+4)
2797 siglen = toint(GET_32BIT(sigblob+pos));
2798 if (siglen != sigblob_len - pos - 4)
2800 /* debug(("signature length is %d\n", siglen)); */
2802 if (len != siglen) {
2803 unsigned char newlen[4];
2804 ssh2_pkt_addstring_start(pkt);
2805 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2806 /* dmemdump(sigblob, pos); */
2807 pos += 4; /* point to start of actual sig */
2808 PUT_32BIT(newlen, len);
2809 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2810 /* dmemdump(newlen, 4); */
2812 while (len-- > siglen) {
2813 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2814 /* dmemdump(newlen, 1); */
2816 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2817 /* dmemdump(sigblob+pos, siglen); */
2821 /* Otherwise fall through and do it the easy way. We also come
2822 * here as a fallback if we discover above that the key blob
2823 * is misformatted in some way. */
2827 ssh2_pkt_addstring_start(pkt);
2828 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2832 * Examine the remote side's version string and compare it against
2833 * a list of known buggy implementations.
2835 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2837 char *imp; /* pointer to implementation part */
2839 imp += strcspn(imp, "-");
2841 imp += strcspn(imp, "-");
2844 ssh->remote_bugs = 0;
2847 * General notes on server version strings:
2848 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2849 * here -- in particular, we've heard of one that's perfectly happy
2850 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2851 * so we can't distinguish them.
2853 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2854 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2855 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2856 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2857 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2858 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2860 * These versions don't support SSH1_MSG_IGNORE, so we have
2861 * to use a different defence against password length
2864 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2865 logevent("We believe remote version has SSH-1 ignore bug");
2868 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2869 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2870 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2872 * These versions need a plain password sent; they can't
2873 * handle having a null and a random length of data after
2876 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2877 logevent("We believe remote version needs a plain SSH-1 password");
2880 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2881 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2882 (!strcmp(imp, "Cisco-1.25")))) {
2884 * These versions apparently have no clue whatever about
2885 * RSA authentication and will panic and die if they see
2886 * an AUTH_RSA message.
2888 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2889 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2892 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2893 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2894 !wc_match("* VShell", imp) &&
2895 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2896 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2897 wc_match("2.1 *", imp)))) {
2899 * These versions have the HMAC bug.
2901 ssh->remote_bugs |= BUG_SSH2_HMAC;
2902 logevent("We believe remote version has SSH-2 HMAC bug");
2905 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2906 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2907 !wc_match("* VShell", imp) &&
2908 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2910 * These versions have the key-derivation bug (failing to
2911 * include the literal shared secret in the hashes that
2912 * generate the keys).
2914 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2915 logevent("We believe remote version has SSH-2 key-derivation bug");
2918 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2919 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2920 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2921 wc_match("OpenSSH_3.[0-2]*", imp) ||
2922 wc_match("mod_sftp/0.[0-8]*", imp) ||
2923 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2925 * These versions have the SSH-2 RSA padding bug.
2927 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2928 logevent("We believe remote version has SSH-2 RSA padding bug");
2931 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2932 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2933 wc_match("OpenSSH_2.[0-2]*", imp))) {
2935 * These versions have the SSH-2 session-ID bug in
2936 * public-key authentication.
2938 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2939 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2942 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2943 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2944 (wc_match("DigiSSH_2.0", imp) ||
2945 wc_match("OpenSSH_2.[0-4]*", imp) ||
2946 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2947 wc_match("Sun_SSH_1.0", imp) ||
2948 wc_match("Sun_SSH_1.0.1", imp) ||
2949 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2950 wc_match("WeOnlyDo-*", imp)))) {
2952 * These versions have the SSH-2 rekey bug.
2954 ssh->remote_bugs |= BUG_SSH2_REKEY;
2955 logevent("We believe remote version has SSH-2 rekey bug");
2958 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2959 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2960 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2961 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2963 * This version ignores our makpkt and needs to be throttled.
2965 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2966 logevent("We believe remote version ignores SSH-2 maximum packet size");
2969 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2971 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2972 * none detected automatically.
2974 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2975 logevent("We believe remote version has SSH-2 ignore bug");
2978 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2979 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2980 (wc_match("OpenSSH_2.[235]*", imp)))) {
2982 * These versions only support the original (pre-RFC4419)
2983 * SSH-2 GEX request, and disconnect with a protocol error if
2984 * we use the newer version.
2986 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2987 logevent("We believe remote version has outdated SSH-2 GEX");
2990 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
2992 * Servers that don't support our winadj request for one
2993 * reason or another. Currently, none detected automatically.
2995 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
2996 logevent("We believe remote version has winadj bug");
2999 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
3000 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
3001 (wc_match("OpenSSH_[2-5].*", imp) ||
3002 wc_match("OpenSSH_6.[0-6]*", imp) ||
3003 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
3004 wc_match("dropbear_0.5[01]*", imp)))) {
3006 * These versions have the SSH-2 channel request bug.
3007 * OpenSSH 6.7 and above do not:
3008 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
3009 * dropbear_0.52 and above do not:
3010 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
3012 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
3013 logevent("We believe remote version has SSH-2 channel request bug");
3018 * The `software version' part of an SSH version string is required
3019 * to contain no spaces or minus signs.
3021 static void ssh_fix_verstring(char *str)
3023 /* Eat "<protoversion>-". */
3024 while (*str && *str != '-') str++;
3025 assert(*str == '-'); str++;
3027 /* Convert minus signs and spaces in the remaining string into
3030 if (*str == '-' || *str == ' ')
3037 * Send an appropriate SSH version string.
3039 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
3043 if (ssh->version == 2) {
3045 * Construct a v2 version string.
3047 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
3050 * Construct a v1 version string.
3052 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
3053 verstring = dupprintf("SSH-%s-%s\012",
3054 (ssh_versioncmp(svers, "1.5") <= 0 ?
3059 ssh_fix_verstring(verstring + strlen(protoname));
3061 /* FUZZING make PuTTY insecure, so make live use difficult. */
3065 if (ssh->version == 2) {
3068 * Record our version string.
3070 len = strcspn(verstring, "\015\012");
3071 ssh->v_c = snewn(len + 1, char);
3072 memcpy(ssh->v_c, verstring, len);
3076 logeventf(ssh, "We claim version: %.*s",
3077 strcspn(verstring, "\015\012"), verstring);
3078 s_write(ssh, verstring, strlen(verstring));
3082 static int do_ssh_init(Ssh ssh, unsigned char c)
3084 static const char protoname[] = "SSH-";
3086 struct do_ssh_init_state {
3095 crState(do_ssh_init_state);
3099 /* Search for a line beginning with the protocol name prefix in
3102 for (s->i = 0; protoname[s->i]; s->i++) {
3103 if ((char)c != protoname[s->i]) goto no;
3113 ssh->session_started = TRUE;
3115 s->vstrsize = sizeof(protoname) + 16;
3116 s->vstring = snewn(s->vstrsize, char);
3117 strcpy(s->vstring, protoname);
3118 s->vslen = strlen(protoname);
3121 if (s->vslen >= s->vstrsize - 1) {
3123 s->vstring = sresize(s->vstring, s->vstrsize, char);
3125 s->vstring[s->vslen++] = c;
3128 s->version[s->i] = '\0';
3130 } else if (s->i < sizeof(s->version) - 1)
3131 s->version[s->i++] = c;
3132 } else if (c == '\012')
3134 crReturn(1); /* get another char */
3137 ssh->agentfwd_enabled = FALSE;
3138 ssh->rdpkt2_state.incoming_sequence = 0;
3140 s->vstring[s->vslen] = 0;
3141 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3142 logeventf(ssh, "Server version: %s", s->vstring);
3143 ssh_detect_bugs(ssh, s->vstring);
3146 * Decide which SSH protocol version to support.
3149 /* Anything strictly below "2.0" means protocol 1 is supported. */
3150 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3151 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3152 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3154 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3156 bombout(("SSH protocol version 1 required by our configuration "
3157 "but not provided by server"));
3160 } else if (conf_get_int(ssh->conf, CONF_sshprot) == 3) {
3162 bombout(("SSH protocol version 2 required by our configuration "
3163 "but server only provides (old, insecure) SSH-1"));
3167 /* No longer support values 1 or 2 for CONF_sshprot */
3168 assert(!"Unexpected value for CONF_sshprot");
3171 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3176 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3178 /* Send the version string, if we haven't already */
3179 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3180 ssh_send_verstring(ssh, protoname, s->version);
3182 if (ssh->version == 2) {
3185 * Record their version string.
3187 len = strcspn(s->vstring, "\015\012");
3188 ssh->v_s = snewn(len + 1, char);
3189 memcpy(ssh->v_s, s->vstring, len);
3193 * Initialise SSH-2 protocol.
3195 ssh->protocol = ssh2_protocol;
3196 ssh2_protocol_setup(ssh);
3197 ssh->s_rdpkt = ssh2_rdpkt;
3200 * Initialise SSH-1 protocol.
3202 ssh->protocol = ssh1_protocol;
3203 ssh1_protocol_setup(ssh);
3204 ssh->s_rdpkt = ssh1_rdpkt;
3206 if (ssh->version == 2)
3207 do_ssh2_transport(ssh, NULL, -1, NULL);
3209 update_specials_menu(ssh->frontend);
3210 ssh->state = SSH_STATE_BEFORE_SIZE;
3211 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3218 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3221 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3222 * the ssh-connection part, extracted and given a trivial binary
3223 * packet protocol, so we replace 'SSH-' at the start with a new
3224 * name. In proper SSH style (though of course this part of the
3225 * proper SSH protocol _isn't_ subject to this kind of
3226 * DNS-domain-based extension), we define the new name in our
3229 static const char protoname[] =
3230 "SSHCONNECTION@putty.projects.tartarus.org-";
3232 struct do_ssh_connection_init_state {
3240 crState(do_ssh_connection_init_state);
3244 /* Search for a line beginning with the protocol name prefix in
3247 for (s->i = 0; protoname[s->i]; s->i++) {
3248 if ((char)c != protoname[s->i]) goto no;
3258 s->vstrsize = sizeof(protoname) + 16;
3259 s->vstring = snewn(s->vstrsize, char);
3260 strcpy(s->vstring, protoname);
3261 s->vslen = strlen(protoname);
3264 if (s->vslen >= s->vstrsize - 1) {
3266 s->vstring = sresize(s->vstring, s->vstrsize, char);
3268 s->vstring[s->vslen++] = c;
3271 s->version[s->i] = '\0';
3273 } else if (s->i < sizeof(s->version) - 1)
3274 s->version[s->i++] = c;
3275 } else if (c == '\012')
3277 crReturn(1); /* get another char */
3280 ssh->agentfwd_enabled = FALSE;
3281 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3283 s->vstring[s->vslen] = 0;
3284 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3285 logeventf(ssh, "Server version: %s", s->vstring);
3286 ssh_detect_bugs(ssh, s->vstring);
3289 * Decide which SSH protocol version to support. This is easy in
3290 * bare ssh-connection mode: only 2.0 is legal.
3292 if (ssh_versioncmp(s->version, "2.0") < 0) {
3293 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3296 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3297 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3303 logeventf(ssh, "Using bare ssh-connection protocol");
3305 /* Send the version string, if we haven't already */
3306 ssh_send_verstring(ssh, protoname, s->version);
3309 * Initialise bare connection protocol.
3311 ssh->protocol = ssh2_bare_connection_protocol;
3312 ssh2_bare_connection_protocol_setup(ssh);
3313 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3315 update_specials_menu(ssh->frontend);
3316 ssh->state = SSH_STATE_BEFORE_SIZE;
3317 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3320 * Get authconn (really just conn) under way.
3322 do_ssh2_authconn(ssh, NULL, 0, NULL);
3329 static void ssh_process_incoming_data(Ssh ssh,
3330 const unsigned char **data, int *datalen)
3332 struct Packet *pktin;
3334 pktin = ssh->s_rdpkt(ssh, data, datalen);
3336 ssh->protocol(ssh, NULL, 0, pktin);
3337 ssh_free_packet(pktin);
3341 static void ssh_queue_incoming_data(Ssh ssh,
3342 const unsigned char **data, int *datalen)
3344 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3349 static void ssh_process_queued_incoming_data(Ssh ssh)
3352 const unsigned char *data;
3355 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3356 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3360 while (!ssh->frozen && len > 0)
3361 ssh_process_incoming_data(ssh, &data, &len);
3364 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3368 static void ssh_set_frozen(Ssh ssh, int frozen)
3371 sk_set_frozen(ssh->s, frozen);
3372 ssh->frozen = frozen;
3375 static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
3377 /* Log raw data, if we're in that mode. */
3379 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3380 0, NULL, NULL, 0, NULL);
3382 crBegin(ssh->ssh_gotdata_crstate);
3385 * To begin with, feed the characters one by one to the
3386 * protocol initialisation / selection function do_ssh_init().
3387 * When that returns 0, we're done with the initial greeting
3388 * exchange and can move on to packet discipline.
3391 int ret; /* need not be kept across crReturn */
3393 crReturnV; /* more data please */
3394 ret = ssh->do_ssh_init(ssh, *data);
3402 * We emerge from that loop when the initial negotiation is
3403 * over and we have selected an s_rdpkt function. Now pass
3404 * everything to s_rdpkt, and then pass the resulting packets
3405 * to the proper protocol handler.
3409 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3411 ssh_queue_incoming_data(ssh, &data, &datalen);
3412 /* This uses up all data and cannot cause anything interesting
3413 * to happen; indeed, for anything to happen at all, we must
3414 * return, so break out. */
3416 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3417 /* This uses up some or all data, and may freeze the
3419 ssh_process_queued_incoming_data(ssh);
3421 /* This uses up some or all data, and may freeze the
3423 ssh_process_incoming_data(ssh, &data, &datalen);
3425 /* FIXME this is probably EBW. */
3426 if (ssh->state == SSH_STATE_CLOSED)
3429 /* We're out of data. Go and get some more. */
3435 static int ssh_do_close(Ssh ssh, int notify_exit)
3438 struct ssh_channel *c;
3440 ssh->state = SSH_STATE_CLOSED;
3441 expire_timer_context(ssh);
3446 notify_remote_exit(ssh->frontend);
3451 * Now we must shut down any port- and X-forwarded channels going
3452 * through this connection.
3454 if (ssh->channels) {
3455 while (NULL != (c = index234(ssh->channels, 0))) {
3458 x11_close(c->u.x11.xconn);
3461 case CHAN_SOCKDATA_DORMANT:
3462 pfd_close(c->u.pfd.pf);
3465 del234(ssh->channels, c); /* moving next one to index 0 */
3466 if (ssh->version == 2)
3467 bufchain_clear(&c->v.v2.outbuffer);
3472 * Go through port-forwardings, and close any associated
3473 * listening sockets.
3475 if (ssh->portfwds) {
3476 struct ssh_portfwd *pf;
3477 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3478 /* Dispose of any listening socket. */
3480 pfl_terminate(pf->local);
3481 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3484 freetree234(ssh->portfwds);
3485 ssh->portfwds = NULL;
3489 * Also stop attempting to connection-share.
3491 if (ssh->connshare) {
3492 sharestate_free(ssh->connshare);
3493 ssh->connshare = NULL;
3499 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3500 const char *error_msg, int error_code)
3502 Ssh ssh = (Ssh) plug;
3505 * While we're attempting connection sharing, don't loudly log
3506 * everything that happens. Real TCP connections need to be logged
3507 * when we _start_ trying to connect, because it might be ages
3508 * before they respond if something goes wrong; but connection
3509 * sharing is local and quick to respond, and it's sufficient to
3510 * simply wait and see whether it worked afterwards.
3513 if (!ssh->attempting_connshare)
3514 backend_socket_log(ssh->frontend, type, addr, port,
3515 error_msg, error_code, ssh->conf,
3516 ssh->session_started);
3519 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3520 const char *ds_err, const char *us_err)
3522 if (event == SHARE_NONE) {
3523 /* In this case, 'logtext' is an error message indicating a
3524 * reason why connection sharing couldn't be set up _at all_.
3525 * Failing that, ds_err and us_err indicate why we couldn't be
3526 * a downstream and an upstream respectively. */
3528 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3531 logeventf(ssh, "Could not set up connection sharing"
3532 " as downstream: %s", ds_err);
3534 logeventf(ssh, "Could not set up connection sharing"
3535 " as upstream: %s", us_err);
3537 } else if (event == SHARE_DOWNSTREAM) {
3538 /* In this case, 'logtext' is a local endpoint address */
3539 logeventf(ssh, "Using existing shared connection at %s", logtext);
3540 /* Also we should mention this in the console window to avoid
3541 * confusing users as to why this window doesn't behave the
3543 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3544 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3546 } else if (event == SHARE_UPSTREAM) {
3547 /* In this case, 'logtext' is a local endpoint address too */
3548 logeventf(ssh, "Sharing this connection at %s", logtext);
3552 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3555 Ssh ssh = (Ssh) plug;
3556 int need_notify = ssh_do_close(ssh, FALSE);
3559 if (!ssh->close_expected)
3560 error_msg = "Server unexpectedly closed network connection";
3562 error_msg = "Server closed network connection";
3565 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3569 notify_remote_exit(ssh->frontend);
3572 logevent(error_msg);
3573 if (!ssh->close_expected || !ssh->clean_exit)
3574 connection_fatal(ssh->frontend, "%s", error_msg);
3578 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3580 Ssh ssh = (Ssh) plug;
3581 ssh_gotdata(ssh, (unsigned char *)data, len);
3582 if (ssh->state == SSH_STATE_CLOSED) {
3583 ssh_do_close(ssh, TRUE);
3589 static void ssh_sent(Plug plug, int bufsize)
3591 Ssh ssh = (Ssh) plug;
3593 * If the send backlog on the SSH socket itself clears, we
3594 * should unthrottle the whole world if it was throttled.
3596 if (bufsize < SSH_MAX_BACKLOG)
3597 ssh_throttle_all(ssh, 0, bufsize);
3600 static void ssh_hostport_setup(const char *host, int port, Conf *conf,
3601 char **savedhost, int *savedport,
3604 char *loghost = conf_get_str(conf, CONF_loghost);
3606 *loghost_ret = loghost;
3612 tmphost = dupstr(loghost);
3613 *savedport = 22; /* default ssh port */
3616 * A colon suffix on the hostname string also lets us affect
3617 * savedport. (Unless there are multiple colons, in which case
3618 * we assume this is an unbracketed IPv6 literal.)
3620 colon = host_strrchr(tmphost, ':');
3621 if (colon && colon == host_strchr(tmphost, ':')) {
3624 *savedport = atoi(colon);
3627 *savedhost = host_strduptrim(tmphost);
3630 *savedhost = host_strduptrim(host);
3632 port = 22; /* default ssh port */
3637 static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
3643 random_ref(); /* platform may need this to determine share socket name */
3644 ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
3645 ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
3653 * Connect to specified host and port.
3654 * Returns an error message, or NULL on success.
3655 * Also places the canonical host name into `realhost'. It must be
3656 * freed by the caller.
3658 static const char *connect_to_host(Ssh ssh, const char *host, int port,
3659 char **realhost, int nodelay, int keepalive)
3661 static const struct plug_function_table fn_table = {
3672 int addressfamily, sshprot;
3674 ssh_hostport_setup(host, port, ssh->conf,
3675 &ssh->savedhost, &ssh->savedport, &loghost);
3677 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3680 * Try connection-sharing, in case that means we don't open a
3681 * socket after all. ssh_connection_sharing_init will connect to a
3682 * previously established upstream if it can, and failing that,
3683 * establish a listening socket for _us_ to be the upstream. In
3684 * the latter case it will return NULL just as if it had done
3685 * nothing, because here we only need to care if we're a
3686 * downstream and need to do our connection setup differently.
3688 ssh->connshare = NULL;
3689 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3690 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3691 ssh->conf, ssh, &ssh->connshare);
3692 ssh->attempting_connshare = FALSE;
3693 if (ssh->s != NULL) {
3695 * We are a downstream.
3697 ssh->bare_connection = TRUE;
3698 ssh->do_ssh_init = do_ssh_connection_init;
3699 ssh->fullhostname = NULL;
3700 *realhost = dupstr(host); /* best we can do */
3703 * We're not a downstream, so open a normal socket.
3705 ssh->do_ssh_init = do_ssh_init;
3710 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3711 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
3712 ssh->frontend, "SSH connection");
3713 if ((err = sk_addr_error(addr)) != NULL) {
3717 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3719 ssh->s = new_connection(addr, *realhost, port,
3720 0, 1, nodelay, keepalive,
3721 (Plug) ssh, ssh->conf);
3722 if ((err = sk_socket_error(ssh->s)) != NULL) {
3724 notify_remote_exit(ssh->frontend);
3730 * The SSH version number is always fixed (since we no longer support
3731 * fallback between versions), so set it now, and if it's SSH-2,
3732 * send the version string now too.
3734 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3735 assert(sshprot == 0 || sshprot == 3);
3739 if (sshprot == 3 && !ssh->bare_connection) {
3742 ssh_send_verstring(ssh, "SSH-", NULL);
3746 * loghost, if configured, overrides realhost.
3750 *realhost = dupstr(loghost);
3757 * Throttle or unthrottle the SSH connection.
3759 static void ssh_throttle_conn(Ssh ssh, int adjust)
3761 int old_count = ssh->conn_throttle_count;
3762 ssh->conn_throttle_count += adjust;
3763 assert(ssh->conn_throttle_count >= 0);
3764 if (ssh->conn_throttle_count && !old_count) {
3765 ssh_set_frozen(ssh, 1);
3766 } else if (!ssh->conn_throttle_count && old_count) {
3767 ssh_set_frozen(ssh, 0);
3772 * Throttle or unthrottle _all_ local data streams (for when sends
3773 * on the SSH connection itself back up).
3775 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3778 struct ssh_channel *c;
3780 if (enable == ssh->throttled_all)
3782 ssh->throttled_all = enable;
3783 ssh->overall_bufsize = bufsize;
3786 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3788 case CHAN_MAINSESSION:
3790 * This is treated separately, outside the switch.
3794 x11_override_throttle(c->u.x11.xconn, enable);
3797 /* Agent channels require no buffer management. */
3800 pfd_override_throttle(c->u.pfd.pf, enable);
3806 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3808 Ssh ssh = (Ssh) sshv;
3810 ssh->agent_response = reply;
3811 ssh->agent_response_len = replylen;
3813 if (ssh->version == 1)
3814 do_ssh1_login(ssh, NULL, -1, NULL);
3816 do_ssh2_authconn(ssh, NULL, -1, NULL);
3819 static void ssh_dialog_callback(void *sshv, int ret)
3821 Ssh ssh = (Ssh) sshv;
3823 ssh->user_response = ret;
3825 if (ssh->version == 1)
3826 do_ssh1_login(ssh, NULL, -1, NULL);
3828 do_ssh2_transport(ssh, NULL, -1, NULL);
3831 * This may have unfrozen the SSH connection, so do a
3834 ssh_process_queued_incoming_data(ssh);
3837 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3839 struct ssh_channel *c = (struct ssh_channel *)cv;
3840 const void *sentreply = reply;
3842 c->u.a.outstanding_requests--;
3844 /* Fake SSH_AGENT_FAILURE. */
3845 sentreply = "\0\0\0\1\5";
3848 ssh_send_channel_data(c, sentreply, replylen);
3852 * If we've already seen an incoming EOF but haven't sent an
3853 * outgoing one, this may be the moment to send it.
3855 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3856 sshfwd_write_eof(c);
3860 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3861 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3862 * => log `wire_reason'.
3864 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3865 const char *wire_reason,
3866 int code, int clean_exit)
3870 client_reason = wire_reason;
3872 error = dupprintf("Disconnected: %s", client_reason);
3874 error = dupstr("Disconnected");
3876 if (ssh->version == 1) {
3877 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3879 } else if (ssh->version == 2) {
3880 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3881 ssh2_pkt_adduint32(pktout, code);
3882 ssh2_pkt_addstring(pktout, wire_reason);
3883 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3884 ssh2_pkt_send_noqueue(ssh, pktout);
3887 ssh->close_expected = TRUE;
3888 ssh->clean_exit = clean_exit;
3889 ssh_closing((Plug)ssh, error, 0, 0);
3893 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3894 const struct ssh_signkey *ssh2keytype,
3897 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3898 return -1; /* no manual keys configured */
3903 * The fingerprint string we've been given will have things
3904 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3905 * narrow down to just the colon-separated hex block at the
3906 * end of the string.
3908 const char *p = strrchr(fingerprint, ' ');
3909 fingerprint = p ? p+1 : fingerprint;
3910 /* Quick sanity checks, including making sure it's in lowercase */
3911 assert(strlen(fingerprint) == 16*3 - 1);
3912 assert(fingerprint[2] == ':');
3913 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3915 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3917 return 1; /* success */
3922 * Construct the base64-encoded public key blob and see if
3925 unsigned char *binblob;
3927 int binlen, atoms, i;
3928 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3929 atoms = (binlen + 2) / 3;
3930 base64blob = snewn(atoms * 4 + 1, char);
3931 for (i = 0; i < atoms; i++)
3932 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3933 base64blob[atoms * 4] = '\0';
3935 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3938 return 1; /* success */
3947 * Handle the key exchange and user authentication phases.
3949 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
3950 struct Packet *pktin)
3953 unsigned char cookie[8], *ptr;
3954 struct MD5Context md5c;
3955 struct do_ssh1_login_state {
3958 unsigned char *rsabuf;
3959 const unsigned char *keystr1, *keystr2;
3960 unsigned long supported_ciphers_mask, supported_auths_mask;
3961 int tried_publickey, tried_agent;
3962 int tis_auth_refused, ccard_auth_refused;
3963 unsigned char session_id[16];
3965 void *publickey_blob;
3966 int publickey_bloblen;
3967 char *publickey_comment;
3968 int privatekey_available, privatekey_encrypted;
3969 prompts_t *cur_prompt;
3972 unsigned char request[5], *response, *p;
3982 struct RSAKey servkey, hostkey;
3984 crState(do_ssh1_login_state);
3991 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3992 bombout(("Public key packet not received"));
3996 logevent("Received public keys");
3998 ptr = ssh_pkt_getdata(pktin, 8);
4000 bombout(("SSH-1 public key packet stopped before random cookie"));
4003 memcpy(cookie, ptr, 8);
4005 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
4006 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
4007 bombout(("Failed to read SSH-1 public keys from public key packet"));
4012 * Log the host key fingerprint.
4016 logevent("Host key fingerprint is:");
4017 strcpy(logmsg, " ");
4018 s->hostkey.comment = NULL;
4019 rsa_fingerprint(logmsg + strlen(logmsg),
4020 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
4024 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
4025 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
4026 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
4027 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
4028 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
4030 ssh->v1_local_protoflags =
4031 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
4032 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
4035 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
4036 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
4037 MD5Update(&md5c, cookie, 8);
4038 MD5Final(s->session_id, &md5c);
4040 for (i = 0; i < 32; i++)
4041 ssh->session_key[i] = random_byte();
4044 * Verify that the `bits' and `bytes' parameters match.
4046 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
4047 s->servkey.bits > s->servkey.bytes * 8) {
4048 bombout(("SSH-1 public keys were badly formatted"));
4052 s->len = (s->hostkey.bytes > s->servkey.bytes ?
4053 s->hostkey.bytes : s->servkey.bytes);
4055 s->rsabuf = snewn(s->len, unsigned char);
4058 * Verify the host key.
4062 * First format the key into a string.
4064 int len = rsastr_len(&s->hostkey);
4065 char fingerprint[100];
4066 char *keystr = snewn(len, char);
4067 rsastr_fmt(keystr, &s->hostkey);
4068 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4070 /* First check against manually configured host keys. */
4071 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4072 if (s->dlgret == 0) { /* did not match */
4073 bombout(("Host key did not appear in manually configured list"));
4076 } else if (s->dlgret < 0) { /* none configured; use standard handling */
4077 ssh_set_frozen(ssh, 1);
4078 s->dlgret = verify_ssh_host_key(ssh->frontend,
4079 ssh->savedhost, ssh->savedport,
4080 "rsa", keystr, fingerprint,
4081 ssh_dialog_callback, ssh);
4086 if (s->dlgret < 0) {
4090 bombout(("Unexpected data from server while waiting"
4091 " for user host key response"));
4094 } while (pktin || inlen > 0);
4095 s->dlgret = ssh->user_response;
4097 ssh_set_frozen(ssh, 0);
4099 if (s->dlgret == 0) {
4100 ssh_disconnect(ssh, "User aborted at host key verification",
4109 for (i = 0; i < 32; i++) {
4110 s->rsabuf[i] = ssh->session_key[i];
4112 s->rsabuf[i] ^= s->session_id[i];
4115 if (s->hostkey.bytes > s->servkey.bytes) {
4116 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4118 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4120 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4122 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4125 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4129 logevent("Encrypted session key");
4132 int cipher_chosen = 0, warn = 0;
4133 const char *cipher_string = NULL;
4135 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4136 int next_cipher = conf_get_int_int(ssh->conf,
4137 CONF_ssh_cipherlist, i);
4138 if (next_cipher == CIPHER_WARN) {
4139 /* If/when we choose a cipher, warn about it */
4141 } else if (next_cipher == CIPHER_AES) {
4142 /* XXX Probably don't need to mention this. */
4143 logevent("AES not supported in SSH-1, skipping");
4145 switch (next_cipher) {
4146 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4147 cipher_string = "3DES"; break;
4148 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4149 cipher_string = "Blowfish"; break;
4150 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4151 cipher_string = "single-DES"; break;
4153 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4157 if (!cipher_chosen) {
4158 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4159 bombout(("Server violates SSH-1 protocol by not "
4160 "supporting 3DES encryption"));
4162 /* shouldn't happen */
4163 bombout(("No supported ciphers found"));
4167 /* Warn about chosen cipher if necessary. */
4169 ssh_set_frozen(ssh, 1);
4170 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4171 ssh_dialog_callback, ssh);
4172 if (s->dlgret < 0) {
4176 bombout(("Unexpected data from server while waiting"
4177 " for user response"));
4180 } while (pktin || inlen > 0);
4181 s->dlgret = ssh->user_response;
4183 ssh_set_frozen(ssh, 0);
4184 if (s->dlgret == 0) {
4185 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4192 switch (s->cipher_type) {
4193 case SSH_CIPHER_3DES:
4194 logevent("Using 3DES encryption");
4196 case SSH_CIPHER_DES:
4197 logevent("Using single-DES encryption");
4199 case SSH_CIPHER_BLOWFISH:
4200 logevent("Using Blowfish encryption");
4204 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4205 PKT_CHAR, s->cipher_type,
4206 PKT_DATA, cookie, 8,
4207 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4208 PKT_DATA, s->rsabuf, s->len,
4209 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4211 logevent("Trying to enable encryption...");
4215 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4216 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4218 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4219 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4220 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4222 ssh->crcda_ctx = crcda_make_context();
4223 logevent("Installing CRC compensation attack detector");
4225 if (s->servkey.modulus) {
4226 sfree(s->servkey.modulus);
4227 s->servkey.modulus = NULL;
4229 if (s->servkey.exponent) {
4230 sfree(s->servkey.exponent);
4231 s->servkey.exponent = NULL;
4233 if (s->hostkey.modulus) {
4234 sfree(s->hostkey.modulus);
4235 s->hostkey.modulus = NULL;
4237 if (s->hostkey.exponent) {
4238 sfree(s->hostkey.exponent);
4239 s->hostkey.exponent = NULL;
4243 if (pktin->type != SSH1_SMSG_SUCCESS) {
4244 bombout(("Encryption not successfully enabled"));
4248 logevent("Successfully started encryption");
4250 fflush(stdout); /* FIXME eh? */
4252 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4253 int ret; /* need not be kept over crReturn */
4254 s->cur_prompt = new_prompts(ssh->frontend);
4255 s->cur_prompt->to_server = TRUE;
4256 s->cur_prompt->name = dupstr("SSH login name");
4257 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4258 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4261 crWaitUntil(!pktin);
4262 ret = get_userpass_input(s->cur_prompt, in, inlen);
4267 * Failed to get a username. Terminate.
4269 free_prompts(s->cur_prompt);
4270 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4273 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4274 free_prompts(s->cur_prompt);
4277 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4279 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4281 if (flags & FLAG_INTERACTIVE &&
4282 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4283 c_write_str(ssh, userlog);
4284 c_write_str(ssh, "\r\n");
4292 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4293 /* We must not attempt PK auth. Pretend we've already tried it. */
4294 s->tried_publickey = s->tried_agent = 1;
4296 s->tried_publickey = s->tried_agent = 0;
4298 s->tis_auth_refused = s->ccard_auth_refused = 0;
4300 * Load the public half of any configured keyfile for later use.
4302 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4303 if (!filename_is_null(s->keyfile)) {
4305 logeventf(ssh, "Reading key file \"%.150s\"",
4306 filename_to_str(s->keyfile));
4307 keytype = key_type(s->keyfile);
4308 if (keytype == SSH_KEYTYPE_SSH1 ||
4309 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4311 if (rsakey_pubblob(s->keyfile,
4312 &s->publickey_blob, &s->publickey_bloblen,
4313 &s->publickey_comment, &error)) {
4314 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4315 if (!s->privatekey_available)
4316 logeventf(ssh, "Key file contains public key only");
4317 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4321 logeventf(ssh, "Unable to load key (%s)", error);
4322 msgbuf = dupprintf("Unable to load key file "
4323 "\"%.150s\" (%s)\r\n",
4324 filename_to_str(s->keyfile),
4326 c_write_str(ssh, msgbuf);
4328 s->publickey_blob = NULL;
4332 logeventf(ssh, "Unable to use this key file (%s)",
4333 key_type_to_str(keytype));
4334 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4336 filename_to_str(s->keyfile),
4337 key_type_to_str(keytype));
4338 c_write_str(ssh, msgbuf);
4340 s->publickey_blob = NULL;
4343 s->publickey_blob = NULL;
4345 while (pktin->type == SSH1_SMSG_FAILURE) {
4346 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4348 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4350 * Attempt RSA authentication using Pageant.
4356 logevent("Pageant is running. Requesting keys.");
4358 /* Request the keys held by the agent. */
4359 PUT_32BIT(s->request, 1);
4360 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4361 if (!agent_query(s->request, 5, &r, &s->responselen,
4362 ssh_agent_callback, ssh)) {
4366 bombout(("Unexpected data from server while waiting"
4367 " for agent response"));
4370 } while (pktin || inlen > 0);
4371 r = ssh->agent_response;
4372 s->responselen = ssh->agent_response_len;
4374 s->response = (unsigned char *) r;
4375 if (s->response && s->responselen >= 5 &&
4376 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4377 s->p = s->response + 5;
4378 s->nkeys = toint(GET_32BIT(s->p));
4380 logeventf(ssh, "Pageant reported negative key count %d",
4385 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4386 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4387 unsigned char *pkblob = s->p;
4391 do { /* do while (0) to make breaking easy */
4392 n = ssh1_read_bignum
4393 (s->p, toint(s->responselen-(s->p-s->response)),
4398 n = ssh1_read_bignum
4399 (s->p, toint(s->responselen-(s->p-s->response)),
4404 if (s->responselen - (s->p-s->response) < 4)
4406 s->commentlen = toint(GET_32BIT(s->p));
4408 if (s->commentlen < 0 ||
4409 toint(s->responselen - (s->p-s->response)) <
4412 s->commentp = (char *)s->p;
4413 s->p += s->commentlen;
4417 logevent("Pageant key list packet was truncated");
4421 if (s->publickey_blob) {
4422 if (!memcmp(pkblob, s->publickey_blob,
4423 s->publickey_bloblen)) {
4424 logeventf(ssh, "Pageant key #%d matches "
4425 "configured key file", s->keyi);
4426 s->tried_publickey = 1;
4428 /* Skip non-configured key */
4431 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4432 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4433 PKT_BIGNUM, s->key.modulus, PKT_END);
4435 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4436 logevent("Key refused");
4439 logevent("Received RSA challenge");
4440 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4441 bombout(("Server's RSA challenge was badly formatted"));
4446 char *agentreq, *q, *ret;
4449 len = 1 + 4; /* message type, bit count */
4450 len += ssh1_bignum_length(s->key.exponent);
4451 len += ssh1_bignum_length(s->key.modulus);
4452 len += ssh1_bignum_length(s->challenge);
4453 len += 16; /* session id */
4454 len += 4; /* response format */
4455 agentreq = snewn(4 + len, char);
4456 PUT_32BIT(agentreq, len);
4458 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4459 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4461 q += ssh1_write_bignum(q, s->key.exponent);
4462 q += ssh1_write_bignum(q, s->key.modulus);
4463 q += ssh1_write_bignum(q, s->challenge);
4464 memcpy(q, s->session_id, 16);
4466 PUT_32BIT(q, 1); /* response format */
4467 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4468 ssh_agent_callback, ssh)) {
4473 bombout(("Unexpected data from server"
4474 " while waiting for agent"
4478 } while (pktin || inlen > 0);
4479 vret = ssh->agent_response;
4480 retlen = ssh->agent_response_len;
4485 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4486 logevent("Sending Pageant's response");
4487 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4488 PKT_DATA, ret + 5, 16,
4492 if (pktin->type == SSH1_SMSG_SUCCESS) {
4494 ("Pageant's response accepted");
4495 if (flags & FLAG_VERBOSE) {
4496 c_write_str(ssh, "Authenticated using"
4498 c_write(ssh, s->commentp,
4500 c_write_str(ssh, "\" from agent\r\n");
4505 ("Pageant's response not accepted");
4508 ("Pageant failed to answer challenge");
4512 logevent("No reply received from Pageant");
4515 freebn(s->key.exponent);
4516 freebn(s->key.modulus);
4517 freebn(s->challenge);
4522 if (s->publickey_blob && !s->tried_publickey)
4523 logevent("Configured key file not in Pageant");
4525 logevent("Failed to get reply from Pageant");
4530 if (s->publickey_blob && s->privatekey_available &&
4531 !s->tried_publickey) {
4533 * Try public key authentication with the specified
4536 int got_passphrase; /* need not be kept over crReturn */
4537 if (flags & FLAG_VERBOSE)
4538 c_write_str(ssh, "Trying public key authentication.\r\n");
4539 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4540 logeventf(ssh, "Trying public key \"%s\"",
4541 filename_to_str(s->keyfile));
4542 s->tried_publickey = 1;
4543 got_passphrase = FALSE;
4544 while (!got_passphrase) {
4546 * Get a passphrase, if necessary.
4548 char *passphrase = NULL; /* only written after crReturn */
4550 if (!s->privatekey_encrypted) {
4551 if (flags & FLAG_VERBOSE)
4552 c_write_str(ssh, "No passphrase required.\r\n");
4555 int ret; /* need not be kept over crReturn */
4556 s->cur_prompt = new_prompts(ssh->frontend);
4557 s->cur_prompt->to_server = FALSE;
4558 s->cur_prompt->name = dupstr("SSH key passphrase");
4559 add_prompt(s->cur_prompt,
4560 dupprintf("Passphrase for key \"%.100s\": ",
4561 s->publickey_comment), FALSE);
4562 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4565 crWaitUntil(!pktin);
4566 ret = get_userpass_input(s->cur_prompt, in, inlen);
4570 /* Failed to get a passphrase. Terminate. */
4571 free_prompts(s->cur_prompt);
4572 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4576 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4577 free_prompts(s->cur_prompt);
4580 * Try decrypting key with passphrase.
4582 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4583 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4586 smemclr(passphrase, strlen(passphrase));
4590 /* Correct passphrase. */
4591 got_passphrase = TRUE;
4592 } else if (ret == 0) {
4593 c_write_str(ssh, "Couldn't load private key from ");
4594 c_write_str(ssh, filename_to_str(s->keyfile));
4595 c_write_str(ssh, " (");
4596 c_write_str(ssh, error);
4597 c_write_str(ssh, ").\r\n");
4598 got_passphrase = FALSE;
4599 break; /* go and try something else */
4600 } else if (ret == -1) {
4601 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4602 got_passphrase = FALSE;
4605 assert(0 && "unexpected return from loadrsakey()");
4606 got_passphrase = FALSE; /* placate optimisers */
4610 if (got_passphrase) {
4613 * Send a public key attempt.
4615 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4616 PKT_BIGNUM, s->key.modulus, PKT_END);
4619 if (pktin->type == SSH1_SMSG_FAILURE) {
4620 c_write_str(ssh, "Server refused our public key.\r\n");
4621 continue; /* go and try something else */
4623 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4624 bombout(("Bizarre response to offer of public key"));
4630 unsigned char buffer[32];
4631 Bignum challenge, response;
4633 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4634 bombout(("Server's RSA challenge was badly formatted"));
4637 response = rsadecrypt(challenge, &s->key);
4638 freebn(s->key.private_exponent);/* burn the evidence */
4640 for (i = 0; i < 32; i++) {
4641 buffer[i] = bignum_byte(response, 31 - i);
4645 MD5Update(&md5c, buffer, 32);
4646 MD5Update(&md5c, s->session_id, 16);
4647 MD5Final(buffer, &md5c);
4649 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4650 PKT_DATA, buffer, 16, PKT_END);
4657 if (pktin->type == SSH1_SMSG_FAILURE) {
4658 if (flags & FLAG_VERBOSE)
4659 c_write_str(ssh, "Failed to authenticate with"
4660 " our public key.\r\n");
4661 continue; /* go and try something else */
4662 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4663 bombout(("Bizarre response to RSA authentication response"));
4667 break; /* we're through! */
4673 * Otherwise, try various forms of password-like authentication.
4675 s->cur_prompt = new_prompts(ssh->frontend);
4677 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4678 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4679 !s->tis_auth_refused) {
4680 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4681 logevent("Requested TIS authentication");
4682 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4684 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4685 logevent("TIS authentication declined");
4686 if (flags & FLAG_INTERACTIVE)
4687 c_write_str(ssh, "TIS authentication refused.\r\n");
4688 s->tis_auth_refused = 1;
4693 char *instr_suf, *prompt;
4695 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4697 bombout(("TIS challenge packet was badly formed"));
4700 logevent("Received TIS challenge");
4701 s->cur_prompt->to_server = TRUE;
4702 s->cur_prompt->name = dupstr("SSH TIS authentication");
4703 /* Prompt heuristic comes from OpenSSH */
4704 if (memchr(challenge, '\n', challengelen)) {
4705 instr_suf = dupstr("");
4706 prompt = dupprintf("%.*s", challengelen, challenge);
4708 instr_suf = dupprintf("%.*s", challengelen, challenge);
4709 prompt = dupstr("Response: ");
4711 s->cur_prompt->instruction =
4712 dupprintf("Using TIS authentication.%s%s",
4713 (*instr_suf) ? "\n" : "",
4715 s->cur_prompt->instr_reqd = TRUE;
4716 add_prompt(s->cur_prompt, prompt, FALSE);
4720 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4721 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4722 !s->ccard_auth_refused) {
4723 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4724 logevent("Requested CryptoCard authentication");
4725 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4727 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4728 logevent("CryptoCard authentication declined");
4729 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4730 s->ccard_auth_refused = 1;
4735 char *instr_suf, *prompt;
4737 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4739 bombout(("CryptoCard challenge packet was badly formed"));
4742 logevent("Received CryptoCard challenge");
4743 s->cur_prompt->to_server = TRUE;
4744 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4745 s->cur_prompt->name_reqd = FALSE;
4746 /* Prompt heuristic comes from OpenSSH */
4747 if (memchr(challenge, '\n', challengelen)) {
4748 instr_suf = dupstr("");
4749 prompt = dupprintf("%.*s", challengelen, challenge);
4751 instr_suf = dupprintf("%.*s", challengelen, challenge);
4752 prompt = dupstr("Response: ");
4754 s->cur_prompt->instruction =
4755 dupprintf("Using CryptoCard authentication.%s%s",
4756 (*instr_suf) ? "\n" : "",
4758 s->cur_prompt->instr_reqd = TRUE;
4759 add_prompt(s->cur_prompt, prompt, FALSE);
4763 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4764 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4765 bombout(("No supported authentication methods available"));
4768 s->cur_prompt->to_server = TRUE;
4769 s->cur_prompt->name = dupstr("SSH password");
4770 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4771 ssh->username, ssh->savedhost),
4776 * Show password prompt, having first obtained it via a TIS
4777 * or CryptoCard exchange if we're doing TIS or CryptoCard
4781 int ret; /* need not be kept over crReturn */
4782 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4785 crWaitUntil(!pktin);
4786 ret = get_userpass_input(s->cur_prompt, in, inlen);
4791 * Failed to get a password (for example
4792 * because one was supplied on the command line
4793 * which has already failed to work). Terminate.
4795 free_prompts(s->cur_prompt);
4796 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4801 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4803 * Defence against traffic analysis: we send a
4804 * whole bunch of packets containing strings of
4805 * different lengths. One of these strings is the
4806 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4807 * The others are all random data in
4808 * SSH1_MSG_IGNORE packets. This way a passive
4809 * listener can't tell which is the password, and
4810 * hence can't deduce the password length.
4812 * Anybody with a password length greater than 16
4813 * bytes is going to have enough entropy in their
4814 * password that a listener won't find it _that_
4815 * much help to know how long it is. So what we'll
4818 * - if password length < 16, we send 15 packets
4819 * containing string lengths 1 through 15
4821 * - otherwise, we let N be the nearest multiple
4822 * of 8 below the password length, and send 8
4823 * packets containing string lengths N through
4824 * N+7. This won't obscure the order of
4825 * magnitude of the password length, but it will
4826 * introduce a bit of extra uncertainty.
4828 * A few servers can't deal with SSH1_MSG_IGNORE, at
4829 * least in this context. For these servers, we need
4830 * an alternative defence. We make use of the fact
4831 * that the password is interpreted as a C string:
4832 * so we can append a NUL, then some random data.
4834 * A few servers can deal with neither SSH1_MSG_IGNORE
4835 * here _nor_ a padded password string.
4836 * For these servers we are left with no defences
4837 * against password length sniffing.
4839 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4840 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4842 * The server can deal with SSH1_MSG_IGNORE, so
4843 * we can use the primary defence.
4845 int bottom, top, pwlen, i;
4848 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4850 bottom = 0; /* zero length passwords are OK! :-) */
4853 bottom = pwlen & ~7;
4857 assert(pwlen >= bottom && pwlen <= top);
4859 randomstr = snewn(top + 1, char);
4861 for (i = bottom; i <= top; i++) {
4863 defer_packet(ssh, s->pwpkt_type,
4864 PKT_STR,s->cur_prompt->prompts[0]->result,
4867 for (j = 0; j < i; j++) {
4869 randomstr[j] = random_byte();
4870 } while (randomstr[j] == '\0');
4872 randomstr[i] = '\0';
4873 defer_packet(ssh, SSH1_MSG_IGNORE,
4874 PKT_STR, randomstr, PKT_END);
4877 logevent("Sending password with camouflage packets");
4878 ssh_pkt_defersend(ssh);
4881 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4883 * The server can't deal with SSH1_MSG_IGNORE
4884 * but can deal with padded passwords, so we
4885 * can use the secondary defence.
4891 len = strlen(s->cur_prompt->prompts[0]->result);
4892 if (len < sizeof(string)) {
4894 strcpy(string, s->cur_prompt->prompts[0]->result);
4895 len++; /* cover the zero byte */
4896 while (len < sizeof(string)) {
4897 string[len++] = (char) random_byte();
4900 ss = s->cur_prompt->prompts[0]->result;
4902 logevent("Sending length-padded password");
4903 send_packet(ssh, s->pwpkt_type,
4904 PKT_INT, len, PKT_DATA, ss, len,
4908 * The server is believed unable to cope with
4909 * any of our password camouflage methods.
4912 len = strlen(s->cur_prompt->prompts[0]->result);
4913 logevent("Sending unpadded password");
4914 send_packet(ssh, s->pwpkt_type,
4916 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4920 send_packet(ssh, s->pwpkt_type,
4921 PKT_STR, s->cur_prompt->prompts[0]->result,
4924 logevent("Sent password");
4925 free_prompts(s->cur_prompt);
4927 if (pktin->type == SSH1_SMSG_FAILURE) {
4928 if (flags & FLAG_VERBOSE)
4929 c_write_str(ssh, "Access denied\r\n");
4930 logevent("Authentication refused");
4931 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4932 bombout(("Strange packet received, type %d", pktin->type));
4938 if (s->publickey_blob) {
4939 sfree(s->publickey_blob);
4940 sfree(s->publickey_comment);
4943 logevent("Authentication successful");
4948 static void ssh_channel_try_eof(struct ssh_channel *c)
4951 assert(c->pending_eof); /* precondition for calling us */
4953 return; /* can't close: not even opened yet */
4954 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4955 return; /* can't send EOF: pending outgoing data */
4957 c->pending_eof = FALSE; /* we're about to send it */
4958 if (ssh->version == 1) {
4959 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4961 c->closes |= CLOSES_SENT_EOF;
4963 struct Packet *pktout;
4964 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4965 ssh2_pkt_adduint32(pktout, c->remoteid);
4966 ssh2_pkt_send(ssh, pktout);
4967 c->closes |= CLOSES_SENT_EOF;
4968 ssh2_channel_check_close(c);
4972 Conf *sshfwd_get_conf(struct ssh_channel *c)
4978 void sshfwd_write_eof(struct ssh_channel *c)
4982 if (ssh->state == SSH_STATE_CLOSED)
4985 if (c->closes & CLOSES_SENT_EOF)
4988 c->pending_eof = TRUE;
4989 ssh_channel_try_eof(c);
4992 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
4996 if (ssh->state == SSH_STATE_CLOSED)
5001 x11_close(c->u.x11.xconn);
5002 logeventf(ssh, "Forwarded X11 connection terminated due to local "
5006 case CHAN_SOCKDATA_DORMANT:
5007 pfd_close(c->u.pfd.pf);
5008 logeventf(ssh, "Forwarded port closed due to local error: %s", err);
5011 c->type = CHAN_ZOMBIE;
5012 c->pending_eof = FALSE; /* this will confuse a zombie channel */
5014 ssh2_channel_check_close(c);
5017 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
5021 if (ssh->state == SSH_STATE_CLOSED)
5024 return ssh_send_channel_data(c, buf, len);
5027 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
5032 if (ssh->state == SSH_STATE_CLOSED)
5035 if (ssh->version == 1) {
5036 buflimit = SSH1_BUFFER_LIMIT;
5038 buflimit = c->v.v2.locmaxwin;
5039 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
5041 if (c->throttling_conn && bufsize <= buflimit) {
5042 c->throttling_conn = 0;
5043 ssh_throttle_conn(ssh, -1);
5047 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
5049 struct queued_handler *qh = ssh->qhead;
5053 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5056 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5057 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5060 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5061 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5065 ssh->qhead = qh->next;
5067 if (ssh->qhead->msg1 > 0) {
5068 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5069 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5071 if (ssh->qhead->msg2 > 0) {
5072 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5073 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5076 ssh->qhead = ssh->qtail = NULL;
5079 qh->handler(ssh, pktin, qh->ctx);
5084 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5085 chandler_fn_t handler, void *ctx)
5087 struct queued_handler *qh;
5089 qh = snew(struct queued_handler);
5092 qh->handler = handler;
5096 if (ssh->qtail == NULL) {
5100 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5101 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5104 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5105 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5108 ssh->qtail->next = qh;
5113 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5115 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5117 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5118 SSH2_MSG_REQUEST_SUCCESS)) {
5119 logeventf(ssh, "Remote port forwarding from %s enabled",
5122 logeventf(ssh, "Remote port forwarding from %s refused",
5125 rpf = del234(ssh->rportfwds, pf);
5127 pf->pfrec->remote = NULL;
5132 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5135 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5138 pf->share_ctx = share_ctx;
5139 pf->shost = dupstr(shost);
5141 pf->sportdesc = NULL;
5142 if (!ssh->rportfwds) {
5143 assert(ssh->version == 2);
5144 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5146 if (add234(ssh->rportfwds, pf) != pf) {
5154 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5157 share_got_pkt_from_server(ctx, pktin->type,
5158 pktin->body, pktin->length);
5161 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5163 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5164 ssh_sharing_global_request_response, share_ctx);
5167 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5169 struct ssh_portfwd *epf;
5173 if (!ssh->portfwds) {
5174 ssh->portfwds = newtree234(ssh_portcmp);
5177 * Go through the existing port forwardings and tag them
5178 * with status==DESTROY. Any that we want to keep will be
5179 * re-enabled (status==KEEP) as we go through the
5180 * configuration and find out which bits are the same as
5183 struct ssh_portfwd *epf;
5185 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5186 epf->status = DESTROY;
5189 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5191 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5192 char *kp, *kp2, *vp, *vp2;
5193 char address_family, type;
5194 int sport,dport,sserv,dserv;
5195 char *sports, *dports, *saddr, *host;
5199 address_family = 'A';
5201 if (*kp == 'A' || *kp == '4' || *kp == '6')
5202 address_family = *kp++;
5203 if (*kp == 'L' || *kp == 'R')
5206 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5208 * There's a colon in the middle of the source port
5209 * string, which means that the part before it is
5210 * actually a source address.
5212 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5213 saddr = host_strduptrim(saddr_tmp);
5220 sport = atoi(sports);
5224 sport = net_service_lookup(sports);
5226 logeventf(ssh, "Service lookup failed for source"
5227 " port \"%s\"", sports);
5231 if (type == 'L' && !strcmp(val, "D")) {
5232 /* dynamic forwarding */
5239 /* ordinary forwarding */
5241 vp2 = vp + host_strcspn(vp, ":");
5242 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5246 dport = atoi(dports);
5250 dport = net_service_lookup(dports);
5252 logeventf(ssh, "Service lookup failed for destination"
5253 " port \"%s\"", dports);
5258 if (sport && dport) {
5259 /* Set up a description of the source port. */
5260 struct ssh_portfwd *pfrec, *epfrec;
5262 pfrec = snew(struct ssh_portfwd);
5264 pfrec->saddr = saddr;
5265 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5266 pfrec->sport = sport;
5267 pfrec->daddr = host;
5268 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5269 pfrec->dport = dport;
5270 pfrec->local = NULL;
5271 pfrec->remote = NULL;
5272 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5273 address_family == '6' ? ADDRTYPE_IPV6 :
5276 epfrec = add234(ssh->portfwds, pfrec);
5277 if (epfrec != pfrec) {
5278 if (epfrec->status == DESTROY) {
5280 * We already have a port forwarding up and running
5281 * with precisely these parameters. Hence, no need
5282 * to do anything; simply re-tag the existing one
5285 epfrec->status = KEEP;
5288 * Anything else indicates that there was a duplicate
5289 * in our input, which we'll silently ignore.
5291 free_portfwd(pfrec);
5293 pfrec->status = CREATE;
5302 * Now go through and destroy any port forwardings which were
5305 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5306 if (epf->status == DESTROY) {
5309 message = dupprintf("%s port forwarding from %s%s%d",
5310 epf->type == 'L' ? "local" :
5311 epf->type == 'R' ? "remote" : "dynamic",
5312 epf->saddr ? epf->saddr : "",
5313 epf->saddr ? ":" : "",
5316 if (epf->type != 'D') {
5317 char *msg2 = dupprintf("%s to %s:%d", message,
5318 epf->daddr, epf->dport);
5323 logeventf(ssh, "Cancelling %s", message);
5326 /* epf->remote or epf->local may be NULL if setting up a
5327 * forwarding failed. */
5329 struct ssh_rportfwd *rpf = epf->remote;
5330 struct Packet *pktout;
5333 * Cancel the port forwarding at the server
5336 if (ssh->version == 1) {
5338 * We cannot cancel listening ports on the
5339 * server side in SSH-1! There's no message
5340 * to support it. Instead, we simply remove
5341 * the rportfwd record from the local end
5342 * so that any connections the server tries
5343 * to make on it are rejected.
5346 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5347 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5348 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5350 ssh2_pkt_addstring(pktout, epf->saddr);
5351 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5352 /* XXX: rport_acceptall may not represent
5353 * what was used to open the original connection,
5354 * since it's reconfigurable. */
5355 ssh2_pkt_addstring(pktout, "");
5357 ssh2_pkt_addstring(pktout, "localhost");
5359 ssh2_pkt_adduint32(pktout, epf->sport);
5360 ssh2_pkt_send(ssh, pktout);
5363 del234(ssh->rportfwds, rpf);
5365 } else if (epf->local) {
5366 pfl_terminate(epf->local);
5369 delpos234(ssh->portfwds, i);
5371 i--; /* so we don't skip one in the list */
5375 * And finally, set up any new port forwardings (status==CREATE).
5377 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5378 if (epf->status == CREATE) {
5379 char *sportdesc, *dportdesc;
5380 sportdesc = dupprintf("%s%s%s%s%d%s",
5381 epf->saddr ? epf->saddr : "",
5382 epf->saddr ? ":" : "",
5383 epf->sserv ? epf->sserv : "",
5384 epf->sserv ? "(" : "",
5386 epf->sserv ? ")" : "");
5387 if (epf->type == 'D') {
5390 dportdesc = dupprintf("%s:%s%s%d%s",
5392 epf->dserv ? epf->dserv : "",
5393 epf->dserv ? "(" : "",
5395 epf->dserv ? ")" : "");
5398 if (epf->type == 'L') {
5399 char *err = pfl_listen(epf->daddr, epf->dport,
5400 epf->saddr, epf->sport,
5401 ssh, conf, &epf->local,
5402 epf->addressfamily);
5404 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5405 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5406 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5407 sportdesc, dportdesc,
5408 err ? " failed: " : "", err ? err : "");
5411 } else if (epf->type == 'D') {
5412 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5413 ssh, conf, &epf->local,
5414 epf->addressfamily);
5416 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5417 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5418 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5420 err ? " failed: " : "", err ? err : "");
5425 struct ssh_rportfwd *pf;
5428 * Ensure the remote port forwardings tree exists.
5430 if (!ssh->rportfwds) {
5431 if (ssh->version == 1)
5432 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5434 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5437 pf = snew(struct ssh_rportfwd);
5438 pf->share_ctx = NULL;
5439 pf->dhost = dupstr(epf->daddr);
5440 pf->dport = epf->dport;
5442 pf->shost = dupstr(epf->saddr);
5443 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5444 pf->shost = dupstr("");
5446 pf->shost = dupstr("localhost");
5448 pf->sport = epf->sport;
5449 if (add234(ssh->rportfwds, pf) != pf) {
5450 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5451 epf->daddr, epf->dport);
5454 logeventf(ssh, "Requesting remote port %s"
5455 " forward to %s", sportdesc, dportdesc);
5457 pf->sportdesc = sportdesc;
5462 if (ssh->version == 1) {
5463 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5464 PKT_INT, epf->sport,
5465 PKT_STR, epf->daddr,
5466 PKT_INT, epf->dport,
5468 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5470 ssh_rportfwd_succfail, pf);
5472 struct Packet *pktout;
5473 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5474 ssh2_pkt_addstring(pktout, "tcpip-forward");
5475 ssh2_pkt_addbool(pktout, 1);/* want reply */
5476 ssh2_pkt_addstring(pktout, pf->shost);
5477 ssh2_pkt_adduint32(pktout, pf->sport);
5478 ssh2_pkt_send(ssh, pktout);
5480 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5481 SSH2_MSG_REQUEST_FAILURE,
5482 ssh_rportfwd_succfail, pf);
5491 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5494 int stringlen, bufsize;
5496 ssh_pkt_getstring(pktin, &string, &stringlen);
5497 if (string == NULL) {
5498 bombout(("Incoming terminal data packet was badly formed"));
5502 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5504 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5505 ssh->v1_stdout_throttling = 1;
5506 ssh_throttle_conn(ssh, +1);
5510 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5512 /* Remote side is trying to open a channel to talk to our
5513 * X-Server. Give them back a local channel number. */
5514 struct ssh_channel *c;
5515 int remoteid = ssh_pkt_getuint32(pktin);
5517 logevent("Received X11 connect request");
5518 /* Refuse if X11 forwarding is disabled. */
5519 if (!ssh->X11_fwd_enabled) {
5520 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5521 PKT_INT, remoteid, PKT_END);
5522 logevent("Rejected X11 connect request");
5524 c = snew(struct ssh_channel);
5527 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5528 c->remoteid = remoteid;
5529 c->halfopen = FALSE;
5530 c->localid = alloc_channel_id(ssh);
5532 c->pending_eof = FALSE;
5533 c->throttling_conn = 0;
5534 c->type = CHAN_X11; /* identify channel type */
5535 add234(ssh->channels, c);
5536 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5537 PKT_INT, c->remoteid, PKT_INT,
5538 c->localid, PKT_END);
5539 logevent("Opened X11 forward channel");
5543 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5545 /* Remote side is trying to open a channel to talk to our
5546 * agent. Give them back a local channel number. */
5547 struct ssh_channel *c;
5548 int remoteid = ssh_pkt_getuint32(pktin);
5550 /* Refuse if agent forwarding is disabled. */
5551 if (!ssh->agentfwd_enabled) {
5552 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5553 PKT_INT, remoteid, PKT_END);
5555 c = snew(struct ssh_channel);
5557 c->remoteid = remoteid;
5558 c->halfopen = FALSE;
5559 c->localid = alloc_channel_id(ssh);
5561 c->pending_eof = FALSE;
5562 c->throttling_conn = 0;
5563 c->type = CHAN_AGENT; /* identify channel type */
5564 c->u.a.lensofar = 0;
5565 c->u.a.message = NULL;
5566 c->u.a.outstanding_requests = 0;
5567 add234(ssh->channels, c);
5568 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5569 PKT_INT, c->remoteid, PKT_INT, c->localid,
5574 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5576 /* Remote side is trying to open a channel to talk to a
5577 * forwarded port. Give them back a local channel number. */
5578 struct ssh_rportfwd pf, *pfp;
5584 remoteid = ssh_pkt_getuint32(pktin);
5585 ssh_pkt_getstring(pktin, &host, &hostsize);
5586 port = ssh_pkt_getuint32(pktin);
5588 pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
5590 pfp = find234(ssh->rportfwds, &pf, NULL);
5593 logeventf(ssh, "Rejected remote port open request for %s:%d",
5595 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5596 PKT_INT, remoteid, PKT_END);
5598 struct ssh_channel *c = snew(struct ssh_channel);
5601 logeventf(ssh, "Received remote port open request for %s:%d",
5603 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5604 c, ssh->conf, pfp->pfrec->addressfamily);
5606 logeventf(ssh, "Port open failed: %s", err);
5609 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5610 PKT_INT, remoteid, PKT_END);
5612 c->remoteid = remoteid;
5613 c->halfopen = FALSE;
5614 c->localid = alloc_channel_id(ssh);
5616 c->pending_eof = FALSE;
5617 c->throttling_conn = 0;
5618 c->type = CHAN_SOCKDATA; /* identify channel type */
5619 add234(ssh->channels, c);
5620 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5621 PKT_INT, c->remoteid, PKT_INT,
5622 c->localid, PKT_END);
5623 logevent("Forwarded port opened successfully");
5630 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5632 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5633 unsigned int localid = ssh_pkt_getuint32(pktin);
5634 struct ssh_channel *c;
5636 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5637 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5638 c->remoteid = localid;
5639 c->halfopen = FALSE;
5640 c->type = CHAN_SOCKDATA;
5641 c->throttling_conn = 0;
5642 pfd_confirm(c->u.pfd.pf);
5645 if (c && c->pending_eof) {
5647 * We have a pending close on this channel,
5648 * which we decided on before the server acked
5649 * the channel open. So now we know the
5650 * remoteid, we can close it again.
5652 ssh_channel_try_eof(c);
5656 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5658 unsigned int remoteid = ssh_pkt_getuint32(pktin);
5659 struct ssh_channel *c;
5661 c = find234(ssh->channels, &remoteid, ssh_channelfind);
5662 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
5663 logevent("Forwarded connection refused by server");
5664 pfd_close(c->u.pfd.pf);
5665 del234(ssh->channels, c);
5670 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5672 /* Remote side closes a channel. */
5673 unsigned i = ssh_pkt_getuint32(pktin);
5674 struct ssh_channel *c;
5675 c = find234(ssh->channels, &i, ssh_channelfind);
5676 if (c && !c->halfopen) {
5678 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
5679 !(c->closes & CLOSES_RCVD_EOF)) {
5681 * Received CHANNEL_CLOSE, which we translate into
5684 int send_close = FALSE;
5686 c->closes |= CLOSES_RCVD_EOF;
5691 x11_send_eof(c->u.x11.xconn);
5697 pfd_send_eof(c->u.pfd.pf);
5706 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
5707 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
5709 c->closes |= CLOSES_SENT_EOF;
5713 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5714 !(c->closes & CLOSES_RCVD_CLOSE)) {
5716 if (!(c->closes & CLOSES_SENT_EOF)) {
5717 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
5718 " for which we never sent CHANNEL_CLOSE\n", i));
5721 c->closes |= CLOSES_RCVD_CLOSE;
5724 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5725 !(c->closes & CLOSES_SENT_CLOSE)) {
5726 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5727 PKT_INT, c->remoteid, PKT_END);
5728 c->closes |= CLOSES_SENT_CLOSE;
5731 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5732 ssh_channel_destroy(c);
5734 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
5735 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
5736 "_CONFIRMATION", c ? "half-open" : "nonexistent",
5742 * Handle incoming data on an SSH-1 or SSH-2 agent-forwarding channel.
5744 static int ssh_agent_channel_data(struct ssh_channel *c, char *data,
5747 while (length > 0) {
5748 if (c->u.a.lensofar < 4) {
5749 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)length);
5750 memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
5753 c->u.a.lensofar += l;
5755 if (c->u.a.lensofar == 4) {
5756 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
5757 c->u.a.message = snewn(c->u.a.totallen, unsigned char);
5758 memcpy(c->u.a.message, c->u.a.msglen, 4);
5760 if (c->u.a.lensofar >= 4 && length > 0) {
5761 unsigned int l = min(c->u.a.totallen - c->u.a.lensofar,
5763 memcpy(c->u.a.message + c->u.a.lensofar, data, l);
5766 c->u.a.lensofar += l;
5768 if (c->u.a.lensofar == c->u.a.totallen) {
5771 c->u.a.outstanding_requests++;
5772 if (agent_query(c->u.a.message, c->u.a.totallen, &reply, &replylen,
5773 ssh_agentf_callback, c))
5774 ssh_agentf_callback(c, reply, replylen);
5775 sfree(c->u.a.message);
5776 c->u.a.message = NULL;
5777 c->u.a.lensofar = 0;
5780 return 0; /* agent channels never back up */
5783 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5785 /* Data sent down one of our channels. */
5786 int i = ssh_pkt_getuint32(pktin);
5789 struct ssh_channel *c;
5791 ssh_pkt_getstring(pktin, &p, &len);
5793 c = find234(ssh->channels, &i, ssh_channelfind);
5798 bufsize = x11_send(c->u.x11.xconn, p, len);
5801 bufsize = pfd_send(c->u.pfd.pf, p, len);
5804 bufsize = ssh_agent_channel_data(c, p, len);
5807 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5808 c->throttling_conn = 1;
5809 ssh_throttle_conn(ssh, +1);
5814 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5816 ssh->exitcode = ssh_pkt_getuint32(pktin);
5817 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5818 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5820 * In case `helpful' firewalls or proxies tack
5821 * extra human-readable text on the end of the
5822 * session which we might mistake for another
5823 * encrypted packet, we close the session once
5824 * we've sent EXIT_CONFIRMATION.
5826 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5829 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5830 static void ssh1_send_ttymode(void *data,
5831 const struct ssh_ttymode *mode, char *val)
5833 struct Packet *pktout = (struct Packet *)data;
5834 unsigned int arg = 0;
5836 switch (mode->type) {
5838 arg = ssh_tty_parse_specchar(val);
5841 arg = ssh_tty_parse_boolean(val);
5844 ssh2_pkt_addbyte(pktout, mode->opcode);
5845 ssh2_pkt_addbyte(pktout, arg);
5848 int ssh_agent_forwarding_permitted(Ssh ssh)
5850 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5853 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5854 struct Packet *pktin)
5856 crBegin(ssh->do_ssh1_connection_crstate);
5858 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5859 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5860 ssh1_smsg_stdout_stderr_data;
5862 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5863 ssh1_msg_channel_open_confirmation;
5864 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5865 ssh1_msg_channel_open_failure;
5866 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5867 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5868 ssh1_msg_channel_close;
5869 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5870 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5872 if (ssh_agent_forwarding_permitted(ssh)) {
5873 logevent("Requesting agent forwarding");
5874 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5878 if (pktin->type != SSH1_SMSG_SUCCESS
5879 && pktin->type != SSH1_SMSG_FAILURE) {
5880 bombout(("Protocol confusion"));
5882 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5883 logevent("Agent forwarding refused");
5885 logevent("Agent forwarding enabled");
5886 ssh->agentfwd_enabled = TRUE;
5887 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5891 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5893 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5895 if (!ssh->x11disp) {
5896 /* FIXME: return an error message from x11_setup_display */
5897 logevent("X11 forwarding not enabled: unable to"
5898 " initialise X display");
5900 ssh->x11auth = x11_invent_fake_auth
5901 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5902 ssh->x11auth->disp = ssh->x11disp;
5904 logevent("Requesting X11 forwarding");
5905 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5906 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5907 PKT_STR, ssh->x11auth->protoname,
5908 PKT_STR, ssh->x11auth->datastring,
5909 PKT_INT, ssh->x11disp->screennum,
5912 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5913 PKT_STR, ssh->x11auth->protoname,
5914 PKT_STR, ssh->x11auth->datastring,
5920 if (pktin->type != SSH1_SMSG_SUCCESS
5921 && pktin->type != SSH1_SMSG_FAILURE) {
5922 bombout(("Protocol confusion"));
5924 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5925 logevent("X11 forwarding refused");
5927 logevent("X11 forwarding enabled");
5928 ssh->X11_fwd_enabled = TRUE;
5929 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5934 ssh_setup_portfwd(ssh, ssh->conf);
5935 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5937 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5939 /* Unpick the terminal-speed string. */
5940 /* XXX perhaps we should allow no speeds to be sent. */
5941 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5942 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5943 /* Send the pty request. */
5944 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5945 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5946 ssh_pkt_adduint32(pkt, ssh->term_height);
5947 ssh_pkt_adduint32(pkt, ssh->term_width);
5948 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5949 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5950 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5951 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5952 ssh_pkt_adduint32(pkt, ssh->ispeed);
5953 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5954 ssh_pkt_adduint32(pkt, ssh->ospeed);
5955 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5957 ssh->state = SSH_STATE_INTERMED;
5961 if (pktin->type != SSH1_SMSG_SUCCESS
5962 && pktin->type != SSH1_SMSG_FAILURE) {
5963 bombout(("Protocol confusion"));
5965 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5966 c_write_str(ssh, "Server refused to allocate pty\r\n");
5967 ssh->editing = ssh->echoing = 1;
5969 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5970 ssh->ospeed, ssh->ispeed);
5971 ssh->got_pty = TRUE;
5974 ssh->editing = ssh->echoing = 1;
5977 if (conf_get_int(ssh->conf, CONF_compression)) {
5978 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5982 if (pktin->type != SSH1_SMSG_SUCCESS
5983 && pktin->type != SSH1_SMSG_FAILURE) {
5984 bombout(("Protocol confusion"));
5986 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5987 c_write_str(ssh, "Server refused to compress\r\n");
5989 logevent("Started compression");
5990 ssh->v1_compressing = TRUE;
5991 ssh->cs_comp_ctx = zlib_compress_init();
5992 logevent("Initialised zlib (RFC1950) compression");
5993 ssh->sc_comp_ctx = zlib_decompress_init();
5994 logevent("Initialised zlib (RFC1950) decompression");
5998 * Start the shell or command.
6000 * Special case: if the first-choice command is an SSH-2
6001 * subsystem (hence not usable here) and the second choice
6002 * exists, we fall straight back to that.
6005 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
6007 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
6008 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
6009 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
6010 ssh->fallback_cmd = TRUE;
6013 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
6015 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
6016 logevent("Started session");
6019 ssh->state = SSH_STATE_SESSION;
6020 if (ssh->size_needed)
6021 ssh_size(ssh, ssh->term_width, ssh->term_height);
6022 if (ssh->eof_needed)
6023 ssh_special(ssh, TS_EOF);
6026 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
6028 ssh->channels = newtree234(ssh_channelcmp);
6032 * By this point, most incoming packets are already being
6033 * handled by the dispatch table, and we need only pay
6034 * attention to the unusual ones.
6039 if (pktin->type == SSH1_SMSG_SUCCESS) {
6040 /* may be from EXEC_SHELL on some servers */
6041 } else if (pktin->type == SSH1_SMSG_FAILURE) {
6042 /* may be from EXEC_SHELL on some servers
6043 * if no pty is available or in other odd cases. Ignore */
6045 bombout(("Strange packet received: type %d", pktin->type));
6050 int len = min(inlen, 512);
6051 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
6052 PKT_INT, len, PKT_DATA, in, len,
6064 * Handle the top-level SSH-2 protocol.
6066 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6071 ssh_pkt_getstring(pktin, &msg, &msglen);
6072 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
6075 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6077 /* log reason code in disconnect message */
6081 ssh_pkt_getstring(pktin, &msg, &msglen);
6082 bombout(("Server sent disconnect message:\n\"%.*s\"",
6083 msglen, NULLTOEMPTY(msg)));
6086 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6088 /* Do nothing, because we're ignoring it! Duhh. */
6091 static void ssh1_protocol_setup(Ssh ssh)
6096 * Most messages are handled by the coroutines.
6098 for (i = 0; i < 256; i++)
6099 ssh->packet_dispatch[i] = NULL;
6102 * These special message types we install handlers for.
6104 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6105 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6106 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6109 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6110 struct Packet *pktin)
6112 const unsigned char *in = (const unsigned char *)vin;
6113 if (ssh->state == SSH_STATE_CLOSED)
6116 if (pktin && ssh->packet_dispatch[pktin->type]) {
6117 ssh->packet_dispatch[pktin->type](ssh, pktin);
6121 if (!ssh->protocol_initial_phase_done) {
6122 if (do_ssh1_login(ssh, in, inlen, pktin))
6123 ssh->protocol_initial_phase_done = TRUE;
6128 do_ssh1_connection(ssh, in, inlen, pktin);
6132 * Utility routines for decoding comma-separated strings in KEXINIT.
6134 static int first_in_commasep_string(char const *needle, char const *haystack,
6138 if (!needle || !haystack) /* protect against null pointers */
6140 needlen = strlen(needle);
6142 if (haylen >= needlen && /* haystack is long enough */
6143 !memcmp(needle, haystack, needlen) && /* initial match */
6144 (haylen == needlen || haystack[needlen] == ',')
6145 /* either , or EOS follows */
6151 static int in_commasep_string(char const *needle, char const *haystack,
6156 if (!needle || !haystack) /* protect against null pointers */
6159 * Is it at the start of the string?
6161 if (first_in_commasep_string(needle, haystack, haylen))
6164 * If not, search for the next comma and resume after that.
6165 * If no comma found, terminate.
6167 p = memchr(haystack, ',', haylen);
6169 /* + 1 to skip over comma */
6170 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6174 * Add a value to the comma-separated string at the end of the packet.
6176 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6178 if (pkt->length - pkt->savedpos > 0)
6179 ssh_pkt_addstring_str(pkt, ",");
6180 ssh_pkt_addstring_str(pkt, data);
6185 * SSH-2 key derivation (RFC 4253 section 7.2).
6187 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6188 char chr, int keylen)
6190 const struct ssh_hash *h = ssh->kex->hash;
6198 /* Round up to the next multiple of hash length. */
6199 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6201 key = snewn(keylen_padded, unsigned char);
6203 /* First hlen bytes. */
6205 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6206 hash_mpint(h, s, K);
6207 h->bytes(s, H, h->hlen);
6208 h->bytes(s, &chr, 1);
6209 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6212 /* Subsequent blocks of hlen bytes. */
6213 if (keylen_padded > h->hlen) {
6217 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6218 hash_mpint(h, s, K);
6219 h->bytes(s, H, h->hlen);
6221 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6222 h->bytes(s, key + offset - h->hlen, h->hlen);
6224 h->final(s2, key + offset);
6230 /* Now clear any extra bytes of key material beyond the length
6231 * we're officially returning, because the caller won't know to
6233 if (keylen_padded > keylen)
6234 smemclr(key + keylen, keylen_padded - keylen);
6240 * Structure for constructing KEXINIT algorithm lists.
6242 #define MAXKEXLIST 16
6243 struct kexinit_algorithm {
6247 const struct ssh_kex *kex;
6251 const struct ssh_signkey *hostkey;
6255 const struct ssh2_cipher *cipher;
6259 const struct ssh_mac *mac;
6262 const struct ssh_compress *comp;
6267 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6268 * If the algorithm is already in the list, return a pointer to its
6269 * entry, otherwise return an entry from the end of the list.
6270 * This assumes that every time a particular name is passed in, it
6271 * comes from the same string constant. If this isn't true, this
6272 * function may need to be rewritten to use strcmp() instead.
6274 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6275 *list, const char *name)
6279 for (i = 0; i < MAXKEXLIST; i++)
6280 if (list[i].name == NULL || list[i].name == name) {
6281 list[i].name = name;
6284 assert(!"No space in KEXINIT list");
6289 * Handle the SSH-2 transport layer.
6291 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6292 struct Packet *pktin)
6294 const unsigned char *in = (const unsigned char *)vin;
6296 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6297 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6300 const char * kexlist_descr[NKEXLIST] = {
6301 "key exchange algorithm", "host key algorithm",
6302 "client-to-server cipher", "server-to-client cipher",
6303 "client-to-server MAC", "server-to-client MAC",
6304 "client-to-server compression method",
6305 "server-to-client compression method" };
6306 struct do_ssh2_transport_state {
6308 int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
6309 Bignum p, g, e, f, K;
6312 int kex_init_value, kex_reply_value;
6313 const struct ssh_mac *const *maclist;
6315 const struct ssh2_cipher *cscipher_tobe;
6316 const struct ssh2_cipher *sccipher_tobe;
6317 const struct ssh_mac *csmac_tobe;
6318 const struct ssh_mac *scmac_tobe;
6319 int csmac_etm_tobe, scmac_etm_tobe;
6320 const struct ssh_compress *cscomp_tobe;
6321 const struct ssh_compress *sccomp_tobe;
6322 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6323 int hostkeylen, siglen, rsakeylen;
6324 void *hkey; /* actual host key */
6325 void *rsakey; /* for RSA kex */
6326 void *eckey; /* for ECDH kex */
6327 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6328 int n_preferred_kex;
6329 const struct ssh_kexes *preferred_kex[KEX_MAX];
6331 int preferred_hk[HK_MAX];
6332 int n_preferred_ciphers;
6333 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6334 const struct ssh_compress *preferred_comp;
6335 int userauth_succeeded; /* for delayed compression */
6336 int pending_compression;
6337 int got_session_id, activated_authconn;
6338 struct Packet *pktout;
6342 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6344 crState(do_ssh2_transport_state);
6346 assert(!ssh->bare_connection);
6347 assert(ssh->version == 2);
6351 s->cscipher_tobe = s->sccipher_tobe = NULL;
6352 s->csmac_tobe = s->scmac_tobe = NULL;
6353 s->cscomp_tobe = s->sccomp_tobe = NULL;
6355 s->got_session_id = s->activated_authconn = FALSE;
6356 s->userauth_succeeded = FALSE;
6357 s->pending_compression = FALSE;
6360 * Be prepared to work around the buggy MAC problem.
6362 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6363 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6365 s->maclist = macs, s->nmacs = lenof(macs);
6368 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6371 struct kexinit_algorithm *alg;
6374 * Set up the preferred key exchange. (NULL => warn below here)
6376 s->n_preferred_kex = 0;
6377 for (i = 0; i < KEX_MAX; i++) {
6378 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6380 s->preferred_kex[s->n_preferred_kex++] =
6381 &ssh_diffiehellman_gex;
6384 s->preferred_kex[s->n_preferred_kex++] =
6385 &ssh_diffiehellman_group14;
6388 s->preferred_kex[s->n_preferred_kex++] =
6389 &ssh_diffiehellman_group1;
6392 s->preferred_kex[s->n_preferred_kex++] =
6396 s->preferred_kex[s->n_preferred_kex++] =
6400 /* Flag for later. Don't bother if it's the last in
6402 if (i < KEX_MAX - 1) {
6403 s->preferred_kex[s->n_preferred_kex++] = NULL;
6410 * Set up the preferred host key types. These are just the ids
6411 * in the enum in putty.h, so 'warn below here' is indicated
6414 s->n_preferred_hk = 0;
6415 for (i = 0; i < HK_MAX; i++) {
6416 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
6417 /* As above, don't bother with HK_WARN if it's last in the
6419 if (id != HK_WARN || i < HK_MAX - 1)
6420 s->preferred_hk[s->n_preferred_hk++] = id;
6424 * Set up the preferred ciphers. (NULL => warn below here)
6426 s->n_preferred_ciphers = 0;
6427 for (i = 0; i < CIPHER_MAX; i++) {
6428 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6429 case CIPHER_BLOWFISH:
6430 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6433 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6434 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6438 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6441 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6443 case CIPHER_ARCFOUR:
6444 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6446 case CIPHER_CHACHA20:
6447 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6450 /* Flag for later. Don't bother if it's the last in
6452 if (i < CIPHER_MAX - 1) {
6453 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6460 * Set up preferred compression.
6462 if (conf_get_int(ssh->conf, CONF_compression))
6463 s->preferred_comp = &ssh_zlib;
6465 s->preferred_comp = &ssh_comp_none;
6468 * Enable queueing of outgoing auth- or connection-layer
6469 * packets while we are in the middle of a key exchange.
6471 ssh->queueing = TRUE;
6474 * Flag that KEX is in progress.
6476 ssh->kex_in_progress = TRUE;
6478 for (i = 0; i < NKEXLIST; i++)
6479 for (j = 0; j < MAXKEXLIST; j++)
6480 s->kexlists[i][j].name = NULL;
6481 /* List key exchange algorithms. */
6483 for (i = 0; i < s->n_preferred_kex; i++) {
6484 const struct ssh_kexes *k = s->preferred_kex[i];
6485 if (!k) warn = TRUE;
6486 else for (j = 0; j < k->nkexes; j++) {
6487 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6489 alg->u.kex.kex = k->list[j];
6490 alg->u.kex.warn = warn;
6493 /* List server host key algorithms. */
6494 if (!s->got_session_id) {
6496 * In the first key exchange, we list all the algorithms
6497 * we're prepared to cope with, but prefer those algorithms
6498 * for which we have a host key for this host.
6500 * If the host key algorithm is below the warning
6501 * threshold, we warn even if we did already have a key
6502 * for it, on the basis that if the user has just
6503 * reconfigured that host key type to be warned about,
6504 * they surely _do_ want to be alerted that a server
6505 * they're actually connecting to is using it.
6508 for (i = 0; i < s->n_preferred_hk; i++) {
6509 if (s->preferred_hk[i] == HK_WARN)
6511 for (j = 0; j < lenof(hostkey_algs); j++) {
6512 if (hostkey_algs[j].id != s->preferred_hk[i])
6514 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6515 hostkey_algs[j].alg->keytype)) {
6516 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6517 hostkey_algs[j].alg->name);
6518 alg->u.hk.hostkey = hostkey_algs[j].alg;
6519 alg->u.hk.warn = warn;
6524 for (i = 0; i < s->n_preferred_hk; i++) {
6525 if (s->preferred_hk[i] == HK_WARN)
6527 for (j = 0; j < lenof(hostkey_algs); j++) {
6528 if (hostkey_algs[j].id != s->preferred_hk[i])
6530 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6531 hostkey_algs[j].alg->name);
6532 alg->u.hk.hostkey = hostkey_algs[j].alg;
6533 alg->u.hk.warn = warn;
6538 * In subsequent key exchanges, we list only the kex
6539 * algorithm that was selected in the first key exchange,
6540 * so that we keep getting the same host key and hence
6541 * don't have to interrupt the user's session to ask for
6545 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6546 ssh->hostkey->name);
6547 alg->u.hk.hostkey = ssh->hostkey;
6548 alg->u.hk.warn = FALSE;
6550 /* List encryption algorithms (client->server then server->client). */
6551 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6554 alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6555 alg->u.cipher.cipher = NULL;
6556 alg->u.cipher.warn = warn;
6557 #endif /* FUZZING */
6558 for (i = 0; i < s->n_preferred_ciphers; i++) {
6559 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6560 if (!c) warn = TRUE;
6561 else for (j = 0; j < c->nciphers; j++) {
6562 alg = ssh2_kexinit_addalg(s->kexlists[k],
6564 alg->u.cipher.cipher = c->list[j];
6565 alg->u.cipher.warn = warn;
6569 /* List MAC algorithms (client->server then server->client). */
6570 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6572 alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6573 alg->u.mac.mac = NULL;
6574 alg->u.mac.etm = FALSE;
6575 #endif /* FUZZING */
6576 for (i = 0; i < s->nmacs; i++) {
6577 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6578 alg->u.mac.mac = s->maclist[i];
6579 alg->u.mac.etm = FALSE;
6581 for (i = 0; i < s->nmacs; i++)
6582 /* For each MAC, there may also be an ETM version,
6583 * which we list second. */
6584 if (s->maclist[i]->etm_name) {
6585 alg = ssh2_kexinit_addalg(s->kexlists[j],
6586 s->maclist[i]->etm_name);
6587 alg->u.mac.mac = s->maclist[i];
6588 alg->u.mac.etm = TRUE;
6591 /* List client->server compression algorithms,
6592 * then server->client compression algorithms. (We use the
6593 * same set twice.) */
6594 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6595 assert(lenof(compressions) > 1);
6596 /* Prefer non-delayed versions */
6597 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6598 alg->u.comp = s->preferred_comp;
6599 /* We don't even list delayed versions of algorithms until
6600 * they're allowed to be used, to avoid a race. See the end of
6602 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6603 alg = ssh2_kexinit_addalg(s->kexlists[j],
6604 s->preferred_comp->delayed_name);
6605 alg->u.comp = s->preferred_comp;
6607 for (i = 0; i < lenof(compressions); i++) {
6608 const struct ssh_compress *c = compressions[i];
6609 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6611 if (s->userauth_succeeded && c->delayed_name) {
6612 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6618 * Construct and send our key exchange packet.
6620 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6621 for (i = 0; i < 16; i++)
6622 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6623 for (i = 0; i < NKEXLIST; i++) {
6624 ssh2_pkt_addstring_start(s->pktout);
6625 for (j = 0; j < MAXKEXLIST; j++) {
6626 if (s->kexlists[i][j].name == NULL) break;
6627 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6630 /* List client->server languages. Empty list. */
6631 ssh2_pkt_addstring_start(s->pktout);
6632 /* List server->client languages. Empty list. */
6633 ssh2_pkt_addstring_start(s->pktout);
6634 /* First KEX packet does _not_ follow, because we're not that brave. */
6635 ssh2_pkt_addbool(s->pktout, FALSE);
6637 ssh2_pkt_adduint32(s->pktout, 0);
6640 s->our_kexinitlen = s->pktout->length - 5;
6641 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6642 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6644 ssh2_pkt_send_noqueue(ssh, s->pktout);
6647 crWaitUntilV(pktin);
6650 * Now examine the other side's KEXINIT to see what we're up
6657 if (pktin->type != SSH2_MSG_KEXINIT) {
6658 bombout(("expected key exchange packet from server"));
6662 ssh->hostkey = NULL;
6663 s->cscipher_tobe = NULL;
6664 s->sccipher_tobe = NULL;
6665 s->csmac_tobe = NULL;
6666 s->scmac_tobe = NULL;
6667 s->cscomp_tobe = NULL;
6668 s->sccomp_tobe = NULL;
6669 s->warn_kex = s->warn_hk = FALSE;
6670 s->warn_cscipher = s->warn_sccipher = FALSE;
6672 pktin->savedpos += 16; /* skip garbage cookie */
6675 for (i = 0; i < NKEXLIST; i++) {
6676 ssh_pkt_getstring(pktin, &str, &len);
6678 bombout(("KEXINIT packet was incomplete"));
6682 /* If we've already selected a cipher which requires a
6683 * particular MAC, then just select that, and don't even
6684 * bother looking through the server's KEXINIT string for
6686 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6687 s->cscipher_tobe->required_mac) {
6688 s->csmac_tobe = s->cscipher_tobe->required_mac;
6689 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6692 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6693 s->sccipher_tobe->required_mac) {
6694 s->scmac_tobe = s->sccipher_tobe->required_mac;
6695 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6699 for (j = 0; j < MAXKEXLIST; j++) {
6700 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6701 if (alg->name == NULL) break;
6702 if (in_commasep_string(alg->name, str, len)) {
6703 /* We've found a matching algorithm. */
6704 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6705 /* Check if we might need to ignore first kex pkt */
6707 !first_in_commasep_string(alg->name, str, len))
6710 if (i == KEXLIST_KEX) {
6711 ssh->kex = alg->u.kex.kex;
6712 s->warn_kex = alg->u.kex.warn;
6713 } else if (i == KEXLIST_HOSTKEY) {
6714 ssh->hostkey = alg->u.hk.hostkey;
6715 s->warn_hk = alg->u.hk.warn;
6716 } else if (i == KEXLIST_CSCIPHER) {
6717 s->cscipher_tobe = alg->u.cipher.cipher;
6718 s->warn_cscipher = alg->u.cipher.warn;
6719 } else if (i == KEXLIST_SCCIPHER) {
6720 s->sccipher_tobe = alg->u.cipher.cipher;
6721 s->warn_sccipher = alg->u.cipher.warn;
6722 } else if (i == KEXLIST_CSMAC) {
6723 s->csmac_tobe = alg->u.mac.mac;
6724 s->csmac_etm_tobe = alg->u.mac.etm;
6725 } else if (i == KEXLIST_SCMAC) {
6726 s->scmac_tobe = alg->u.mac.mac;
6727 s->scmac_etm_tobe = alg->u.mac.etm;
6728 } else if (i == KEXLIST_CSCOMP) {
6729 s->cscomp_tobe = alg->u.comp;
6730 } else if (i == KEXLIST_SCCOMP) {
6731 s->sccomp_tobe = alg->u.comp;
6735 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6736 in_commasep_string(alg->u.comp->delayed_name, str, len))
6737 s->pending_compression = TRUE; /* try this later */
6739 bombout(("Couldn't agree a %s (available: %.*s)",
6740 kexlist_descr[i], len, str));
6744 if (i == KEXLIST_HOSTKEY) {
6748 * In addition to deciding which host key we're
6749 * actually going to use, we should make a list of the
6750 * host keys offered by the server which we _don't_
6751 * have cached. These will be offered as cross-
6752 * certification options by ssh_get_specials.
6754 * We also count the key we're currently using for KEX
6755 * as one we've already got, because by the time this
6756 * menu becomes visible, it will be.
6758 ssh->n_uncert_hostkeys = 0;
6760 for (j = 0; j < lenof(hostkey_algs); j++) {
6761 if (hostkey_algs[j].alg != ssh->hostkey &&
6762 in_commasep_string(hostkey_algs[j].alg->name,
6764 !have_ssh_host_key(ssh->savedhost, ssh->savedport,
6765 hostkey_algs[j].alg->keytype)) {
6766 ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
6772 if (s->pending_compression) {
6773 logevent("Server supports delayed compression; "
6774 "will try this later");
6776 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6777 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6778 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6780 ssh->exhash = ssh->kex->hash->init();
6781 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6782 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6783 hash_string(ssh->kex->hash, ssh->exhash,
6784 s->our_kexinit, s->our_kexinitlen);
6785 sfree(s->our_kexinit);
6786 /* Include the type byte in the hash of server's KEXINIT */
6787 hash_string(ssh->kex->hash, ssh->exhash,
6788 pktin->body - 1, pktin->length + 1);
6791 ssh_set_frozen(ssh, 1);
6792 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6794 ssh_dialog_callback, ssh);
6795 if (s->dlgret < 0) {
6799 bombout(("Unexpected data from server while"
6800 " waiting for user response"));
6803 } while (pktin || inlen > 0);
6804 s->dlgret = ssh->user_response;
6806 ssh_set_frozen(ssh, 0);
6807 if (s->dlgret == 0) {
6808 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6818 ssh_set_frozen(ssh, 1);
6821 * Change warning box wording depending on why we chose a
6822 * warning-level host key algorithm. If it's because
6823 * that's all we have *cached*, use the askhk mechanism,
6824 * and list the host keys we could usefully cross-certify.
6825 * Otherwise, use askalg for the standard wording.
6828 for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
6829 const struct ssh_signkey_with_user_pref_id *hktype =
6830 &hostkey_algs[ssh->uncert_hostkeys[j]];
6832 for (k = 0; k < HK_MAX; k++) {
6833 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
6834 if (id == HK_WARN) {
6836 } else if (id == hktype->id) {
6843 char *old_ba = betteralgs;
6844 betteralgs = dupcat(betteralgs, ",",
6846 (const char *)NULL);
6849 betteralgs = dupstr(hktype->alg->name);
6854 s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
6855 betteralgs, ssh_dialog_callback, ssh);
6858 s->dlgret = askalg(ssh->frontend, "host key type",
6860 ssh_dialog_callback, ssh);
6862 if (s->dlgret < 0) {
6866 bombout(("Unexpected data from server while"
6867 " waiting for user response"));
6870 } while (pktin || inlen > 0);
6871 s->dlgret = ssh->user_response;
6873 ssh_set_frozen(ssh, 0);
6874 if (s->dlgret == 0) {
6875 ssh_disconnect(ssh, "User aborted at host key warning", NULL,
6881 if (s->warn_cscipher) {
6882 ssh_set_frozen(ssh, 1);
6883 s->dlgret = askalg(ssh->frontend,
6884 "client-to-server cipher",
6885 s->cscipher_tobe->name,
6886 ssh_dialog_callback, ssh);
6887 if (s->dlgret < 0) {
6891 bombout(("Unexpected data from server while"
6892 " waiting for user response"));
6895 } while (pktin || inlen > 0);
6896 s->dlgret = ssh->user_response;
6898 ssh_set_frozen(ssh, 0);
6899 if (s->dlgret == 0) {
6900 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6906 if (s->warn_sccipher) {
6907 ssh_set_frozen(ssh, 1);
6908 s->dlgret = askalg(ssh->frontend,
6909 "server-to-client cipher",
6910 s->sccipher_tobe->name,
6911 ssh_dialog_callback, ssh);
6912 if (s->dlgret < 0) {
6916 bombout(("Unexpected data from server while"
6917 " waiting for user response"));
6920 } while (pktin || inlen > 0);
6921 s->dlgret = ssh->user_response;
6923 ssh_set_frozen(ssh, 0);
6924 if (s->dlgret == 0) {
6925 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6931 if (s->ignorepkt) /* first_kex_packet_follows */
6932 crWaitUntilV(pktin); /* Ignore packet */
6935 if (ssh->kex->main_type == KEXTYPE_DH) {
6937 * Work out the number of bits of key we will need from the
6938 * key exchange. We start with the maximum key length of
6944 csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6945 scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6946 s->nbits = (csbits > scbits ? csbits : scbits);
6948 /* The keys only have hlen-bit entropy, since they're based on
6949 * a hash. So cap the key size at hlen bits. */
6950 if (s->nbits > ssh->kex->hash->hlen * 8)
6951 s->nbits = ssh->kex->hash->hlen * 8;
6954 * If we're doing Diffie-Hellman group exchange, start by
6955 * requesting a group.
6957 if (dh_is_gex(ssh->kex)) {
6958 logevent("Doing Diffie-Hellman group exchange");
6959 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6961 * Work out how big a DH group we will need to allow that
6964 s->pbits = 512 << ((s->nbits - 1) / 64);
6965 if (s->pbits < DH_MIN_SIZE)
6966 s->pbits = DH_MIN_SIZE;
6967 if (s->pbits > DH_MAX_SIZE)
6968 s->pbits = DH_MAX_SIZE;
6969 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6970 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6971 ssh2_pkt_adduint32(s->pktout, s->pbits);
6973 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6974 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6975 ssh2_pkt_adduint32(s->pktout, s->pbits);
6976 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6978 ssh2_pkt_send_noqueue(ssh, s->pktout);
6980 crWaitUntilV(pktin);
6981 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6982 bombout(("expected key exchange group packet from server"));
6985 s->p = ssh2_pkt_getmp(pktin);
6986 s->g = ssh2_pkt_getmp(pktin);
6987 if (!s->p || !s->g) {
6988 bombout(("unable to read mp-ints from incoming group packet"));
6991 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6992 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6993 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6995 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6996 ssh->kex_ctx = dh_setup_group(ssh->kex);
6997 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6998 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6999 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
7000 ssh->kex->groupname);
7003 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
7004 ssh->kex->hash->text_name);
7006 * Now generate and send e for Diffie-Hellman.
7008 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
7009 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
7010 s->pktout = ssh2_pkt_init(s->kex_init_value);
7011 ssh2_pkt_addmp(s->pktout, s->e);
7012 ssh2_pkt_send_noqueue(ssh, s->pktout);
7014 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
7015 crWaitUntilV(pktin);
7016 if (pktin->type != s->kex_reply_value) {
7017 bombout(("expected key exchange reply packet from server"));
7020 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
7021 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7022 if (!s->hostkeydata) {
7023 bombout(("unable to parse key exchange reply packet"));
7026 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7027 s->hostkeydata, s->hostkeylen);
7028 s->f = ssh2_pkt_getmp(pktin);
7030 bombout(("unable to parse key exchange reply packet"));
7033 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7035 bombout(("unable to parse key exchange reply packet"));
7040 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
7042 bombout(("key exchange reply failed validation: %s", err));
7046 s->K = dh_find_K(ssh->kex_ctx, s->f);
7048 /* We assume everything from now on will be quick, and it might
7049 * involve user interaction. */
7050 set_busy_status(ssh->frontend, BUSY_NOT);
7052 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7053 if (dh_is_gex(ssh->kex)) {
7054 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7055 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
7056 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
7057 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7058 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
7059 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
7060 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
7062 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
7063 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
7065 dh_cleanup(ssh->kex_ctx);
7067 if (dh_is_gex(ssh->kex)) {
7071 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
7073 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
7074 ssh_ecdhkex_curve_textname(ssh->kex),
7075 ssh->kex->hash->text_name);
7076 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
7078 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
7080 bombout(("Unable to generate key for ECDH"));
7086 int publicPointLength;
7087 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7089 ssh_ecdhkex_freekey(s->eckey);
7090 bombout(("Unable to encode public key for ECDH"));
7093 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
7094 ssh2_pkt_addstring_start(s->pktout);
7095 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
7099 ssh2_pkt_send_noqueue(ssh, s->pktout);
7101 crWaitUntilV(pktin);
7102 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
7103 ssh_ecdhkex_freekey(s->eckey);
7104 bombout(("expected ECDH reply packet from server"));
7108 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7109 if (!s->hostkeydata) {
7110 bombout(("unable to parse ECDH reply packet"));
7113 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7114 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7115 s->hostkeydata, s->hostkeylen);
7119 int publicPointLength;
7120 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7122 ssh_ecdhkex_freekey(s->eckey);
7123 bombout(("Unable to encode public key for ECDH hash"));
7126 hash_string(ssh->kex->hash, ssh->exhash,
7127 publicPoint, publicPointLength);
7134 ssh_pkt_getstring(pktin, &keydata, &keylen);
7136 bombout(("unable to parse ECDH reply packet"));
7139 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
7140 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
7142 ssh_ecdhkex_freekey(s->eckey);
7143 bombout(("point received in ECDH was not valid"));
7148 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7150 bombout(("unable to parse key exchange reply packet"));
7154 ssh_ecdhkex_freekey(s->eckey);
7156 logeventf(ssh, "Doing RSA key exchange with hash %s",
7157 ssh->kex->hash->text_name);
7158 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7160 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7163 crWaitUntilV(pktin);
7164 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7165 bombout(("expected RSA public key packet from server"));
7169 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7170 if (!s->hostkeydata) {
7171 bombout(("unable to parse RSA public key packet"));
7174 hash_string(ssh->kex->hash, ssh->exhash,
7175 s->hostkeydata, s->hostkeylen);
7176 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7177 s->hostkeydata, s->hostkeylen);
7181 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7183 bombout(("unable to parse RSA public key packet"));
7186 s->rsakeydata = snewn(s->rsakeylen, char);
7187 memcpy(s->rsakeydata, keydata, s->rsakeylen);
7190 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7192 sfree(s->rsakeydata);
7193 bombout(("unable to parse RSA public key from server"));
7197 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7200 * Next, set up a shared secret K, of precisely KLEN -
7201 * 2*HLEN - 49 bits, where KLEN is the bit length of the
7202 * RSA key modulus and HLEN is the bit length of the hash
7206 int klen = ssh_rsakex_klen(s->rsakey);
7207 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7209 unsigned char *kstr1, *kstr2, *outstr;
7210 int kstr1len, kstr2len, outstrlen;
7212 s->K = bn_power_2(nbits - 1);
7214 for (i = 0; i < nbits; i++) {
7216 byte = random_byte();
7218 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7222 * Encode this as an mpint.
7224 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7225 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7226 PUT_32BIT(kstr2, kstr1len);
7227 memcpy(kstr2 + 4, kstr1, kstr1len);
7230 * Encrypt it with the given RSA key.
7232 outstrlen = (klen + 7) / 8;
7233 outstr = snewn(outstrlen, unsigned char);
7234 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7235 outstr, outstrlen, s->rsakey);
7238 * And send it off in a return packet.
7240 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7241 ssh2_pkt_addstring_start(s->pktout);
7242 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7243 ssh2_pkt_send_noqueue(ssh, s->pktout);
7245 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7252 ssh_rsakex_freekey(s->rsakey);
7254 crWaitUntilV(pktin);
7255 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7256 sfree(s->rsakeydata);
7257 bombout(("expected signature packet from server"));
7261 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7263 bombout(("unable to parse signature packet"));
7267 sfree(s->rsakeydata);
7270 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7271 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7272 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7274 ssh->kex_ctx = NULL;
7277 debug(("Exchange hash is:\n"));
7278 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7282 bombout(("Server's host key is invalid"));
7286 if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7287 (char *)s->exchange_hash,
7288 ssh->kex->hash->hlen)) {
7290 bombout(("Server's host key did not match the signature supplied"));
7295 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7296 if (!s->got_session_id) {
7298 * Make a note of any other host key formats that are available.
7301 int i, j, nkeys = 0;
7303 for (i = 0; i < lenof(hostkey_algs); i++) {
7304 if (hostkey_algs[i].alg == ssh->hostkey)
7307 for (j = 0; j < ssh->n_uncert_hostkeys; j++)
7308 if (ssh->uncert_hostkeys[j] == i)
7311 if (j < ssh->n_uncert_hostkeys) {
7314 newlist = dupprintf("%s/%s", list,
7315 hostkey_algs[i].alg->name);
7317 newlist = dupprintf("%s", hostkey_algs[i].alg->name);
7325 "Server also has %s host key%s, but we "
7326 "don't know %s", list,
7327 nkeys > 1 ? "s" : "",
7328 nkeys > 1 ? "any of them" : "it");
7334 * Authenticate remote host: verify host key. (We've already
7335 * checked the signature of the exchange hash.)
7337 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7338 logevent("Host key fingerprint is:");
7339 logevent(s->fingerprint);
7340 /* First check against manually configured host keys. */
7341 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7342 ssh->hostkey, s->hkey);
7343 if (s->dlgret == 0) { /* did not match */
7344 bombout(("Host key did not appear in manually configured list"));
7346 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7347 ssh_set_frozen(ssh, 1);
7348 s->dlgret = verify_ssh_host_key(ssh->frontend,
7349 ssh->savedhost, ssh->savedport,
7350 ssh->hostkey->keytype, s->keystr,
7352 ssh_dialog_callback, ssh);
7356 if (s->dlgret < 0) {
7360 bombout(("Unexpected data from server while waiting"
7361 " for user host key response"));
7364 } while (pktin || inlen > 0);
7365 s->dlgret = ssh->user_response;
7367 ssh_set_frozen(ssh, 0);
7368 if (s->dlgret == 0) {
7369 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7374 sfree(s->fingerprint);
7376 * Save this host key, to check against the one presented in
7377 * subsequent rekeys.
7379 ssh->hostkey_str = s->keystr;
7380 } else if (ssh->cross_certifying) {
7381 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7382 logevent("Storing additional host key for this host:");
7383 logevent(s->fingerprint);
7384 store_host_key(ssh->savedhost, ssh->savedport,
7385 ssh->hostkey->keytype, s->keystr);
7386 ssh->cross_certifying = FALSE;
7388 * Don't forget to store the new key as the one we'll be
7389 * re-checking in future normal rekeys.
7391 ssh->hostkey_str = s->keystr;
7394 * In a rekey, we never present an interactive host key
7395 * verification request to the user. Instead, we simply
7396 * enforce that the key we're seeing this time is identical to
7397 * the one we saw before.
7399 if (strcmp(ssh->hostkey_str, s->keystr)) {
7401 bombout(("Host key was different in repeat key exchange"));
7407 ssh->hostkey->freekey(s->hkey);
7410 * The exchange hash from the very first key exchange is also
7411 * the session id, used in session key construction and
7414 if (!s->got_session_id) {
7415 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7416 memcpy(ssh->v2_session_id, s->exchange_hash,
7417 sizeof(s->exchange_hash));
7418 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7419 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7420 s->got_session_id = TRUE;
7424 * Send SSH2_MSG_NEWKEYS.
7426 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7427 ssh2_pkt_send_noqueue(ssh, s->pktout);
7428 ssh->outgoing_data_size = 0; /* start counting from here */
7431 * We've sent client NEWKEYS, so create and initialise
7432 * client-to-server session keys.
7434 if (ssh->cs_cipher_ctx)
7435 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7436 ssh->cscipher = s->cscipher_tobe;
7437 if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7439 if (ssh->cs_mac_ctx)
7440 ssh->csmac->free_context(ssh->cs_mac_ctx);
7441 ssh->csmac = s->csmac_tobe;
7442 ssh->csmac_etm = s->csmac_etm_tobe;
7444 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7446 if (ssh->cs_comp_ctx)
7447 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7448 ssh->cscomp = s->cscomp_tobe;
7449 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7452 * Set IVs on client-to-server keys. Here we use the exchange
7453 * hash from the _first_ key exchange.
7455 if (ssh->cscipher) {
7458 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7459 ssh->cscipher->padded_keybytes);
7460 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7461 smemclr(key, ssh->cscipher->padded_keybytes);
7464 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7465 ssh->cscipher->blksize);
7466 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7467 smemclr(key, ssh->cscipher->blksize);
7473 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7474 ssh->csmac->keylen);
7475 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7476 smemclr(key, ssh->csmac->keylen);
7481 logeventf(ssh, "Initialised %.200s client->server encryption",
7482 ssh->cscipher->text_name);
7484 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7485 ssh->csmac->text_name,
7486 ssh->csmac_etm ? " (in ETM mode)" : "",
7487 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7488 if (ssh->cscomp->text_name)
7489 logeventf(ssh, "Initialised %s compression",
7490 ssh->cscomp->text_name);
7493 * Now our end of the key exchange is complete, we can send all
7494 * our queued higher-layer packets.
7496 ssh->queueing = FALSE;
7497 ssh2_pkt_queuesend(ssh);
7500 * Expect SSH2_MSG_NEWKEYS from server.
7502 crWaitUntilV(pktin);
7503 if (pktin->type != SSH2_MSG_NEWKEYS) {
7504 bombout(("expected new-keys packet from server"));
7507 ssh->incoming_data_size = 0; /* start counting from here */
7510 * We've seen server NEWKEYS, so create and initialise
7511 * server-to-client session keys.
7513 if (ssh->sc_cipher_ctx)
7514 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7515 if (s->sccipher_tobe) {
7516 ssh->sccipher = s->sccipher_tobe;
7517 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7520 if (ssh->sc_mac_ctx)
7521 ssh->scmac->free_context(ssh->sc_mac_ctx);
7522 if (s->scmac_tobe) {
7523 ssh->scmac = s->scmac_tobe;
7524 ssh->scmac_etm = s->scmac_etm_tobe;
7525 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7528 if (ssh->sc_comp_ctx)
7529 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7530 ssh->sccomp = s->sccomp_tobe;
7531 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7534 * Set IVs on server-to-client keys. Here we use the exchange
7535 * hash from the _first_ key exchange.
7537 if (ssh->sccipher) {
7540 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7541 ssh->sccipher->padded_keybytes);
7542 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7543 smemclr(key, ssh->sccipher->padded_keybytes);
7546 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7547 ssh->sccipher->blksize);
7548 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7549 smemclr(key, ssh->sccipher->blksize);
7555 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7556 ssh->scmac->keylen);
7557 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7558 smemclr(key, ssh->scmac->keylen);
7562 logeventf(ssh, "Initialised %.200s server->client encryption",
7563 ssh->sccipher->text_name);
7565 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7566 ssh->scmac->text_name,
7567 ssh->scmac_etm ? " (in ETM mode)" : "",
7568 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7569 if (ssh->sccomp->text_name)
7570 logeventf(ssh, "Initialised %s decompression",
7571 ssh->sccomp->text_name);
7574 * Free shared secret.
7579 * Update the specials menu to list the remaining uncertified host
7582 update_specials_menu(ssh->frontend);
7585 * Key exchange is over. Loop straight back round if we have a
7586 * deferred rekey reason.
7588 if (ssh->deferred_rekey_reason) {
7589 logevent(ssh->deferred_rekey_reason);
7591 ssh->deferred_rekey_reason = NULL;
7592 goto begin_key_exchange;
7596 * Otherwise, schedule a timer for our next rekey.
7598 ssh->kex_in_progress = FALSE;
7599 ssh->last_rekey = GETTICKCOUNT();
7600 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7601 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7605 * Now we're encrypting. Begin returning 1 to the protocol main
7606 * function so that other things can run on top of the
7607 * transport. If we ever see a KEXINIT, we must go back to the
7610 * We _also_ go back to the start if we see pktin==NULL and
7611 * inlen negative, because this is a special signal meaning
7612 * `initiate client-driven rekey', and `in' contains a message
7613 * giving the reason for the rekey.
7615 * inlen==-1 means always initiate a rekey;
7616 * inlen==-2 means that userauth has completed successfully and
7617 * we should consider rekeying (for delayed compression).
7619 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7620 (!pktin && inlen < 0))) {
7622 if (!ssh->protocol_initial_phase_done) {
7623 ssh->protocol_initial_phase_done = TRUE;
7625 * Allow authconn to initialise itself.
7627 do_ssh2_authconn(ssh, NULL, 0, NULL);
7632 logevent("Server initiated key re-exchange");
7636 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7637 * delayed compression, if it's available.
7639 * draft-miller-secsh-compression-delayed-00 says that you
7640 * negotiate delayed compression in the first key exchange, and
7641 * both sides start compressing when the server has sent
7642 * USERAUTH_SUCCESS. This has a race condition -- the server
7643 * can't know when the client has seen it, and thus which incoming
7644 * packets it should treat as compressed.
7646 * Instead, we do the initial key exchange without offering the
7647 * delayed methods, but note if the server offers them; when we
7648 * get here, if a delayed method was available that was higher
7649 * on our list than what we got, we initiate a rekey in which we
7650 * _do_ list the delayed methods (and hopefully get it as a
7651 * result). Subsequent rekeys will do the same.
7653 assert(!s->userauth_succeeded); /* should only happen once */
7654 s->userauth_succeeded = TRUE;
7655 if (!s->pending_compression)
7656 /* Can't see any point rekeying. */
7657 goto wait_for_rekey; /* this is utterly horrid */
7658 /* else fall through to rekey... */
7659 s->pending_compression = FALSE;
7662 * Now we've decided to rekey.
7664 * Special case: if the server bug is set that doesn't
7665 * allow rekeying, we give a different log message and
7666 * continue waiting. (If such a server _initiates_ a rekey,
7667 * we process it anyway!)
7669 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7670 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7672 /* Reset the counters, so that at least this message doesn't
7673 * hit the event log _too_ often. */
7674 ssh->outgoing_data_size = 0;
7675 ssh->incoming_data_size = 0;
7676 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7678 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7681 goto wait_for_rekey; /* this is still utterly horrid */
7683 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7686 goto begin_key_exchange;
7692 * Send data on an SSH channel. In SSH-2, this involves buffering it
7695 static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
7698 if (c->ssh->version == 2) {
7699 bufchain_add(&c->v.v2.outbuffer, buf, len);
7700 return ssh2_try_send(c);
7702 send_packet(c->ssh, SSH1_MSG_CHANNEL_DATA,
7703 PKT_INT, c->remoteid,
7708 * In SSH-1 we can return 0 here - implying that channels are
7709 * never individually throttled - because the only
7710 * circumstance that can cause throttling will be the whole
7711 * SSH connection backing up, in which case _everything_ will
7712 * be throttled as a whole.
7719 * Attempt to send data on an SSH-2 channel.
7721 static int ssh2_try_send(struct ssh_channel *c)
7724 struct Packet *pktout;
7727 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7730 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7731 if ((unsigned)len > c->v.v2.remwindow)
7732 len = c->v.v2.remwindow;
7733 if ((unsigned)len > c->v.v2.remmaxpkt)
7734 len = c->v.v2.remmaxpkt;
7735 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7736 ssh2_pkt_adduint32(pktout, c->remoteid);
7737 ssh2_pkt_addstring_start(pktout);
7738 ssh2_pkt_addstring_data(pktout, data, len);
7739 ssh2_pkt_send(ssh, pktout);
7740 bufchain_consume(&c->v.v2.outbuffer, len);
7741 c->v.v2.remwindow -= len;
7745 * After having sent as much data as we can, return the amount
7748 ret = bufchain_size(&c->v.v2.outbuffer);
7751 * And if there's no data pending but we need to send an EOF, send
7754 if (!ret && c->pending_eof)
7755 ssh_channel_try_eof(c);
7760 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7763 if (c->closes & CLOSES_SENT_EOF)
7764 return; /* don't send on channels we've EOFed */
7765 bufsize = ssh2_try_send(c);
7768 case CHAN_MAINSESSION:
7769 /* stdin need not receive an unthrottle
7770 * notification since it will be polled */
7773 x11_unthrottle(c->u.x11.xconn);
7776 /* agent sockets are request/response and need no
7777 * buffer management */
7780 pfd_unthrottle(c->u.pfd.pf);
7786 static int ssh_is_simple(Ssh ssh)
7789 * We use the 'simple' variant of the SSH protocol if we're asked
7790 * to, except not if we're also doing connection-sharing (either
7791 * tunnelling our packets over an upstream or expecting to be
7792 * tunnelled over ourselves), since then the assumption that we
7793 * have only one channel to worry about is not true after all.
7795 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7796 !ssh->bare_connection && !ssh->connshare);
7800 * Set up most of a new ssh_channel for SSH-2.
7802 static void ssh2_channel_init(struct ssh_channel *c)
7805 c->localid = alloc_channel_id(ssh);
7807 c->pending_eof = FALSE;
7808 c->throttling_conn = FALSE;
7809 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7810 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7811 c->v.v2.chanreq_head = NULL;
7812 c->v.v2.throttle_state = UNTHROTTLED;
7813 bufchain_init(&c->v.v2.outbuffer);
7817 * Construct the common parts of a CHANNEL_OPEN.
7819 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7822 struct Packet *pktout;
7824 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7825 ssh2_pkt_addstring(pktout, type);
7826 ssh2_pkt_adduint32(pktout, c->localid);
7827 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7828 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7833 * CHANNEL_FAILURE doesn't come with any indication of what message
7834 * caused it, so we have to keep track of the outstanding
7835 * CHANNEL_REQUESTs ourselves.
7837 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7838 cchandler_fn_t handler, void *ctx)
7840 struct outstanding_channel_request *ocr =
7841 snew(struct outstanding_channel_request);
7843 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7844 ocr->handler = handler;
7847 if (!c->v.v2.chanreq_head)
7848 c->v.v2.chanreq_head = ocr;
7850 c->v.v2.chanreq_tail->next = ocr;
7851 c->v.v2.chanreq_tail = ocr;
7855 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7856 * NULL then a reply will be requested and the handler will be called
7857 * when it arrives. The returned packet is ready to have any
7858 * request-specific data added and be sent. Note that if a handler is
7859 * provided, it's essential that the request actually be sent.
7861 * The handler will usually be passed the response packet in pktin. If
7862 * pktin is NULL, this means that no reply will ever be forthcoming
7863 * (e.g. because the entire connection is being destroyed, or because
7864 * the server initiated channel closure before we saw the response)
7865 * and the handler should free any storage it's holding.
7867 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7869 cchandler_fn_t handler, void *ctx)
7871 struct Packet *pktout;
7873 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7874 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7875 ssh2_pkt_adduint32(pktout, c->remoteid);
7876 ssh2_pkt_addstring(pktout, type);
7877 ssh2_pkt_addbool(pktout, handler != NULL);
7878 if (handler != NULL)
7879 ssh2_queue_chanreq_handler(c, handler, ctx);
7884 * Potentially enlarge the window on an SSH-2 channel.
7886 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7888 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7893 * Never send WINDOW_ADJUST for a channel that the remote side has
7894 * already sent EOF on; there's no point, since it won't be
7895 * sending any more data anyway. Ditto if _we've_ already sent
7898 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7902 * Also, never widen the window for an X11 channel when we're
7903 * still waiting to see its initial auth and may yet hand it off
7906 if (c->type == CHAN_X11 && c->u.x11.initial)
7910 * If the remote end has a habit of ignoring maxpkt, limit the
7911 * window so that it has no choice (assuming it doesn't ignore the
7914 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7915 newwin = OUR_V2_MAXPKT;
7918 * Only send a WINDOW_ADJUST if there's significantly more window
7919 * available than the other end thinks there is. This saves us
7920 * sending a WINDOW_ADJUST for every character in a shell session.
7922 * "Significant" is arbitrarily defined as half the window size.
7924 if (newwin / 2 >= c->v.v2.locwindow) {
7925 struct Packet *pktout;
7929 * In order to keep track of how much window the client
7930 * actually has available, we'd like it to acknowledge each
7931 * WINDOW_ADJUST. We can't do that directly, so we accompany
7932 * it with a CHANNEL_REQUEST that has to be acknowledged.
7934 * This is only necessary if we're opening the window wide.
7935 * If we're not, then throughput is being constrained by
7936 * something other than the maximum window size anyway.
7938 if (newwin == c->v.v2.locmaxwin &&
7939 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7940 up = snew(unsigned);
7941 *up = newwin - c->v.v2.locwindow;
7942 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7943 ssh2_handle_winadj_response, up);
7944 ssh2_pkt_send(ssh, pktout);
7946 if (c->v.v2.throttle_state != UNTHROTTLED)
7947 c->v.v2.throttle_state = UNTHROTTLING;
7949 /* Pretend the WINDOW_ADJUST was acked immediately. */
7950 c->v.v2.remlocwin = newwin;
7951 c->v.v2.throttle_state = THROTTLED;
7953 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7954 ssh2_pkt_adduint32(pktout, c->remoteid);
7955 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7956 ssh2_pkt_send(ssh, pktout);
7957 c->v.v2.locwindow = newwin;
7962 * Find the channel associated with a message. If there's no channel,
7963 * or it's not properly open, make a noise about it and return NULL.
7965 static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
7967 unsigned localid = ssh_pkt_getuint32(pktin);
7968 struct ssh_channel *c;
7970 c = find234(ssh->channels, &localid, ssh_channelfind);
7972 (c->type != CHAN_SHARING && c->halfopen &&
7973 pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
7974 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
7975 char *buf = dupprintf("Received %s for %s channel %u",
7976 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
7978 c ? "half-open" : "nonexistent", localid);
7979 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7986 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7987 struct Packet *pktin, void *ctx)
7989 unsigned *sizep = ctx;
7992 * Winadj responses should always be failures. However, at least
7993 * one server ("boks_sshd") is known to return SUCCESS for channel
7994 * requests it's never heard of, such as "winadj@putty". Raised
7995 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7996 * life, we don't worry about what kind of response we got.
7999 c->v.v2.remlocwin += *sizep;
8002 * winadj messages are only sent when the window is fully open, so
8003 * if we get an ack of one, we know any pending unthrottle is
8006 if (c->v.v2.throttle_state == UNTHROTTLING)
8007 c->v.v2.throttle_state = UNTHROTTLED;
8010 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
8012 struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
8013 struct outstanding_channel_request *ocr;
8016 if (c->type == CHAN_SHARING) {
8017 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8018 pktin->body, pktin->length);
8021 ocr = c->v.v2.chanreq_head;
8023 ssh2_msg_unexpected(ssh, pktin);
8026 ocr->handler(c, pktin, ocr->ctx);
8027 c->v.v2.chanreq_head = ocr->next;
8030 * We may now initiate channel-closing procedures, if that
8031 * CHANNEL_REQUEST was the last thing outstanding before we send
8034 ssh2_channel_check_close(c);
8037 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
8039 struct ssh_channel *c;
8040 c = ssh2_channel_msg(ssh, pktin);
8043 if (c->type == CHAN_SHARING) {
8044 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8045 pktin->body, pktin->length);
8048 if (!(c->closes & CLOSES_SENT_EOF)) {
8049 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
8050 ssh2_try_send_and_unthrottle(ssh, c);
8054 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
8058 struct ssh_channel *c;
8059 c = ssh2_channel_msg(ssh, pktin);
8062 if (c->type == CHAN_SHARING) {
8063 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8064 pktin->body, pktin->length);
8067 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
8068 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
8069 return; /* extended but not stderr */
8070 ssh_pkt_getstring(pktin, &data, &length);
8073 c->v.v2.locwindow -= length;
8074 c->v.v2.remlocwin -= length;
8076 case CHAN_MAINSESSION:
8078 from_backend(ssh->frontend, pktin->type ==
8079 SSH2_MSG_CHANNEL_EXTENDED_DATA,
8083 bufsize = x11_send(c->u.x11.xconn, data, length);
8086 bufsize = pfd_send(c->u.pfd.pf, data, length);
8089 bufsize = ssh_agent_channel_data(c, data, length);
8093 * If it looks like the remote end hit the end of its window,
8094 * and we didn't want it to do that, think about using a
8097 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
8098 c->v.v2.locmaxwin < 0x40000000)
8099 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
8101 * If we are not buffering too much data,
8102 * enlarge the window again at the remote side.
8103 * If we are buffering too much, we may still
8104 * need to adjust the window if the server's
8107 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
8108 c->v.v2.locmaxwin - bufsize : 0);
8110 * If we're either buffering way too much data, or if we're
8111 * buffering anything at all and we're in "simple" mode,
8112 * throttle the whole channel.
8114 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
8115 && !c->throttling_conn) {
8116 c->throttling_conn = 1;
8117 ssh_throttle_conn(ssh, +1);
8122 static void ssh_check_termination(Ssh ssh)
8124 if (ssh->version == 2 &&
8125 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
8126 (ssh->channels && count234(ssh->channels) == 0) &&
8127 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
8129 * We used to send SSH_MSG_DISCONNECT here, because I'd
8130 * believed that _every_ conforming SSH-2 connection had to
8131 * end with a disconnect being sent by at least one side;
8132 * apparently I was wrong and it's perfectly OK to
8133 * unceremoniously slam the connection shut when you're done,
8134 * and indeed OpenSSH feels this is more polite than sending a
8135 * DISCONNECT. So now we don't.
8137 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
8141 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
8142 const char *peerinfo)
8145 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
8148 logeventf(ssh, "Connection sharing downstream #%u connected", id);
8151 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
8153 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
8154 ssh_check_termination(ssh);
8157 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
8162 va_start(ap, logfmt);
8163 buf = dupvprintf(logfmt, ap);
8166 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
8168 logeventf(ssh, "Connection sharing: %s", buf);
8172 static void ssh_channel_destroy(struct ssh_channel *c)
8177 case CHAN_MAINSESSION:
8178 ssh->mainchan = NULL;
8179 update_specials_menu(ssh->frontend);
8182 if (c->u.x11.xconn != NULL)
8183 x11_close(c->u.x11.xconn);
8184 logevent("Forwarded X11 connection terminated");
8187 sfree(c->u.a.message);
8190 if (c->u.pfd.pf != NULL)
8191 pfd_close(c->u.pfd.pf);
8192 logevent("Forwarded port closed");
8196 del234(ssh->channels, c);
8197 if (ssh->version == 2) {
8198 bufchain_clear(&c->v.v2.outbuffer);
8199 assert(c->v.v2.chanreq_head == NULL);
8204 * If that was the last channel left open, we might need to
8207 ssh_check_termination(ssh);
8210 static void ssh2_channel_check_close(struct ssh_channel *c)
8213 struct Packet *pktout;
8217 * If we've sent out our own CHANNEL_OPEN but not yet seen
8218 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8219 * it's too early to be sending close messages of any kind.
8224 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8225 c->type == CHAN_ZOMBIE) &&
8226 !c->v.v2.chanreq_head &&
8227 !(c->closes & CLOSES_SENT_CLOSE)) {
8229 * We have both sent and received EOF (or the channel is a
8230 * zombie), and we have no outstanding channel requests, which
8231 * means the channel is in final wind-up. But we haven't sent
8232 * CLOSE, so let's do so now.
8234 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8235 ssh2_pkt_adduint32(pktout, c->remoteid);
8236 ssh2_pkt_send(ssh, pktout);
8237 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8240 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8241 assert(c->v.v2.chanreq_head == NULL);
8243 * We have both sent and received CLOSE, which means we're
8244 * completely done with the channel.
8246 ssh_channel_destroy(c);
8250 static void ssh2_channel_got_eof(struct ssh_channel *c)
8252 if (c->closes & CLOSES_RCVD_EOF)
8253 return; /* already seen EOF */
8254 c->closes |= CLOSES_RCVD_EOF;
8256 if (c->type == CHAN_X11) {
8257 x11_send_eof(c->u.x11.xconn);
8258 } else if (c->type == CHAN_AGENT) {
8259 if (c->u.a.outstanding_requests == 0) {
8260 /* Manufacture an outgoing EOF in response to the incoming one. */
8261 sshfwd_write_eof(c);
8263 } else if (c->type == CHAN_SOCKDATA) {
8264 pfd_send_eof(c->u.pfd.pf);
8265 } else if (c->type == CHAN_MAINSESSION) {
8268 if (!ssh->sent_console_eof &&
8269 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8271 * Either from_backend_eof told us that the front end
8272 * wants us to close the outgoing side of the connection
8273 * as soon as we see EOF from the far end, or else we've
8274 * unilaterally decided to do that because we've allocated
8275 * a remote pty and hence EOF isn't a particularly
8276 * meaningful concept.
8278 sshfwd_write_eof(c);
8280 ssh->sent_console_eof = TRUE;
8283 ssh2_channel_check_close(c);
8286 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8288 struct ssh_channel *c;
8290 c = ssh2_channel_msg(ssh, pktin);
8293 if (c->type == CHAN_SHARING) {
8294 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8295 pktin->body, pktin->length);
8298 ssh2_channel_got_eof(c);
8301 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8303 struct ssh_channel *c;
8305 c = ssh2_channel_msg(ssh, pktin);
8308 if (c->type == CHAN_SHARING) {
8309 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8310 pktin->body, pktin->length);
8315 * When we receive CLOSE on a channel, we assume it comes with an
8316 * implied EOF if we haven't seen EOF yet.
8318 ssh2_channel_got_eof(c);
8320 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8322 * It also means we stop expecting to see replies to any
8323 * outstanding channel requests, so clean those up too.
8324 * (ssh_chanreq_init will enforce by assertion that we don't
8325 * subsequently put anything back on this list.)
8327 while (c->v.v2.chanreq_head) {
8328 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8329 ocr->handler(c, NULL, ocr->ctx);
8330 c->v.v2.chanreq_head = ocr->next;
8336 * And we also send an outgoing EOF, if we haven't already, on the
8337 * assumption that CLOSE is a pretty forceful announcement that
8338 * the remote side is doing away with the entire channel. (If it
8339 * had wanted to send us EOF and continue receiving data from us,
8340 * it would have just sent CHANNEL_EOF.)
8342 if (!(c->closes & CLOSES_SENT_EOF)) {
8344 * Make sure we don't read any more from whatever our local
8345 * data source is for this channel.
8348 case CHAN_MAINSESSION:
8349 ssh->send_ok = 0; /* stop trying to read from stdin */
8352 x11_override_throttle(c->u.x11.xconn, 1);
8355 pfd_override_throttle(c->u.pfd.pf, 1);
8360 * Abandon any buffered data we still wanted to send to this
8361 * channel. Receiving a CHANNEL_CLOSE is an indication that
8362 * the server really wants to get on and _destroy_ this
8363 * channel, and it isn't going to send us any further
8364 * WINDOW_ADJUSTs to permit us to send pending stuff.
8366 bufchain_clear(&c->v.v2.outbuffer);
8369 * Send outgoing EOF.
8371 sshfwd_write_eof(c);
8375 * Now process the actual close.
8377 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8378 c->closes |= CLOSES_RCVD_CLOSE;
8379 ssh2_channel_check_close(c);
8383 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8385 struct ssh_channel *c;
8387 c = ssh2_channel_msg(ssh, pktin);
8390 if (c->type == CHAN_SHARING) {
8391 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8392 pktin->body, pktin->length);
8395 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8396 c->remoteid = ssh_pkt_getuint32(pktin);
8397 c->halfopen = FALSE;
8398 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8399 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8401 if (c->type == CHAN_SOCKDATA_DORMANT) {
8402 c->type = CHAN_SOCKDATA;
8404 pfd_confirm(c->u.pfd.pf);
8405 } else if (c->type == CHAN_ZOMBIE) {
8407 * This case can occur if a local socket error occurred
8408 * between us sending out CHANNEL_OPEN and receiving
8409 * OPEN_CONFIRMATION. In this case, all we can do is
8410 * immediately initiate close proceedings now that we know the
8411 * server's id to put in the close message.
8413 ssh2_channel_check_close(c);
8416 * We never expect to receive OPEN_CONFIRMATION for any
8417 * *other* channel type (since only local-to-remote port
8418 * forwardings cause us to send CHANNEL_OPEN after the main
8419 * channel is live - all other auxiliary channel types are
8420 * initiated from the server end). It's safe to enforce this
8421 * by assertion rather than by ssh_disconnect, because the
8422 * real point is that we never constructed a half-open channel
8423 * structure in the first place with any type other than the
8426 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8430 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8433 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8435 static const char *const reasons[] = {
8436 "<unknown reason code>",
8437 "Administratively prohibited",
8439 "Unknown channel type",
8440 "Resource shortage",
8442 unsigned reason_code;
8443 char *reason_string;
8445 struct ssh_channel *c;
8447 c = ssh2_channel_msg(ssh, pktin);
8450 if (c->type == CHAN_SHARING) {
8451 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8452 pktin->body, pktin->length);
8455 assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
8457 if (c->type == CHAN_SOCKDATA_DORMANT) {
8458 reason_code = ssh_pkt_getuint32(pktin);
8459 if (reason_code >= lenof(reasons))
8460 reason_code = 0; /* ensure reasons[reason_code] in range */
8461 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8462 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8463 reasons[reason_code], reason_length,
8464 NULLTOEMPTY(reason_string));
8466 pfd_close(c->u.pfd.pf);
8467 } else if (c->type == CHAN_ZOMBIE) {
8469 * This case can occur if a local socket error occurred
8470 * between us sending out CHANNEL_OPEN and receiving
8471 * OPEN_FAILURE. In this case, we need do nothing except allow
8472 * the code below to throw the half-open channel away.
8476 * We never expect to receive OPEN_FAILURE for any *other*
8477 * channel type (since only local-to-remote port forwardings
8478 * cause us to send CHANNEL_OPEN after the main channel is
8479 * live - all other auxiliary channel types are initiated from
8480 * the server end). It's safe to enforce this by assertion
8481 * rather than by ssh_disconnect, because the real point is
8482 * that we never constructed a half-open channel structure in
8483 * the first place with any type other than the above.
8485 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8488 del234(ssh->channels, c);
8492 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8495 int typelen, want_reply;
8496 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8497 struct ssh_channel *c;
8498 struct Packet *pktout;
8500 c = ssh2_channel_msg(ssh, pktin);
8503 if (c->type == CHAN_SHARING) {
8504 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
8505 pktin->body, pktin->length);
8508 ssh_pkt_getstring(pktin, &type, &typelen);
8509 want_reply = ssh2_pkt_getbool(pktin);
8511 if (c->closes & CLOSES_SENT_CLOSE) {
8513 * We don't reply to channel requests after we've sent
8514 * CHANNEL_CLOSE for the channel, because our reply might
8515 * cross in the network with the other side's CHANNEL_CLOSE
8516 * and arrive after they have wound the channel up completely.
8522 * Having got the channel number, we now look at
8523 * the request type string to see if it's something
8526 if (c == ssh->mainchan) {
8528 * We recognise "exit-status" and "exit-signal" on
8529 * the primary channel.
8531 if (typelen == 11 &&
8532 !memcmp(type, "exit-status", 11)) {
8534 ssh->exitcode = ssh_pkt_getuint32(pktin);
8535 logeventf(ssh, "Server sent command exit status %d",
8537 reply = SSH2_MSG_CHANNEL_SUCCESS;
8539 } else if (typelen == 11 &&
8540 !memcmp(type, "exit-signal", 11)) {
8542 int is_plausible = TRUE, is_int = FALSE;
8543 char *fmt_sig = NULL, *fmt_msg = NULL;
8545 int msglen = 0, core = FALSE;
8546 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8547 * provide an `int' for the signal, despite its
8548 * having been a `string' in the drafts of RFC 4254 since at
8549 * least 2001. (Fixed in session.c 1.147.) Try to
8550 * infer which we can safely parse it as. */
8552 unsigned char *p = pktin->body +
8554 long len = pktin->length - pktin->savedpos;
8555 unsigned long num = GET_32BIT(p); /* what is it? */
8556 /* If it's 0, it hardly matters; assume string */
8560 int maybe_int = FALSE, maybe_str = FALSE;
8561 #define CHECK_HYPOTHESIS(offset, result) \
8564 int q = toint(offset); \
8565 if (q >= 0 && q+4 <= len) { \
8566 q = toint(q + 4 + GET_32BIT(p+q)); \
8567 if (q >= 0 && q+4 <= len && \
8568 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8573 CHECK_HYPOTHESIS(4+1, maybe_int);
8574 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8575 #undef CHECK_HYPOTHESIS
8576 if (maybe_int && !maybe_str)
8578 else if (!maybe_int && maybe_str)
8581 /* Crikey. Either or neither. Panic. */
8582 is_plausible = FALSE;
8585 ssh->exitcode = 128; /* means `unknown signal' */
8588 /* Old non-standard OpenSSH. */
8589 int signum = ssh_pkt_getuint32(pktin);
8590 fmt_sig = dupprintf(" %d", signum);
8591 ssh->exitcode = 128 + signum;
8593 /* As per RFC 4254. */
8596 ssh_pkt_getstring(pktin, &sig, &siglen);
8597 /* Signal name isn't supposed to be blank, but
8598 * let's cope gracefully if it is. */
8600 fmt_sig = dupprintf(" \"%.*s\"",
8605 * Really hideous method of translating the
8606 * signal description back into a locally
8607 * meaningful number.
8612 #define TRANSLATE_SIGNAL(s) \
8613 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8614 ssh->exitcode = 128 + SIG ## s
8616 TRANSLATE_SIGNAL(ABRT);
8619 TRANSLATE_SIGNAL(ALRM);
8622 TRANSLATE_SIGNAL(FPE);
8625 TRANSLATE_SIGNAL(HUP);
8628 TRANSLATE_SIGNAL(ILL);
8631 TRANSLATE_SIGNAL(INT);
8634 TRANSLATE_SIGNAL(KILL);
8637 TRANSLATE_SIGNAL(PIPE);
8640 TRANSLATE_SIGNAL(QUIT);
8643 TRANSLATE_SIGNAL(SEGV);
8646 TRANSLATE_SIGNAL(TERM);
8649 TRANSLATE_SIGNAL(USR1);
8652 TRANSLATE_SIGNAL(USR2);
8654 #undef TRANSLATE_SIGNAL
8656 ssh->exitcode = 128;
8658 core = ssh2_pkt_getbool(pktin);
8659 ssh_pkt_getstring(pktin, &msg, &msglen);
8661 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8663 /* ignore lang tag */
8664 } /* else don't attempt to parse */
8665 logeventf(ssh, "Server exited on signal%s%s%s",
8666 fmt_sig ? fmt_sig : "",
8667 core ? " (core dumped)" : "",
8668 fmt_msg ? fmt_msg : "");
8671 reply = SSH2_MSG_CHANNEL_SUCCESS;
8676 * This is a channel request we don't know
8677 * about, so we now either ignore the request
8678 * or respond with CHANNEL_FAILURE, depending
8681 reply = SSH2_MSG_CHANNEL_FAILURE;
8684 pktout = ssh2_pkt_init(reply);
8685 ssh2_pkt_adduint32(pktout, c->remoteid);
8686 ssh2_pkt_send(ssh, pktout);
8690 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8693 int typelen, want_reply;
8694 struct Packet *pktout;
8696 ssh_pkt_getstring(pktin, &type, &typelen);
8697 want_reply = ssh2_pkt_getbool(pktin);
8700 * We currently don't support any global requests
8701 * at all, so we either ignore the request or
8702 * respond with REQUEST_FAILURE, depending on
8706 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8707 ssh2_pkt_send(ssh, pktout);
8711 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8715 struct X11FakeAuth *auth;
8718 * Make up a new set of fake X11 auth data, and add it to the tree
8719 * of currently valid ones with an indication of the sharing
8720 * context that it's relevant to.
8722 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8723 auth->share_cs = share_cs;
8724 auth->share_chan = share_chan;
8729 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8731 del234(ssh->x11authtree, auth);
8732 x11_free_fake_auth(auth);
8735 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8742 const char *error = NULL;
8743 struct ssh_channel *c;
8744 unsigned remid, winsize, pktsize;
8745 unsigned our_winsize_override = 0;
8746 struct Packet *pktout;
8748 ssh_pkt_getstring(pktin, &type, &typelen);
8749 c = snew(struct ssh_channel);
8752 remid = ssh_pkt_getuint32(pktin);
8753 winsize = ssh_pkt_getuint32(pktin);
8754 pktsize = ssh_pkt_getuint32(pktin);
8756 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8759 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8760 addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
8761 peerport = ssh_pkt_getuint32(pktin);
8763 logeventf(ssh, "Received X11 connect request from %s:%d",
8766 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8767 error = "X11 forwarding is not enabled";
8769 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8772 c->u.x11.initial = TRUE;
8775 * If we are a connection-sharing upstream, then we should
8776 * initially present a very small window, adequate to take
8777 * the X11 initial authorisation packet but not much more.
8778 * Downstream will then present us a larger window (by
8779 * fiat of the connection-sharing protocol) and we can
8780 * guarantee to send a positive-valued WINDOW_ADJUST.
8783 our_winsize_override = 128;
8785 logevent("Opened X11 forward channel");
8789 } else if (typelen == 15 &&
8790 !memcmp(type, "forwarded-tcpip", 15)) {
8791 struct ssh_rportfwd pf, *realpf;
8794 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8795 pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
8796 pf.sport = ssh_pkt_getuint32(pktin);
8797 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8798 peerport = ssh_pkt_getuint32(pktin);
8799 realpf = find234(ssh->rportfwds, &pf, NULL);
8800 logeventf(ssh, "Received remote port %s:%d open request "
8801 "from %.*s:%d", pf.shost, pf.sport,
8802 peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
8805 if (realpf == NULL) {
8806 error = "Remote port is not recognised";
8810 if (realpf->share_ctx) {
8812 * This port forwarding is on behalf of a
8813 * connection-sharing downstream, so abandon our own
8814 * channel-open procedure and just pass the message on
8817 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8818 pktin->body, pktin->length);
8823 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8824 c, ssh->conf, realpf->pfrec->addressfamily);
8825 logeventf(ssh, "Attempting to forward remote port to "
8826 "%s:%d", realpf->dhost, realpf->dport);
8828 logeventf(ssh, "Port open failed: %s", err);
8830 error = "Port open failed";
8832 logevent("Forwarded port opened successfully");
8833 c->type = CHAN_SOCKDATA;
8836 } else if (typelen == 22 &&
8837 !memcmp(type, "auth-agent@openssh.com", 22)) {
8838 if (!ssh->agentfwd_enabled)
8839 error = "Agent forwarding is not enabled";
8841 c->type = CHAN_AGENT; /* identify channel type */
8842 c->u.a.lensofar = 0;
8843 c->u.a.message = NULL;
8844 c->u.a.outstanding_requests = 0;
8847 error = "Unsupported channel type requested";
8850 c->remoteid = remid;
8851 c->halfopen = FALSE;
8853 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8854 ssh2_pkt_adduint32(pktout, c->remoteid);
8855 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8856 ssh2_pkt_addstring(pktout, error);
8857 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8858 ssh2_pkt_send(ssh, pktout);
8859 logeventf(ssh, "Rejected channel open: %s", error);
8862 ssh2_channel_init(c);
8863 c->v.v2.remwindow = winsize;
8864 c->v.v2.remmaxpkt = pktsize;
8865 if (our_winsize_override) {
8866 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8867 our_winsize_override;
8869 add234(ssh->channels, c);
8870 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8871 ssh2_pkt_adduint32(pktout, c->remoteid);
8872 ssh2_pkt_adduint32(pktout, c->localid);
8873 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8874 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8875 ssh2_pkt_send(ssh, pktout);
8879 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8880 void *share_cs, void *share_chan,
8881 const char *peer_addr, int peer_port,
8882 int endian, int protomajor, int protominor,
8883 const void *initial_data, int initial_len)
8886 * This function is called when we've just discovered that an X
8887 * forwarding channel on which we'd been handling the initial auth
8888 * ourselves turns out to be destined for a connection-sharing
8889 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8890 * that we completely stop tracking windows and buffering data and
8891 * just pass more or less unmodified SSH messages back and forth.
8893 c->type = CHAN_SHARING;
8894 c->u.sharing.ctx = share_cs;
8895 share_setup_x11_channel(share_cs, share_chan,
8896 c->localid, c->remoteid, c->v.v2.remwindow,
8897 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8898 peer_addr, peer_port, endian,
8899 protomajor, protominor,
8900 initial_data, initial_len);
8903 void sshfwd_x11_is_local(struct ssh_channel *c)
8906 * This function is called when we've just discovered that an X
8907 * forwarding channel is _not_ destined for a connection-sharing
8908 * downstream but we're going to handle it ourselves. We stop
8909 * presenting a cautiously small window and go into ordinary data
8912 c->u.x11.initial = FALSE;
8913 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8917 * Buffer banner messages for later display at some convenient point,
8918 * if we're going to display them.
8920 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8922 /* Arbitrary limit to prevent unbounded inflation of buffer */
8923 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8924 bufchain_size(&ssh->banner) <= 131072) {
8925 char *banner = NULL;
8927 ssh_pkt_getstring(pktin, &banner, &size);
8929 bufchain_add(&ssh->banner, banner, size);
8933 /* Helper function to deal with sending tty modes for "pty-req" */
8934 static void ssh2_send_ttymode(void *data,
8935 const struct ssh_ttymode *mode, char *val)
8937 struct Packet *pktout = (struct Packet *)data;
8938 unsigned int arg = 0;
8940 switch (mode->type) {
8942 arg = ssh_tty_parse_specchar(val);
8945 arg = ssh_tty_parse_boolean(val);
8948 ssh2_pkt_addbyte(pktout, mode->opcode);
8949 ssh2_pkt_adduint32(pktout, arg);
8952 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8955 struct ssh2_setup_x11_state {
8959 struct Packet *pktout;
8960 crStateP(ssh2_setup_x11_state, ctx);
8964 logevent("Requesting X11 forwarding");
8965 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8967 ssh2_pkt_addbool(pktout, 0); /* many connections */
8968 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8969 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8970 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8971 ssh2_pkt_send(ssh, pktout);
8973 /* Wait to be called back with either a response packet, or NULL
8974 * meaning clean up and free our data */
8978 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8979 logevent("X11 forwarding enabled");
8980 ssh->X11_fwd_enabled = TRUE;
8982 logevent("X11 forwarding refused");
8988 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8991 struct ssh2_setup_agent_state {
8995 struct Packet *pktout;
8996 crStateP(ssh2_setup_agent_state, ctx);
9000 logevent("Requesting OpenSSH-style agent forwarding");
9001 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
9002 ssh2_setup_agent, s);
9003 ssh2_pkt_send(ssh, pktout);
9005 /* Wait to be called back with either a response packet, or NULL
9006 * meaning clean up and free our data */
9010 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9011 logevent("Agent forwarding enabled");
9012 ssh->agentfwd_enabled = TRUE;
9014 logevent("Agent forwarding refused");
9020 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
9023 struct ssh2_setup_pty_state {
9027 struct Packet *pktout;
9028 crStateP(ssh2_setup_pty_state, ctx);
9032 /* Unpick the terminal-speed string. */
9033 /* XXX perhaps we should allow no speeds to be sent. */
9034 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
9035 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
9036 /* Build the pty request. */
9037 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
9039 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
9040 ssh2_pkt_adduint32(pktout, ssh->term_width);
9041 ssh2_pkt_adduint32(pktout, ssh->term_height);
9042 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
9043 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
9044 ssh2_pkt_addstring_start(pktout);
9045 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
9046 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
9047 ssh2_pkt_adduint32(pktout, ssh->ispeed);
9048 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
9049 ssh2_pkt_adduint32(pktout, ssh->ospeed);
9050 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
9051 ssh2_pkt_send(ssh, pktout);
9052 ssh->state = SSH_STATE_INTERMED;
9054 /* Wait to be called back with either a response packet, or NULL
9055 * meaning clean up and free our data */
9059 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9060 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9061 ssh->ospeed, ssh->ispeed);
9062 ssh->got_pty = TRUE;
9064 c_write_str(ssh, "Server refused to allocate pty\r\n");
9065 ssh->editing = ssh->echoing = 1;
9072 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
9075 struct ssh2_setup_env_state {
9077 int num_env, env_left, env_ok;
9080 struct Packet *pktout;
9081 crStateP(ssh2_setup_env_state, ctx);
9086 * Send environment variables.
9088 * Simplest thing here is to send all the requests at once, and
9089 * then wait for a whole bunch of successes or failures.
9095 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9097 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9098 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
9099 ssh2_pkt_addstring(pktout, key);
9100 ssh2_pkt_addstring(pktout, val);
9101 ssh2_pkt_send(ssh, pktout);
9106 logeventf(ssh, "Sent %d environment variables", s->num_env);
9111 s->env_left = s->num_env;
9113 while (s->env_left > 0) {
9114 /* Wait to be called back with either a response packet,
9115 * or NULL meaning clean up and free our data */
9117 if (!pktin) goto out;
9118 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
9123 if (s->env_ok == s->num_env) {
9124 logevent("All environment variables successfully set");
9125 } else if (s->env_ok == 0) {
9126 logevent("All environment variables refused");
9127 c_write_str(ssh, "Server refused to set environment variables\r\n");
9129 logeventf(ssh, "%d environment variables refused",
9130 s->num_env - s->env_ok);
9131 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9139 * Handle the SSH-2 userauth and connection layers.
9141 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
9143 do_ssh2_authconn(ssh, NULL, 0, pktin);
9146 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
9150 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
9153 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
9154 struct Packet *pktin)
9156 struct do_ssh2_authconn_state {
9160 AUTH_TYPE_PUBLICKEY,
9161 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
9162 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
9164 AUTH_TYPE_GSSAPI, /* always QUIET */
9165 AUTH_TYPE_KEYBOARD_INTERACTIVE,
9166 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
9168 int done_service_req;
9169 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
9170 int tried_pubkey_config, done_agent;
9175 int kbd_inter_refused;
9176 int we_are_in, userauth_success;
9177 prompts_t *cur_prompt;
9182 void *publickey_blob;
9183 int publickey_bloblen;
9184 int privatekey_available, privatekey_encrypted;
9185 char *publickey_algorithm;
9186 char *publickey_comment;
9187 unsigned char agent_request[5], *agent_response, *agentp;
9188 int agent_responselen;
9189 unsigned char *pkblob_in_agent;
9191 char *pkblob, *alg, *commentp;
9192 int pklen, alglen, commentlen;
9193 int siglen, retlen, len;
9194 char *q, *agentreq, *ret;
9195 struct Packet *pktout;
9198 struct ssh_gss_library *gsslib;
9199 Ssh_gss_ctx gss_ctx;
9200 Ssh_gss_buf gss_buf;
9201 Ssh_gss_buf gss_rcvtok, gss_sndtok;
9202 Ssh_gss_name gss_srv_name;
9203 Ssh_gss_stat gss_stat;
9206 crState(do_ssh2_authconn_state);
9210 /* Register as a handler for all the messages this coroutine handles. */
9211 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9212 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9213 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9214 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9215 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9216 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9217 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9218 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9219 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9220 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9221 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9222 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9223 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9224 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9225 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9226 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9227 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9228 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9229 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9230 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9232 s->done_service_req = FALSE;
9233 s->we_are_in = s->userauth_success = FALSE;
9234 s->agent_response = NULL;
9236 s->tried_gssapi = FALSE;
9239 if (!ssh->bare_connection) {
9240 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9242 * Request userauth protocol, and await a response to it.
9244 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9245 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9246 ssh2_pkt_send(ssh, s->pktout);
9247 crWaitUntilV(pktin);
9248 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9249 s->done_service_req = TRUE;
9251 if (!s->done_service_req) {
9253 * Request connection protocol directly, without authentication.
9255 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9256 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9257 ssh2_pkt_send(ssh, s->pktout);
9258 crWaitUntilV(pktin);
9259 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9260 s->we_are_in = TRUE; /* no auth required */
9262 bombout(("Server refused service request"));
9267 s->we_are_in = TRUE;
9270 /* Arrange to be able to deal with any BANNERs that come in.
9271 * (We do this now as packets may come in during the next bit.) */
9272 bufchain_init(&ssh->banner);
9273 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9274 ssh2_msg_userauth_banner;
9277 * Misc one-time setup for authentication.
9279 s->publickey_blob = NULL;
9280 if (!s->we_are_in) {
9283 * Load the public half of any configured public key file
9286 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9287 if (!filename_is_null(s->keyfile)) {
9289 logeventf(ssh, "Reading key file \"%.150s\"",
9290 filename_to_str(s->keyfile));
9291 keytype = key_type(s->keyfile);
9292 if (keytype == SSH_KEYTYPE_SSH2 ||
9293 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9294 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9297 ssh2_userkey_loadpub(s->keyfile,
9298 &s->publickey_algorithm,
9299 &s->publickey_bloblen,
9300 &s->publickey_comment, &error);
9301 if (s->publickey_blob) {
9302 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9303 if (!s->privatekey_available)
9304 logeventf(ssh, "Key file contains public key only");
9305 s->privatekey_encrypted =
9306 ssh2_userkey_encrypted(s->keyfile, NULL);
9309 logeventf(ssh, "Unable to load key (%s)",
9311 msgbuf = dupprintf("Unable to load key file "
9312 "\"%.150s\" (%s)\r\n",
9313 filename_to_str(s->keyfile),
9315 c_write_str(ssh, msgbuf);
9320 logeventf(ssh, "Unable to use this key file (%s)",
9321 key_type_to_str(keytype));
9322 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9324 filename_to_str(s->keyfile),
9325 key_type_to_str(keytype));
9326 c_write_str(ssh, msgbuf);
9328 s->publickey_blob = NULL;
9333 * Find out about any keys Pageant has (but if there's a
9334 * public key configured, filter out all others).
9337 s->agent_response = NULL;
9338 s->pkblob_in_agent = NULL;
9339 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9343 logevent("Pageant is running. Requesting keys.");
9345 /* Request the keys held by the agent. */
9346 PUT_32BIT(s->agent_request, 1);
9347 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9348 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9349 ssh_agent_callback, ssh)) {
9353 bombout(("Unexpected data from server while"
9354 " waiting for agent response"));
9357 } while (pktin || inlen > 0);
9358 r = ssh->agent_response;
9359 s->agent_responselen = ssh->agent_response_len;
9361 s->agent_response = (unsigned char *) r;
9362 if (s->agent_response && s->agent_responselen >= 5 &&
9363 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9366 p = s->agent_response + 5;
9367 s->nkeys = toint(GET_32BIT(p));
9370 * Vet the Pageant response to ensure that the key
9371 * count and blob lengths make sense.
9374 logeventf(ssh, "Pageant response contained a negative"
9375 " key count %d", s->nkeys);
9377 goto done_agent_query;
9379 unsigned char *q = p + 4;
9380 int lenleft = s->agent_responselen - 5 - 4;
9382 for (keyi = 0; keyi < s->nkeys; keyi++) {
9383 int bloblen, commentlen;
9385 logeventf(ssh, "Pageant response was truncated");
9387 goto done_agent_query;
9389 bloblen = toint(GET_32BIT(q));
9390 if (bloblen < 0 || bloblen > lenleft) {
9391 logeventf(ssh, "Pageant response was truncated");
9393 goto done_agent_query;
9395 lenleft -= 4 + bloblen;
9397 commentlen = toint(GET_32BIT(q));
9398 if (commentlen < 0 || commentlen > lenleft) {
9399 logeventf(ssh, "Pageant response was truncated");
9401 goto done_agent_query;
9403 lenleft -= 4 + commentlen;
9404 q += 4 + commentlen;
9409 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9410 if (s->publickey_blob) {
9411 /* See if configured key is in agent. */
9412 for (keyi = 0; keyi < s->nkeys; keyi++) {
9413 s->pklen = toint(GET_32BIT(p));
9414 if (s->pklen == s->publickey_bloblen &&
9415 !memcmp(p+4, s->publickey_blob,
9416 s->publickey_bloblen)) {
9417 logeventf(ssh, "Pageant key #%d matches "
9418 "configured key file", keyi);
9420 s->pkblob_in_agent = p;
9424 p += toint(GET_32BIT(p)) + 4; /* comment */
9426 if (!s->pkblob_in_agent) {
9427 logevent("Configured key file not in Pageant");
9432 logevent("Failed to get reply from Pageant");
9440 * We repeat this whole loop, including the username prompt,
9441 * until we manage a successful authentication. If the user
9442 * types the wrong _password_, they can be sent back to the
9443 * beginning to try another username, if this is configured on.
9444 * (If they specify a username in the config, they are never
9445 * asked, even if they do give a wrong password.)
9447 * I think this best serves the needs of
9449 * - the people who have no configuration, no keys, and just
9450 * want to try repeated (username,password) pairs until they
9451 * type both correctly
9453 * - people who have keys and configuration but occasionally
9454 * need to fall back to passwords
9456 * - people with a key held in Pageant, who might not have
9457 * logged in to a particular machine before; so they want to
9458 * type a username, and then _either_ their key will be
9459 * accepted, _or_ they will type a password. If they mistype
9460 * the username they will want to be able to get back and
9463 s->got_username = FALSE;
9464 while (!s->we_are_in) {
9468 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9470 * We got a username last time round this loop, and
9471 * with change_username turned off we don't try to get
9474 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9475 int ret; /* need not be kept over crReturn */
9476 s->cur_prompt = new_prompts(ssh->frontend);
9477 s->cur_prompt->to_server = TRUE;
9478 s->cur_prompt->name = dupstr("SSH login name");
9479 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9480 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9483 crWaitUntilV(!pktin);
9484 ret = get_userpass_input(s->cur_prompt, in, inlen);
9489 * get_userpass_input() failed to get a username.
9492 free_prompts(s->cur_prompt);
9493 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9496 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9497 free_prompts(s->cur_prompt);
9500 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9501 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9502 c_write_str(ssh, stuff);
9506 s->got_username = TRUE;
9509 * Send an authentication request using method "none": (a)
9510 * just in case it succeeds, and (b) so that we know what
9511 * authentication methods we can usefully try next.
9513 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9515 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9516 ssh2_pkt_addstring(s->pktout, ssh->username);
9517 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9518 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9519 ssh2_pkt_send(ssh, s->pktout);
9520 s->type = AUTH_TYPE_NONE;
9522 s->we_are_in = FALSE;
9524 s->tried_pubkey_config = FALSE;
9525 s->kbd_inter_refused = FALSE;
9527 /* Reset agent request state. */
9528 s->done_agent = FALSE;
9529 if (s->agent_response) {
9530 if (s->pkblob_in_agent) {
9531 s->agentp = s->pkblob_in_agent;
9533 s->agentp = s->agent_response + 5 + 4;
9539 char *methods = NULL;
9543 * Wait for the result of the last authentication request.
9546 crWaitUntilV(pktin);
9548 * Now is a convenient point to spew any banner material
9549 * that we've accumulated. (This should ensure that when
9550 * we exit the auth loop, we haven't any left to deal
9554 int size = bufchain_size(&ssh->banner);
9556 * Don't show the banner if we're operating in
9557 * non-verbose non-interactive mode. (It's probably
9558 * a script, which means nobody will read the
9559 * banner _anyway_, and moreover the printing of
9560 * the banner will screw up processing on the
9561 * output of (say) plink.)
9563 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9564 char *banner = snewn(size, char);
9565 bufchain_fetch(&ssh->banner, banner, size);
9566 c_write_untrusted(ssh, banner, size);
9569 bufchain_clear(&ssh->banner);
9571 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9572 logevent("Access granted");
9573 s->we_are_in = s->userauth_success = TRUE;
9577 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9578 bombout(("Strange packet received during authentication: "
9579 "type %d", pktin->type));
9586 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9587 * we can look at the string in it and know what we can
9588 * helpfully try next.
9590 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9591 ssh_pkt_getstring(pktin, &methods, &methlen);
9592 if (!ssh2_pkt_getbool(pktin)) {
9594 * We have received an unequivocal Access
9595 * Denied. This can translate to a variety of
9596 * messages, or no message at all.
9598 * For forms of authentication which are attempted
9599 * implicitly, by which I mean without printing
9600 * anything in the window indicating that we're
9601 * trying them, we should never print 'Access
9604 * If we do print a message saying that we're
9605 * attempting some kind of authentication, it's OK
9606 * to print a followup message saying it failed -
9607 * but the message may sometimes be more specific
9608 * than simply 'Access denied'.
9610 * Additionally, if we'd just tried password
9611 * authentication, we should break out of this
9612 * whole loop so as to go back to the username
9613 * prompt (iff we're configured to allow
9614 * username change attempts).
9616 if (s->type == AUTH_TYPE_NONE) {
9618 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9619 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9620 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9621 c_write_str(ssh, "Server refused our key\r\n");
9622 logevent("Server refused our key");
9623 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9624 /* This _shouldn't_ happen except by a
9625 * protocol bug causing client and server to
9626 * disagree on what is a correct signature. */
9627 c_write_str(ssh, "Server refused public-key signature"
9628 " despite accepting key!\r\n");
9629 logevent("Server refused public-key signature"
9630 " despite accepting key!");
9631 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9632 /* quiet, so no c_write */
9633 logevent("Server refused keyboard-interactive authentication");
9634 } else if (s->type==AUTH_TYPE_GSSAPI) {
9635 /* always quiet, so no c_write */
9636 /* also, the code down in the GSSAPI block has
9637 * already logged this in the Event Log */
9638 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9639 logevent("Keyboard-interactive authentication failed");
9640 c_write_str(ssh, "Access denied\r\n");
9642 assert(s->type == AUTH_TYPE_PASSWORD);
9643 logevent("Password authentication failed");
9644 c_write_str(ssh, "Access denied\r\n");
9646 if (conf_get_int(ssh->conf, CONF_change_username)) {
9647 /* XXX perhaps we should allow
9648 * keyboard-interactive to do this too? */
9649 s->we_are_in = FALSE;
9654 c_write_str(ssh, "Further authentication required\r\n");
9655 logevent("Further authentication required");
9659 in_commasep_string("publickey", methods, methlen);
9661 in_commasep_string("password", methods, methlen);
9662 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9663 in_commasep_string("keyboard-interactive", methods, methlen);
9665 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9666 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9667 /* Try loading the GSS libraries and see if we
9670 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9671 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9673 /* No point in even bothering to try to load the
9674 * GSS libraries, if the user configuration and
9675 * server aren't both prepared to attempt GSSAPI
9676 * auth in the first place. */
9677 s->can_gssapi = FALSE;
9682 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9684 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9687 * Attempt public-key authentication using a key from Pageant.
9690 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9692 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9694 /* Unpack key from agent response */
9695 s->pklen = toint(GET_32BIT(s->agentp));
9697 s->pkblob = (char *)s->agentp;
9698 s->agentp += s->pklen;
9699 s->alglen = toint(GET_32BIT(s->pkblob));
9700 s->alg = s->pkblob + 4;
9701 s->commentlen = toint(GET_32BIT(s->agentp));
9703 s->commentp = (char *)s->agentp;
9704 s->agentp += s->commentlen;
9705 /* s->agentp now points at next key, if any */
9707 /* See if server will 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");
9714 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9715 ssh2_pkt_addstring_start(s->pktout);
9716 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9717 ssh2_pkt_addstring_start(s->pktout);
9718 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9719 ssh2_pkt_send(ssh, s->pktout);
9720 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9722 crWaitUntilV(pktin);
9723 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9725 /* Offer of key refused. */
9732 if (flags & FLAG_VERBOSE) {
9733 c_write_str(ssh, "Authenticating with "
9735 c_write(ssh, s->commentp, s->commentlen);
9736 c_write_str(ssh, "\" from agent\r\n");
9740 * Server is willing to accept the key.
9741 * Construct a SIGN_REQUEST.
9743 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9744 ssh2_pkt_addstring(s->pktout, ssh->username);
9745 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9746 /* service requested */
9747 ssh2_pkt_addstring(s->pktout, "publickey");
9749 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9750 ssh2_pkt_addstring_start(s->pktout);
9751 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9752 ssh2_pkt_addstring_start(s->pktout);
9753 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9755 /* Ask agent for signature. */
9756 s->siglen = s->pktout->length - 5 + 4 +
9757 ssh->v2_session_id_len;
9758 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9760 s->len = 1; /* message type */
9761 s->len += 4 + s->pklen; /* key blob */
9762 s->len += 4 + s->siglen; /* data to sign */
9763 s->len += 4; /* flags */
9764 s->agentreq = snewn(4 + s->len, char);
9765 PUT_32BIT(s->agentreq, s->len);
9766 s->q = s->agentreq + 4;
9767 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9768 PUT_32BIT(s->q, s->pklen);
9770 memcpy(s->q, s->pkblob, s->pklen);
9772 PUT_32BIT(s->q, s->siglen);
9774 /* Now the data to be signed... */
9775 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9776 PUT_32BIT(s->q, ssh->v2_session_id_len);
9779 memcpy(s->q, ssh->v2_session_id,
9780 ssh->v2_session_id_len);
9781 s->q += ssh->v2_session_id_len;
9782 memcpy(s->q, s->pktout->data + 5,
9783 s->pktout->length - 5);
9784 s->q += s->pktout->length - 5;
9785 /* And finally the (zero) flags word. */
9787 if (!agent_query(s->agentreq, s->len + 4,
9789 ssh_agent_callback, ssh)) {
9793 bombout(("Unexpected data from server"
9794 " while waiting for agent"
9798 } while (pktin || inlen > 0);
9799 vret = ssh->agent_response;
9800 s->retlen = ssh->agent_response_len;
9805 if (s->retlen >= 9 &&
9806 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9807 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9808 logevent("Sending Pageant's response");
9809 ssh2_add_sigblob(ssh, s->pktout,
9810 s->pkblob, s->pklen,
9812 GET_32BIT(s->ret + 5));
9813 ssh2_pkt_send(ssh, s->pktout);
9814 s->type = AUTH_TYPE_PUBLICKEY;
9816 /* FIXME: less drastic response */
9817 bombout(("Pageant failed to answer challenge"));
9823 /* Do we have any keys left to try? */
9824 if (s->pkblob_in_agent) {
9825 s->done_agent = TRUE;
9826 s->tried_pubkey_config = TRUE;
9829 if (s->keyi >= s->nkeys)
9830 s->done_agent = TRUE;
9833 } else if (s->can_pubkey && s->publickey_blob &&
9834 s->privatekey_available && !s->tried_pubkey_config) {
9836 struct ssh2_userkey *key; /* not live over crReturn */
9837 char *passphrase; /* not live over crReturn */
9839 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9841 s->tried_pubkey_config = TRUE;
9844 * Try the public key supplied in the configuration.
9846 * First, offer the public blob to see if the server is
9847 * willing to accept it.
9849 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9850 ssh2_pkt_addstring(s->pktout, ssh->username);
9851 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9852 /* service requested */
9853 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9854 ssh2_pkt_addbool(s->pktout, FALSE);
9855 /* no signature included */
9856 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9857 ssh2_pkt_addstring_start(s->pktout);
9858 ssh2_pkt_addstring_data(s->pktout,
9859 (char *)s->publickey_blob,
9860 s->publickey_bloblen);
9861 ssh2_pkt_send(ssh, s->pktout);
9862 logevent("Offered public key");
9864 crWaitUntilV(pktin);
9865 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9866 /* Key refused. Give up. */
9867 s->gotit = TRUE; /* reconsider message next loop */
9868 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9869 continue; /* process this new message */
9871 logevent("Offer of public key accepted");
9874 * Actually attempt a serious authentication using
9877 if (flags & FLAG_VERBOSE) {
9878 c_write_str(ssh, "Authenticating with public key \"");
9879 c_write_str(ssh, s->publickey_comment);
9880 c_write_str(ssh, "\"\r\n");
9884 const char *error; /* not live over crReturn */
9885 if (s->privatekey_encrypted) {
9887 * Get a passphrase from the user.
9889 int ret; /* need not be kept over crReturn */
9890 s->cur_prompt = new_prompts(ssh->frontend);
9891 s->cur_prompt->to_server = FALSE;
9892 s->cur_prompt->name = dupstr("SSH key passphrase");
9893 add_prompt(s->cur_prompt,
9894 dupprintf("Passphrase for key \"%.100s\": ",
9895 s->publickey_comment),
9897 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9900 crWaitUntilV(!pktin);
9901 ret = get_userpass_input(s->cur_prompt,
9906 /* Failed to get a passphrase. Terminate. */
9907 free_prompts(s->cur_prompt);
9908 ssh_disconnect(ssh, NULL,
9909 "Unable to authenticate",
9910 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9915 dupstr(s->cur_prompt->prompts[0]->result);
9916 free_prompts(s->cur_prompt);
9918 passphrase = NULL; /* no passphrase needed */
9922 * Try decrypting the key.
9924 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9925 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9927 /* burn the evidence */
9928 smemclr(passphrase, strlen(passphrase));
9931 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9933 (key == SSH2_WRONG_PASSPHRASE)) {
9934 c_write_str(ssh, "Wrong passphrase\r\n");
9936 /* and loop again */
9938 c_write_str(ssh, "Unable to load private key (");
9939 c_write_str(ssh, error);
9940 c_write_str(ssh, ")\r\n");
9942 break; /* try something else */
9948 unsigned char *pkblob, *sigblob, *sigdata;
9949 int pkblob_len, sigblob_len, sigdata_len;
9953 * We have loaded the private key and the server
9954 * has announced that it's willing to accept it.
9955 * Hallelujah. Generate a signature and send it.
9957 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9958 ssh2_pkt_addstring(s->pktout, ssh->username);
9959 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9960 /* service requested */
9961 ssh2_pkt_addstring(s->pktout, "publickey");
9963 ssh2_pkt_addbool(s->pktout, TRUE);
9964 /* signature follows */
9965 ssh2_pkt_addstring(s->pktout, key->alg->name);
9966 pkblob = key->alg->public_blob(key->data,
9968 ssh2_pkt_addstring_start(s->pktout);
9969 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9973 * The data to be signed is:
9977 * followed by everything so far placed in the
9980 sigdata_len = s->pktout->length - 5 + 4 +
9981 ssh->v2_session_id_len;
9982 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9984 sigdata = snewn(sigdata_len, unsigned char);
9986 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9987 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9990 memcpy(sigdata+p, ssh->v2_session_id,
9991 ssh->v2_session_id_len);
9992 p += ssh->v2_session_id_len;
9993 memcpy(sigdata+p, s->pktout->data + 5,
9994 s->pktout->length - 5);
9995 p += s->pktout->length - 5;
9996 assert(p == sigdata_len);
9997 sigblob = key->alg->sign(key->data, (char *)sigdata,
9998 sigdata_len, &sigblob_len);
9999 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
10000 sigblob, sigblob_len);
10005 ssh2_pkt_send(ssh, s->pktout);
10006 logevent("Sent public key signature");
10007 s->type = AUTH_TYPE_PUBLICKEY;
10008 key->alg->freekey(key->data);
10009 sfree(key->comment);
10014 } else if (s->can_gssapi && !s->tried_gssapi) {
10016 /* GSSAPI Authentication */
10018 int micoffset, len;
10021 s->type = AUTH_TYPE_GSSAPI;
10022 s->tried_gssapi = TRUE;
10024 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
10027 * Pick the highest GSS library on the preference
10033 for (i = 0; i < ngsslibs; i++) {
10034 int want_id = conf_get_int_int(ssh->conf,
10035 CONF_ssh_gsslist, i);
10036 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
10037 if (ssh->gsslibs->libraries[j].id == want_id) {
10038 s->gsslib = &ssh->gsslibs->libraries[j];
10039 goto got_gsslib; /* double break */
10044 * We always expect to have found something in
10045 * the above loop: we only came here if there
10046 * was at least one viable GSS library, and the
10047 * preference list should always mention
10048 * everything and only change the order.
10053 if (s->gsslib->gsslogmsg)
10054 logevent(s->gsslib->gsslogmsg);
10056 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
10057 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10058 ssh2_pkt_addstring(s->pktout, ssh->username);
10059 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10060 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
10061 logevent("Attempting GSSAPI authentication");
10063 /* add mechanism info */
10064 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
10066 /* number of GSSAPI mechanisms */
10067 ssh2_pkt_adduint32(s->pktout,1);
10069 /* length of OID + 2 */
10070 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
10071 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
10073 /* length of OID */
10074 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
10076 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
10077 s->gss_buf.length);
10078 ssh2_pkt_send(ssh, s->pktout);
10079 crWaitUntilV(pktin);
10080 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
10081 logevent("GSSAPI authentication request refused");
10085 /* check returned packet ... */
10087 ssh_pkt_getstring(pktin, &data, &len);
10088 s->gss_rcvtok.value = data;
10089 s->gss_rcvtok.length = len;
10090 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
10091 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
10092 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
10093 memcmp((char *)s->gss_rcvtok.value + 2,
10094 s->gss_buf.value,s->gss_buf.length) ) {
10095 logevent("GSSAPI authentication - wrong response from server");
10099 /* now start running */
10100 s->gss_stat = s->gsslib->import_name(s->gsslib,
10103 if (s->gss_stat != SSH_GSS_OK) {
10104 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
10105 logevent("GSSAPI import name failed - Bad service name");
10107 logevent("GSSAPI import name failed");
10111 /* fetch TGT into GSS engine */
10112 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
10114 if (s->gss_stat != SSH_GSS_OK) {
10115 logevent("GSSAPI authentication failed to get credentials");
10116 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10120 /* initial tokens are empty */
10121 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
10122 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
10124 /* now enter the loop */
10126 s->gss_stat = s->gsslib->init_sec_context
10130 conf_get_int(ssh->conf, CONF_gssapifwd),
10134 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
10135 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
10136 logevent("GSSAPI authentication initialisation failed");
10138 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
10139 &s->gss_buf) == SSH_GSS_OK) {
10140 logevent(s->gss_buf.value);
10141 sfree(s->gss_buf.value);
10146 logevent("GSSAPI authentication initialised");
10148 /* Client and server now exchange tokens until GSSAPI
10149 * no longer says CONTINUE_NEEDED */
10151 if (s->gss_sndtok.length != 0) {
10152 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
10153 ssh_pkt_addstring_start(s->pktout);
10154 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
10155 ssh2_pkt_send(ssh, s->pktout);
10156 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
10159 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
10160 crWaitUntilV(pktin);
10161 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
10162 logevent("GSSAPI authentication - bad server response");
10163 s->gss_stat = SSH_GSS_FAILURE;
10166 ssh_pkt_getstring(pktin, &data, &len);
10167 s->gss_rcvtok.value = data;
10168 s->gss_rcvtok.length = len;
10170 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
10172 if (s->gss_stat != SSH_GSS_OK) {
10173 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10174 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10177 logevent("GSSAPI authentication loop finished OK");
10179 /* Now send the MIC */
10181 s->pktout = ssh2_pkt_init(0);
10182 micoffset = s->pktout->length;
10183 ssh_pkt_addstring_start(s->pktout);
10184 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10185 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10186 ssh_pkt_addstring(s->pktout, ssh->username);
10187 ssh_pkt_addstring(s->pktout, "ssh-connection");
10188 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10190 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10191 s->gss_buf.length = s->pktout->length - micoffset;
10193 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10194 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10195 ssh_pkt_addstring_start(s->pktout);
10196 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10197 ssh2_pkt_send(ssh, s->pktout);
10198 s->gsslib->free_mic(s->gsslib, &mic);
10202 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10203 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10206 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10209 * Keyboard-interactive authentication.
10212 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10214 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10216 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10217 ssh2_pkt_addstring(s->pktout, ssh->username);
10218 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10219 /* service requested */
10220 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10222 ssh2_pkt_addstring(s->pktout, ""); /* lang */
10223 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
10224 ssh2_pkt_send(ssh, s->pktout);
10226 logevent("Attempting keyboard-interactive authentication");
10228 crWaitUntilV(pktin);
10229 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10230 /* Server is not willing to do keyboard-interactive
10231 * at all (or, bizarrely but legally, accepts the
10232 * user without actually issuing any prompts).
10233 * Give up on it entirely. */
10235 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10236 s->kbd_inter_refused = TRUE; /* don't try it again */
10241 * Loop while the server continues to send INFO_REQUESTs.
10243 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10245 char *name, *inst, *lang;
10246 int name_len, inst_len, lang_len;
10250 * We've got a fresh USERAUTH_INFO_REQUEST.
10251 * Get the preamble and start building a prompt.
10253 ssh_pkt_getstring(pktin, &name, &name_len);
10254 ssh_pkt_getstring(pktin, &inst, &inst_len);
10255 ssh_pkt_getstring(pktin, &lang, &lang_len);
10256 s->cur_prompt = new_prompts(ssh->frontend);
10257 s->cur_prompt->to_server = TRUE;
10260 * Get any prompt(s) from the packet.
10262 s->num_prompts = ssh_pkt_getuint32(pktin);
10263 for (i = 0; i < s->num_prompts; i++) {
10267 static char noprompt[] =
10268 "<server failed to send prompt>: ";
10270 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10271 echo = ssh2_pkt_getbool(pktin);
10274 prompt_len = lenof(noprompt)-1;
10276 add_prompt(s->cur_prompt,
10277 dupprintf("%.*s", prompt_len, prompt),
10282 /* FIXME: better prefix to distinguish from
10283 * local prompts? */
10284 s->cur_prompt->name =
10285 dupprintf("SSH server: %.*s", name_len, name);
10286 s->cur_prompt->name_reqd = TRUE;
10288 s->cur_prompt->name =
10289 dupstr("SSH server authentication");
10290 s->cur_prompt->name_reqd = FALSE;
10292 /* We add a prefix to try to make it clear that a prompt
10293 * has come from the server.
10294 * FIXME: ugly to print "Using..." in prompt _every_
10295 * time round. Can this be done more subtly? */
10296 /* Special case: for reasons best known to themselves,
10297 * some servers send k-i requests with no prompts and
10298 * nothing to display. Keep quiet in this case. */
10299 if (s->num_prompts || name_len || inst_len) {
10300 s->cur_prompt->instruction =
10301 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10302 inst_len ? "\n" : "", inst_len, inst);
10303 s->cur_prompt->instr_reqd = TRUE;
10305 s->cur_prompt->instr_reqd = FALSE;
10309 * Display any instructions, and get the user's
10313 int ret; /* not live over crReturn */
10314 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10317 crWaitUntilV(!pktin);
10318 ret = get_userpass_input(s->cur_prompt, in, inlen);
10323 * Failed to get responses. Terminate.
10325 free_prompts(s->cur_prompt);
10326 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10327 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10334 * Send the response(s) to the server.
10336 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10337 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10338 for (i=0; i < s->num_prompts; i++) {
10339 ssh2_pkt_addstring(s->pktout,
10340 s->cur_prompt->prompts[i]->result);
10342 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10345 * Free the prompts structure from this iteration.
10346 * If there's another, a new one will be allocated
10347 * when we return to the top of this while loop.
10349 free_prompts(s->cur_prompt);
10352 * Get the next packet in case it's another
10355 crWaitUntilV(pktin);
10360 * We should have SUCCESS or FAILURE now.
10364 } else if (s->can_passwd) {
10367 * Plain old password authentication.
10369 int ret; /* not live over crReturn */
10370 int changereq_first_time; /* not live over crReturn */
10372 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10374 s->cur_prompt = new_prompts(ssh->frontend);
10375 s->cur_prompt->to_server = TRUE;
10376 s->cur_prompt->name = dupstr("SSH password");
10377 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10382 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10385 crWaitUntilV(!pktin);
10386 ret = get_userpass_input(s->cur_prompt, in, inlen);
10391 * Failed to get responses. Terminate.
10393 free_prompts(s->cur_prompt);
10394 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10395 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10400 * Squirrel away the password. (We may need it later if
10401 * asked to change it.)
10403 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10404 free_prompts(s->cur_prompt);
10407 * Send the password packet.
10409 * We pad out the password packet to 256 bytes to make
10410 * it harder for an attacker to find the length of the
10413 * Anyone using a password longer than 256 bytes
10414 * probably doesn't have much to worry about from
10415 * people who find out how long their password is!
10417 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10418 ssh2_pkt_addstring(s->pktout, ssh->username);
10419 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10420 /* service requested */
10421 ssh2_pkt_addstring(s->pktout, "password");
10422 ssh2_pkt_addbool(s->pktout, FALSE);
10423 ssh2_pkt_addstring(s->pktout, s->password);
10424 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10425 logevent("Sent password");
10426 s->type = AUTH_TYPE_PASSWORD;
10429 * Wait for next packet, in case it's a password change
10432 crWaitUntilV(pktin);
10433 changereq_first_time = TRUE;
10435 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10438 * We're being asked for a new password
10439 * (perhaps not for the first time).
10440 * Loop until the server accepts it.
10443 int got_new = FALSE; /* not live over crReturn */
10444 char *prompt; /* not live over crReturn */
10445 int prompt_len; /* not live over crReturn */
10449 if (changereq_first_time)
10450 msg = "Server requested password change";
10452 msg = "Server rejected new password";
10454 c_write_str(ssh, msg);
10455 c_write_str(ssh, "\r\n");
10458 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10460 s->cur_prompt = new_prompts(ssh->frontend);
10461 s->cur_prompt->to_server = TRUE;
10462 s->cur_prompt->name = dupstr("New SSH password");
10463 s->cur_prompt->instruction =
10464 dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
10465 s->cur_prompt->instr_reqd = TRUE;
10467 * There's no explicit requirement in the protocol
10468 * for the "old" passwords in the original and
10469 * password-change messages to be the same, and
10470 * apparently some Cisco kit supports password change
10471 * by the user entering a blank password originally
10472 * and the real password subsequently, so,
10473 * reluctantly, we prompt for the old password again.
10475 * (On the other hand, some servers don't even bother
10476 * to check this field.)
10478 add_prompt(s->cur_prompt,
10479 dupstr("Current password (blank for previously entered password): "),
10481 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10483 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10487 * Loop until the user manages to enter the same
10492 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10495 crWaitUntilV(!pktin);
10496 ret = get_userpass_input(s->cur_prompt, in, inlen);
10501 * Failed to get responses. Terminate.
10503 /* burn the evidence */
10504 free_prompts(s->cur_prompt);
10505 smemclr(s->password, strlen(s->password));
10506 sfree(s->password);
10507 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10508 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10514 * If the user specified a new original password
10515 * (IYSWIM), overwrite any previously specified
10517 * (A side effect is that the user doesn't have to
10518 * re-enter it if they louse up the new password.)
10520 if (s->cur_prompt->prompts[0]->result[0]) {
10521 smemclr(s->password, strlen(s->password));
10522 /* burn the evidence */
10523 sfree(s->password);
10525 dupstr(s->cur_prompt->prompts[0]->result);
10529 * Check the two new passwords match.
10531 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10532 s->cur_prompt->prompts[2]->result)
10535 /* They don't. Silly user. */
10536 c_write_str(ssh, "Passwords do not match\r\n");
10541 * Send the new password (along with the old one).
10542 * (see above for padding rationale)
10544 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10545 ssh2_pkt_addstring(s->pktout, ssh->username);
10546 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10547 /* service requested */
10548 ssh2_pkt_addstring(s->pktout, "password");
10549 ssh2_pkt_addbool(s->pktout, TRUE);
10550 ssh2_pkt_addstring(s->pktout, s->password);
10551 ssh2_pkt_addstring(s->pktout,
10552 s->cur_prompt->prompts[1]->result);
10553 free_prompts(s->cur_prompt);
10554 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10555 logevent("Sent new password");
10558 * Now see what the server has to say about it.
10559 * (If it's CHANGEREQ again, it's not happy with the
10562 crWaitUntilV(pktin);
10563 changereq_first_time = FALSE;
10568 * We need to reexamine the current pktin at the top
10569 * of the loop. Either:
10570 * - we weren't asked to change password at all, in
10571 * which case it's a SUCCESS or FAILURE with the
10573 * - we sent a new password, and the server was
10574 * either OK with it (SUCCESS or FAILURE w/partial
10575 * success) or unhappy with the _old_ password
10576 * (FAILURE w/o partial success)
10577 * In any of these cases, we go back to the top of
10578 * the loop and start again.
10583 * We don't need the old password any more, in any
10584 * case. Burn the evidence.
10586 smemclr(s->password, strlen(s->password));
10587 sfree(s->password);
10590 char *str = dupprintf("No supported authentication methods available"
10591 " (server sent: %.*s)",
10594 ssh_disconnect(ssh, str,
10595 "No supported authentication methods available",
10596 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10606 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10608 /* Clear up various bits and pieces from authentication. */
10609 if (s->publickey_blob) {
10610 sfree(s->publickey_algorithm);
10611 sfree(s->publickey_blob);
10612 sfree(s->publickey_comment);
10614 if (s->agent_response)
10615 sfree(s->agent_response);
10617 if (s->userauth_success && !ssh->bare_connection) {
10619 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10620 * packets since. Signal the transport layer to consider enacting
10621 * delayed compression.
10623 * (Relying on we_are_in is not sufficient, as
10624 * draft-miller-secsh-compression-delayed is quite clear that it
10625 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10626 * become set for other reasons.)
10628 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10631 ssh->channels = newtree234(ssh_channelcmp);
10634 * Set up handlers for some connection protocol messages, so we
10635 * don't have to handle them repeatedly in this coroutine.
10637 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10638 ssh2_msg_channel_window_adjust;
10639 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10640 ssh2_msg_global_request;
10643 * Create the main session channel.
10645 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10646 ssh->mainchan = NULL;
10648 ssh->mainchan = snew(struct ssh_channel);
10649 ssh->mainchan->ssh = ssh;
10650 ssh2_channel_init(ssh->mainchan);
10652 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10654 * Just start a direct-tcpip channel and use it as the main
10657 ssh_send_port_open(ssh->mainchan,
10658 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10659 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10661 ssh->ncmode = TRUE;
10663 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10664 logevent("Opening session as main channel");
10665 ssh2_pkt_send(ssh, s->pktout);
10666 ssh->ncmode = FALSE;
10668 crWaitUntilV(pktin);
10669 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10670 bombout(("Server refused to open channel"));
10672 /* FIXME: error data comes back in FAILURE packet */
10674 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10675 bombout(("Server's channel confirmation cited wrong channel"));
10678 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10679 ssh->mainchan->halfopen = FALSE;
10680 ssh->mainchan->type = CHAN_MAINSESSION;
10681 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10682 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10683 add234(ssh->channels, ssh->mainchan);
10684 update_specials_menu(ssh->frontend);
10685 logevent("Opened main channel");
10689 * Now we have a channel, make dispatch table entries for
10690 * general channel-based messages.
10692 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10693 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10694 ssh2_msg_channel_data;
10695 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10696 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10697 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10698 ssh2_msg_channel_open_confirmation;
10699 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10700 ssh2_msg_channel_open_failure;
10701 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10702 ssh2_msg_channel_request;
10703 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10704 ssh2_msg_channel_open;
10705 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10706 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10709 * Now the connection protocol is properly up and running, with
10710 * all those dispatch table entries, so it's safe to let
10711 * downstreams start trying to open extra channels through us.
10713 if (ssh->connshare)
10714 share_activate(ssh->connshare, ssh->v_s);
10716 if (ssh->mainchan && ssh_is_simple(ssh)) {
10718 * This message indicates to the server that we promise
10719 * not to try to run any other channel in parallel with
10720 * this one, so it's safe for it to advertise a very large
10721 * window and leave the flow control to TCP.
10723 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10724 "simple@putty.projects.tartarus.org",
10726 ssh2_pkt_send(ssh, s->pktout);
10730 * Enable port forwardings.
10732 ssh_setup_portfwd(ssh, ssh->conf);
10734 if (ssh->mainchan && !ssh->ncmode) {
10736 * Send the CHANNEL_REQUESTS for the main session channel.
10737 * Each one is handled by its own little asynchronous
10741 /* Potentially enable X11 forwarding. */
10742 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10744 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10746 if (!ssh->x11disp) {
10747 /* FIXME: return an error message from x11_setup_display */
10748 logevent("X11 forwarding not enabled: unable to"
10749 " initialise X display");
10751 ssh->x11auth = x11_invent_fake_auth
10752 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10753 ssh->x11auth->disp = ssh->x11disp;
10755 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10759 /* Potentially enable agent forwarding. */
10760 if (ssh_agent_forwarding_permitted(ssh))
10761 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10763 /* Now allocate a pty for the session. */
10764 if (!conf_get_int(ssh->conf, CONF_nopty))
10765 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10767 /* Send environment variables. */
10768 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10771 * Start a shell or a remote command. We may have to attempt
10772 * this twice if the config data has provided a second choice
10779 if (ssh->fallback_cmd) {
10780 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10781 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10783 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10784 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10788 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10789 ssh2_response_authconn, NULL);
10790 ssh2_pkt_addstring(s->pktout, cmd);
10792 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10793 ssh2_response_authconn, NULL);
10794 ssh2_pkt_addstring(s->pktout, cmd);
10796 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10797 ssh2_response_authconn, NULL);
10799 ssh2_pkt_send(ssh, s->pktout);
10801 crWaitUntilV(pktin);
10803 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10804 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10805 bombout(("Unexpected response to shell/command request:"
10806 " packet type %d", pktin->type));
10810 * We failed to start the command. If this is the
10811 * fallback command, we really are finished; if it's
10812 * not, and if the fallback command exists, try falling
10813 * back to it before complaining.
10815 if (!ssh->fallback_cmd &&
10816 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10817 logevent("Primary command failed; attempting fallback");
10818 ssh->fallback_cmd = TRUE;
10821 bombout(("Server refused to start a shell/command"));
10824 logevent("Started a shell/command");
10829 ssh->editing = ssh->echoing = TRUE;
10832 ssh->state = SSH_STATE_SESSION;
10833 if (ssh->size_needed)
10834 ssh_size(ssh, ssh->term_width, ssh->term_height);
10835 if (ssh->eof_needed)
10836 ssh_special(ssh, TS_EOF);
10842 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10850 * _All_ the connection-layer packets we expect to
10851 * receive are now handled by the dispatch table.
10852 * Anything that reaches here must be bogus.
10855 bombout(("Strange packet received: type %d", pktin->type));
10857 } else if (ssh->mainchan) {
10859 * We have spare data. Add it to the channel buffer.
10861 ssh_send_channel_data(ssh->mainchan, (char *)in, inlen);
10869 * Handlers for SSH-2 messages that might arrive at any moment.
10871 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10873 /* log reason code in disconnect message */
10875 int reason, msglen;
10877 reason = ssh_pkt_getuint32(pktin);
10878 ssh_pkt_getstring(pktin, &msg, &msglen);
10880 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10881 buf = dupprintf("Received disconnect message (%s)",
10882 ssh2_disconnect_reasons[reason]);
10884 buf = dupprintf("Received disconnect message (unknown"
10885 " type %d)", reason);
10889 buf = dupprintf("Disconnection message text: %.*s",
10890 msglen, NULLTOEMPTY(msg));
10892 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10894 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10895 ssh2_disconnect_reasons[reason] : "unknown",
10896 msglen, NULLTOEMPTY(msg)));
10900 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10902 /* log the debug message */
10906 /* XXX maybe we should actually take notice of the return value */
10907 ssh2_pkt_getbool(pktin);
10908 ssh_pkt_getstring(pktin, &msg, &msglen);
10910 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
10913 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10915 do_ssh2_transport(ssh, NULL, 0, pktin);
10919 * Called if we receive a packet that isn't allowed by the protocol.
10920 * This only applies to packets whose meaning PuTTY understands.
10921 * Entirely unknown packets are handled below.
10923 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10925 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10926 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10928 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10932 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10934 struct Packet *pktout;
10935 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10936 ssh2_pkt_adduint32(pktout, pktin->sequence);
10938 * UNIMPLEMENTED messages MUST appear in the same order as the
10939 * messages they respond to. Hence, never queue them.
10941 ssh2_pkt_send_noqueue(ssh, pktout);
10945 * Handle the top-level SSH-2 protocol.
10947 static void ssh2_protocol_setup(Ssh ssh)
10952 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10954 for (i = 0; i < 256; i++)
10955 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10958 * Initially, we only accept transport messages (and a few generic
10959 * ones). do_ssh2_authconn will add more when it starts.
10960 * Messages that are understood but not currently acceptable go to
10961 * ssh2_msg_unexpected.
10963 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10964 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10965 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10966 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10967 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10968 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10969 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10970 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10971 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10972 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10973 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10974 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10975 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10976 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10977 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10978 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10979 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10980 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10981 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10982 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10983 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10984 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10985 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10986 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10987 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10988 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10989 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10990 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10991 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10992 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10993 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10994 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10995 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10998 * These messages have a special handler from the start.
11000 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11001 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
11002 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11005 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
11010 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
11012 for (i = 0; i < 256; i++)
11013 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
11016 * Initially, we set all ssh-connection messages to 'unexpected';
11017 * do_ssh2_authconn will fill things in properly. We also handle a
11018 * couple of messages from the transport protocol which aren't
11019 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
11022 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
11023 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
11024 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
11025 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
11026 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
11027 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
11028 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
11029 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
11030 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
11031 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
11032 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
11033 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
11034 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
11035 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
11037 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
11040 * These messages have a special handler from the start.
11042 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
11043 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
11044 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
11047 static void ssh2_timer(void *ctx, unsigned long now)
11049 Ssh ssh = (Ssh)ctx;
11051 if (ssh->state == SSH_STATE_CLOSED)
11054 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11055 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
11056 now == ssh->next_rekey) {
11057 do_ssh2_transport(ssh, "timeout", -1, NULL);
11061 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
11062 struct Packet *pktin)
11064 const unsigned char *in = (const unsigned char *)vin;
11065 if (ssh->state == SSH_STATE_CLOSED)
11069 ssh->incoming_data_size += pktin->encrypted_len;
11070 if (!ssh->kex_in_progress &&
11071 ssh->max_data_size != 0 &&
11072 ssh->incoming_data_size > ssh->max_data_size)
11073 do_ssh2_transport(ssh, "too much data received", -1, NULL);
11077 ssh->packet_dispatch[pktin->type](ssh, pktin);
11078 else if (!ssh->protocol_initial_phase_done)
11079 do_ssh2_transport(ssh, in, inlen, pktin);
11081 do_ssh2_authconn(ssh, in, inlen, pktin);
11084 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
11085 struct Packet *pktin)
11087 const unsigned char *in = (const unsigned char *)vin;
11088 if (ssh->state == SSH_STATE_CLOSED)
11092 ssh->packet_dispatch[pktin->type](ssh, pktin);
11094 do_ssh2_authconn(ssh, in, inlen, pktin);
11097 static void ssh_cache_conf_values(Ssh ssh)
11099 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
11103 * Called to set up the connection.
11105 * Returns an error message, or NULL on success.
11107 static const char *ssh_init(void *frontend_handle, void **backend_handle,
11109 const char *host, int port, char **realhost,
11110 int nodelay, int keepalive)
11115 ssh = snew(struct ssh_tag);
11116 ssh->conf = conf_copy(conf);
11117 ssh_cache_conf_values(ssh);
11118 ssh->version = 0; /* when not ready yet */
11120 ssh->cipher = NULL;
11121 ssh->v1_cipher_ctx = NULL;
11122 ssh->crcda_ctx = NULL;
11123 ssh->cscipher = NULL;
11124 ssh->cs_cipher_ctx = NULL;
11125 ssh->sccipher = NULL;
11126 ssh->sc_cipher_ctx = NULL;
11128 ssh->cs_mac_ctx = NULL;
11130 ssh->sc_mac_ctx = NULL;
11131 ssh->cscomp = NULL;
11132 ssh->cs_comp_ctx = NULL;
11133 ssh->sccomp = NULL;
11134 ssh->sc_comp_ctx = NULL;
11136 ssh->kex_ctx = NULL;
11137 ssh->hostkey = NULL;
11138 ssh->hostkey_str = NULL;
11139 ssh->exitcode = -1;
11140 ssh->close_expected = FALSE;
11141 ssh->clean_exit = FALSE;
11142 ssh->state = SSH_STATE_PREPACKET;
11143 ssh->size_needed = FALSE;
11144 ssh->eof_needed = FALSE;
11146 ssh->logctx = NULL;
11147 ssh->deferred_send_data = NULL;
11148 ssh->deferred_len = 0;
11149 ssh->deferred_size = 0;
11150 ssh->fallback_cmd = 0;
11151 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
11152 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
11153 ssh->x11disp = NULL;
11154 ssh->x11auth = NULL;
11155 ssh->x11authtree = newtree234(x11_authcmp);
11156 ssh->v1_compressing = FALSE;
11157 ssh->v2_outgoing_sequence = 0;
11158 ssh->ssh1_rdpkt_crstate = 0;
11159 ssh->ssh2_rdpkt_crstate = 0;
11160 ssh->ssh2_bare_rdpkt_crstate = 0;
11161 ssh->ssh_gotdata_crstate = 0;
11162 ssh->do_ssh1_connection_crstate = 0;
11163 ssh->do_ssh_init_state = NULL;
11164 ssh->do_ssh_connection_init_state = NULL;
11165 ssh->do_ssh1_login_state = NULL;
11166 ssh->do_ssh2_transport_state = NULL;
11167 ssh->do_ssh2_authconn_state = NULL;
11170 ssh->mainchan = NULL;
11171 ssh->throttled_all = 0;
11172 ssh->v1_stdout_throttling = 0;
11174 ssh->queuelen = ssh->queuesize = 0;
11175 ssh->queueing = FALSE;
11176 ssh->qhead = ssh->qtail = NULL;
11177 ssh->deferred_rekey_reason = NULL;
11178 bufchain_init(&ssh->queued_incoming_data);
11179 ssh->frozen = FALSE;
11180 ssh->username = NULL;
11181 ssh->sent_console_eof = FALSE;
11182 ssh->got_pty = FALSE;
11183 ssh->bare_connection = FALSE;
11184 ssh->X11_fwd_enabled = FALSE;
11185 ssh->connshare = NULL;
11186 ssh->attempting_connshare = FALSE;
11187 ssh->session_started = FALSE;
11188 ssh->specials = NULL;
11189 ssh->n_uncert_hostkeys = 0;
11190 ssh->cross_certifying = FALSE;
11192 *backend_handle = ssh;
11195 if (crypto_startup() == 0)
11196 return "Microsoft high encryption pack not installed!";
11199 ssh->frontend = frontend_handle;
11200 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11201 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11203 ssh->channels = NULL;
11204 ssh->rportfwds = NULL;
11205 ssh->portfwds = NULL;
11210 ssh->conn_throttle_count = 0;
11211 ssh->overall_bufsize = 0;
11212 ssh->fallback_cmd = 0;
11214 ssh->protocol = NULL;
11216 ssh->protocol_initial_phase_done = FALSE;
11218 ssh->pinger = NULL;
11220 ssh->incoming_data_size = ssh->outgoing_data_size =
11221 ssh->deferred_data_size = 0L;
11222 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11223 CONF_ssh_rekey_data));
11224 ssh->kex_in_progress = FALSE;
11227 ssh->gsslibs = NULL;
11230 random_ref(); /* do this now - may be needed by sharing setup code */
11232 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11241 static void ssh_free(void *handle)
11243 Ssh ssh = (Ssh) handle;
11244 struct ssh_channel *c;
11245 struct ssh_rportfwd *pf;
11246 struct X11FakeAuth *auth;
11248 if (ssh->v1_cipher_ctx)
11249 ssh->cipher->free_context(ssh->v1_cipher_ctx);
11250 if (ssh->cs_cipher_ctx)
11251 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11252 if (ssh->sc_cipher_ctx)
11253 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11254 if (ssh->cs_mac_ctx)
11255 ssh->csmac->free_context(ssh->cs_mac_ctx);
11256 if (ssh->sc_mac_ctx)
11257 ssh->scmac->free_context(ssh->sc_mac_ctx);
11258 if (ssh->cs_comp_ctx) {
11260 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11262 zlib_compress_cleanup(ssh->cs_comp_ctx);
11264 if (ssh->sc_comp_ctx) {
11266 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11268 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11271 dh_cleanup(ssh->kex_ctx);
11272 sfree(ssh->savedhost);
11274 while (ssh->queuelen-- > 0)
11275 ssh_free_packet(ssh->queue[ssh->queuelen]);
11278 while (ssh->qhead) {
11279 struct queued_handler *qh = ssh->qhead;
11280 ssh->qhead = qh->next;
11283 ssh->qhead = ssh->qtail = NULL;
11285 if (ssh->channels) {
11286 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11289 if (c->u.x11.xconn != NULL)
11290 x11_close(c->u.x11.xconn);
11292 case CHAN_SOCKDATA:
11293 case CHAN_SOCKDATA_DORMANT:
11294 if (c->u.pfd.pf != NULL)
11295 pfd_close(c->u.pfd.pf);
11298 if (ssh->version == 2) {
11299 struct outstanding_channel_request *ocr, *nocr;
11300 ocr = c->v.v2.chanreq_head;
11302 ocr->handler(c, NULL, ocr->ctx);
11307 bufchain_clear(&c->v.v2.outbuffer);
11311 freetree234(ssh->channels);
11312 ssh->channels = NULL;
11315 if (ssh->connshare)
11316 sharestate_free(ssh->connshare);
11318 if (ssh->rportfwds) {
11319 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11321 freetree234(ssh->rportfwds);
11322 ssh->rportfwds = NULL;
11324 sfree(ssh->deferred_send_data);
11326 x11_free_display(ssh->x11disp);
11327 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11328 x11_free_fake_auth(auth);
11329 freetree234(ssh->x11authtree);
11330 sfree(ssh->do_ssh_init_state);
11331 sfree(ssh->do_ssh1_login_state);
11332 sfree(ssh->do_ssh2_transport_state);
11333 sfree(ssh->do_ssh2_authconn_state);
11336 sfree(ssh->fullhostname);
11337 sfree(ssh->hostkey_str);
11338 sfree(ssh->specials);
11339 if (ssh->crcda_ctx) {
11340 crcda_free_context(ssh->crcda_ctx);
11341 ssh->crcda_ctx = NULL;
11344 ssh_do_close(ssh, TRUE);
11345 expire_timer_context(ssh);
11347 pinger_free(ssh->pinger);
11348 bufchain_clear(&ssh->queued_incoming_data);
11349 sfree(ssh->username);
11350 conf_free(ssh->conf);
11353 ssh_gss_cleanup(ssh->gsslibs);
11361 * Reconfigure the SSH backend.
11363 static void ssh_reconfig(void *handle, Conf *conf)
11365 Ssh ssh = (Ssh) handle;
11366 const char *rekeying = NULL;
11367 int rekey_mandatory = FALSE;
11368 unsigned long old_max_data_size;
11371 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11373 ssh_setup_portfwd(ssh, conf);
11375 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11376 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11378 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11379 unsigned long now = GETTICKCOUNT();
11381 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11382 rekeying = "timeout shortened";
11384 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11388 old_max_data_size = ssh->max_data_size;
11389 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11390 CONF_ssh_rekey_data));
11391 if (old_max_data_size != ssh->max_data_size &&
11392 ssh->max_data_size != 0) {
11393 if (ssh->outgoing_data_size > ssh->max_data_size ||
11394 ssh->incoming_data_size > ssh->max_data_size)
11395 rekeying = "data limit lowered";
11398 if (conf_get_int(ssh->conf, CONF_compression) !=
11399 conf_get_int(conf, CONF_compression)) {
11400 rekeying = "compression setting changed";
11401 rekey_mandatory = TRUE;
11404 for (i = 0; i < CIPHER_MAX; i++)
11405 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11406 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11407 rekeying = "cipher settings changed";
11408 rekey_mandatory = TRUE;
11410 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11411 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11412 rekeying = "cipher settings changed";
11413 rekey_mandatory = TRUE;
11416 conf_free(ssh->conf);
11417 ssh->conf = conf_copy(conf);
11418 ssh_cache_conf_values(ssh);
11420 if (!ssh->bare_connection && rekeying) {
11421 if (!ssh->kex_in_progress) {
11422 do_ssh2_transport(ssh, rekeying, -1, NULL);
11423 } else if (rekey_mandatory) {
11424 ssh->deferred_rekey_reason = rekeying;
11430 * Called to send data down the SSH connection.
11432 static int ssh_send(void *handle, const char *buf, int len)
11434 Ssh ssh = (Ssh) handle;
11436 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11439 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11441 return ssh_sendbuffer(ssh);
11445 * Called to query the current amount of buffered stdin data.
11447 static int ssh_sendbuffer(void *handle)
11449 Ssh ssh = (Ssh) handle;
11450 int override_value;
11452 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11456 * If the SSH socket itself has backed up, add the total backup
11457 * size on that to any individual buffer on the stdin channel.
11459 override_value = 0;
11460 if (ssh->throttled_all)
11461 override_value = ssh->overall_bufsize;
11463 if (ssh->version == 1) {
11464 return override_value;
11465 } else if (ssh->version == 2) {
11466 if (!ssh->mainchan)
11467 return override_value;
11469 return (override_value +
11470 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11477 * Called to set the size of the window from SSH's POV.
11479 static void ssh_size(void *handle, int width, int height)
11481 Ssh ssh = (Ssh) handle;
11482 struct Packet *pktout;
11484 ssh->term_width = width;
11485 ssh->term_height = height;
11487 switch (ssh->state) {
11488 case SSH_STATE_BEFORE_SIZE:
11489 case SSH_STATE_PREPACKET:
11490 case SSH_STATE_CLOSED:
11491 break; /* do nothing */
11492 case SSH_STATE_INTERMED:
11493 ssh->size_needed = TRUE; /* buffer for later */
11495 case SSH_STATE_SESSION:
11496 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11497 if (ssh->version == 1) {
11498 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11499 PKT_INT, ssh->term_height,
11500 PKT_INT, ssh->term_width,
11501 PKT_INT, 0, PKT_INT, 0, PKT_END);
11502 } else if (ssh->mainchan) {
11503 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11505 ssh2_pkt_adduint32(pktout, ssh->term_width);
11506 ssh2_pkt_adduint32(pktout, ssh->term_height);
11507 ssh2_pkt_adduint32(pktout, 0);
11508 ssh2_pkt_adduint32(pktout, 0);
11509 ssh2_pkt_send(ssh, pktout);
11517 * Return a list of the special codes that make sense in this
11520 static const struct telnet_special *ssh_get_specials(void *handle)
11522 static const struct telnet_special ssh1_ignore_special[] = {
11523 {"IGNORE message", TS_NOP}
11525 static const struct telnet_special ssh2_ignore_special[] = {
11526 {"IGNORE message", TS_NOP},
11528 static const struct telnet_special ssh2_rekey_special[] = {
11529 {"Repeat key exchange", TS_REKEY},
11531 static const struct telnet_special ssh2_session_specials[] = {
11534 /* These are the signal names defined by RFC 4254.
11535 * They include all the ISO C signals, but are a subset of the POSIX
11536 * required signals. */
11537 {"SIGINT (Interrupt)", TS_SIGINT},
11538 {"SIGTERM (Terminate)", TS_SIGTERM},
11539 {"SIGKILL (Kill)", TS_SIGKILL},
11540 {"SIGQUIT (Quit)", TS_SIGQUIT},
11541 {"SIGHUP (Hangup)", TS_SIGHUP},
11542 {"More signals", TS_SUBMENU},
11543 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11544 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11545 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11546 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11547 {NULL, TS_EXITMENU}
11549 static const struct telnet_special specials_end[] = {
11550 {NULL, TS_EXITMENU}
11553 struct telnet_special *specials = NULL;
11554 int nspecials = 0, specialsize = 0;
11556 Ssh ssh = (Ssh) handle;
11558 sfree(ssh->specials);
11560 #define ADD_SPECIALS(name) do \
11562 int len = lenof(name); \
11563 if (nspecials + len > specialsize) { \
11564 specialsize = (nspecials + len) * 5 / 4 + 32; \
11565 specials = sresize(specials, specialsize, struct telnet_special); \
11567 memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
11568 nspecials += len; \
11571 if (ssh->version == 1) {
11572 /* Don't bother offering IGNORE if we've decided the remote
11573 * won't cope with it, since we wouldn't bother sending it if
11575 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11576 ADD_SPECIALS(ssh1_ignore_special);
11577 } else if (ssh->version == 2) {
11578 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11579 ADD_SPECIALS(ssh2_ignore_special);
11580 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11581 ADD_SPECIALS(ssh2_rekey_special);
11583 ADD_SPECIALS(ssh2_session_specials);
11585 if (ssh->n_uncert_hostkeys) {
11586 static const struct telnet_special uncert_start[] = {
11588 {"Cache new host key type", TS_SUBMENU},
11590 static const struct telnet_special uncert_end[] = {
11591 {NULL, TS_EXITMENU},
11595 ADD_SPECIALS(uncert_start);
11596 for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
11597 struct telnet_special uncert[1];
11598 const struct ssh_signkey *alg =
11599 hostkey_algs[ssh->uncert_hostkeys[i]].alg;
11600 uncert[0].name = alg->name;
11601 uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
11602 ADD_SPECIALS(uncert);
11604 ADD_SPECIALS(uncert_end);
11606 } /* else we're not ready yet */
11609 ADD_SPECIALS(specials_end);
11611 ssh->specials = specials;
11618 #undef ADD_SPECIALS
11622 * Send special codes. TS_EOF is useful for `plink', so you
11623 * can send an EOF and collect resulting output (e.g. `plink
11626 static void ssh_special(void *handle, Telnet_Special code)
11628 Ssh ssh = (Ssh) handle;
11629 struct Packet *pktout;
11631 if (code == TS_EOF) {
11632 if (ssh->state != SSH_STATE_SESSION) {
11634 * Buffer the EOF in case we are pre-SESSION, so we can
11635 * send it as soon as we reach SESSION.
11637 if (code == TS_EOF)
11638 ssh->eof_needed = TRUE;
11641 if (ssh->version == 1) {
11642 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11643 } else if (ssh->mainchan) {
11644 sshfwd_write_eof(ssh->mainchan);
11645 ssh->send_ok = 0; /* now stop trying to read from stdin */
11647 logevent("Sent EOF message");
11648 } else if (code == TS_PING || code == TS_NOP) {
11649 if (ssh->state == SSH_STATE_CLOSED
11650 || ssh->state == SSH_STATE_PREPACKET) return;
11651 if (ssh->version == 1) {
11652 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11653 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11655 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11656 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11657 ssh2_pkt_addstring_start(pktout);
11658 ssh2_pkt_send_noqueue(ssh, pktout);
11661 } else if (code == TS_REKEY) {
11662 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11663 ssh->version == 2) {
11664 do_ssh2_transport(ssh, "at user request", -1, NULL);
11666 } else if (code >= TS_LOCALSTART) {
11667 ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
11668 ssh->cross_certifying = TRUE;
11669 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11670 ssh->version == 2) {
11671 do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
11673 } else if (code == TS_BRK) {
11674 if (ssh->state == SSH_STATE_CLOSED
11675 || ssh->state == SSH_STATE_PREPACKET) return;
11676 if (ssh->version == 1) {
11677 logevent("Unable to send BREAK signal in SSH-1");
11678 } else if (ssh->mainchan) {
11679 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11680 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11681 ssh2_pkt_send(ssh, pktout);
11684 /* Is is a POSIX signal? */
11685 const char *signame = NULL;
11686 if (code == TS_SIGABRT) signame = "ABRT";
11687 if (code == TS_SIGALRM) signame = "ALRM";
11688 if (code == TS_SIGFPE) signame = "FPE";
11689 if (code == TS_SIGHUP) signame = "HUP";
11690 if (code == TS_SIGILL) signame = "ILL";
11691 if (code == TS_SIGINT) signame = "INT";
11692 if (code == TS_SIGKILL) signame = "KILL";
11693 if (code == TS_SIGPIPE) signame = "PIPE";
11694 if (code == TS_SIGQUIT) signame = "QUIT";
11695 if (code == TS_SIGSEGV) signame = "SEGV";
11696 if (code == TS_SIGTERM) signame = "TERM";
11697 if (code == TS_SIGUSR1) signame = "USR1";
11698 if (code == TS_SIGUSR2) signame = "USR2";
11699 /* The SSH-2 protocol does in principle support arbitrary named
11700 * signals, including signame@domain, but we don't support those. */
11702 /* It's a signal. */
11703 if (ssh->version == 2 && ssh->mainchan) {
11704 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11705 ssh2_pkt_addstring(pktout, signame);
11706 ssh2_pkt_send(ssh, pktout);
11707 logeventf(ssh, "Sent signal SIG%s", signame);
11710 /* Never heard of it. Do nothing */
11715 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11717 Ssh ssh = (Ssh) handle;
11718 struct ssh_channel *c;
11719 c = snew(struct ssh_channel);
11722 ssh2_channel_init(c);
11723 c->halfopen = TRUE;
11724 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
11726 add234(ssh->channels, c);
11730 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11732 struct ssh_channel *c;
11733 c = snew(struct ssh_channel);
11736 ssh2_channel_init(c);
11737 c->type = CHAN_SHARING;
11738 c->u.sharing.ctx = sharing_ctx;
11739 add234(ssh->channels, c);
11743 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11745 struct ssh_channel *c;
11747 c = find234(ssh->channels, &localid, ssh_channelfind);
11749 ssh_channel_destroy(c);
11752 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11753 const void *data, int datalen,
11754 const char *additional_log_text)
11756 struct Packet *pkt;
11758 pkt = ssh2_pkt_init(type);
11759 pkt->downstream_id = id;
11760 pkt->additional_log_text = additional_log_text;
11761 ssh2_pkt_adddata(pkt, data, datalen);
11762 ssh2_pkt_send(ssh, pkt);
11766 * This is called when stdout/stderr (the entity to which
11767 * from_backend sends data) manages to clear some backlog.
11769 static void ssh_unthrottle(void *handle, int bufsize)
11771 Ssh ssh = (Ssh) handle;
11774 if (ssh->version == 1) {
11775 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11776 ssh->v1_stdout_throttling = 0;
11777 ssh_throttle_conn(ssh, -1);
11780 if (ssh->mainchan) {
11781 ssh2_set_window(ssh->mainchan,
11782 bufsize < ssh->mainchan->v.v2.locmaxwin ?
11783 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
11784 if (ssh_is_simple(ssh))
11787 buflimit = ssh->mainchan->v.v2.locmaxwin;
11788 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
11789 ssh->mainchan->throttling_conn = 0;
11790 ssh_throttle_conn(ssh, -1);
11796 * Now process any SSH connection data that was stashed in our
11797 * queue while we were frozen.
11799 ssh_process_queued_incoming_data(ssh);
11802 void ssh_send_port_open(void *channel, const char *hostname, int port,
11805 struct ssh_channel *c = (struct ssh_channel *)channel;
11807 struct Packet *pktout;
11809 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11811 if (ssh->version == 1) {
11812 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11813 PKT_INT, c->localid,
11816 /* PKT_STR, <org:orgport>, */
11819 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11821 char *trimmed_host = host_strduptrim(hostname);
11822 ssh2_pkt_addstring(pktout, trimmed_host);
11823 sfree(trimmed_host);
11825 ssh2_pkt_adduint32(pktout, port);
11827 * We make up values for the originator data; partly it's
11828 * too much hassle to keep track, and partly I'm not
11829 * convinced the server should be told details like that
11830 * about my local network configuration.
11831 * The "originator IP address" is syntactically a numeric
11832 * IP address, and some servers (e.g., Tectia) get upset
11833 * if it doesn't match this syntax.
11835 ssh2_pkt_addstring(pktout, "0.0.0.0");
11836 ssh2_pkt_adduint32(pktout, 0);
11837 ssh2_pkt_send(ssh, pktout);
11841 static int ssh_connected(void *handle)
11843 Ssh ssh = (Ssh) handle;
11844 return ssh->s != NULL;
11847 static int ssh_sendok(void *handle)
11849 Ssh ssh = (Ssh) handle;
11850 return ssh->send_ok;
11853 static int ssh_ldisc(void *handle, int option)
11855 Ssh ssh = (Ssh) handle;
11856 if (option == LD_ECHO)
11857 return ssh->echoing;
11858 if (option == LD_EDIT)
11859 return ssh->editing;
11863 static void ssh_provide_ldisc(void *handle, void *ldisc)
11865 Ssh ssh = (Ssh) handle;
11866 ssh->ldisc = ldisc;
11869 static void ssh_provide_logctx(void *handle, void *logctx)
11871 Ssh ssh = (Ssh) handle;
11872 ssh->logctx = logctx;
11875 static int ssh_return_exitcode(void *handle)
11877 Ssh ssh = (Ssh) handle;
11878 if (ssh->s != NULL)
11881 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11885 * cfg_info for SSH is the protocol running in this session.
11886 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11887 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11889 static int ssh_cfg_info(void *handle)
11891 Ssh ssh = (Ssh) handle;
11892 if (ssh->version == 0)
11893 return 0; /* don't know yet */
11894 else if (ssh->bare_connection)
11897 return ssh->version;
11901 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11902 * that fails. This variable is the means by which scp.c can reach
11903 * into the SSH code and find out which one it got.
11905 extern int ssh_fallback_cmd(void *handle)
11907 Ssh ssh = (Ssh) handle;
11908 return ssh->fallback_cmd;
11911 Backend ssh_backend = {
11921 ssh_return_exitcode,
11925 ssh_provide_logctx,
11928 ssh_test_for_upstream,