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 ssh_channel_init(struct ssh_channel *c);
368 static struct ssh_channel *ssh_channel_msg(Ssh ssh, struct Packet *pktin);
369 static void ssh_channel_got_eof(struct ssh_channel *c);
370 static void ssh2_channel_check_close(struct ssh_channel *c);
371 static void ssh_channel_close_local(struct ssh_channel *c, char const *reason);
372 static void ssh_channel_destroy(struct ssh_channel *c);
373 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize);
374 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin);
377 * Buffer management constants. There are several of these for
378 * various different purposes:
380 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
381 * on a local data stream before we throttle the whole SSH
382 * connection (in SSH-1 only). Throttling the whole connection is
383 * pretty drastic so we set this high in the hope it won't
386 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
387 * on the SSH connection itself before we defensively throttle
388 * _all_ local data streams. This is pretty drastic too (though
389 * thankfully unlikely in SSH-2 since the window mechanism should
390 * ensure that the server never has any need to throttle its end
391 * of the connection), so we set this high as well.
393 * - OUR_V2_WINSIZE is the default window size we present on SSH-2
396 * - OUR_V2_BIGWIN is the window size we advertise for the only
397 * channel in a simple connection. It must be <= INT_MAX.
399 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
400 * to the remote side. This actually has nothing to do with the
401 * size of the _packet_, but is instead a limit on the amount
402 * of data we're willing to receive in a single SSH2 channel
405 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
406 * _packet_ we're prepared to cope with. It must be a multiple
407 * of the cipher block size, and must be at least 35000.
410 #define SSH1_BUFFER_LIMIT 32768
411 #define SSH_MAX_BACKLOG 32768
412 #define OUR_V2_WINSIZE 16384
413 #define OUR_V2_BIGWIN 0x7fffffff
414 #define OUR_V2_MAXPKT 0x4000UL
415 #define OUR_V2_PACKETLIMIT 0x9000UL
417 struct ssh_signkey_with_user_pref_id {
418 const struct ssh_signkey *alg;
421 const static struct ssh_signkey_with_user_pref_id hostkey_algs[] = {
422 { &ssh_ecdsa_ed25519, HK_ED25519 },
423 { &ssh_ecdsa_nistp256, HK_ECDSA },
424 { &ssh_ecdsa_nistp384, HK_ECDSA },
425 { &ssh_ecdsa_nistp521, HK_ECDSA },
426 { &ssh_dss, HK_DSA },
427 { &ssh_rsa, HK_RSA },
430 const static struct ssh_mac *const macs[] = {
431 &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
433 const static struct ssh_mac *const buggymacs[] = {
434 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
437 static void *ssh_comp_none_init(void)
441 static void ssh_comp_none_cleanup(void *handle)
444 static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
445 unsigned char **outblock, int *outlen)
449 static int ssh_comp_none_disable(void *handle)
453 const static struct ssh_compress ssh_comp_none = {
455 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
456 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
457 ssh_comp_none_disable, NULL
459 extern const struct ssh_compress ssh_zlib;
460 const static struct ssh_compress *const compressions[] = {
461 &ssh_zlib, &ssh_comp_none
464 enum { /* channel types */
470 * CHAN_SHARING indicates a channel which is tracked here on
471 * behalf of a connection-sharing downstream. We do almost nothing
472 * with these channels ourselves: all messages relating to them
473 * get thrown straight to sshshare.c and passed on almost
474 * unmodified to downstream.
478 * CHAN_ZOMBIE is used to indicate a channel for which we've
479 * already destroyed the local data source: for instance, if a
480 * forwarded port experiences a socket error on the local side, we
481 * immediately destroy its local socket and turn the SSH channel
487 typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
488 typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
489 typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
492 * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
495 struct outstanding_channel_request {
496 cchandler_fn_t handler;
498 struct outstanding_channel_request *next;
502 * 2-3-4 tree storing channels.
505 Ssh ssh; /* pointer back to main context */
506 unsigned remoteid, localid;
508 /* True if we opened this channel but server hasn't confirmed. */
511 * In SSH-1, this value contains four bits:
513 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
514 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
515 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
516 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
518 * A channel is completely finished with when all four bits are set.
520 * In SSH-2, the four bits mean:
522 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
523 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
524 * 4 We have received SSH2_MSG_CHANNEL_EOF.
525 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
527 * A channel is completely finished with when we have both sent
528 * and received CLOSE.
530 * The symbolic constants below use the SSH-2 terminology, which
531 * is a bit confusing in SSH-1, but we have to use _something_.
533 #define CLOSES_SENT_EOF 1
534 #define CLOSES_SENT_CLOSE 2
535 #define CLOSES_RCVD_EOF 4
536 #define CLOSES_RCVD_CLOSE 8
540 * This flag indicates that an EOF is pending on the outgoing side
541 * of the channel: that is, wherever we're getting the data for
542 * this channel has sent us some data followed by EOF. We can't
543 * actually send the EOF until we've finished sending the data, so
544 * we set this flag instead to remind us to do so once our buffer
550 * True if this channel is causing the underlying connection to be
555 struct ssh2_data_channel {
557 unsigned remwindow, remmaxpkt;
558 /* locwindow is signed so we can cope with excess data. */
559 int locwindow, locmaxwin;
561 * remlocwin is the amount of local window that we think
562 * the remote end had available to it after it sent the
563 * last data packet or window adjust ack.
567 * These store the list of channel requests that haven't
570 struct outstanding_channel_request *chanreq_head, *chanreq_tail;
571 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
575 struct ssh_agent_channel {
576 unsigned char *message;
577 unsigned char msglen[4];
578 unsigned lensofar, totallen;
579 int outstanding_requests;
581 struct ssh_x11_channel {
582 struct X11Connection *xconn;
585 struct ssh_pfd_channel {
586 struct PortForwarding *pf;
588 struct ssh_sharing_channel {
595 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
596 * use this structure in different ways, reflecting SSH-2's
597 * altogether saner approach to port forwarding.
599 * In SSH-1, you arrange a remote forwarding by sending the server
600 * the remote port number, and the local destination host:port.
601 * When a connection comes in, the server sends you back that
602 * host:port pair, and you connect to it. This is a ready-made
603 * security hole if you're not on the ball: a malicious server
604 * could send you back _any_ host:port pair, so if you trustingly
605 * connect to the address it gives you then you've just opened the
606 * entire inside of your corporate network just by connecting
607 * through it to a dodgy SSH server. Hence, we must store a list of
608 * host:port pairs we _are_ trying to forward to, and reject a
609 * connection request from the server if it's not in the list.
611 * In SSH-2, each side of the connection minds its own business and
612 * doesn't send unnecessary information to the other. You arrange a
613 * remote forwarding by sending the server just the remote port
614 * number. When a connection comes in, the server tells you which
615 * of its ports was connected to; and _you_ have to remember what
616 * local host:port pair went with that port number.
618 * Hence, in SSH-1 this structure is indexed by destination
619 * host:port pair, whereas in SSH-2 it is indexed by source port.
621 struct ssh_portfwd; /* forward declaration */
623 struct ssh_rportfwd {
624 unsigned sport, dport;
628 struct ssh_portfwd *pfrec;
631 static void free_rportfwd(struct ssh_rportfwd *pf)
634 sfree(pf->sportdesc);
642 * Separately to the rportfwd tree (which is for looking up port
643 * open requests from the server), a tree of _these_ structures is
644 * used to keep track of all the currently open port forwardings,
645 * so that we can reconfigure in mid-session if the user requests
649 enum { DESTROY, KEEP, CREATE } status;
651 unsigned sport, dport;
654 struct ssh_rportfwd *remote;
656 struct PortListener *local;
658 #define free_portfwd(pf) ( \
659 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
660 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
663 long length; /* length of packet: see below */
664 long forcepad; /* SSH-2: force padding to at least this length */
665 int type; /* only used for incoming packets */
666 unsigned long sequence; /* SSH-2 incoming sequence number */
667 unsigned char *data; /* allocated storage */
668 unsigned char *body; /* offset of payload within `data' */
669 long savedpos; /* dual-purpose saved packet position: see below */
670 long maxlen; /* amount of storage allocated for `data' */
671 long encrypted_len; /* for SSH-2 total-size counting */
674 * A note on the 'length' and 'savedpos' fields above.
676 * Incoming packets are set up so that pkt->length is measured
677 * relative to pkt->body, which itself points to a few bytes after
678 * pkt->data (skipping some uninteresting header fields including
679 * the packet type code). The ssh_pkt_get* functions all expect
680 * this setup, and they also use pkt->savedpos to indicate how far
681 * through the packet being decoded they've got - and that, too,
682 * is an offset from pkt->body rather than pkt->data.
684 * During construction of an outgoing packet, however, pkt->length
685 * is measured relative to the base pointer pkt->data, and
686 * pkt->body is not really used for anything until the packet is
687 * ready for sending. In this mode, pkt->savedpos is reused as a
688 * temporary variable by the addstring functions, which write out
689 * a string length field and then keep going back and updating it
690 * as more data is appended to the subsequent string data field;
691 * pkt->savedpos stores the offset (again relative to pkt->data)
692 * of the start of the string data field.
695 /* Extra metadata used in SSH packet logging mode, allowing us to
696 * log in the packet header line that the packet came from a
697 * connection-sharing downstream and what if anything unusual was
698 * done to it. The additional_log_text field is expected to be a
699 * static string - it will not be freed. */
700 unsigned downstream_id;
701 const char *additional_log_text;
704 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
705 struct Packet *pktin);
706 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
707 struct Packet *pktin);
708 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
709 struct Packet *pktin);
710 static void ssh1_protocol_setup(Ssh ssh);
711 static void ssh2_protocol_setup(Ssh ssh);
712 static void ssh2_bare_connection_protocol_setup(Ssh ssh);
713 static void ssh_size(void *handle, int width, int height);
714 static void ssh_special(void *handle, Telnet_Special);
715 static int ssh2_try_send(struct ssh_channel *c);
716 static int ssh_send_channel_data(struct ssh_channel *c,
717 const char *buf, int len);
718 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
719 static void ssh2_set_window(struct ssh_channel *c, int newwin);
720 static int ssh_sendbuffer(void *handle);
721 static int ssh_do_close(Ssh ssh, int notify_exit);
722 static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
723 static int ssh2_pkt_getbool(struct Packet *pkt);
724 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
725 static void ssh2_timer(void *ctx, unsigned long now);
726 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
727 struct Packet *pktin);
728 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
730 struct rdpkt1_state_tag {
731 long len, pad, biglen, to_read;
732 unsigned long realcrc, gotcrc;
736 struct Packet *pktin;
739 struct rdpkt2_state_tag {
740 long len, pad, payload, packetlen, maclen;
743 unsigned long incoming_sequence;
744 struct Packet *pktin;
747 struct rdpkt2_bare_state_tag {
751 unsigned long incoming_sequence;
752 struct Packet *pktin;
755 struct queued_handler;
756 struct queued_handler {
758 chandler_fn_t handler;
760 struct queued_handler *next;
764 const struct plug_function_table *fn;
765 /* the above field _must_ be first in the structure */
775 unsigned char session_key[32];
777 int v1_remote_protoflags;
778 int v1_local_protoflags;
779 int agentfwd_enabled;
782 const struct ssh_cipher *cipher;
785 const struct ssh2_cipher *cscipher, *sccipher;
786 void *cs_cipher_ctx, *sc_cipher_ctx;
787 const struct ssh_mac *csmac, *scmac;
788 int csmac_etm, scmac_etm;
789 void *cs_mac_ctx, *sc_mac_ctx;
790 const struct ssh_compress *cscomp, *sccomp;
791 void *cs_comp_ctx, *sc_comp_ctx;
792 const struct ssh_kex *kex;
793 const struct ssh_signkey *hostkey;
794 char *hostkey_str; /* string representation, for easy checking in rekeys */
795 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
796 int v2_session_id_len;
800 int attempting_connshare;
806 int echoing, editing;
811 int ospeed, ispeed; /* temporaries */
812 int term_width, term_height;
814 tree234 *channels; /* indexed by local id */
815 struct ssh_channel *mainchan; /* primary session channel */
816 int ncmode; /* is primary channel direct-tcpip? */
821 tree234 *rportfwds, *portfwds;
825 SSH_STATE_BEFORE_SIZE,
831 int size_needed, eof_needed;
832 int sent_console_eof;
833 int got_pty; /* affects EOF behaviour on main channel */
835 struct Packet **queue;
836 int queuelen, queuesize;
838 unsigned char *deferred_send_data;
839 int deferred_len, deferred_size;
842 * Gross hack: pscp will try to start SFTP but fall back to
843 * scp1 if that fails. This variable is the means by which
844 * scp.c can reach into the SSH code and find out which one it
849 bufchain banner; /* accumulates banners during do_ssh2_authconn */
854 struct X11Display *x11disp;
855 struct X11FakeAuth *x11auth;
856 tree234 *x11authtree;
859 int conn_throttle_count;
862 int v1_stdout_throttling;
863 unsigned long v2_outgoing_sequence;
865 int ssh1_rdpkt_crstate;
866 int ssh2_rdpkt_crstate;
867 int ssh2_bare_rdpkt_crstate;
868 int ssh_gotdata_crstate;
869 int do_ssh1_connection_crstate;
871 void *do_ssh_init_state;
872 void *do_ssh1_login_state;
873 void *do_ssh2_transport_state;
874 void *do_ssh2_authconn_state;
875 void *do_ssh_connection_init_state;
877 struct rdpkt1_state_tag rdpkt1_state;
878 struct rdpkt2_state_tag rdpkt2_state;
879 struct rdpkt2_bare_state_tag rdpkt2_bare_state;
881 /* SSH-1 and SSH-2 use this for different things, but both use it */
882 int protocol_initial_phase_done;
884 void (*protocol) (Ssh ssh, const void *vin, int inlen,
886 struct Packet *(*s_rdpkt) (Ssh ssh, const unsigned char **data,
888 int (*do_ssh_init)(Ssh ssh, unsigned char c);
891 * We maintain our own copy of a Conf structure here. That way,
892 * when we're passed a new one for reconfiguration, we can check
893 * the differences and potentially reconfigure port forwardings
894 * etc in mid-session.
899 * Values cached out of conf so as to avoid the tree234 lookup
900 * cost every time they're used.
905 * Dynamically allocated username string created during SSH
906 * login. Stored in here rather than in the coroutine state so
907 * that it'll be reliably freed if we shut down the SSH session
908 * at some unexpected moment.
913 * Used to transfer data back from async callbacks.
915 void *agent_response;
916 int agent_response_len;
920 * The SSH connection can be set as `frozen', meaning we are
921 * not currently accepting incoming data from the network. This
922 * is slightly more serious than setting the _socket_ as
923 * frozen, because we may already have had data passed to us
924 * from the network which we need to delay processing until
925 * after the freeze is lifted, so we also need a bufchain to
929 bufchain queued_incoming_data;
932 * Dispatch table for packet types that we may have to deal
935 handler_fn_t packet_dispatch[256];
938 * Queues of one-off handler functions for success/failure
939 * indications from a request.
941 struct queued_handler *qhead, *qtail;
942 handler_fn_t q_saved_handler1, q_saved_handler2;
945 * This module deals with sending keepalives.
950 * Track incoming and outgoing data sizes and time, for
953 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
954 unsigned long max_data_size;
956 unsigned long next_rekey, last_rekey;
957 const char *deferred_rekey_reason;
960 * Fully qualified host name, which we need if doing GSSAPI.
966 * GSSAPI libraries for this session.
968 struct ssh_gss_liblist *gsslibs;
972 * The last list returned from get_specials.
974 struct telnet_special *specials;
977 * List of host key algorithms for which we _don't_ have a stored
978 * host key. These are indices into the main hostkey_algs[] array
980 int uncert_hostkeys[lenof(hostkey_algs)];
981 int n_uncert_hostkeys;
984 * Flag indicating that the current rekey is intended to finish
985 * with a newly cross-certified host key.
987 int cross_certifying;
990 static const char *ssh_pkt_type(Ssh ssh, int type)
992 if (ssh->version == 1)
993 return ssh1_pkt_type(type);
995 return ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, type);
998 #define logevent(s) logevent(ssh->frontend, s)
1000 /* logevent, only printf-formatted. */
1001 static void logeventf(Ssh ssh, const char *fmt, ...)
1007 buf = dupvprintf(fmt, ap);
1013 static void bomb_out(Ssh ssh, char *text)
1015 ssh_do_close(ssh, FALSE);
1017 connection_fatal(ssh->frontend, "%s", text);
1021 #define bombout(msg) bomb_out(ssh, dupprintf msg)
1023 /* Helper function for common bits of parsing ttymodes. */
1024 static void parse_ttymodes(Ssh ssh,
1025 void (*do_mode)(void *data,
1026 const struct ssh_ttymode *mode,
1031 const struct ssh_ttymode *mode;
1033 char default_val[2];
1035 strcpy(default_val, "A");
1037 for (i = 0; i < lenof(ssh_ttymodes); i++) {
1038 mode = ssh_ttymodes + i;
1039 val = conf_get_str_str_opt(ssh->conf, CONF_ttymodes, mode->mode);
1044 * val[0] is either 'V', indicating that an explicit value
1045 * follows it, or 'A' indicating that we should pass the
1046 * value through from the local environment via get_ttymode.
1048 if (val[0] == 'A') {
1049 val = get_ttymode(ssh->frontend, mode->mode);
1051 do_mode(data, mode, val);
1055 do_mode(data, mode, val + 1); /* skip the 'V' */
1059 static int ssh_channelcmp(void *av, void *bv)
1061 struct ssh_channel *a = (struct ssh_channel *) av;
1062 struct ssh_channel *b = (struct ssh_channel *) bv;
1063 if (a->localid < b->localid)
1065 if (a->localid > b->localid)
1069 static int ssh_channelfind(void *av, void *bv)
1071 unsigned *a = (unsigned *) av;
1072 struct ssh_channel *b = (struct ssh_channel *) bv;
1073 if (*a < b->localid)
1075 if (*a > b->localid)
1080 static int ssh_rportcmp_ssh1(void *av, void *bv)
1082 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1083 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1085 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
1086 return i < 0 ? -1 : +1;
1087 if (a->dport > b->dport)
1089 if (a->dport < b->dport)
1094 static int ssh_rportcmp_ssh2(void *av, void *bv)
1096 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1097 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1099 if ( (i = strcmp(a->shost, b->shost)) != 0)
1100 return i < 0 ? -1 : +1;
1101 if (a->sport > b->sport)
1103 if (a->sport < b->sport)
1109 * Special form of strcmp which can cope with NULL inputs. NULL is
1110 * defined to sort before even the empty string.
1112 static int nullstrcmp(const char *a, const char *b)
1114 if (a == NULL && b == NULL)
1120 return strcmp(a, b);
1123 static int ssh_portcmp(void *av, void *bv)
1125 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1126 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1128 if (a->type > b->type)
1130 if (a->type < b->type)
1132 if (a->addressfamily > b->addressfamily)
1134 if (a->addressfamily < b->addressfamily)
1136 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1137 return i < 0 ? -1 : +1;
1138 if (a->sport > b->sport)
1140 if (a->sport < b->sport)
1142 if (a->type != 'D') {
1143 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1144 return i < 0 ? -1 : +1;
1145 if (a->dport > b->dport)
1147 if (a->dport < b->dport)
1153 static int alloc_channel_id(Ssh ssh)
1155 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1156 unsigned low, high, mid;
1158 struct ssh_channel *c;
1161 * First-fit allocation of channel numbers: always pick the
1162 * lowest unused one. To do this, binary-search using the
1163 * counted B-tree to find the largest channel ID which is in a
1164 * contiguous sequence from the beginning. (Precisely
1165 * everything in that sequence must have ID equal to its tree
1166 * index plus CHANNEL_NUMBER_OFFSET.)
1168 tsize = count234(ssh->channels);
1172 while (high - low > 1) {
1173 mid = (high + low) / 2;
1174 c = index234(ssh->channels, mid);
1175 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1176 low = mid; /* this one is fine */
1178 high = mid; /* this one is past it */
1181 * Now low points to either -1, or the tree index of the
1182 * largest ID in the initial sequence.
1185 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
1186 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
1188 return low + 1 + CHANNEL_NUMBER_OFFSET;
1191 static void c_write_stderr(int trusted, const char *buf, int len)
1194 for (i = 0; i < len; i++)
1195 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
1196 fputc(buf[i], stderr);
1199 static void c_write(Ssh ssh, const char *buf, int len)
1201 if (flags & FLAG_STDERR)
1202 c_write_stderr(1, buf, len);
1204 from_backend(ssh->frontend, 1, buf, len);
1207 static void c_write_untrusted(Ssh ssh, const char *buf, int len)
1209 if (flags & FLAG_STDERR)
1210 c_write_stderr(0, buf, len);
1212 from_backend_untrusted(ssh->frontend, buf, len);
1215 static void c_write_str(Ssh ssh, const char *buf)
1217 c_write(ssh, buf, strlen(buf));
1220 static void ssh_free_packet(struct Packet *pkt)
1225 static struct Packet *ssh_new_packet(void)
1227 struct Packet *pkt = snew(struct Packet);
1229 pkt->body = pkt->data = NULL;
1235 static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1238 struct logblank_t blanks[4];
1244 if (ssh->logomitdata &&
1245 (pkt->type == SSH1_SMSG_STDOUT_DATA ||
1246 pkt->type == SSH1_SMSG_STDERR_DATA ||
1247 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1248 /* "Session data" packets - omit the data string. */
1249 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1250 ssh_pkt_getuint32(pkt); /* skip channel id */
1251 blanks[nblanks].offset = pkt->savedpos + 4;
1252 blanks[nblanks].type = PKTLOG_OMIT;
1253 ssh_pkt_getstring(pkt, &str, &slen);
1255 blanks[nblanks].len = slen;
1259 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1260 ssh1_pkt_type(pkt->type),
1261 pkt->body, pkt->length, nblanks, blanks, NULL,
1265 static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1268 struct logblank_t blanks[4];
1273 * For outgoing packets, pkt->length represents the length of the
1274 * whole packet starting at pkt->data (including some header), and
1275 * pkt->body refers to the point within that where the log-worthy
1276 * payload begins. However, incoming packets expect pkt->length to
1277 * represent only the payload length (that is, it's measured from
1278 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1279 * packet to conform to the incoming-packet semantics, so that we
1280 * can analyse it with the ssh_pkt_get functions.
1282 pkt->length -= (pkt->body - pkt->data);
1285 if (ssh->logomitdata &&
1286 (pkt->type == SSH1_CMSG_STDIN_DATA ||
1287 pkt->type == SSH1_MSG_CHANNEL_DATA)) {
1288 /* "Session data" packets - omit the data string. */
1289 if (pkt->type == SSH1_MSG_CHANNEL_DATA)
1290 ssh_pkt_getuint32(pkt); /* skip channel id */
1291 blanks[nblanks].offset = pkt->savedpos + 4;
1292 blanks[nblanks].type = PKTLOG_OMIT;
1293 ssh_pkt_getstring(pkt, &str, &slen);
1295 blanks[nblanks].len = slen;
1300 if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
1301 pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
1302 pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
1303 conf_get_int(ssh->conf, CONF_logomitpass)) {
1304 /* If this is a password or similar packet, blank the password(s). */
1305 blanks[nblanks].offset = 0;
1306 blanks[nblanks].len = pkt->length;
1307 blanks[nblanks].type = PKTLOG_BLANK;
1309 } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
1310 conf_get_int(ssh->conf, CONF_logomitpass)) {
1312 * If this is an X forwarding request packet, blank the fake
1315 * Note that while we blank the X authentication data here, we
1316 * don't take any special action to blank the start of an X11
1317 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1318 * an X connection without having session blanking enabled is
1319 * likely to leak your cookie into the log.
1322 ssh_pkt_getstring(pkt, &str, &slen);
1323 blanks[nblanks].offset = pkt->savedpos;
1324 blanks[nblanks].type = PKTLOG_BLANK;
1325 ssh_pkt_getstring(pkt, &str, &slen);
1327 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1332 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1333 ssh1_pkt_type(pkt->data[12]),
1334 pkt->body, pkt->length,
1335 nblanks, blanks, NULL, 0, NULL);
1338 * Undo the above adjustment of pkt->length, to put the packet
1339 * back in the state we found it.
1341 pkt->length += (pkt->body - pkt->data);
1345 * Collect incoming data in the incoming packet buffer.
1346 * Decipher and verify the packet when it is completely read.
1347 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
1348 * Update the *data and *datalen variables.
1349 * Return a Packet structure when a packet is completed.
1351 static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
1354 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
1356 crBegin(ssh->ssh1_rdpkt_crstate);
1358 st->pktin = ssh_new_packet();
1360 st->pktin->type = 0;
1361 st->pktin->length = 0;
1363 for (st->i = st->len = 0; st->i < 4; st->i++) {
1364 while ((*datalen) == 0)
1366 st->len = (st->len << 8) + **data;
1367 (*data)++, (*datalen)--;
1370 st->pad = 8 - (st->len % 8);
1371 st->biglen = st->len + st->pad;
1372 st->pktin->length = st->len - 5;
1374 if (st->biglen < 0) {
1375 bombout(("Extremely large packet length from server suggests"
1376 " data stream corruption"));
1377 ssh_free_packet(st->pktin);
1381 st->pktin->maxlen = st->biglen;
1382 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
1384 st->to_read = st->biglen;
1385 st->p = st->pktin->data;
1386 while (st->to_read > 0) {
1387 st->chunk = st->to_read;
1388 while ((*datalen) == 0)
1390 if (st->chunk > (*datalen))
1391 st->chunk = (*datalen);
1392 memcpy(st->p, *data, st->chunk);
1394 *datalen -= st->chunk;
1396 st->to_read -= st->chunk;
1399 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
1400 st->biglen, NULL)) {
1401 bombout(("Network attack (CRC compensation) detected!"));
1402 ssh_free_packet(st->pktin);
1407 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
1409 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1410 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
1411 if (st->gotcrc != st->realcrc) {
1412 bombout(("Incorrect CRC received on packet"));
1413 ssh_free_packet(st->pktin);
1417 st->pktin->body = st->pktin->data + st->pad + 1;
1419 if (ssh->v1_compressing) {
1420 unsigned char *decompblk;
1422 if (!zlib_decompress_block(ssh->sc_comp_ctx,
1423 st->pktin->body - 1, st->pktin->length + 1,
1424 &decompblk, &decomplen)) {
1425 bombout(("Zlib decompression encountered invalid data"));
1426 ssh_free_packet(st->pktin);
1430 if (st->pktin->maxlen < st->pad + decomplen) {
1431 st->pktin->maxlen = st->pad + decomplen;
1432 st->pktin->data = sresize(st->pktin->data,
1433 st->pktin->maxlen + APIEXTRA,
1435 st->pktin->body = st->pktin->data + st->pad + 1;
1438 memcpy(st->pktin->body - 1, decompblk, decomplen);
1440 st->pktin->length = decomplen - 1;
1443 st->pktin->type = st->pktin->body[-1];
1446 * Now pktin->body and pktin->length identify the semantic content
1447 * of the packet, excluding the initial type byte.
1451 ssh1_log_incoming_packet(ssh, st->pktin);
1453 st->pktin->savedpos = 0;
1455 crFinish(st->pktin);
1458 static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
1461 struct logblank_t blanks[4];
1467 if (ssh->logomitdata &&
1468 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1469 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1470 /* "Session data" packets - omit the data string. */
1471 ssh_pkt_getuint32(pkt); /* skip channel id */
1472 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1473 ssh_pkt_getuint32(pkt); /* skip extended data type */
1474 blanks[nblanks].offset = pkt->savedpos + 4;
1475 blanks[nblanks].type = PKTLOG_OMIT;
1476 ssh_pkt_getstring(pkt, &str, &slen);
1478 blanks[nblanks].len = slen;
1483 log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
1484 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
1485 pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
1489 static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
1492 struct logblank_t blanks[4];
1497 * For outgoing packets, pkt->length represents the length of the
1498 * whole packet starting at pkt->data (including some header), and
1499 * pkt->body refers to the point within that where the log-worthy
1500 * payload begins. However, incoming packets expect pkt->length to
1501 * represent only the payload length (that is, it's measured from
1502 * pkt->body not from pkt->data). Temporarily adjust our outgoing
1503 * packet to conform to the incoming-packet semantics, so that we
1504 * can analyse it with the ssh_pkt_get functions.
1506 pkt->length -= (pkt->body - pkt->data);
1509 if (ssh->logomitdata &&
1510 (pkt->type == SSH2_MSG_CHANNEL_DATA ||
1511 pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
1512 /* "Session data" packets - omit the data string. */
1513 ssh_pkt_getuint32(pkt); /* skip channel id */
1514 if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
1515 ssh_pkt_getuint32(pkt); /* skip extended data type */
1516 blanks[nblanks].offset = pkt->savedpos + 4;
1517 blanks[nblanks].type = PKTLOG_OMIT;
1518 ssh_pkt_getstring(pkt, &str, &slen);
1520 blanks[nblanks].len = slen;
1525 if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
1526 conf_get_int(ssh->conf, CONF_logomitpass)) {
1527 /* If this is a password packet, blank the password(s). */
1529 ssh_pkt_getstring(pkt, &str, &slen);
1530 ssh_pkt_getstring(pkt, &str, &slen);
1531 ssh_pkt_getstring(pkt, &str, &slen);
1532 if (slen == 8 && !memcmp(str, "password", 8)) {
1533 ssh2_pkt_getbool(pkt);
1534 /* Blank the password field. */
1535 blanks[nblanks].offset = pkt->savedpos;
1536 blanks[nblanks].type = PKTLOG_BLANK;
1537 ssh_pkt_getstring(pkt, &str, &slen);
1539 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1541 /* If there's another password field beyond it (change of
1542 * password), blank that too. */
1543 ssh_pkt_getstring(pkt, &str, &slen);
1545 blanks[nblanks-1].len =
1546 pkt->savedpos - blanks[nblanks].offset;
1549 } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
1550 pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
1551 conf_get_int(ssh->conf, CONF_logomitpass)) {
1552 /* If this is a keyboard-interactive response packet, blank
1555 ssh_pkt_getuint32(pkt);
1556 blanks[nblanks].offset = pkt->savedpos;
1557 blanks[nblanks].type = PKTLOG_BLANK;
1559 ssh_pkt_getstring(pkt, &str, &slen);
1563 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1565 } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
1566 conf_get_int(ssh->conf, CONF_logomitpass)) {
1568 * If this is an X forwarding request packet, blank the fake
1571 * Note that while we blank the X authentication data here, we
1572 * don't take any special action to blank the start of an X11
1573 * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
1574 * an X connection without having session blanking enabled is
1575 * likely to leak your cookie into the log.
1578 ssh_pkt_getuint32(pkt);
1579 ssh_pkt_getstring(pkt, &str, &slen);
1580 if (slen == 7 && !memcmp(str, "x11-req", 0)) {
1581 ssh2_pkt_getbool(pkt);
1582 ssh2_pkt_getbool(pkt);
1583 ssh_pkt_getstring(pkt, &str, &slen);
1584 blanks[nblanks].offset = pkt->savedpos;
1585 blanks[nblanks].type = PKTLOG_BLANK;
1586 ssh_pkt_getstring(pkt, &str, &slen);
1588 blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
1594 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
1595 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
1596 pkt->body, pkt->length, nblanks, blanks,
1597 &ssh->v2_outgoing_sequence,
1598 pkt->downstream_id, pkt->additional_log_text);
1601 * Undo the above adjustment of pkt->length, to put the packet
1602 * back in the state we found it.
1604 pkt->length += (pkt->body - pkt->data);
1607 static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
1610 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
1612 crBegin(ssh->ssh2_rdpkt_crstate);
1614 st->pktin = ssh_new_packet();
1616 st->pktin->type = 0;
1617 st->pktin->length = 0;
1619 st->cipherblk = ssh->sccipher->blksize;
1622 if (st->cipherblk < 8)
1624 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
1626 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1627 ssh->scmac && !ssh->scmac_etm) {
1629 * When dealing with a CBC-mode cipher, we want to avoid the
1630 * possibility of an attacker's tweaking the ciphertext stream
1631 * so as to cause us to feed the same block to the block
1632 * cipher more than once and thus leak information
1633 * (VU#958563). The way we do this is not to take any
1634 * decisions on the basis of anything we've decrypted until
1635 * we've verified it with a MAC. That includes the packet
1636 * length, so we just read data and check the MAC repeatedly,
1637 * and when the MAC passes, see if the length we've got is
1640 * This defence is unnecessary in OpenSSH ETM mode, because
1641 * the whole point of ETM mode is that the attacker can't
1642 * tweak the ciphertext stream at all without the MAC
1643 * detecting it before we decrypt anything.
1646 /* May as well allocate the whole lot now. */
1647 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1650 /* Read an amount corresponding to the MAC. */
1651 for (st->i = 0; st->i < st->maclen; st->i++) {
1652 while ((*datalen) == 0)
1654 st->pktin->data[st->i] = *(*data)++;
1660 unsigned char seq[4];
1661 ssh->scmac->start(ssh->sc_mac_ctx);
1662 PUT_32BIT(seq, st->incoming_sequence);
1663 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1666 for (;;) { /* Once around this loop per cipher block. */
1667 /* Read another cipher-block's worth, and tack it onto the end. */
1668 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1669 while ((*datalen) == 0)
1671 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1674 /* Decrypt one more block (a little further back in the stream). */
1675 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1676 st->pktin->data + st->packetlen,
1678 /* Feed that block to the MAC. */
1679 ssh->scmac->bytes(ssh->sc_mac_ctx,
1680 st->pktin->data + st->packetlen, st->cipherblk);
1681 st->packetlen += st->cipherblk;
1682 /* See if that gives us a valid packet. */
1683 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1684 st->pktin->data + st->packetlen) &&
1685 ((st->len = toint(GET_32BIT(st->pktin->data))) ==
1688 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1689 bombout(("No valid incoming packet found"));
1690 ssh_free_packet(st->pktin);
1694 st->pktin->maxlen = st->packetlen + st->maclen;
1695 st->pktin->data = sresize(st->pktin->data,
1696 st->pktin->maxlen + APIEXTRA,
1698 } else if (ssh->scmac && ssh->scmac_etm) {
1699 st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
1702 * OpenSSH encrypt-then-MAC mode: the packet length is
1703 * unencrypted, unless the cipher supports length encryption.
1705 for (st->i = st->len = 0; st->i < 4; st->i++) {
1706 while ((*datalen) == 0)
1708 st->pktin->data[st->i] = *(*data)++;
1711 /* Cipher supports length decryption, so do it */
1712 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
1713 /* Keep the packet the same though, so the MAC passes */
1714 unsigned char len[4];
1715 memcpy(len, st->pktin->data, 4);
1716 ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
1717 st->len = toint(GET_32BIT(len));
1719 st->len = toint(GET_32BIT(st->pktin->data));
1723 * _Completely_ silly lengths should be stomped on before they
1724 * do us any more damage.
1726 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1727 st->len % st->cipherblk != 0) {
1728 bombout(("Incoming packet length field was garbled"));
1729 ssh_free_packet(st->pktin);
1734 * So now we can work out the total packet length.
1736 st->packetlen = st->len + 4;
1739 * Allocate memory for the rest of the packet.
1741 st->pktin->maxlen = st->packetlen + st->maclen;
1742 st->pktin->data = sresize(st->pktin->data,
1743 st->pktin->maxlen + APIEXTRA,
1747 * Read the remainder of the packet.
1749 for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
1750 while ((*datalen) == 0)
1752 st->pktin->data[st->i] = *(*data)++;
1760 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1761 st->len + 4, st->incoming_sequence)) {
1762 bombout(("Incorrect MAC received on packet"));
1763 ssh_free_packet(st->pktin);
1767 /* Decrypt everything between the length field and the MAC. */
1769 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1770 st->pktin->data + 4,
1773 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1776 * Acquire and decrypt the first block of the packet. This will
1777 * contain the length and padding details.
1779 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1780 while ((*datalen) == 0)
1782 st->pktin->data[st->i] = *(*data)++;
1787 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1788 st->pktin->data, st->cipherblk);
1791 * Now get the length figure.
1793 st->len = toint(GET_32BIT(st->pktin->data));
1796 * _Completely_ silly lengths should be stomped on before they
1797 * do us any more damage.
1799 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1800 (st->len + 4) % st->cipherblk != 0) {
1801 bombout(("Incoming packet was garbled on decryption"));
1802 ssh_free_packet(st->pktin);
1807 * So now we can work out the total packet length.
1809 st->packetlen = st->len + 4;
1812 * Allocate memory for the rest of the packet.
1814 st->pktin->maxlen = st->packetlen + st->maclen;
1815 st->pktin->data = sresize(st->pktin->data,
1816 st->pktin->maxlen + APIEXTRA,
1820 * Read and decrypt the remainder of the packet.
1822 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1824 while ((*datalen) == 0)
1826 st->pktin->data[st->i] = *(*data)++;
1829 /* Decrypt everything _except_ the MAC. */
1831 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1832 st->pktin->data + st->cipherblk,
1833 st->packetlen - st->cipherblk);
1839 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1840 st->len + 4, st->incoming_sequence)) {
1841 bombout(("Incorrect MAC received on packet"));
1842 ssh_free_packet(st->pktin);
1846 /* Get and sanity-check the amount of random padding. */
1847 st->pad = st->pktin->data[4];
1848 if (st->pad < 4 || st->len - st->pad < 1) {
1849 bombout(("Invalid padding length on received packet"));
1850 ssh_free_packet(st->pktin);
1854 * This enables us to deduce the payload length.
1856 st->payload = st->len - st->pad - 1;
1858 st->pktin->length = st->payload + 5;
1859 st->pktin->encrypted_len = st->packetlen;
1861 st->pktin->sequence = st->incoming_sequence++;
1863 st->pktin->length = st->packetlen - st->pad;
1864 assert(st->pktin->length >= 0);
1867 * Decompress packet payload.
1870 unsigned char *newpayload;
1873 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1874 st->pktin->data + 5, st->pktin->length - 5,
1875 &newpayload, &newlen)) {
1876 if (st->pktin->maxlen < newlen + 5) {
1877 st->pktin->maxlen = newlen + 5;
1878 st->pktin->data = sresize(st->pktin->data,
1879 st->pktin->maxlen + APIEXTRA,
1882 st->pktin->length = 5 + newlen;
1883 memcpy(st->pktin->data + 5, newpayload, newlen);
1889 * RFC 4253 doesn't explicitly say that completely empty packets
1890 * with no type byte are forbidden, so treat them as deserving
1891 * an SSH_MSG_UNIMPLEMENTED.
1893 if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */
1894 ssh2_msg_something_unimplemented(ssh, st->pktin);
1898 * pktin->body and pktin->length should identify the semantic
1899 * content of the packet, excluding the initial type byte.
1901 st->pktin->type = st->pktin->data[5];
1902 st->pktin->body = st->pktin->data + 6;
1903 st->pktin->length -= 6;
1904 assert(st->pktin->length >= 0); /* one last double-check */
1907 ssh2_log_incoming_packet(ssh, st->pktin);
1909 st->pktin->savedpos = 0;
1911 crFinish(st->pktin);
1914 static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
1915 const unsigned char **data,
1918 struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
1920 crBegin(ssh->ssh2_bare_rdpkt_crstate);
1923 * Read the packet length field.
1925 for (st->i = 0; st->i < 4; st->i++) {
1926 while ((*datalen) == 0)
1928 st->length[st->i] = *(*data)++;
1932 st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
1933 if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
1934 bombout(("Invalid packet length received"));
1938 st->pktin = ssh_new_packet();
1939 st->pktin->data = snewn(st->packetlen, unsigned char);
1941 st->pktin->encrypted_len = st->packetlen;
1943 st->pktin->sequence = st->incoming_sequence++;
1946 * Read the remainder of the packet.
1948 for (st->i = 0; st->i < st->packetlen; st->i++) {
1949 while ((*datalen) == 0)
1951 st->pktin->data[st->i] = *(*data)++;
1956 * pktin->body and pktin->length should identify the semantic
1957 * content of the packet, excluding the initial type byte.
1959 st->pktin->type = st->pktin->data[0];
1960 st->pktin->body = st->pktin->data + 1;
1961 st->pktin->length = st->packetlen - 1;
1964 * Log incoming packet, possibly omitting sensitive fields.
1967 ssh2_log_incoming_packet(ssh, st->pktin);
1969 st->pktin->savedpos = 0;
1971 crFinish(st->pktin);
1974 static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
1976 int pad, biglen, i, pktoffs;
1980 * XXX various versions of SC (including 8.8.4) screw up the
1981 * register allocation in this function and use the same register
1982 * (D6) for len and as a temporary, with predictable results. The
1983 * following sledgehammer prevents this.
1990 ssh1_log_outgoing_packet(ssh, pkt);
1992 if (ssh->v1_compressing) {
1993 unsigned char *compblk;
1995 zlib_compress_block(ssh->cs_comp_ctx,
1996 pkt->data + 12, pkt->length - 12,
1997 &compblk, &complen);
1998 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
1999 memcpy(pkt->data + 12, compblk, complen);
2001 pkt->length = complen + 12;
2004 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
2006 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
2007 pad = 8 - (len % 8);
2009 biglen = len + pad; /* len(padding+type+data+CRC) */
2011 for (i = pktoffs; i < 4+8; i++)
2012 pkt->data[i] = random_byte();
2013 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
2014 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
2015 PUT_32BIT(pkt->data + pktoffs, len);
2018 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
2019 pkt->data + pktoffs + 4, biglen);
2021 if (offset_p) *offset_p = pktoffs;
2022 return biglen + 4; /* len(length+padding+type+data+CRC) */
2025 static int s_write(Ssh ssh, void *data, int len)
2028 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
2029 0, NULL, NULL, 0, NULL);
2032 return sk_write(ssh->s, (char *)data, len);
2035 static void s_wrpkt(Ssh ssh, struct Packet *pkt)
2037 int len, backlog, offset;
2038 len = s_wrpkt_prepare(ssh, pkt, &offset);
2039 backlog = s_write(ssh, pkt->data + offset, len);
2040 if (backlog > SSH_MAX_BACKLOG)
2041 ssh_throttle_all(ssh, 1, backlog);
2042 ssh_free_packet(pkt);
2045 static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
2048 len = s_wrpkt_prepare(ssh, pkt, &offset);
2049 if (ssh->deferred_len + len > ssh->deferred_size) {
2050 ssh->deferred_size = ssh->deferred_len + len + 128;
2051 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2055 memcpy(ssh->deferred_send_data + ssh->deferred_len,
2056 pkt->data + offset, len);
2057 ssh->deferred_len += len;
2058 ssh_free_packet(pkt);
2062 * Construct a SSH-1 packet with the specified contents.
2063 * (This all-at-once interface used to be the only one, but now SSH-1
2064 * packets can also be constructed incrementally.)
2066 static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
2072 pkt = ssh1_pkt_init(pkttype);
2074 while ((argtype = va_arg(ap, int)) != PKT_END) {
2075 unsigned char *argp, argchar;
2077 unsigned long argint;
2080 /* Actual fields in the packet */
2082 argint = va_arg(ap, int);
2083 ssh_pkt_adduint32(pkt, argint);
2086 argchar = (unsigned char) va_arg(ap, int);
2087 ssh_pkt_addbyte(pkt, argchar);
2090 argp = va_arg(ap, unsigned char *);
2091 arglen = va_arg(ap, int);
2092 ssh_pkt_adddata(pkt, argp, arglen);
2095 sargp = va_arg(ap, char *);
2096 ssh_pkt_addstring(pkt, sargp);
2099 bn = va_arg(ap, Bignum);
2100 ssh1_pkt_addmp(pkt, bn);
2108 static void send_packet(Ssh ssh, int pkttype, ...)
2112 va_start(ap, pkttype);
2113 pkt = construct_packet(ssh, pkttype, ap);
2118 static void defer_packet(Ssh ssh, int pkttype, ...)
2122 va_start(ap, pkttype);
2123 pkt = construct_packet(ssh, pkttype, ap);
2125 s_wrpkt_defer(ssh, pkt);
2128 static int ssh_versioncmp(const char *a, const char *b)
2131 unsigned long av, bv;
2133 av = strtoul(a, &ae, 10);
2134 bv = strtoul(b, &be, 10);
2136 return (av < bv ? -1 : +1);
2141 av = strtoul(ae, &ae, 10);
2142 bv = strtoul(be, &be, 10);
2144 return (av < bv ? -1 : +1);
2149 * Utility routines for putting an SSH-protocol `string' and
2150 * `uint32' into a hash state.
2152 static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
2154 unsigned char lenblk[4];
2155 PUT_32BIT(lenblk, len);
2156 h->bytes(s, lenblk, 4);
2157 h->bytes(s, str, len);
2160 static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
2162 unsigned char intblk[4];
2163 PUT_32BIT(intblk, i);
2164 h->bytes(s, intblk, 4);
2168 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
2170 static void ssh_pkt_ensure(struct Packet *pkt, int length)
2172 if (pkt->maxlen < length) {
2173 unsigned char *body = pkt->body;
2174 int offset = body ? body - pkt->data : 0;
2175 pkt->maxlen = length + 256;
2176 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
2177 if (body) pkt->body = pkt->data + offset;
2180 static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
2183 ssh_pkt_ensure(pkt, pkt->length);
2184 memcpy(pkt->data + pkt->length - len, data, len);
2186 static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
2188 ssh_pkt_adddata(pkt, &byte, 1);
2190 static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
2192 ssh_pkt_adddata(pkt, &value, 1);
2194 static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
2197 PUT_32BIT(x, value);
2198 ssh_pkt_adddata(pkt, x, 4);
2200 static void ssh_pkt_addstring_start(struct Packet *pkt)
2202 ssh_pkt_adduint32(pkt, 0);
2203 pkt->savedpos = pkt->length;
2205 static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
2208 ssh_pkt_adddata(pkt, data, len);
2209 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
2211 static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
2213 ssh_pkt_addstring_data(pkt, data, strlen(data));
2215 static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
2217 ssh_pkt_addstring_start(pkt);
2218 ssh_pkt_addstring_str(pkt, data);
2220 static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
2222 int len = ssh1_bignum_length(b);
2223 unsigned char *data = snewn(len, unsigned char);
2224 (void) ssh1_write_bignum(data, b);
2225 ssh_pkt_adddata(pkt, data, len);
2228 static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
2231 int i, n = (bignum_bitcount(b) + 7) / 8;
2232 p = snewn(n + 1, unsigned char);
2234 for (i = 1; i <= n; i++)
2235 p[i] = bignum_byte(b, n - i);
2237 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
2239 memmove(p, p + i, n + 1 - i);
2243 static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
2247 p = ssh2_mpint_fmt(b, &len);
2248 ssh_pkt_addstring_start(pkt);
2249 ssh_pkt_addstring_data(pkt, (char *)p, len);
2253 static struct Packet *ssh1_pkt_init(int pkt_type)
2255 struct Packet *pkt = ssh_new_packet();
2256 pkt->length = 4 + 8; /* space for length + max padding */
2257 ssh_pkt_addbyte(pkt, pkt_type);
2258 pkt->body = pkt->data + pkt->length;
2259 pkt->type = pkt_type;
2260 pkt->downstream_id = 0;
2261 pkt->additional_log_text = NULL;
2265 /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
2266 #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
2267 #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
2268 #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
2269 #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
2270 #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
2271 #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
2272 #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
2273 #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
2275 static struct Packet *ssh2_pkt_init(int pkt_type)
2277 struct Packet *pkt = ssh_new_packet();
2278 pkt->length = 5; /* space for packet length + padding length */
2280 pkt->type = pkt_type;
2281 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
2282 pkt->body = pkt->data + pkt->length; /* after packet type */
2283 pkt->downstream_id = 0;
2284 pkt->additional_log_text = NULL;
2289 * Construct an SSH-2 final-form packet: compress it, encrypt it,
2290 * put the MAC on it. Final packet, ready to be sent, is stored in
2291 * pkt->data. Total length is returned.
2293 static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
2295 int cipherblk, maclen, padding, unencrypted_prefix, i;
2298 ssh2_log_outgoing_packet(ssh, pkt);
2300 if (ssh->bare_connection) {
2302 * Trivial packet construction for the bare connection
2305 PUT_32BIT(pkt->data + 1, pkt->length - 5);
2306 pkt->body = pkt->data + 1;
2307 ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
2308 return pkt->length - 1;
2312 * Compress packet payload.
2315 unsigned char *newpayload;
2318 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
2320 &newpayload, &newlen)) {
2322 ssh2_pkt_adddata(pkt, newpayload, newlen);
2328 * Add padding. At least four bytes, and must also bring total
2329 * length (minus MAC) up to a multiple of the block size.
2330 * If pkt->forcepad is set, make sure the packet is at least that size
2333 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
2334 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
2336 unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
2337 if (pkt->length + padding < pkt->forcepad)
2338 padding = pkt->forcepad - pkt->length;
2340 (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
2342 assert(padding <= 255);
2343 maclen = ssh->csmac ? ssh->csmac->len : 0;
2344 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
2345 pkt->data[4] = padding;
2346 for (i = 0; i < padding; i++)
2347 pkt->data[pkt->length + i] = random_byte();
2348 PUT_32BIT(pkt->data, pkt->length + padding - 4);
2350 /* Encrypt length if the scheme requires it */
2351 if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
2352 ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
2353 ssh->v2_outgoing_sequence);
2356 if (ssh->csmac && ssh->csmac_etm) {
2358 * OpenSSH-defined encrypt-then-MAC protocol.
2361 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2362 pkt->data + 4, pkt->length + padding - 4);
2363 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2364 pkt->length + padding,
2365 ssh->v2_outgoing_sequence);
2368 * SSH-2 standard protocol.
2371 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
2372 pkt->length + padding,
2373 ssh->v2_outgoing_sequence);
2375 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
2376 pkt->data, pkt->length + padding);
2379 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
2380 pkt->encrypted_len = pkt->length + padding;
2382 /* Ready-to-send packet starts at pkt->data. We return length. */
2383 pkt->body = pkt->data;
2384 return pkt->length + padding + maclen;
2388 * Routines called from the main SSH code to send packets. There
2389 * are quite a few of these, because we have two separate
2390 * mechanisms for delaying the sending of packets:
2392 * - In order to send an IGNORE message and a password message in
2393 * a single fixed-length blob, we require the ability to
2394 * concatenate the encrypted forms of those two packets _into_ a
2395 * single blob and then pass it to our <network.h> transport
2396 * layer in one go. Hence, there's a deferment mechanism which
2397 * works after packet encryption.
2399 * - In order to avoid sending any connection-layer messages
2400 * during repeat key exchange, we have to queue up any such
2401 * outgoing messages _before_ they are encrypted (and in
2402 * particular before they're allocated sequence numbers), and
2403 * then send them once we've finished.
2405 * I call these mechanisms `defer' and `queue' respectively, so as
2406 * to distinguish them reasonably easily.
2408 * The functions send_noqueue() and defer_noqueue() free the packet
2409 * structure they are passed. Every outgoing packet goes through
2410 * precisely one of these functions in its life; packets passed to
2411 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2412 * these or get queued, and then when the queue is later emptied
2413 * the packets are all passed to defer_noqueue().
2415 * When using a CBC-mode cipher, it's necessary to ensure that an
2416 * attacker can't provide data to be encrypted using an IV that they
2417 * know. We ensure this by prefixing each packet that might contain
2418 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2419 * mechanism, so in this case send_noqueue() ends up redirecting to
2420 * defer_noqueue(). If you don't like this inefficiency, don't use
2424 static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2425 static void ssh_pkt_defersend(Ssh);
2428 * Send an SSH-2 packet immediately, without queuing or deferring.
2430 static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
2434 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2435 /* We need to send two packets, so use the deferral mechanism. */
2436 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2437 ssh_pkt_defersend(ssh);
2440 len = ssh2_pkt_construct(ssh, pkt);
2441 backlog = s_write(ssh, pkt->body, len);
2442 if (backlog > SSH_MAX_BACKLOG)
2443 ssh_throttle_all(ssh, 1, backlog);
2445 ssh->outgoing_data_size += pkt->encrypted_len;
2446 if (!ssh->kex_in_progress &&
2447 !ssh->bare_connection &&
2448 ssh->max_data_size != 0 &&
2449 ssh->outgoing_data_size > ssh->max_data_size)
2450 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2452 ssh_free_packet(pkt);
2456 * Defer an SSH-2 packet.
2458 static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
2461 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
2462 ssh->deferred_len == 0 && !noignore &&
2463 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2465 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2466 * get encrypted with a known IV.
2468 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2469 ssh2_pkt_addstring_start(ipkt);
2470 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2472 len = ssh2_pkt_construct(ssh, pkt);
2473 if (ssh->deferred_len + len > ssh->deferred_size) {
2474 ssh->deferred_size = ssh->deferred_len + len + 128;
2475 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2479 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
2480 ssh->deferred_len += len;
2481 ssh->deferred_data_size += pkt->encrypted_len;
2482 ssh_free_packet(pkt);
2486 * Queue an SSH-2 packet.
2488 static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2490 assert(ssh->queueing);
2492 if (ssh->queuelen >= ssh->queuesize) {
2493 ssh->queuesize = ssh->queuelen + 32;
2494 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2497 ssh->queue[ssh->queuelen++] = pkt;
2501 * Either queue or send a packet, depending on whether queueing is
2504 static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2507 ssh2_pkt_queue(ssh, pkt);
2509 ssh2_pkt_send_noqueue(ssh, pkt);
2513 * Either queue or defer a packet, depending on whether queueing is
2516 static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2519 ssh2_pkt_queue(ssh, pkt);
2521 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2525 * Send the whole deferred data block constructed by
2526 * ssh2_pkt_defer() or SSH-1's defer_packet().
2528 * The expected use of the defer mechanism is that you call
2529 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2530 * not currently queueing, this simply sets up deferred_send_data
2531 * and then sends it. If we _are_ currently queueing, the calls to
2532 * ssh2_pkt_defer() put the deferred packets on to the queue
2533 * instead, and therefore ssh_pkt_defersend() has no deferred data
2534 * to send. Hence, there's no need to make it conditional on
2537 static void ssh_pkt_defersend(Ssh ssh)
2540 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
2541 ssh->deferred_len = ssh->deferred_size = 0;
2542 sfree(ssh->deferred_send_data);
2543 ssh->deferred_send_data = NULL;
2544 if (backlog > SSH_MAX_BACKLOG)
2545 ssh_throttle_all(ssh, 1, backlog);
2547 if (ssh->version == 2) {
2548 ssh->outgoing_data_size += ssh->deferred_data_size;
2549 ssh->deferred_data_size = 0;
2550 if (!ssh->kex_in_progress &&
2551 !ssh->bare_connection &&
2552 ssh->max_data_size != 0 &&
2553 ssh->outgoing_data_size > ssh->max_data_size)
2554 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
2559 * Send a packet whose length needs to be disguised (typically
2560 * passwords or keyboard-interactive responses).
2562 static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2568 * The simplest way to do this is to adjust the
2569 * variable-length padding field in the outgoing packet.
2571 * Currently compiled out, because some Cisco SSH servers
2572 * don't like excessively padded packets (bah, why's it
2575 pkt->forcepad = padsize;
2576 ssh2_pkt_send(ssh, pkt);
2581 * If we can't do that, however, an alternative approach is
2582 * to use the pkt_defer mechanism to bundle the packet
2583 * tightly together with an SSH_MSG_IGNORE such that their
2584 * combined length is a constant. So first we construct the
2585 * final form of this packet and defer its sending.
2587 ssh2_pkt_defer(ssh, pkt);
2590 * Now construct an SSH_MSG_IGNORE which includes a string
2591 * that's an exact multiple of the cipher block size. (If
2592 * the cipher is NULL so that the block size is
2593 * unavailable, we don't do this trick at all, because we
2594 * gain nothing by it.)
2596 if (ssh->cscipher &&
2597 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
2600 stringlen = (256 - ssh->deferred_len);
2601 stringlen += ssh->cscipher->blksize - 1;
2602 stringlen -= (stringlen % ssh->cscipher->blksize);
2605 * Temporarily disable actual compression, so we
2606 * can guarantee to get this string exactly the
2607 * length we want it. The compression-disabling
2608 * routine should return an integer indicating how
2609 * many bytes we should adjust our string length
2613 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2615 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2616 ssh2_pkt_addstring_start(pkt);
2617 for (i = 0; i < stringlen; i++) {
2618 char c = (char) random_byte();
2619 ssh2_pkt_addstring_data(pkt, &c, 1);
2621 ssh2_pkt_defer(ssh, pkt);
2623 ssh_pkt_defersend(ssh);
2628 * Send all queued SSH-2 packets. We send them by means of
2629 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2630 * packets that needed to be lumped together.
2632 static void ssh2_pkt_queuesend(Ssh ssh)
2636 assert(!ssh->queueing);
2638 for (i = 0; i < ssh->queuelen; i++)
2639 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
2642 ssh_pkt_defersend(ssh);
2646 void bndebug(char *string, Bignum b)
2650 p = ssh2_mpint_fmt(b, &len);
2651 debug(("%s", string));
2652 for (i = 0; i < len; i++)
2653 debug((" %02x", p[i]));
2659 static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
2663 p = ssh2_mpint_fmt(b, &len);
2664 hash_string(h, s, p, len);
2669 * Packet decode functions for both SSH-1 and SSH-2.
2671 static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
2673 unsigned long value;
2674 if (pkt->length - pkt->savedpos < 4)
2675 return 0; /* arrgh, no way to decline (FIXME?) */
2676 value = GET_32BIT(pkt->body + pkt->savedpos);
2680 static int ssh2_pkt_getbool(struct Packet *pkt)
2682 unsigned long value;
2683 if (pkt->length - pkt->savedpos < 1)
2684 return 0; /* arrgh, no way to decline (FIXME?) */
2685 value = pkt->body[pkt->savedpos] != 0;
2689 static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
2694 if (pkt->length - pkt->savedpos < 4)
2696 len = toint(GET_32BIT(pkt->body + pkt->savedpos));
2701 if (pkt->length - pkt->savedpos < *length)
2703 *p = (char *)(pkt->body + pkt->savedpos);
2704 pkt->savedpos += *length;
2706 static void *ssh_pkt_getdata(struct Packet *pkt, int length)
2708 if (pkt->length - pkt->savedpos < length)
2710 pkt->savedpos += length;
2711 return pkt->body + (pkt->savedpos - length);
2713 static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
2714 const unsigned char **keystr)
2718 j = makekey(pkt->body + pkt->savedpos,
2719 pkt->length - pkt->savedpos,
2726 assert(pkt->savedpos < pkt->length);
2730 static Bignum ssh1_pkt_getmp(struct Packet *pkt)
2735 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2736 pkt->length - pkt->savedpos, &b);
2744 static Bignum ssh2_pkt_getmp(struct Packet *pkt)
2750 ssh_pkt_getstring(pkt, &p, &length);
2755 b = bignum_from_bytes((unsigned char *)p, length);
2760 * Helper function to add an SSH-2 signature blob to a packet.
2761 * Expects to be shown the public key blob as well as the signature
2762 * blob. Normally works just like ssh2_pkt_addstring, but will
2763 * fiddle with the signature packet if necessary for
2764 * BUG_SSH2_RSA_PADDING.
2766 static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2767 void *pkblob_v, int pkblob_len,
2768 void *sigblob_v, int sigblob_len)
2770 unsigned char *pkblob = (unsigned char *)pkblob_v;
2771 unsigned char *sigblob = (unsigned char *)sigblob_v;
2773 /* dmemdump(pkblob, pkblob_len); */
2774 /* dmemdump(sigblob, sigblob_len); */
2777 * See if this is in fact an ssh-rsa signature and a buggy
2778 * server; otherwise we can just do this the easy way.
2780 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
2781 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2782 int pos, len, siglen;
2785 * Find the byte length of the modulus.
2788 pos = 4+7; /* skip over "ssh-rsa" */
2789 len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
2790 if (len < 0 || len > pkblob_len - pos - 4)
2792 pos += 4 + len; /* skip over exponent */
2793 if (pkblob_len - pos < 4)
2795 len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
2796 if (len < 0 || len > pkblob_len - pos - 4)
2798 pos += 4; /* find modulus itself */
2799 while (len > 0 && pkblob[pos] == 0)
2801 /* debug(("modulus length is %d\n", len)); */
2804 * Now find the signature integer.
2806 pos = 4+7; /* skip over "ssh-rsa" */
2807 if (sigblob_len < pos+4)
2809 siglen = toint(GET_32BIT(sigblob+pos));
2810 if (siglen != sigblob_len - pos - 4)
2812 /* debug(("signature length is %d\n", siglen)); */
2814 if (len != siglen) {
2815 unsigned char newlen[4];
2816 ssh2_pkt_addstring_start(pkt);
2817 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
2818 /* dmemdump(sigblob, pos); */
2819 pos += 4; /* point to start of actual sig */
2820 PUT_32BIT(newlen, len);
2821 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
2822 /* dmemdump(newlen, 4); */
2824 while (len-- > siglen) {
2825 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
2826 /* dmemdump(newlen, 1); */
2828 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
2829 /* dmemdump(sigblob+pos, siglen); */
2833 /* Otherwise fall through and do it the easy way. We also come
2834 * here as a fallback if we discover above that the key blob
2835 * is misformatted in some way. */
2839 ssh2_pkt_addstring_start(pkt);
2840 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
2844 * Examine the remote side's version string and compare it against
2845 * a list of known buggy implementations.
2847 static void ssh_detect_bugs(Ssh ssh, char *vstring)
2849 char *imp; /* pointer to implementation part */
2851 imp += strcspn(imp, "-");
2853 imp += strcspn(imp, "-");
2856 ssh->remote_bugs = 0;
2859 * General notes on server version strings:
2860 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2861 * here -- in particular, we've heard of one that's perfectly happy
2862 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2863 * so we can't distinguish them.
2865 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2866 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2867 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2868 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
2869 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
2870 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
2872 * These versions don't support SSH1_MSG_IGNORE, so we have
2873 * to use a different defence against password length
2876 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2877 logevent("We believe remote version has SSH-1 ignore bug");
2880 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2881 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
2882 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
2884 * These versions need a plain password sent; they can't
2885 * handle having a null and a random length of data after
2888 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2889 logevent("We believe remote version needs a plain SSH-1 password");
2892 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2893 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2894 (!strcmp(imp, "Cisco-1.25")))) {
2896 * These versions apparently have no clue whatever about
2897 * RSA authentication and will panic and die if they see
2898 * an AUTH_RSA message.
2900 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
2901 logevent("We believe remote version can't handle SSH-1 RSA authentication");
2904 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2905 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
2906 !wc_match("* VShell", imp) &&
2907 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2908 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2909 wc_match("2.1 *", imp)))) {
2911 * These versions have the HMAC bug.
2913 ssh->remote_bugs |= BUG_SSH2_HMAC;
2914 logevent("We believe remote version has SSH-2 HMAC bug");
2917 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2918 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
2919 !wc_match("* VShell", imp) &&
2920 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
2922 * These versions have the key-derivation bug (failing to
2923 * include the literal shared secret in the hashes that
2924 * generate the keys).
2926 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2927 logevent("We believe remote version has SSH-2 key-derivation bug");
2930 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2931 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
2932 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2933 wc_match("OpenSSH_3.[0-2]*", imp) ||
2934 wc_match("mod_sftp/0.[0-8]*", imp) ||
2935 wc_match("mod_sftp/0.9.[0-8]", imp)))) {
2937 * These versions have the SSH-2 RSA padding bug.
2939 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2940 logevent("We believe remote version has SSH-2 RSA padding bug");
2943 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2944 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
2945 wc_match("OpenSSH_2.[0-2]*", imp))) {
2947 * These versions have the SSH-2 session-ID bug in
2948 * public-key authentication.
2950 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2951 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
2954 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2955 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
2956 (wc_match("DigiSSH_2.0", imp) ||
2957 wc_match("OpenSSH_2.[0-4]*", imp) ||
2958 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2959 wc_match("Sun_SSH_1.0", imp) ||
2960 wc_match("Sun_SSH_1.0.1", imp) ||
2961 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2962 wc_match("WeOnlyDo-*", imp)))) {
2964 * These versions have the SSH-2 rekey bug.
2966 ssh->remote_bugs |= BUG_SSH2_REKEY;
2967 logevent("We believe remote version has SSH-2 rekey bug");
2970 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2971 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
2972 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2973 wc_match("1.36 sshlib: GlobalScape", imp)))) {
2975 * This version ignores our makpkt and needs to be throttled.
2977 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2978 logevent("We believe remote version ignores SSH-2 maximum packet size");
2981 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
2983 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2984 * none detected automatically.
2986 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2987 logevent("We believe remote version has SSH-2 ignore bug");
2990 if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
2991 (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
2992 (wc_match("OpenSSH_2.[235]*", imp)))) {
2994 * These versions only support the original (pre-RFC4419)
2995 * SSH-2 GEX request, and disconnect with a protocol error if
2996 * we use the newer version.
2998 ssh->remote_bugs |= BUG_SSH2_OLDGEX;
2999 logevent("We believe remote version has outdated SSH-2 GEX");
3002 if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
3004 * Servers that don't support our winadj request for one
3005 * reason or another. Currently, none detected automatically.
3007 ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
3008 logevent("We believe remote version has winadj bug");
3011 if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
3012 (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
3013 (wc_match("OpenSSH_[2-5].*", imp) ||
3014 wc_match("OpenSSH_6.[0-6]*", imp) ||
3015 wc_match("dropbear_0.[2-4][0-9]*", imp) ||
3016 wc_match("dropbear_0.5[01]*", imp)))) {
3018 * These versions have the SSH-2 channel request bug.
3019 * OpenSSH 6.7 and above do not:
3020 * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
3021 * dropbear_0.52 and above do not:
3022 * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
3024 ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
3025 logevent("We believe remote version has SSH-2 channel request bug");
3030 * The `software version' part of an SSH version string is required
3031 * to contain no spaces or minus signs.
3033 static void ssh_fix_verstring(char *str)
3035 /* Eat "<protoversion>-". */
3036 while (*str && *str != '-') str++;
3037 assert(*str == '-'); str++;
3039 /* Convert minus signs and spaces in the remaining string into
3042 if (*str == '-' || *str == ' ')
3049 * Send an appropriate SSH version string.
3051 static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
3055 if (ssh->version == 2) {
3057 * Construct a v2 version string.
3059 verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
3062 * Construct a v1 version string.
3064 assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
3065 verstring = dupprintf("SSH-%s-%s\012",
3066 (ssh_versioncmp(svers, "1.5") <= 0 ?
3071 ssh_fix_verstring(verstring + strlen(protoname));
3073 /* FUZZING make PuTTY insecure, so make live use difficult. */
3077 if (ssh->version == 2) {
3080 * Record our version string.
3082 len = strcspn(verstring, "\015\012");
3083 ssh->v_c = snewn(len + 1, char);
3084 memcpy(ssh->v_c, verstring, len);
3088 logeventf(ssh, "We claim version: %.*s",
3089 strcspn(verstring, "\015\012"), verstring);
3090 s_write(ssh, verstring, strlen(verstring));
3094 static int do_ssh_init(Ssh ssh, unsigned char c)
3096 static const char protoname[] = "SSH-";
3098 struct do_ssh_init_state {
3107 crState(do_ssh_init_state);
3111 /* Search for a line beginning with the protocol name prefix in
3114 for (s->i = 0; protoname[s->i]; s->i++) {
3115 if ((char)c != protoname[s->i]) goto no;
3125 ssh->session_started = TRUE;
3127 s->vstrsize = sizeof(protoname) + 16;
3128 s->vstring = snewn(s->vstrsize, char);
3129 strcpy(s->vstring, protoname);
3130 s->vslen = strlen(protoname);
3133 if (s->vslen >= s->vstrsize - 1) {
3135 s->vstring = sresize(s->vstring, s->vstrsize, char);
3137 s->vstring[s->vslen++] = c;
3140 s->version[s->i] = '\0';
3142 } else if (s->i < sizeof(s->version) - 1)
3143 s->version[s->i++] = c;
3144 } else if (c == '\012')
3146 crReturn(1); /* get another char */
3149 ssh->agentfwd_enabled = FALSE;
3150 ssh->rdpkt2_state.incoming_sequence = 0;
3152 s->vstring[s->vslen] = 0;
3153 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3154 logeventf(ssh, "Server version: %s", s->vstring);
3155 ssh_detect_bugs(ssh, s->vstring);
3158 * Decide which SSH protocol version to support.
3161 /* Anything strictly below "2.0" means protocol 1 is supported. */
3162 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
3163 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
3164 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
3166 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3168 bombout(("SSH protocol version 1 required by our configuration "
3169 "but not provided by server"));
3172 } else if (conf_get_int(ssh->conf, CONF_sshprot) == 3) {
3174 bombout(("SSH protocol version 2 required by our configuration "
3175 "but server only provides (old, insecure) SSH-1"));
3179 /* No longer support values 1 or 2 for CONF_sshprot */
3180 assert(!"Unexpected value for CONF_sshprot");
3183 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
3188 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
3190 /* Send the version string, if we haven't already */
3191 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
3192 ssh_send_verstring(ssh, protoname, s->version);
3194 if (ssh->version == 2) {
3197 * Record their version string.
3199 len = strcspn(s->vstring, "\015\012");
3200 ssh->v_s = snewn(len + 1, char);
3201 memcpy(ssh->v_s, s->vstring, len);
3205 * Initialise SSH-2 protocol.
3207 ssh->protocol = ssh2_protocol;
3208 ssh2_protocol_setup(ssh);
3209 ssh->s_rdpkt = ssh2_rdpkt;
3212 * Initialise SSH-1 protocol.
3214 ssh->protocol = ssh1_protocol;
3215 ssh1_protocol_setup(ssh);
3216 ssh->s_rdpkt = ssh1_rdpkt;
3218 if (ssh->version == 2)
3219 do_ssh2_transport(ssh, NULL, -1, NULL);
3221 update_specials_menu(ssh->frontend);
3222 ssh->state = SSH_STATE_BEFORE_SIZE;
3223 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3230 static int do_ssh_connection_init(Ssh ssh, unsigned char c)
3233 * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
3234 * the ssh-connection part, extracted and given a trivial binary
3235 * packet protocol, so we replace 'SSH-' at the start with a new
3236 * name. In proper SSH style (though of course this part of the
3237 * proper SSH protocol _isn't_ subject to this kind of
3238 * DNS-domain-based extension), we define the new name in our
3241 static const char protoname[] =
3242 "SSHCONNECTION@putty.projects.tartarus.org-";
3244 struct do_ssh_connection_init_state {
3252 crState(do_ssh_connection_init_state);
3256 /* Search for a line beginning with the protocol name prefix in
3259 for (s->i = 0; protoname[s->i]; s->i++) {
3260 if ((char)c != protoname[s->i]) goto no;
3270 s->vstrsize = sizeof(protoname) + 16;
3271 s->vstring = snewn(s->vstrsize, char);
3272 strcpy(s->vstring, protoname);
3273 s->vslen = strlen(protoname);
3276 if (s->vslen >= s->vstrsize - 1) {
3278 s->vstring = sresize(s->vstring, s->vstrsize, char);
3280 s->vstring[s->vslen++] = c;
3283 s->version[s->i] = '\0';
3285 } else if (s->i < sizeof(s->version) - 1)
3286 s->version[s->i++] = c;
3287 } else if (c == '\012')
3289 crReturn(1); /* get another char */
3292 ssh->agentfwd_enabled = FALSE;
3293 ssh->rdpkt2_bare_state.incoming_sequence = 0;
3295 s->vstring[s->vslen] = 0;
3296 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
3297 logeventf(ssh, "Server version: %s", s->vstring);
3298 ssh_detect_bugs(ssh, s->vstring);
3301 * Decide which SSH protocol version to support. This is easy in
3302 * bare ssh-connection mode: only 2.0 is legal.
3304 if (ssh_versioncmp(s->version, "2.0") < 0) {
3305 bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
3308 if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
3309 bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
3315 logeventf(ssh, "Using bare ssh-connection protocol");
3317 /* Send the version string, if we haven't already */
3318 ssh_send_verstring(ssh, protoname, s->version);
3321 * Initialise bare connection protocol.
3323 ssh->protocol = ssh2_bare_connection_protocol;
3324 ssh2_bare_connection_protocol_setup(ssh);
3325 ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
3327 update_specials_menu(ssh->frontend);
3328 ssh->state = SSH_STATE_BEFORE_SIZE;
3329 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
3332 * Get authconn (really just conn) under way.
3334 do_ssh2_authconn(ssh, NULL, 0, NULL);
3341 static void ssh_process_incoming_data(Ssh ssh,
3342 const unsigned char **data, int *datalen)
3344 struct Packet *pktin;
3346 pktin = ssh->s_rdpkt(ssh, data, datalen);
3348 ssh->protocol(ssh, NULL, 0, pktin);
3349 ssh_free_packet(pktin);
3353 static void ssh_queue_incoming_data(Ssh ssh,
3354 const unsigned char **data, int *datalen)
3356 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
3361 static void ssh_process_queued_incoming_data(Ssh ssh)
3364 const unsigned char *data;
3367 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
3368 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
3372 while (!ssh->frozen && len > 0)
3373 ssh_process_incoming_data(ssh, &data, &len);
3376 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
3380 static void ssh_set_frozen(Ssh ssh, int frozen)
3383 sk_set_frozen(ssh->s, frozen);
3384 ssh->frozen = frozen;
3387 static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
3389 /* Log raw data, if we're in that mode. */
3391 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
3392 0, NULL, NULL, 0, NULL);
3394 crBegin(ssh->ssh_gotdata_crstate);
3397 * To begin with, feed the characters one by one to the
3398 * protocol initialisation / selection function do_ssh_init().
3399 * When that returns 0, we're done with the initial greeting
3400 * exchange and can move on to packet discipline.
3403 int ret; /* need not be kept across crReturn */
3405 crReturnV; /* more data please */
3406 ret = ssh->do_ssh_init(ssh, *data);
3414 * We emerge from that loop when the initial negotiation is
3415 * over and we have selected an s_rdpkt function. Now pass
3416 * everything to s_rdpkt, and then pass the resulting packets
3417 * to the proper protocol handler.
3421 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
3423 ssh_queue_incoming_data(ssh, &data, &datalen);
3424 /* This uses up all data and cannot cause anything interesting
3425 * to happen; indeed, for anything to happen at all, we must
3426 * return, so break out. */
3428 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
3429 /* This uses up some or all data, and may freeze the
3431 ssh_process_queued_incoming_data(ssh);
3433 /* This uses up some or all data, and may freeze the
3435 ssh_process_incoming_data(ssh, &data, &datalen);
3437 /* FIXME this is probably EBW. */
3438 if (ssh->state == SSH_STATE_CLOSED)
3441 /* We're out of data. Go and get some more. */
3447 static int ssh_do_close(Ssh ssh, int notify_exit)
3450 struct ssh_channel *c;
3452 ssh->state = SSH_STATE_CLOSED;
3453 expire_timer_context(ssh);
3458 notify_remote_exit(ssh->frontend);
3463 * Now we must shut down any port- and X-forwarded channels going
3464 * through this connection.
3466 if (ssh->channels) {
3467 while (NULL != (c = index234(ssh->channels, 0))) {
3468 ssh_channel_close_local(c, NULL);
3469 del234(ssh->channels, c); /* moving next one to index 0 */
3470 if (ssh->version == 2)
3471 bufchain_clear(&c->v.v2.outbuffer);
3476 * Go through port-forwardings, and close any associated
3477 * listening sockets.
3479 if (ssh->portfwds) {
3480 struct ssh_portfwd *pf;
3481 while (NULL != (pf = index234(ssh->portfwds, 0))) {
3482 /* Dispose of any listening socket. */
3484 pfl_terminate(pf->local);
3485 del234(ssh->portfwds, pf); /* moving next one to index 0 */
3488 freetree234(ssh->portfwds);
3489 ssh->portfwds = NULL;
3493 * Also stop attempting to connection-share.
3495 if (ssh->connshare) {
3496 sharestate_free(ssh->connshare);
3497 ssh->connshare = NULL;
3503 static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
3504 const char *error_msg, int error_code)
3506 Ssh ssh = (Ssh) plug;
3509 * While we're attempting connection sharing, don't loudly log
3510 * everything that happens. Real TCP connections need to be logged
3511 * when we _start_ trying to connect, because it might be ages
3512 * before they respond if something goes wrong; but connection
3513 * sharing is local and quick to respond, and it's sufficient to
3514 * simply wait and see whether it worked afterwards.
3517 if (!ssh->attempting_connshare)
3518 backend_socket_log(ssh->frontend, type, addr, port,
3519 error_msg, error_code, ssh->conf,
3520 ssh->session_started);
3523 void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
3524 const char *ds_err, const char *us_err)
3526 if (event == SHARE_NONE) {
3527 /* In this case, 'logtext' is an error message indicating a
3528 * reason why connection sharing couldn't be set up _at all_.
3529 * Failing that, ds_err and us_err indicate why we couldn't be
3530 * a downstream and an upstream respectively. */
3532 logeventf(ssh, "Could not set up connection sharing: %s", logtext);
3535 logeventf(ssh, "Could not set up connection sharing"
3536 " as downstream: %s", ds_err);
3538 logeventf(ssh, "Could not set up connection sharing"
3539 " as upstream: %s", us_err);
3541 } else if (event == SHARE_DOWNSTREAM) {
3542 /* In this case, 'logtext' is a local endpoint address */
3543 logeventf(ssh, "Using existing shared connection at %s", logtext);
3544 /* Also we should mention this in the console window to avoid
3545 * confusing users as to why this window doesn't behave the
3547 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
3548 c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
3550 } else if (event == SHARE_UPSTREAM) {
3551 /* In this case, 'logtext' is a local endpoint address too */
3552 logeventf(ssh, "Sharing this connection at %s", logtext);
3556 static int ssh_closing(Plug plug, const char *error_msg, int error_code,
3559 Ssh ssh = (Ssh) plug;
3560 int need_notify = ssh_do_close(ssh, FALSE);
3563 if (!ssh->close_expected)
3564 error_msg = "Server unexpectedly closed network connection";
3566 error_msg = "Server closed network connection";
3569 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
3573 notify_remote_exit(ssh->frontend);
3576 logevent(error_msg);
3577 if (!ssh->close_expected || !ssh->clean_exit)
3578 connection_fatal(ssh->frontend, "%s", error_msg);
3582 static int ssh_receive(Plug plug, int urgent, char *data, int len)
3584 Ssh ssh = (Ssh) plug;
3585 ssh_gotdata(ssh, (unsigned char *)data, len);
3586 if (ssh->state == SSH_STATE_CLOSED) {
3587 ssh_do_close(ssh, TRUE);
3593 static void ssh_sent(Plug plug, int bufsize)
3595 Ssh ssh = (Ssh) plug;
3597 * If the send backlog on the SSH socket itself clears, we
3598 * should unthrottle the whole world if it was throttled.
3600 if (bufsize < SSH_MAX_BACKLOG)
3601 ssh_throttle_all(ssh, 0, bufsize);
3604 static void ssh_hostport_setup(const char *host, int port, Conf *conf,
3605 char **savedhost, int *savedport,
3608 char *loghost = conf_get_str(conf, CONF_loghost);
3610 *loghost_ret = loghost;
3616 tmphost = dupstr(loghost);
3617 *savedport = 22; /* default ssh port */
3620 * A colon suffix on the hostname string also lets us affect
3621 * savedport. (Unless there are multiple colons, in which case
3622 * we assume this is an unbracketed IPv6 literal.)
3624 colon = host_strrchr(tmphost, ':');
3625 if (colon && colon == host_strchr(tmphost, ':')) {
3628 *savedport = atoi(colon);
3631 *savedhost = host_strduptrim(tmphost);
3634 *savedhost = host_strduptrim(host);
3636 port = 22; /* default ssh port */
3641 static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
3647 random_ref(); /* platform may need this to determine share socket name */
3648 ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
3649 ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
3657 * Connect to specified host and port.
3658 * Returns an error message, or NULL on success.
3659 * Also places the canonical host name into `realhost'. It must be
3660 * freed by the caller.
3662 static const char *connect_to_host(Ssh ssh, const char *host, int port,
3663 char **realhost, int nodelay, int keepalive)
3665 static const struct plug_function_table fn_table = {
3676 int addressfamily, sshprot;
3678 ssh_hostport_setup(host, port, ssh->conf,
3679 &ssh->savedhost, &ssh->savedport, &loghost);
3681 ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
3684 * Try connection-sharing, in case that means we don't open a
3685 * socket after all. ssh_connection_sharing_init will connect to a
3686 * previously established upstream if it can, and failing that,
3687 * establish a listening socket for _us_ to be the upstream. In
3688 * the latter case it will return NULL just as if it had done
3689 * nothing, because here we only need to care if we're a
3690 * downstream and need to do our connection setup differently.
3692 ssh->connshare = NULL;
3693 ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
3694 ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
3695 ssh->conf, ssh, &ssh->connshare);
3696 ssh->attempting_connshare = FALSE;
3697 if (ssh->s != NULL) {
3699 * We are a downstream.
3701 ssh->bare_connection = TRUE;
3702 ssh->do_ssh_init = do_ssh_connection_init;
3703 ssh->fullhostname = NULL;
3704 *realhost = dupstr(host); /* best we can do */
3707 * We're not a downstream, so open a normal socket.
3709 ssh->do_ssh_init = do_ssh_init;
3714 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
3715 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
3716 ssh->frontend, "SSH connection");
3717 if ((err = sk_addr_error(addr)) != NULL) {
3721 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
3723 ssh->s = new_connection(addr, *realhost, port,
3724 0, 1, nodelay, keepalive,
3725 (Plug) ssh, ssh->conf);
3726 if ((err = sk_socket_error(ssh->s)) != NULL) {
3728 notify_remote_exit(ssh->frontend);
3734 * The SSH version number is always fixed (since we no longer support
3735 * fallback between versions), so set it now, and if it's SSH-2,
3736 * send the version string now too.
3738 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3739 assert(sshprot == 0 || sshprot == 3);
3743 if (sshprot == 3 && !ssh->bare_connection) {
3746 ssh_send_verstring(ssh, "SSH-", NULL);
3750 * loghost, if configured, overrides realhost.
3754 *realhost = dupstr(loghost);
3761 * Throttle or unthrottle the SSH connection.
3763 static void ssh_throttle_conn(Ssh ssh, int adjust)
3765 int old_count = ssh->conn_throttle_count;
3766 ssh->conn_throttle_count += adjust;
3767 assert(ssh->conn_throttle_count >= 0);
3768 if (ssh->conn_throttle_count && !old_count) {
3769 ssh_set_frozen(ssh, 1);
3770 } else if (!ssh->conn_throttle_count && old_count) {
3771 ssh_set_frozen(ssh, 0);
3776 * Throttle or unthrottle _all_ local data streams (for when sends
3777 * on the SSH connection itself back up).
3779 static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
3782 struct ssh_channel *c;
3784 if (enable == ssh->throttled_all)
3786 ssh->throttled_all = enable;
3787 ssh->overall_bufsize = bufsize;
3790 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
3792 case CHAN_MAINSESSION:
3794 * This is treated separately, outside the switch.
3798 x11_override_throttle(c->u.x11.xconn, enable);
3801 /* Agent channels require no buffer management. */
3804 pfd_override_throttle(c->u.pfd.pf, enable);
3810 static void ssh_agent_callback(void *sshv, void *reply, int replylen)
3812 Ssh ssh = (Ssh) sshv;
3814 ssh->agent_response = reply;
3815 ssh->agent_response_len = replylen;
3817 if (ssh->version == 1)
3818 do_ssh1_login(ssh, NULL, -1, NULL);
3820 do_ssh2_authconn(ssh, NULL, -1, NULL);
3823 static void ssh_dialog_callback(void *sshv, int ret)
3825 Ssh ssh = (Ssh) sshv;
3827 ssh->user_response = ret;
3829 if (ssh->version == 1)
3830 do_ssh1_login(ssh, NULL, -1, NULL);
3832 do_ssh2_transport(ssh, NULL, -1, NULL);
3835 * This may have unfrozen the SSH connection, so do a
3838 ssh_process_queued_incoming_data(ssh);
3841 static void ssh_agentf_callback(void *cv, void *reply, int replylen)
3843 struct ssh_channel *c = (struct ssh_channel *)cv;
3844 const void *sentreply = reply;
3846 c->u.a.outstanding_requests--;
3848 /* Fake SSH_AGENT_FAILURE. */
3849 sentreply = "\0\0\0\1\5";
3852 ssh_send_channel_data(c, sentreply, replylen);
3856 * If we've already seen an incoming EOF but haven't sent an
3857 * outgoing one, this may be the moment to send it.
3859 if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
3860 sshfwd_write_eof(c);
3864 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3865 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3866 * => log `wire_reason'.
3868 static void ssh_disconnect(Ssh ssh, const char *client_reason,
3869 const char *wire_reason,
3870 int code, int clean_exit)
3874 client_reason = wire_reason;
3876 error = dupprintf("Disconnected: %s", client_reason);
3878 error = dupstr("Disconnected");
3880 if (ssh->version == 1) {
3881 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3883 } else if (ssh->version == 2) {
3884 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3885 ssh2_pkt_adduint32(pktout, code);
3886 ssh2_pkt_addstring(pktout, wire_reason);
3887 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3888 ssh2_pkt_send_noqueue(ssh, pktout);
3891 ssh->close_expected = TRUE;
3892 ssh->clean_exit = clean_exit;
3893 ssh_closing((Plug)ssh, error, 0, 0);
3897 int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
3898 const struct ssh_signkey *ssh2keytype,
3901 if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
3902 return -1; /* no manual keys configured */
3907 * The fingerprint string we've been given will have things
3908 * like 'ssh-rsa 2048' at the front of it. Strip those off and
3909 * narrow down to just the colon-separated hex block at the
3910 * end of the string.
3912 const char *p = strrchr(fingerprint, ' ');
3913 fingerprint = p ? p+1 : fingerprint;
3914 /* Quick sanity checks, including making sure it's in lowercase */
3915 assert(strlen(fingerprint) == 16*3 - 1);
3916 assert(fingerprint[2] == ':');
3917 assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
3919 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3921 return 1; /* success */
3926 * Construct the base64-encoded public key blob and see if
3929 unsigned char *binblob;
3931 int binlen, atoms, i;
3932 binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
3933 atoms = (binlen + 2) / 3;
3934 base64blob = snewn(atoms * 4 + 1, char);
3935 for (i = 0; i < atoms; i++)
3936 base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
3937 base64blob[atoms * 4] = '\0';
3939 if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
3942 return 1; /* success */
3951 * Handle the key exchange and user authentication phases.
3953 static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
3954 struct Packet *pktin)
3957 unsigned char cookie[8], *ptr;
3958 struct MD5Context md5c;
3959 struct do_ssh1_login_state {
3962 unsigned char *rsabuf;
3963 const unsigned char *keystr1, *keystr2;
3964 unsigned long supported_ciphers_mask, supported_auths_mask;
3965 int tried_publickey, tried_agent;
3966 int tis_auth_refused, ccard_auth_refused;
3967 unsigned char session_id[16];
3969 void *publickey_blob;
3970 int publickey_bloblen;
3971 char *publickey_comment;
3972 int privatekey_available, privatekey_encrypted;
3973 prompts_t *cur_prompt;
3976 unsigned char request[5], *response, *p;
3986 struct RSAKey servkey, hostkey;
3988 crState(do_ssh1_login_state);
3995 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
3996 bombout(("Public key packet not received"));
4000 logevent("Received public keys");
4002 ptr = ssh_pkt_getdata(pktin, 8);
4004 bombout(("SSH-1 public key packet stopped before random cookie"));
4007 memcpy(cookie, ptr, 8);
4009 if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
4010 !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
4011 bombout(("Failed to read SSH-1 public keys from public key packet"));
4016 * Log the host key fingerprint.
4020 logevent("Host key fingerprint is:");
4021 strcpy(logmsg, " ");
4022 s->hostkey.comment = NULL;
4023 rsa_fingerprint(logmsg + strlen(logmsg),
4024 sizeof(logmsg) - strlen(logmsg), &s->hostkey);
4028 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
4029 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
4030 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
4031 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
4032 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
4034 ssh->v1_local_protoflags =
4035 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
4036 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
4039 MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
4040 MD5Update(&md5c, s->keystr1, s->servkey.bytes);
4041 MD5Update(&md5c, cookie, 8);
4042 MD5Final(s->session_id, &md5c);
4044 for (i = 0; i < 32; i++)
4045 ssh->session_key[i] = random_byte();
4048 * Verify that the `bits' and `bytes' parameters match.
4050 if (s->hostkey.bits > s->hostkey.bytes * 8 ||
4051 s->servkey.bits > s->servkey.bytes * 8) {
4052 bombout(("SSH-1 public keys were badly formatted"));
4056 s->len = (s->hostkey.bytes > s->servkey.bytes ?
4057 s->hostkey.bytes : s->servkey.bytes);
4059 s->rsabuf = snewn(s->len, unsigned char);
4062 * Verify the host key.
4066 * First format the key into a string.
4068 int len = rsastr_len(&s->hostkey);
4069 char fingerprint[100];
4070 char *keystr = snewn(len, char);
4071 rsastr_fmt(keystr, &s->hostkey);
4072 rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
4074 /* First check against manually configured host keys. */
4075 s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
4076 if (s->dlgret == 0) { /* did not match */
4077 bombout(("Host key did not appear in manually configured list"));
4080 } else if (s->dlgret < 0) { /* none configured; use standard handling */
4081 ssh_set_frozen(ssh, 1);
4082 s->dlgret = verify_ssh_host_key(ssh->frontend,
4083 ssh->savedhost, ssh->savedport,
4084 "rsa", keystr, fingerprint,
4085 ssh_dialog_callback, ssh);
4090 if (s->dlgret < 0) {
4094 bombout(("Unexpected data from server while waiting"
4095 " for user host key response"));
4098 } while (pktin || inlen > 0);
4099 s->dlgret = ssh->user_response;
4101 ssh_set_frozen(ssh, 0);
4103 if (s->dlgret == 0) {
4104 ssh_disconnect(ssh, "User aborted at host key verification",
4113 for (i = 0; i < 32; i++) {
4114 s->rsabuf[i] = ssh->session_key[i];
4116 s->rsabuf[i] ^= s->session_id[i];
4119 if (s->hostkey.bytes > s->servkey.bytes) {
4120 ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
4122 ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
4124 ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
4126 ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
4129 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
4133 logevent("Encrypted session key");
4136 int cipher_chosen = 0, warn = 0;
4137 const char *cipher_string = NULL;
4139 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4140 int next_cipher = conf_get_int_int(ssh->conf,
4141 CONF_ssh_cipherlist, i);
4142 if (next_cipher == CIPHER_WARN) {
4143 /* If/when we choose a cipher, warn about it */
4145 } else if (next_cipher == CIPHER_AES) {
4146 /* XXX Probably don't need to mention this. */
4147 logevent("AES not supported in SSH-1, skipping");
4149 switch (next_cipher) {
4150 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
4151 cipher_string = "3DES"; break;
4152 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
4153 cipher_string = "Blowfish"; break;
4154 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
4155 cipher_string = "single-DES"; break;
4157 if (s->supported_ciphers_mask & (1 << s->cipher_type))
4161 if (!cipher_chosen) {
4162 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
4163 bombout(("Server violates SSH-1 protocol by not "
4164 "supporting 3DES encryption"));
4166 /* shouldn't happen */
4167 bombout(("No supported ciphers found"));
4171 /* Warn about chosen cipher if necessary. */
4173 ssh_set_frozen(ssh, 1);
4174 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
4175 ssh_dialog_callback, ssh);
4176 if (s->dlgret < 0) {
4180 bombout(("Unexpected data from server while waiting"
4181 " for user response"));
4184 } while (pktin || inlen > 0);
4185 s->dlgret = ssh->user_response;
4187 ssh_set_frozen(ssh, 0);
4188 if (s->dlgret == 0) {
4189 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
4196 switch (s->cipher_type) {
4197 case SSH_CIPHER_3DES:
4198 logevent("Using 3DES encryption");
4200 case SSH_CIPHER_DES:
4201 logevent("Using single-DES encryption");
4203 case SSH_CIPHER_BLOWFISH:
4204 logevent("Using Blowfish encryption");
4208 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
4209 PKT_CHAR, s->cipher_type,
4210 PKT_DATA, cookie, 8,
4211 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
4212 PKT_DATA, s->rsabuf, s->len,
4213 PKT_INT, ssh->v1_local_protoflags, PKT_END);
4215 logevent("Trying to enable encryption...");
4219 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
4220 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
4222 ssh->v1_cipher_ctx = ssh->cipher->make_context();
4223 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
4224 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
4226 ssh->crcda_ctx = crcda_make_context();
4227 logevent("Installing CRC compensation attack detector");
4229 if (s->servkey.modulus) {
4230 sfree(s->servkey.modulus);
4231 s->servkey.modulus = NULL;
4233 if (s->servkey.exponent) {
4234 sfree(s->servkey.exponent);
4235 s->servkey.exponent = NULL;
4237 if (s->hostkey.modulus) {
4238 sfree(s->hostkey.modulus);
4239 s->hostkey.modulus = NULL;
4241 if (s->hostkey.exponent) {
4242 sfree(s->hostkey.exponent);
4243 s->hostkey.exponent = NULL;
4247 if (pktin->type != SSH1_SMSG_SUCCESS) {
4248 bombout(("Encryption not successfully enabled"));
4252 logevent("Successfully started encryption");
4254 fflush(stdout); /* FIXME eh? */
4256 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
4257 int ret; /* need not be kept over crReturn */
4258 s->cur_prompt = new_prompts(ssh->frontend);
4259 s->cur_prompt->to_server = TRUE;
4260 s->cur_prompt->name = dupstr("SSH login name");
4261 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
4262 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4265 crWaitUntil(!pktin);
4266 ret = get_userpass_input(s->cur_prompt, in, inlen);
4271 * Failed to get a username. Terminate.
4273 free_prompts(s->cur_prompt);
4274 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
4277 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
4278 free_prompts(s->cur_prompt);
4281 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
4283 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
4285 if (flags & FLAG_INTERACTIVE &&
4286 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
4287 c_write_str(ssh, userlog);
4288 c_write_str(ssh, "\r\n");
4296 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
4297 /* We must not attempt PK auth. Pretend we've already tried it. */
4298 s->tried_publickey = s->tried_agent = 1;
4300 s->tried_publickey = s->tried_agent = 0;
4302 s->tis_auth_refused = s->ccard_auth_refused = 0;
4304 * Load the public half of any configured keyfile for later use.
4306 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4307 if (!filename_is_null(s->keyfile)) {
4309 logeventf(ssh, "Reading key file \"%.150s\"",
4310 filename_to_str(s->keyfile));
4311 keytype = key_type(s->keyfile);
4312 if (keytype == SSH_KEYTYPE_SSH1 ||
4313 keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
4315 if (rsakey_pubblob(s->keyfile,
4316 &s->publickey_blob, &s->publickey_bloblen,
4317 &s->publickey_comment, &error)) {
4318 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
4319 if (!s->privatekey_available)
4320 logeventf(ssh, "Key file contains public key only");
4321 s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
4325 logeventf(ssh, "Unable to load key (%s)", error);
4326 msgbuf = dupprintf("Unable to load key file "
4327 "\"%.150s\" (%s)\r\n",
4328 filename_to_str(s->keyfile),
4330 c_write_str(ssh, msgbuf);
4332 s->publickey_blob = NULL;
4336 logeventf(ssh, "Unable to use this key file (%s)",
4337 key_type_to_str(keytype));
4338 msgbuf = dupprintf("Unable to use key file \"%.150s\""
4340 filename_to_str(s->keyfile),
4341 key_type_to_str(keytype));
4342 c_write_str(ssh, msgbuf);
4344 s->publickey_blob = NULL;
4347 s->publickey_blob = NULL;
4349 while (pktin->type == SSH1_SMSG_FAILURE) {
4350 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
4352 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
4354 * Attempt RSA authentication using Pageant.
4360 logevent("Pageant is running. Requesting keys.");
4362 /* Request the keys held by the agent. */
4363 PUT_32BIT(s->request, 1);
4364 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
4365 if (!agent_query(s->request, 5, &r, &s->responselen,
4366 ssh_agent_callback, ssh)) {
4370 bombout(("Unexpected data from server while waiting"
4371 " for agent response"));
4374 } while (pktin || inlen > 0);
4375 r = ssh->agent_response;
4376 s->responselen = ssh->agent_response_len;
4378 s->response = (unsigned char *) r;
4379 if (s->response && s->responselen >= 5 &&
4380 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
4381 s->p = s->response + 5;
4382 s->nkeys = toint(GET_32BIT(s->p));
4384 logeventf(ssh, "Pageant reported negative key count %d",
4389 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
4390 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
4391 unsigned char *pkblob = s->p;
4395 do { /* do while (0) to make breaking easy */
4396 n = ssh1_read_bignum
4397 (s->p, toint(s->responselen-(s->p-s->response)),
4402 n = ssh1_read_bignum
4403 (s->p, toint(s->responselen-(s->p-s->response)),
4408 if (s->responselen - (s->p-s->response) < 4)
4410 s->commentlen = toint(GET_32BIT(s->p));
4412 if (s->commentlen < 0 ||
4413 toint(s->responselen - (s->p-s->response)) <
4416 s->commentp = (char *)s->p;
4417 s->p += s->commentlen;
4421 logevent("Pageant key list packet was truncated");
4425 if (s->publickey_blob) {
4426 if (!memcmp(pkblob, s->publickey_blob,
4427 s->publickey_bloblen)) {
4428 logeventf(ssh, "Pageant key #%d matches "
4429 "configured key file", s->keyi);
4430 s->tried_publickey = 1;
4432 /* Skip non-configured key */
4435 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
4436 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4437 PKT_BIGNUM, s->key.modulus, PKT_END);
4439 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4440 logevent("Key refused");
4443 logevent("Received RSA challenge");
4444 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4445 bombout(("Server's RSA challenge was badly formatted"));
4450 char *agentreq, *q, *ret;
4453 len = 1 + 4; /* message type, bit count */
4454 len += ssh1_bignum_length(s->key.exponent);
4455 len += ssh1_bignum_length(s->key.modulus);
4456 len += ssh1_bignum_length(s->challenge);
4457 len += 16; /* session id */
4458 len += 4; /* response format */
4459 agentreq = snewn(4 + len, char);
4460 PUT_32BIT(agentreq, len);
4462 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
4463 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
4465 q += ssh1_write_bignum(q, s->key.exponent);
4466 q += ssh1_write_bignum(q, s->key.modulus);
4467 q += ssh1_write_bignum(q, s->challenge);
4468 memcpy(q, s->session_id, 16);
4470 PUT_32BIT(q, 1); /* response format */
4471 if (!agent_query(agentreq, len + 4, &vret, &retlen,
4472 ssh_agent_callback, ssh)) {
4477 bombout(("Unexpected data from server"
4478 " while waiting for agent"
4482 } while (pktin || inlen > 0);
4483 vret = ssh->agent_response;
4484 retlen = ssh->agent_response_len;
4489 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
4490 logevent("Sending Pageant's response");
4491 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4492 PKT_DATA, ret + 5, 16,
4496 if (pktin->type == SSH1_SMSG_SUCCESS) {
4498 ("Pageant's response accepted");
4499 if (flags & FLAG_VERBOSE) {
4500 c_write_str(ssh, "Authenticated using"
4502 c_write(ssh, s->commentp,
4504 c_write_str(ssh, "\" from agent\r\n");
4509 ("Pageant's response not accepted");
4512 ("Pageant failed to answer challenge");
4516 logevent("No reply received from Pageant");
4519 freebn(s->key.exponent);
4520 freebn(s->key.modulus);
4521 freebn(s->challenge);
4526 if (s->publickey_blob && !s->tried_publickey)
4527 logevent("Configured key file not in Pageant");
4529 logevent("Failed to get reply from Pageant");
4534 if (s->publickey_blob && s->privatekey_available &&
4535 !s->tried_publickey) {
4537 * Try public key authentication with the specified
4540 int got_passphrase; /* need not be kept over crReturn */
4541 if (flags & FLAG_VERBOSE)
4542 c_write_str(ssh, "Trying public key authentication.\r\n");
4543 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4544 logeventf(ssh, "Trying public key \"%s\"",
4545 filename_to_str(s->keyfile));
4546 s->tried_publickey = 1;
4547 got_passphrase = FALSE;
4548 while (!got_passphrase) {
4550 * Get a passphrase, if necessary.
4552 char *passphrase = NULL; /* only written after crReturn */
4554 if (!s->privatekey_encrypted) {
4555 if (flags & FLAG_VERBOSE)
4556 c_write_str(ssh, "No passphrase required.\r\n");
4559 int ret; /* need not be kept over crReturn */
4560 s->cur_prompt = new_prompts(ssh->frontend);
4561 s->cur_prompt->to_server = FALSE;
4562 s->cur_prompt->name = dupstr("SSH key passphrase");
4563 add_prompt(s->cur_prompt,
4564 dupprintf("Passphrase for key \"%.100s\": ",
4565 s->publickey_comment), FALSE);
4566 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4569 crWaitUntil(!pktin);
4570 ret = get_userpass_input(s->cur_prompt, in, inlen);
4574 /* Failed to get a passphrase. Terminate. */
4575 free_prompts(s->cur_prompt);
4576 ssh_disconnect(ssh, NULL, "Unable to authenticate",
4580 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
4581 free_prompts(s->cur_prompt);
4584 * Try decrypting key with passphrase.
4586 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
4587 ret = loadrsakey(s->keyfile, &s->key, passphrase,
4590 smemclr(passphrase, strlen(passphrase));
4594 /* Correct passphrase. */
4595 got_passphrase = TRUE;
4596 } else if (ret == 0) {
4597 c_write_str(ssh, "Couldn't load private key from ");
4598 c_write_str(ssh, filename_to_str(s->keyfile));
4599 c_write_str(ssh, " (");
4600 c_write_str(ssh, error);
4601 c_write_str(ssh, ").\r\n");
4602 got_passphrase = FALSE;
4603 break; /* go and try something else */
4604 } else if (ret == -1) {
4605 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
4606 got_passphrase = FALSE;
4609 assert(0 && "unexpected return from loadrsakey()");
4610 got_passphrase = FALSE; /* placate optimisers */
4614 if (got_passphrase) {
4617 * Send a public key attempt.
4619 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
4620 PKT_BIGNUM, s->key.modulus, PKT_END);
4623 if (pktin->type == SSH1_SMSG_FAILURE) {
4624 c_write_str(ssh, "Server refused our public key.\r\n");
4625 continue; /* go and try something else */
4627 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
4628 bombout(("Bizarre response to offer of public key"));
4634 unsigned char buffer[32];
4635 Bignum challenge, response;
4637 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
4638 bombout(("Server's RSA challenge was badly formatted"));
4641 response = rsadecrypt(challenge, &s->key);
4642 freebn(s->key.private_exponent);/* burn the evidence */
4644 for (i = 0; i < 32; i++) {
4645 buffer[i] = bignum_byte(response, 31 - i);
4649 MD5Update(&md5c, buffer, 32);
4650 MD5Update(&md5c, s->session_id, 16);
4651 MD5Final(buffer, &md5c);
4653 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
4654 PKT_DATA, buffer, 16, PKT_END);
4661 if (pktin->type == SSH1_SMSG_FAILURE) {
4662 if (flags & FLAG_VERBOSE)
4663 c_write_str(ssh, "Failed to authenticate with"
4664 " our public key.\r\n");
4665 continue; /* go and try something else */
4666 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4667 bombout(("Bizarre response to RSA authentication response"));
4671 break; /* we're through! */
4677 * Otherwise, try various forms of password-like authentication.
4679 s->cur_prompt = new_prompts(ssh->frontend);
4681 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4682 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
4683 !s->tis_auth_refused) {
4684 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
4685 logevent("Requested TIS authentication");
4686 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
4688 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
4689 logevent("TIS authentication declined");
4690 if (flags & FLAG_INTERACTIVE)
4691 c_write_str(ssh, "TIS authentication refused.\r\n");
4692 s->tis_auth_refused = 1;
4697 char *instr_suf, *prompt;
4699 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4701 bombout(("TIS challenge packet was badly formed"));
4704 logevent("Received TIS challenge");
4705 s->cur_prompt->to_server = TRUE;
4706 s->cur_prompt->name = dupstr("SSH TIS authentication");
4707 /* Prompt heuristic comes from OpenSSH */
4708 if (memchr(challenge, '\n', challengelen)) {
4709 instr_suf = dupstr("");
4710 prompt = dupprintf("%.*s", challengelen, challenge);
4712 instr_suf = dupprintf("%.*s", challengelen, challenge);
4713 prompt = dupstr("Response: ");
4715 s->cur_prompt->instruction =
4716 dupprintf("Using TIS authentication.%s%s",
4717 (*instr_suf) ? "\n" : "",
4719 s->cur_prompt->instr_reqd = TRUE;
4720 add_prompt(s->cur_prompt, prompt, FALSE);
4724 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
4725 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
4726 !s->ccard_auth_refused) {
4727 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
4728 logevent("Requested CryptoCard authentication");
4729 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
4731 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
4732 logevent("CryptoCard authentication declined");
4733 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
4734 s->ccard_auth_refused = 1;
4739 char *instr_suf, *prompt;
4741 ssh_pkt_getstring(pktin, &challenge, &challengelen);
4743 bombout(("CryptoCard challenge packet was badly formed"));
4746 logevent("Received CryptoCard challenge");
4747 s->cur_prompt->to_server = TRUE;
4748 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4749 s->cur_prompt->name_reqd = FALSE;
4750 /* Prompt heuristic comes from OpenSSH */
4751 if (memchr(challenge, '\n', challengelen)) {
4752 instr_suf = dupstr("");
4753 prompt = dupprintf("%.*s", challengelen, challenge);
4755 instr_suf = dupprintf("%.*s", challengelen, challenge);
4756 prompt = dupstr("Response: ");
4758 s->cur_prompt->instruction =
4759 dupprintf("Using CryptoCard authentication.%s%s",
4760 (*instr_suf) ? "\n" : "",
4762 s->cur_prompt->instr_reqd = TRUE;
4763 add_prompt(s->cur_prompt, prompt, FALSE);
4767 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4768 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4769 bombout(("No supported authentication methods available"));
4772 s->cur_prompt->to_server = TRUE;
4773 s->cur_prompt->name = dupstr("SSH password");
4774 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4775 ssh->username, ssh->savedhost),
4780 * Show password prompt, having first obtained it via a TIS
4781 * or CryptoCard exchange if we're doing TIS or CryptoCard
4785 int ret; /* need not be kept over crReturn */
4786 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4789 crWaitUntil(!pktin);
4790 ret = get_userpass_input(s->cur_prompt, in, inlen);
4795 * Failed to get a password (for example
4796 * because one was supplied on the command line
4797 * which has already failed to work). Terminate.
4799 free_prompts(s->cur_prompt);
4800 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4805 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
4807 * Defence against traffic analysis: we send a
4808 * whole bunch of packets containing strings of
4809 * different lengths. One of these strings is the
4810 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4811 * The others are all random data in
4812 * SSH1_MSG_IGNORE packets. This way a passive
4813 * listener can't tell which is the password, and
4814 * hence can't deduce the password length.
4816 * Anybody with a password length greater than 16
4817 * bytes is going to have enough entropy in their
4818 * password that a listener won't find it _that_
4819 * much help to know how long it is. So what we'll
4822 * - if password length < 16, we send 15 packets
4823 * containing string lengths 1 through 15
4825 * - otherwise, we let N be the nearest multiple
4826 * of 8 below the password length, and send 8
4827 * packets containing string lengths N through
4828 * N+7. This won't obscure the order of
4829 * magnitude of the password length, but it will
4830 * introduce a bit of extra uncertainty.
4832 * A few servers can't deal with SSH1_MSG_IGNORE, at
4833 * least in this context. For these servers, we need
4834 * an alternative defence. We make use of the fact
4835 * that the password is interpreted as a C string:
4836 * so we can append a NUL, then some random data.
4838 * A few servers can deal with neither SSH1_MSG_IGNORE
4839 * here _nor_ a padded password string.
4840 * For these servers we are left with no defences
4841 * against password length sniffing.
4843 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4844 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4846 * The server can deal with SSH1_MSG_IGNORE, so
4847 * we can use the primary defence.
4849 int bottom, top, pwlen, i;
4852 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4854 bottom = 0; /* zero length passwords are OK! :-) */
4857 bottom = pwlen & ~7;
4861 assert(pwlen >= bottom && pwlen <= top);
4863 randomstr = snewn(top + 1, char);
4865 for (i = bottom; i <= top; i++) {
4867 defer_packet(ssh, s->pwpkt_type,
4868 PKT_STR,s->cur_prompt->prompts[0]->result,
4871 for (j = 0; j < i; j++) {
4873 randomstr[j] = random_byte();
4874 } while (randomstr[j] == '\0');
4876 randomstr[i] = '\0';
4877 defer_packet(ssh, SSH1_MSG_IGNORE,
4878 PKT_STR, randomstr, PKT_END);
4881 logevent("Sending password with camouflage packets");
4882 ssh_pkt_defersend(ssh);
4885 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4887 * The server can't deal with SSH1_MSG_IGNORE
4888 * but can deal with padded passwords, so we
4889 * can use the secondary defence.
4895 len = strlen(s->cur_prompt->prompts[0]->result);
4896 if (len < sizeof(string)) {
4898 strcpy(string, s->cur_prompt->prompts[0]->result);
4899 len++; /* cover the zero byte */
4900 while (len < sizeof(string)) {
4901 string[len++] = (char) random_byte();
4904 ss = s->cur_prompt->prompts[0]->result;
4906 logevent("Sending length-padded password");
4907 send_packet(ssh, s->pwpkt_type,
4908 PKT_INT, len, PKT_DATA, ss, len,
4912 * The server is believed unable to cope with
4913 * any of our password camouflage methods.
4916 len = strlen(s->cur_prompt->prompts[0]->result);
4917 logevent("Sending unpadded password");
4918 send_packet(ssh, s->pwpkt_type,
4920 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4924 send_packet(ssh, s->pwpkt_type,
4925 PKT_STR, s->cur_prompt->prompts[0]->result,
4928 logevent("Sent password");
4929 free_prompts(s->cur_prompt);
4931 if (pktin->type == SSH1_SMSG_FAILURE) {
4932 if (flags & FLAG_VERBOSE)
4933 c_write_str(ssh, "Access denied\r\n");
4934 logevent("Authentication refused");
4935 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4936 bombout(("Strange packet received, type %d", pktin->type));
4942 if (s->publickey_blob) {
4943 sfree(s->publickey_blob);
4944 sfree(s->publickey_comment);
4947 logevent("Authentication successful");
4952 static void ssh_channel_try_eof(struct ssh_channel *c)
4955 assert(c->pending_eof); /* precondition for calling us */
4957 return; /* can't close: not even opened yet */
4958 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4959 return; /* can't send EOF: pending outgoing data */
4961 c->pending_eof = FALSE; /* we're about to send it */
4962 if (ssh->version == 1) {
4963 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4965 c->closes |= CLOSES_SENT_EOF;
4967 struct Packet *pktout;
4968 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4969 ssh2_pkt_adduint32(pktout, c->remoteid);
4970 ssh2_pkt_send(ssh, pktout);
4971 c->closes |= CLOSES_SENT_EOF;
4972 ssh2_channel_check_close(c);
4976 Conf *sshfwd_get_conf(struct ssh_channel *c)
4982 void sshfwd_write_eof(struct ssh_channel *c)
4986 if (ssh->state == SSH_STATE_CLOSED)
4989 if (c->closes & CLOSES_SENT_EOF)
4992 c->pending_eof = TRUE;
4993 ssh_channel_try_eof(c);
4996 void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
5001 if (ssh->state == SSH_STATE_CLOSED)
5004 reason = dupprintf("due to local error: %s", err);
5005 ssh_channel_close_local(c, reason);
5007 c->pending_eof = FALSE; /* this will confuse a zombie channel */
5009 ssh2_channel_check_close(c);
5012 int sshfwd_write(struct ssh_channel *c, char *buf, int len)
5016 if (ssh->state == SSH_STATE_CLOSED)
5019 return ssh_send_channel_data(c, buf, len);
5022 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
5026 if (ssh->state == SSH_STATE_CLOSED)
5029 ssh_channel_unthrottle(c, bufsize);
5032 static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
5034 struct queued_handler *qh = ssh->qhead;
5038 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
5041 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
5042 ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
5045 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
5046 ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
5050 ssh->qhead = qh->next;
5052 if (ssh->qhead->msg1 > 0) {
5053 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5054 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
5056 if (ssh->qhead->msg2 > 0) {
5057 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5058 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
5061 ssh->qhead = ssh->qtail = NULL;
5064 qh->handler(ssh, pktin, qh->ctx);
5069 static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
5070 chandler_fn_t handler, void *ctx)
5072 struct queued_handler *qh;
5074 qh = snew(struct queued_handler);
5077 qh->handler = handler;
5081 if (ssh->qtail == NULL) {
5085 ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
5086 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
5089 ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
5090 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
5093 ssh->qtail->next = qh;
5098 static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
5100 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
5102 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
5103 SSH2_MSG_REQUEST_SUCCESS)) {
5104 logeventf(ssh, "Remote port forwarding from %s enabled",
5107 logeventf(ssh, "Remote port forwarding from %s refused",
5110 rpf = del234(ssh->rportfwds, pf);
5112 pf->pfrec->remote = NULL;
5117 int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
5120 struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
5123 pf->share_ctx = share_ctx;
5124 pf->shost = dupstr(shost);
5126 pf->sportdesc = NULL;
5127 if (!ssh->rportfwds) {
5128 assert(ssh->version == 2);
5129 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5131 if (add234(ssh->rportfwds, pf) != pf) {
5139 static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
5142 share_got_pkt_from_server(ctx, pktin->type,
5143 pktin->body, pktin->length);
5146 void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
5148 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
5149 ssh_sharing_global_request_response, share_ctx);
5152 static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
5154 struct ssh_portfwd *epf;
5158 if (!ssh->portfwds) {
5159 ssh->portfwds = newtree234(ssh_portcmp);
5162 * Go through the existing port forwardings and tag them
5163 * with status==DESTROY. Any that we want to keep will be
5164 * re-enabled (status==KEEP) as we go through the
5165 * configuration and find out which bits are the same as
5168 struct ssh_portfwd *epf;
5170 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5171 epf->status = DESTROY;
5174 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
5176 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
5177 char *kp, *kp2, *vp, *vp2;
5178 char address_family, type;
5179 int sport,dport,sserv,dserv;
5180 char *sports, *dports, *saddr, *host;
5184 address_family = 'A';
5186 if (*kp == 'A' || *kp == '4' || *kp == '6')
5187 address_family = *kp++;
5188 if (*kp == 'L' || *kp == 'R')
5191 if ((kp2 = host_strchr(kp, ':')) != NULL) {
5193 * There's a colon in the middle of the source port
5194 * string, which means that the part before it is
5195 * actually a source address.
5197 char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
5198 saddr = host_strduptrim(saddr_tmp);
5205 sport = atoi(sports);
5209 sport = net_service_lookup(sports);
5211 logeventf(ssh, "Service lookup failed for source"
5212 " port \"%s\"", sports);
5216 if (type == 'L' && !strcmp(val, "D")) {
5217 /* dynamic forwarding */
5224 /* ordinary forwarding */
5226 vp2 = vp + host_strcspn(vp, ":");
5227 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
5231 dport = atoi(dports);
5235 dport = net_service_lookup(dports);
5237 logeventf(ssh, "Service lookup failed for destination"
5238 " port \"%s\"", dports);
5243 if (sport && dport) {
5244 /* Set up a description of the source port. */
5245 struct ssh_portfwd *pfrec, *epfrec;
5247 pfrec = snew(struct ssh_portfwd);
5249 pfrec->saddr = saddr;
5250 pfrec->sserv = sserv ? dupstr(sports) : NULL;
5251 pfrec->sport = sport;
5252 pfrec->daddr = host;
5253 pfrec->dserv = dserv ? dupstr(dports) : NULL;
5254 pfrec->dport = dport;
5255 pfrec->local = NULL;
5256 pfrec->remote = NULL;
5257 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
5258 address_family == '6' ? ADDRTYPE_IPV6 :
5261 epfrec = add234(ssh->portfwds, pfrec);
5262 if (epfrec != pfrec) {
5263 if (epfrec->status == DESTROY) {
5265 * We already have a port forwarding up and running
5266 * with precisely these parameters. Hence, no need
5267 * to do anything; simply re-tag the existing one
5270 epfrec->status = KEEP;
5273 * Anything else indicates that there was a duplicate
5274 * in our input, which we'll silently ignore.
5276 free_portfwd(pfrec);
5278 pfrec->status = CREATE;
5287 * Now go through and destroy any port forwardings which were
5290 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5291 if (epf->status == DESTROY) {
5294 message = dupprintf("%s port forwarding from %s%s%d",
5295 epf->type == 'L' ? "local" :
5296 epf->type == 'R' ? "remote" : "dynamic",
5297 epf->saddr ? epf->saddr : "",
5298 epf->saddr ? ":" : "",
5301 if (epf->type != 'D') {
5302 char *msg2 = dupprintf("%s to %s:%d", message,
5303 epf->daddr, epf->dport);
5308 logeventf(ssh, "Cancelling %s", message);
5311 /* epf->remote or epf->local may be NULL if setting up a
5312 * forwarding failed. */
5314 struct ssh_rportfwd *rpf = epf->remote;
5315 struct Packet *pktout;
5318 * Cancel the port forwarding at the server
5321 if (ssh->version == 1) {
5323 * We cannot cancel listening ports on the
5324 * server side in SSH-1! There's no message
5325 * to support it. Instead, we simply remove
5326 * the rportfwd record from the local end
5327 * so that any connections the server tries
5328 * to make on it are rejected.
5331 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5332 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
5333 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
5335 ssh2_pkt_addstring(pktout, epf->saddr);
5336 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5337 /* XXX: rport_acceptall may not represent
5338 * what was used to open the original connection,
5339 * since it's reconfigurable. */
5340 ssh2_pkt_addstring(pktout, "");
5342 ssh2_pkt_addstring(pktout, "localhost");
5344 ssh2_pkt_adduint32(pktout, epf->sport);
5345 ssh2_pkt_send(ssh, pktout);
5348 del234(ssh->rportfwds, rpf);
5350 } else if (epf->local) {
5351 pfl_terminate(epf->local);
5354 delpos234(ssh->portfwds, i);
5356 i--; /* so we don't skip one in the list */
5360 * And finally, set up any new port forwardings (status==CREATE).
5362 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
5363 if (epf->status == CREATE) {
5364 char *sportdesc, *dportdesc;
5365 sportdesc = dupprintf("%s%s%s%s%d%s",
5366 epf->saddr ? epf->saddr : "",
5367 epf->saddr ? ":" : "",
5368 epf->sserv ? epf->sserv : "",
5369 epf->sserv ? "(" : "",
5371 epf->sserv ? ")" : "");
5372 if (epf->type == 'D') {
5375 dportdesc = dupprintf("%s:%s%s%d%s",
5377 epf->dserv ? epf->dserv : "",
5378 epf->dserv ? "(" : "",
5380 epf->dserv ? ")" : "");
5383 if (epf->type == 'L') {
5384 char *err = pfl_listen(epf->daddr, epf->dport,
5385 epf->saddr, epf->sport,
5386 ssh, conf, &epf->local,
5387 epf->addressfamily);
5389 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
5390 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5391 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5392 sportdesc, dportdesc,
5393 err ? " failed: " : "", err ? err : "");
5396 } else if (epf->type == 'D') {
5397 char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
5398 ssh, conf, &epf->local,
5399 epf->addressfamily);
5401 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
5402 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
5403 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
5405 err ? " failed: " : "", err ? err : "");
5410 struct ssh_rportfwd *pf;
5413 * Ensure the remote port forwardings tree exists.
5415 if (!ssh->rportfwds) {
5416 if (ssh->version == 1)
5417 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
5419 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
5422 pf = snew(struct ssh_rportfwd);
5423 pf->share_ctx = NULL;
5424 pf->dhost = dupstr(epf->daddr);
5425 pf->dport = epf->dport;
5427 pf->shost = dupstr(epf->saddr);
5428 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
5429 pf->shost = dupstr("");
5431 pf->shost = dupstr("localhost");
5433 pf->sport = epf->sport;
5434 if (add234(ssh->rportfwds, pf) != pf) {
5435 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
5436 epf->daddr, epf->dport);
5439 logeventf(ssh, "Requesting remote port %s"
5440 " forward to %s", sportdesc, dportdesc);
5442 pf->sportdesc = sportdesc;
5447 if (ssh->version == 1) {
5448 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
5449 PKT_INT, epf->sport,
5450 PKT_STR, epf->daddr,
5451 PKT_INT, epf->dport,
5453 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
5455 ssh_rportfwd_succfail, pf);
5457 struct Packet *pktout;
5458 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
5459 ssh2_pkt_addstring(pktout, "tcpip-forward");
5460 ssh2_pkt_addbool(pktout, 1);/* want reply */
5461 ssh2_pkt_addstring(pktout, pf->shost);
5462 ssh2_pkt_adduint32(pktout, pf->sport);
5463 ssh2_pkt_send(ssh, pktout);
5465 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
5466 SSH2_MSG_REQUEST_FAILURE,
5467 ssh_rportfwd_succfail, pf);
5476 static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
5479 int stringlen, bufsize;
5481 ssh_pkt_getstring(pktin, &string, &stringlen);
5482 if (string == NULL) {
5483 bombout(("Incoming terminal data packet was badly formed"));
5487 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
5489 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
5490 ssh->v1_stdout_throttling = 1;
5491 ssh_throttle_conn(ssh, +1);
5495 static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
5497 /* Remote side is trying to open a channel to talk to our
5498 * X-Server. Give them back a local channel number. */
5499 struct ssh_channel *c;
5500 int remoteid = ssh_pkt_getuint32(pktin);
5502 logevent("Received X11 connect request");
5503 /* Refuse if X11 forwarding is disabled. */
5504 if (!ssh->X11_fwd_enabled) {
5505 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5506 PKT_INT, remoteid, PKT_END);
5507 logevent("Rejected X11 connect request");
5509 c = snew(struct ssh_channel);
5512 ssh_channel_init(c);
5513 c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
5514 c->remoteid = remoteid;
5515 c->halfopen = FALSE;
5516 c->type = CHAN_X11; /* identify channel type */
5517 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5518 PKT_INT, c->remoteid, PKT_INT,
5519 c->localid, PKT_END);
5520 logevent("Opened X11 forward channel");
5524 static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
5526 /* Remote side is trying to open a channel to talk to our
5527 * agent. Give them back a local channel number. */
5528 struct ssh_channel *c;
5529 int remoteid = ssh_pkt_getuint32(pktin);
5531 /* Refuse if agent forwarding is disabled. */
5532 if (!ssh->agentfwd_enabled) {
5533 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5534 PKT_INT, remoteid, PKT_END);
5536 c = snew(struct ssh_channel);
5538 ssh_channel_init(c);
5539 c->remoteid = remoteid;
5540 c->halfopen = FALSE;
5541 c->type = CHAN_AGENT; /* identify channel type */
5542 c->u.a.lensofar = 0;
5543 c->u.a.message = NULL;
5544 c->u.a.outstanding_requests = 0;
5545 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5546 PKT_INT, c->remoteid, PKT_INT, c->localid,
5551 static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
5553 /* Remote side is trying to open a channel to talk to a
5554 * forwarded port. Give them back a local channel number. */
5555 struct ssh_rportfwd pf, *pfp;
5561 remoteid = ssh_pkt_getuint32(pktin);
5562 ssh_pkt_getstring(pktin, &host, &hostsize);
5563 port = ssh_pkt_getuint32(pktin);
5565 pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
5567 pfp = find234(ssh->rportfwds, &pf, NULL);
5570 logeventf(ssh, "Rejected remote port open request for %s:%d",
5572 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5573 PKT_INT, remoteid, PKT_END);
5575 struct ssh_channel *c = snew(struct ssh_channel);
5578 logeventf(ssh, "Received remote port open request for %s:%d",
5580 err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
5581 c, ssh->conf, pfp->pfrec->addressfamily);
5583 logeventf(ssh, "Port open failed: %s", err);
5586 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
5587 PKT_INT, remoteid, PKT_END);
5589 ssh_channel_init(c);
5590 c->remoteid = remoteid;
5591 c->halfopen = FALSE;
5592 c->type = CHAN_SOCKDATA; /* identify channel type */
5593 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
5594 PKT_INT, c->remoteid, PKT_INT,
5595 c->localid, PKT_END);
5596 logevent("Forwarded port opened successfully");
5603 static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5605 struct ssh_channel *c;
5607 c = ssh_channel_msg(ssh, pktin);
5608 if (c && c->type == CHAN_SOCKDATA) {
5609 c->remoteid = ssh_pkt_getuint32(pktin);
5610 c->halfopen = FALSE;
5611 c->throttling_conn = 0;
5612 pfd_confirm(c->u.pfd.pf);
5615 if (c && c->pending_eof) {
5617 * We have a pending close on this channel,
5618 * which we decided on before the server acked
5619 * the channel open. So now we know the
5620 * remoteid, we can close it again.
5622 ssh_channel_try_eof(c);
5626 static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5628 struct ssh_channel *c;
5630 c = ssh_channel_msg(ssh, pktin);
5631 if (c && c->type == CHAN_SOCKDATA) {
5632 logevent("Forwarded connection refused by server");
5633 pfd_close(c->u.pfd.pf);
5634 del234(ssh->channels, c);
5639 static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
5641 /* Remote side closes a channel. */
5642 struct ssh_channel *c;
5644 c = ssh_channel_msg(ssh, pktin);
5647 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE) {
5649 * Received CHANNEL_CLOSE, which we translate into
5652 ssh_channel_got_eof(c);
5655 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
5656 !(c->closes & CLOSES_RCVD_CLOSE)) {
5658 if (!(c->closes & CLOSES_SENT_EOF)) {
5659 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %u"
5660 " for which we never sent CHANNEL_CLOSE\n",
5664 c->closes |= CLOSES_RCVD_CLOSE;
5667 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
5668 !(c->closes & CLOSES_SENT_CLOSE)) {
5669 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
5670 PKT_INT, c->remoteid, PKT_END);
5671 c->closes |= CLOSES_SENT_CLOSE;
5674 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
5675 ssh_channel_destroy(c);
5680 * Handle incoming data on an SSH-1 or SSH-2 agent-forwarding channel.
5682 static int ssh_agent_channel_data(struct ssh_channel *c, char *data,
5685 while (length > 0) {
5686 if (c->u.a.lensofar < 4) {
5687 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)length);
5688 memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
5691 c->u.a.lensofar += l;
5693 if (c->u.a.lensofar == 4) {
5694 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
5695 c->u.a.message = snewn(c->u.a.totallen, unsigned char);
5696 memcpy(c->u.a.message, c->u.a.msglen, 4);
5698 if (c->u.a.lensofar >= 4 && length > 0) {
5699 unsigned int l = min(c->u.a.totallen - c->u.a.lensofar,
5701 memcpy(c->u.a.message + c->u.a.lensofar, data, l);
5704 c->u.a.lensofar += l;
5706 if (c->u.a.lensofar == c->u.a.totallen) {
5709 c->u.a.outstanding_requests++;
5710 if (agent_query(c->u.a.message, c->u.a.totallen, &reply, &replylen,
5711 ssh_agentf_callback, c))
5712 ssh_agentf_callback(c, reply, replylen);
5713 sfree(c->u.a.message);
5714 c->u.a.message = NULL;
5715 c->u.a.lensofar = 0;
5718 return 0; /* agent channels never back up */
5721 static int ssh_channel_data(struct ssh_channel *c, int is_stderr,
5722 char *data, int length)
5725 case CHAN_MAINSESSION:
5726 return from_backend(c->ssh->frontend, is_stderr, data, length);
5728 return x11_send(c->u.x11.xconn, data, length);
5730 return pfd_send(c->u.pfd.pf, data, length);
5732 return ssh_agent_channel_data(c, data, length);
5737 static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
5739 /* Data sent down one of our channels. */
5742 struct ssh_channel *c;
5744 c = ssh_channel_msg(ssh, pktin);
5745 ssh_pkt_getstring(pktin, &p, &len);
5748 int bufsize = ssh_channel_data(c, FALSE, p, len);
5749 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5750 c->throttling_conn = 1;
5751 ssh_throttle_conn(ssh, +1);
5756 static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5758 ssh->exitcode = ssh_pkt_getuint32(pktin);
5759 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
5760 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5762 * In case `helpful' firewalls or proxies tack
5763 * extra human-readable text on the end of the
5764 * session which we might mistake for another
5765 * encrypted packet, we close the session once
5766 * we've sent EXIT_CONFIRMATION.
5768 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
5771 /* Helper function to deal with sending tty modes for REQUEST_PTY */
5772 static void ssh1_send_ttymode(void *data,
5773 const struct ssh_ttymode *mode, char *val)
5775 struct Packet *pktout = (struct Packet *)data;
5776 unsigned int arg = 0;
5778 switch (mode->type) {
5780 arg = ssh_tty_parse_specchar(val);
5783 arg = ssh_tty_parse_boolean(val);
5786 ssh2_pkt_addbyte(pktout, mode->opcode);
5787 ssh2_pkt_addbyte(pktout, arg);
5790 int ssh_agent_forwarding_permitted(Ssh ssh)
5792 return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
5795 static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
5796 struct Packet *pktin)
5798 crBegin(ssh->do_ssh1_connection_crstate);
5800 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5801 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5802 ssh1_smsg_stdout_stderr_data;
5804 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5805 ssh1_msg_channel_open_confirmation;
5806 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5807 ssh1_msg_channel_open_failure;
5808 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5809 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5810 ssh1_msg_channel_close;
5811 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5812 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5814 if (ssh_agent_forwarding_permitted(ssh)) {
5815 logevent("Requesting agent forwarding");
5816 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
5820 if (pktin->type != SSH1_SMSG_SUCCESS
5821 && pktin->type != SSH1_SMSG_FAILURE) {
5822 bombout(("Protocol confusion"));
5824 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5825 logevent("Agent forwarding refused");
5827 logevent("Agent forwarding enabled");
5828 ssh->agentfwd_enabled = TRUE;
5829 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
5833 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
5835 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5837 if (!ssh->x11disp) {
5838 /* FIXME: return an error message from x11_setup_display */
5839 logevent("X11 forwarding not enabled: unable to"
5840 " initialise X display");
5842 ssh->x11auth = x11_invent_fake_auth
5843 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
5844 ssh->x11auth->disp = ssh->x11disp;
5846 logevent("Requesting X11 forwarding");
5847 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5848 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5849 PKT_STR, ssh->x11auth->protoname,
5850 PKT_STR, ssh->x11auth->datastring,
5851 PKT_INT, ssh->x11disp->screennum,
5854 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
5855 PKT_STR, ssh->x11auth->protoname,
5856 PKT_STR, ssh->x11auth->datastring,
5862 if (pktin->type != SSH1_SMSG_SUCCESS
5863 && pktin->type != SSH1_SMSG_FAILURE) {
5864 bombout(("Protocol confusion"));
5866 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5867 logevent("X11 forwarding refused");
5869 logevent("X11 forwarding enabled");
5870 ssh->X11_fwd_enabled = TRUE;
5871 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
5876 ssh_setup_portfwd(ssh, ssh->conf);
5877 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
5879 if (!conf_get_int(ssh->conf, CONF_nopty)) {
5881 /* Unpick the terminal-speed string. */
5882 /* XXX perhaps we should allow no speeds to be sent. */
5883 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
5884 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
5885 /* Send the pty request. */
5886 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
5887 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
5888 ssh_pkt_adduint32(pkt, ssh->term_height);
5889 ssh_pkt_adduint32(pkt, ssh->term_width);
5890 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5891 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
5892 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
5893 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5894 ssh_pkt_adduint32(pkt, ssh->ispeed);
5895 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5896 ssh_pkt_adduint32(pkt, ssh->ospeed);
5897 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5899 ssh->state = SSH_STATE_INTERMED;
5903 if (pktin->type != SSH1_SMSG_SUCCESS
5904 && pktin->type != SSH1_SMSG_FAILURE) {
5905 bombout(("Protocol confusion"));
5907 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5908 c_write_str(ssh, "Server refused to allocate pty\r\n");
5909 ssh->editing = ssh->echoing = 1;
5911 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5912 ssh->ospeed, ssh->ispeed);
5913 ssh->got_pty = TRUE;
5916 ssh->editing = ssh->echoing = 1;
5919 if (conf_get_int(ssh->conf, CONF_compression)) {
5920 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
5924 if (pktin->type != SSH1_SMSG_SUCCESS
5925 && pktin->type != SSH1_SMSG_FAILURE) {
5926 bombout(("Protocol confusion"));
5928 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5929 c_write_str(ssh, "Server refused to compress\r\n");
5931 logevent("Started compression");
5932 ssh->v1_compressing = TRUE;
5933 ssh->cs_comp_ctx = zlib_compress_init();
5934 logevent("Initialised zlib (RFC1950) compression");
5935 ssh->sc_comp_ctx = zlib_decompress_init();
5936 logevent("Initialised zlib (RFC1950) decompression");
5940 * Start the shell or command.
5942 * Special case: if the first-choice command is an SSH-2
5943 * subsystem (hence not usable here) and the second choice
5944 * exists, we fall straight back to that.
5947 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
5949 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5950 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5951 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
5952 ssh->fallback_cmd = TRUE;
5955 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
5957 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
5958 logevent("Started session");
5961 ssh->state = SSH_STATE_SESSION;
5962 if (ssh->size_needed)
5963 ssh_size(ssh, ssh->term_width, ssh->term_height);
5964 if (ssh->eof_needed)
5965 ssh_special(ssh, TS_EOF);
5968 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
5970 ssh->channels = newtree234(ssh_channelcmp);
5974 * By this point, most incoming packets are already being
5975 * handled by the dispatch table, and we need only pay
5976 * attention to the unusual ones.
5981 if (pktin->type == SSH1_SMSG_SUCCESS) {
5982 /* may be from EXEC_SHELL on some servers */
5983 } else if (pktin->type == SSH1_SMSG_FAILURE) {
5984 /* may be from EXEC_SHELL on some servers
5985 * if no pty is available or in other odd cases. Ignore */
5987 bombout(("Strange packet received: type %d", pktin->type));
5992 int len = min(inlen, 512);
5993 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5994 PKT_INT, len, PKT_DATA, in, len,
6006 * Handle the top-level SSH-2 protocol.
6008 static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
6013 ssh_pkt_getstring(pktin, &msg, &msglen);
6014 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
6017 static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
6019 /* log reason code in disconnect message */
6023 ssh_pkt_getstring(pktin, &msg, &msglen);
6024 bombout(("Server sent disconnect message:\n\"%.*s\"",
6025 msglen, NULLTOEMPTY(msg)));
6028 static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
6030 /* Do nothing, because we're ignoring it! Duhh. */
6033 static void ssh1_protocol_setup(Ssh ssh)
6038 * Most messages are handled by the coroutines.
6040 for (i = 0; i < 256; i++)
6041 ssh->packet_dispatch[i] = NULL;
6044 * These special message types we install handlers for.
6046 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
6047 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
6048 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
6051 static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
6052 struct Packet *pktin)
6054 const unsigned char *in = (const unsigned char *)vin;
6055 if (ssh->state == SSH_STATE_CLOSED)
6058 if (pktin && ssh->packet_dispatch[pktin->type]) {
6059 ssh->packet_dispatch[pktin->type](ssh, pktin);
6063 if (!ssh->protocol_initial_phase_done) {
6064 if (do_ssh1_login(ssh, in, inlen, pktin))
6065 ssh->protocol_initial_phase_done = TRUE;
6070 do_ssh1_connection(ssh, in, inlen, pktin);
6074 * Utility routines for decoding comma-separated strings in KEXINIT.
6076 static int first_in_commasep_string(char const *needle, char const *haystack,
6080 if (!needle || !haystack) /* protect against null pointers */
6082 needlen = strlen(needle);
6084 if (haylen >= needlen && /* haystack is long enough */
6085 !memcmp(needle, haystack, needlen) && /* initial match */
6086 (haylen == needlen || haystack[needlen] == ',')
6087 /* either , or EOS follows */
6093 static int in_commasep_string(char const *needle, char const *haystack,
6098 if (!needle || !haystack) /* protect against null pointers */
6101 * Is it at the start of the string?
6103 if (first_in_commasep_string(needle, haystack, haylen))
6106 * If not, search for the next comma and resume after that.
6107 * If no comma found, terminate.
6109 p = memchr(haystack, ',', haylen);
6111 /* + 1 to skip over comma */
6112 return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
6116 * Add a value to the comma-separated string at the end of the packet.
6118 static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
6120 if (pkt->length - pkt->savedpos > 0)
6121 ssh_pkt_addstring_str(pkt, ",");
6122 ssh_pkt_addstring_str(pkt, data);
6127 * SSH-2 key derivation (RFC 4253 section 7.2).
6129 static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
6130 char chr, int keylen)
6132 const struct ssh_hash *h = ssh->kex->hash;
6140 /* Round up to the next multiple of hash length. */
6141 keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
6143 key = snewn(keylen_padded, unsigned char);
6145 /* First hlen bytes. */
6147 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6148 hash_mpint(h, s, K);
6149 h->bytes(s, H, h->hlen);
6150 h->bytes(s, &chr, 1);
6151 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
6154 /* Subsequent blocks of hlen bytes. */
6155 if (keylen_padded > h->hlen) {
6159 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
6160 hash_mpint(h, s, K);
6161 h->bytes(s, H, h->hlen);
6163 for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
6164 h->bytes(s, key + offset - h->hlen, h->hlen);
6166 h->final(s2, key + offset);
6172 /* Now clear any extra bytes of key material beyond the length
6173 * we're officially returning, because the caller won't know to
6175 if (keylen_padded > keylen)
6176 smemclr(key + keylen, keylen_padded - keylen);
6182 * Structure for constructing KEXINIT algorithm lists.
6184 #define MAXKEXLIST 16
6185 struct kexinit_algorithm {
6189 const struct ssh_kex *kex;
6193 const struct ssh_signkey *hostkey;
6197 const struct ssh2_cipher *cipher;
6201 const struct ssh_mac *mac;
6204 const struct ssh_compress *comp;
6209 * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
6210 * If the algorithm is already in the list, return a pointer to its
6211 * entry, otherwise return an entry from the end of the list.
6212 * This assumes that every time a particular name is passed in, it
6213 * comes from the same string constant. If this isn't true, this
6214 * function may need to be rewritten to use strcmp() instead.
6216 static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
6217 *list, const char *name)
6221 for (i = 0; i < MAXKEXLIST; i++)
6222 if (list[i].name == NULL || list[i].name == name) {
6223 list[i].name = name;
6226 assert(!"No space in KEXINIT list");
6231 * Handle the SSH-2 transport layer.
6233 static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
6234 struct Packet *pktin)
6236 const unsigned char *in = (const unsigned char *)vin;
6238 KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
6239 KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
6242 const char * kexlist_descr[NKEXLIST] = {
6243 "key exchange algorithm", "host key algorithm",
6244 "client-to-server cipher", "server-to-client cipher",
6245 "client-to-server MAC", "server-to-client MAC",
6246 "client-to-server compression method",
6247 "server-to-client compression method" };
6248 struct do_ssh2_transport_state {
6250 int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
6251 Bignum p, g, e, f, K;
6254 int kex_init_value, kex_reply_value;
6255 const struct ssh_mac *const *maclist;
6257 const struct ssh2_cipher *cscipher_tobe;
6258 const struct ssh2_cipher *sccipher_tobe;
6259 const struct ssh_mac *csmac_tobe;
6260 const struct ssh_mac *scmac_tobe;
6261 int csmac_etm_tobe, scmac_etm_tobe;
6262 const struct ssh_compress *cscomp_tobe;
6263 const struct ssh_compress *sccomp_tobe;
6264 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
6265 int hostkeylen, siglen, rsakeylen;
6266 void *hkey; /* actual host key */
6267 void *rsakey; /* for RSA kex */
6268 void *eckey; /* for ECDH kex */
6269 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
6270 int n_preferred_kex;
6271 const struct ssh_kexes *preferred_kex[KEX_MAX];
6273 int preferred_hk[HK_MAX];
6274 int n_preferred_ciphers;
6275 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
6276 const struct ssh_compress *preferred_comp;
6277 int userauth_succeeded; /* for delayed compression */
6278 int pending_compression;
6279 int got_session_id, activated_authconn;
6280 struct Packet *pktout;
6284 struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
6286 crState(do_ssh2_transport_state);
6288 assert(!ssh->bare_connection);
6289 assert(ssh->version == 2);
6293 s->cscipher_tobe = s->sccipher_tobe = NULL;
6294 s->csmac_tobe = s->scmac_tobe = NULL;
6295 s->cscomp_tobe = s->sccomp_tobe = NULL;
6297 s->got_session_id = s->activated_authconn = FALSE;
6298 s->userauth_succeeded = FALSE;
6299 s->pending_compression = FALSE;
6302 * Be prepared to work around the buggy MAC problem.
6304 if (ssh->remote_bugs & BUG_SSH2_HMAC)
6305 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
6307 s->maclist = macs, s->nmacs = lenof(macs);
6310 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
6313 struct kexinit_algorithm *alg;
6316 * Set up the preferred key exchange. (NULL => warn below here)
6318 s->n_preferred_kex = 0;
6319 for (i = 0; i < KEX_MAX; i++) {
6320 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
6322 s->preferred_kex[s->n_preferred_kex++] =
6323 &ssh_diffiehellman_gex;
6326 s->preferred_kex[s->n_preferred_kex++] =
6327 &ssh_diffiehellman_group14;
6330 s->preferred_kex[s->n_preferred_kex++] =
6331 &ssh_diffiehellman_group1;
6334 s->preferred_kex[s->n_preferred_kex++] =
6338 s->preferred_kex[s->n_preferred_kex++] =
6342 /* Flag for later. Don't bother if it's the last in
6344 if (i < KEX_MAX - 1) {
6345 s->preferred_kex[s->n_preferred_kex++] = NULL;
6352 * Set up the preferred host key types. These are just the ids
6353 * in the enum in putty.h, so 'warn below here' is indicated
6356 s->n_preferred_hk = 0;
6357 for (i = 0; i < HK_MAX; i++) {
6358 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
6359 /* As above, don't bother with HK_WARN if it's last in the
6361 if (id != HK_WARN || i < HK_MAX - 1)
6362 s->preferred_hk[s->n_preferred_hk++] = id;
6366 * Set up the preferred ciphers. (NULL => warn below here)
6368 s->n_preferred_ciphers = 0;
6369 for (i = 0; i < CIPHER_MAX; i++) {
6370 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
6371 case CIPHER_BLOWFISH:
6372 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
6375 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
6376 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
6380 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
6383 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
6385 case CIPHER_ARCFOUR:
6386 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
6388 case CIPHER_CHACHA20:
6389 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
6392 /* Flag for later. Don't bother if it's the last in
6394 if (i < CIPHER_MAX - 1) {
6395 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
6402 * Set up preferred compression.
6404 if (conf_get_int(ssh->conf, CONF_compression))
6405 s->preferred_comp = &ssh_zlib;
6407 s->preferred_comp = &ssh_comp_none;
6410 * Enable queueing of outgoing auth- or connection-layer
6411 * packets while we are in the middle of a key exchange.
6413 ssh->queueing = TRUE;
6416 * Flag that KEX is in progress.
6418 ssh->kex_in_progress = TRUE;
6420 for (i = 0; i < NKEXLIST; i++)
6421 for (j = 0; j < MAXKEXLIST; j++)
6422 s->kexlists[i][j].name = NULL;
6423 /* List key exchange algorithms. */
6425 for (i = 0; i < s->n_preferred_kex; i++) {
6426 const struct ssh_kexes *k = s->preferred_kex[i];
6427 if (!k) warn = TRUE;
6428 else for (j = 0; j < k->nkexes; j++) {
6429 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
6431 alg->u.kex.kex = k->list[j];
6432 alg->u.kex.warn = warn;
6435 /* List server host key algorithms. */
6436 if (!s->got_session_id) {
6438 * In the first key exchange, we list all the algorithms
6439 * we're prepared to cope with, but prefer those algorithms
6440 * for which we have a host key for this host.
6442 * If the host key algorithm is below the warning
6443 * threshold, we warn even if we did already have a key
6444 * for it, on the basis that if the user has just
6445 * reconfigured that host key type to be warned about,
6446 * they surely _do_ want to be alerted that a server
6447 * they're actually connecting to is using it.
6450 for (i = 0; i < s->n_preferred_hk; i++) {
6451 if (s->preferred_hk[i] == HK_WARN)
6453 for (j = 0; j < lenof(hostkey_algs); j++) {
6454 if (hostkey_algs[j].id != s->preferred_hk[i])
6456 if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
6457 hostkey_algs[j].alg->keytype)) {
6458 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6459 hostkey_algs[j].alg->name);
6460 alg->u.hk.hostkey = hostkey_algs[j].alg;
6461 alg->u.hk.warn = warn;
6466 for (i = 0; i < s->n_preferred_hk; i++) {
6467 if (s->preferred_hk[i] == HK_WARN)
6469 for (j = 0; j < lenof(hostkey_algs); j++) {
6470 if (hostkey_algs[j].id != s->preferred_hk[i])
6472 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6473 hostkey_algs[j].alg->name);
6474 alg->u.hk.hostkey = hostkey_algs[j].alg;
6475 alg->u.hk.warn = warn;
6480 * In subsequent key exchanges, we list only the kex
6481 * algorithm that was selected in the first key exchange,
6482 * so that we keep getting the same host key and hence
6483 * don't have to interrupt the user's session to ask for
6487 alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
6488 ssh->hostkey->name);
6489 alg->u.hk.hostkey = ssh->hostkey;
6490 alg->u.hk.warn = FALSE;
6492 /* List encryption algorithms (client->server then server->client). */
6493 for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
6496 alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
6497 alg->u.cipher.cipher = NULL;
6498 alg->u.cipher.warn = warn;
6499 #endif /* FUZZING */
6500 for (i = 0; i < s->n_preferred_ciphers; i++) {
6501 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
6502 if (!c) warn = TRUE;
6503 else for (j = 0; j < c->nciphers; j++) {
6504 alg = ssh2_kexinit_addalg(s->kexlists[k],
6506 alg->u.cipher.cipher = c->list[j];
6507 alg->u.cipher.warn = warn;
6511 /* List MAC algorithms (client->server then server->client). */
6512 for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
6514 alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
6515 alg->u.mac.mac = NULL;
6516 alg->u.mac.etm = FALSE;
6517 #endif /* FUZZING */
6518 for (i = 0; i < s->nmacs; i++) {
6519 alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
6520 alg->u.mac.mac = s->maclist[i];
6521 alg->u.mac.etm = FALSE;
6523 for (i = 0; i < s->nmacs; i++)
6524 /* For each MAC, there may also be an ETM version,
6525 * which we list second. */
6526 if (s->maclist[i]->etm_name) {
6527 alg = ssh2_kexinit_addalg(s->kexlists[j],
6528 s->maclist[i]->etm_name);
6529 alg->u.mac.mac = s->maclist[i];
6530 alg->u.mac.etm = TRUE;
6533 /* List client->server compression algorithms,
6534 * then server->client compression algorithms. (We use the
6535 * same set twice.) */
6536 for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
6537 assert(lenof(compressions) > 1);
6538 /* Prefer non-delayed versions */
6539 alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
6540 alg->u.comp = s->preferred_comp;
6541 /* We don't even list delayed versions of algorithms until
6542 * they're allowed to be used, to avoid a race. See the end of
6544 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
6545 alg = ssh2_kexinit_addalg(s->kexlists[j],
6546 s->preferred_comp->delayed_name);
6547 alg->u.comp = s->preferred_comp;
6549 for (i = 0; i < lenof(compressions); i++) {
6550 const struct ssh_compress *c = compressions[i];
6551 alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
6553 if (s->userauth_succeeded && c->delayed_name) {
6554 alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
6560 * Construct and send our key exchange packet.
6562 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
6563 for (i = 0; i < 16; i++)
6564 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
6565 for (i = 0; i < NKEXLIST; i++) {
6566 ssh2_pkt_addstring_start(s->pktout);
6567 for (j = 0; j < MAXKEXLIST; j++) {
6568 if (s->kexlists[i][j].name == NULL) break;
6569 ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
6572 /* List client->server languages. Empty list. */
6573 ssh2_pkt_addstring_start(s->pktout);
6574 /* List server->client languages. Empty list. */
6575 ssh2_pkt_addstring_start(s->pktout);
6576 /* First KEX packet does _not_ follow, because we're not that brave. */
6577 ssh2_pkt_addbool(s->pktout, FALSE);
6579 ssh2_pkt_adduint32(s->pktout, 0);
6582 s->our_kexinitlen = s->pktout->length - 5;
6583 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
6584 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
6586 ssh2_pkt_send_noqueue(ssh, s->pktout);
6589 crWaitUntilV(pktin);
6592 * Now examine the other side's KEXINIT to see what we're up
6599 if (pktin->type != SSH2_MSG_KEXINIT) {
6600 bombout(("expected key exchange packet from server"));
6604 ssh->hostkey = NULL;
6605 s->cscipher_tobe = NULL;
6606 s->sccipher_tobe = NULL;
6607 s->csmac_tobe = NULL;
6608 s->scmac_tobe = NULL;
6609 s->cscomp_tobe = NULL;
6610 s->sccomp_tobe = NULL;
6611 s->warn_kex = s->warn_hk = FALSE;
6612 s->warn_cscipher = s->warn_sccipher = FALSE;
6614 pktin->savedpos += 16; /* skip garbage cookie */
6617 for (i = 0; i < NKEXLIST; i++) {
6618 ssh_pkt_getstring(pktin, &str, &len);
6620 bombout(("KEXINIT packet was incomplete"));
6624 /* If we've already selected a cipher which requires a
6625 * particular MAC, then just select that, and don't even
6626 * bother looking through the server's KEXINIT string for
6628 if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
6629 s->cscipher_tobe->required_mac) {
6630 s->csmac_tobe = s->cscipher_tobe->required_mac;
6631 s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
6634 if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
6635 s->sccipher_tobe->required_mac) {
6636 s->scmac_tobe = s->sccipher_tobe->required_mac;
6637 s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
6641 for (j = 0; j < MAXKEXLIST; j++) {
6642 struct kexinit_algorithm *alg = &s->kexlists[i][j];
6643 if (alg->name == NULL) break;
6644 if (in_commasep_string(alg->name, str, len)) {
6645 /* We've found a matching algorithm. */
6646 if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
6647 /* Check if we might need to ignore first kex pkt */
6649 !first_in_commasep_string(alg->name, str, len))
6652 if (i == KEXLIST_KEX) {
6653 ssh->kex = alg->u.kex.kex;
6654 s->warn_kex = alg->u.kex.warn;
6655 } else if (i == KEXLIST_HOSTKEY) {
6656 ssh->hostkey = alg->u.hk.hostkey;
6657 s->warn_hk = alg->u.hk.warn;
6658 } else if (i == KEXLIST_CSCIPHER) {
6659 s->cscipher_tobe = alg->u.cipher.cipher;
6660 s->warn_cscipher = alg->u.cipher.warn;
6661 } else if (i == KEXLIST_SCCIPHER) {
6662 s->sccipher_tobe = alg->u.cipher.cipher;
6663 s->warn_sccipher = alg->u.cipher.warn;
6664 } else if (i == KEXLIST_CSMAC) {
6665 s->csmac_tobe = alg->u.mac.mac;
6666 s->csmac_etm_tobe = alg->u.mac.etm;
6667 } else if (i == KEXLIST_SCMAC) {
6668 s->scmac_tobe = alg->u.mac.mac;
6669 s->scmac_etm_tobe = alg->u.mac.etm;
6670 } else if (i == KEXLIST_CSCOMP) {
6671 s->cscomp_tobe = alg->u.comp;
6672 } else if (i == KEXLIST_SCCOMP) {
6673 s->sccomp_tobe = alg->u.comp;
6677 if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
6678 in_commasep_string(alg->u.comp->delayed_name, str, len))
6679 s->pending_compression = TRUE; /* try this later */
6681 bombout(("Couldn't agree a %s (available: %.*s)",
6682 kexlist_descr[i], len, str));
6686 if (i == KEXLIST_HOSTKEY) {
6690 * In addition to deciding which host key we're
6691 * actually going to use, we should make a list of the
6692 * host keys offered by the server which we _don't_
6693 * have cached. These will be offered as cross-
6694 * certification options by ssh_get_specials.
6696 * We also count the key we're currently using for KEX
6697 * as one we've already got, because by the time this
6698 * menu becomes visible, it will be.
6700 ssh->n_uncert_hostkeys = 0;
6702 for (j = 0; j < lenof(hostkey_algs); j++) {
6703 if (hostkey_algs[j].alg != ssh->hostkey &&
6704 in_commasep_string(hostkey_algs[j].alg->name,
6706 !have_ssh_host_key(ssh->savedhost, ssh->savedport,
6707 hostkey_algs[j].alg->keytype)) {
6708 ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
6714 if (s->pending_compression) {
6715 logevent("Server supports delayed compression; "
6716 "will try this later");
6718 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
6719 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
6720 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
6722 ssh->exhash = ssh->kex->hash->init();
6723 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
6724 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
6725 hash_string(ssh->kex->hash, ssh->exhash,
6726 s->our_kexinit, s->our_kexinitlen);
6727 sfree(s->our_kexinit);
6728 /* Include the type byte in the hash of server's KEXINIT */
6729 hash_string(ssh->kex->hash, ssh->exhash,
6730 pktin->body - 1, pktin->length + 1);
6733 ssh_set_frozen(ssh, 1);
6734 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
6736 ssh_dialog_callback, ssh);
6737 if (s->dlgret < 0) {
6741 bombout(("Unexpected data from server while"
6742 " waiting for user response"));
6745 } while (pktin || inlen > 0);
6746 s->dlgret = ssh->user_response;
6748 ssh_set_frozen(ssh, 0);
6749 if (s->dlgret == 0) {
6750 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
6760 ssh_set_frozen(ssh, 1);
6763 * Change warning box wording depending on why we chose a
6764 * warning-level host key algorithm. If it's because
6765 * that's all we have *cached*, use the askhk mechanism,
6766 * and list the host keys we could usefully cross-certify.
6767 * Otherwise, use askalg for the standard wording.
6770 for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
6771 const struct ssh_signkey_with_user_pref_id *hktype =
6772 &hostkey_algs[ssh->uncert_hostkeys[j]];
6774 for (k = 0; k < HK_MAX; k++) {
6775 int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
6776 if (id == HK_WARN) {
6778 } else if (id == hktype->id) {
6785 char *old_ba = betteralgs;
6786 betteralgs = dupcat(betteralgs, ",",
6788 (const char *)NULL);
6791 betteralgs = dupstr(hktype->alg->name);
6796 s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
6797 betteralgs, ssh_dialog_callback, ssh);
6800 s->dlgret = askalg(ssh->frontend, "host key type",
6802 ssh_dialog_callback, ssh);
6804 if (s->dlgret < 0) {
6808 bombout(("Unexpected data from server while"
6809 " waiting for user response"));
6812 } while (pktin || inlen > 0);
6813 s->dlgret = ssh->user_response;
6815 ssh_set_frozen(ssh, 0);
6816 if (s->dlgret == 0) {
6817 ssh_disconnect(ssh, "User aborted at host key warning", NULL,
6823 if (s->warn_cscipher) {
6824 ssh_set_frozen(ssh, 1);
6825 s->dlgret = askalg(ssh->frontend,
6826 "client-to-server cipher",
6827 s->cscipher_tobe->name,
6828 ssh_dialog_callback, ssh);
6829 if (s->dlgret < 0) {
6833 bombout(("Unexpected data from server while"
6834 " waiting for user response"));
6837 } while (pktin || inlen > 0);
6838 s->dlgret = ssh->user_response;
6840 ssh_set_frozen(ssh, 0);
6841 if (s->dlgret == 0) {
6842 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6848 if (s->warn_sccipher) {
6849 ssh_set_frozen(ssh, 1);
6850 s->dlgret = askalg(ssh->frontend,
6851 "server-to-client cipher",
6852 s->sccipher_tobe->name,
6853 ssh_dialog_callback, ssh);
6854 if (s->dlgret < 0) {
6858 bombout(("Unexpected data from server while"
6859 " waiting for user response"));
6862 } while (pktin || inlen > 0);
6863 s->dlgret = ssh->user_response;
6865 ssh_set_frozen(ssh, 0);
6866 if (s->dlgret == 0) {
6867 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
6873 if (s->ignorepkt) /* first_kex_packet_follows */
6874 crWaitUntilV(pktin); /* Ignore packet */
6877 if (ssh->kex->main_type == KEXTYPE_DH) {
6879 * Work out the number of bits of key we will need from the
6880 * key exchange. We start with the maximum key length of
6886 csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
6887 scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
6888 s->nbits = (csbits > scbits ? csbits : scbits);
6890 /* The keys only have hlen-bit entropy, since they're based on
6891 * a hash. So cap the key size at hlen bits. */
6892 if (s->nbits > ssh->kex->hash->hlen * 8)
6893 s->nbits = ssh->kex->hash->hlen * 8;
6896 * If we're doing Diffie-Hellman group exchange, start by
6897 * requesting a group.
6899 if (dh_is_gex(ssh->kex)) {
6900 logevent("Doing Diffie-Hellman group exchange");
6901 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
6903 * Work out how big a DH group we will need to allow that
6906 s->pbits = 512 << ((s->nbits - 1) / 64);
6907 if (s->pbits < DH_MIN_SIZE)
6908 s->pbits = DH_MIN_SIZE;
6909 if (s->pbits > DH_MAX_SIZE)
6910 s->pbits = DH_MAX_SIZE;
6911 if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
6912 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
6913 ssh2_pkt_adduint32(s->pktout, s->pbits);
6915 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6916 ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
6917 ssh2_pkt_adduint32(s->pktout, s->pbits);
6918 ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
6920 ssh2_pkt_send_noqueue(ssh, s->pktout);
6922 crWaitUntilV(pktin);
6923 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6924 bombout(("expected key exchange group packet from server"));
6927 s->p = ssh2_pkt_getmp(pktin);
6928 s->g = ssh2_pkt_getmp(pktin);
6929 if (!s->p || !s->g) {
6930 bombout(("unable to read mp-ints from incoming group packet"));
6933 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6934 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6935 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6937 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
6938 ssh->kex_ctx = dh_setup_group(ssh->kex);
6939 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6940 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6941 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6942 ssh->kex->groupname);
6945 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6946 ssh->kex->hash->text_name);
6948 * Now generate and send e for Diffie-Hellman.
6950 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6951 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6952 s->pktout = ssh2_pkt_init(s->kex_init_value);
6953 ssh2_pkt_addmp(s->pktout, s->e);
6954 ssh2_pkt_send_noqueue(ssh, s->pktout);
6956 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6957 crWaitUntilV(pktin);
6958 if (pktin->type != s->kex_reply_value) {
6959 bombout(("expected key exchange reply packet from server"));
6962 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6963 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6964 if (!s->hostkeydata) {
6965 bombout(("unable to parse key exchange reply packet"));
6968 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
6969 s->hostkeydata, s->hostkeylen);
6970 s->f = ssh2_pkt_getmp(pktin);
6972 bombout(("unable to parse key exchange reply packet"));
6975 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6977 bombout(("unable to parse key exchange reply packet"));
6982 const char *err = dh_validate_f(ssh->kex_ctx, s->f);
6984 bombout(("key exchange reply failed validation: %s", err));
6988 s->K = dh_find_K(ssh->kex_ctx, s->f);
6990 /* We assume everything from now on will be quick, and it might
6991 * involve user interaction. */
6992 set_busy_status(ssh->frontend, BUSY_NOT);
6994 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6995 if (dh_is_gex(ssh->kex)) {
6996 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
6997 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
6998 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6999 if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
7000 hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
7001 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
7002 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
7004 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
7005 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
7007 dh_cleanup(ssh->kex_ctx);
7009 if (dh_is_gex(ssh->kex)) {
7013 } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
7015 logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
7016 ssh_ecdhkex_curve_textname(ssh->kex),
7017 ssh->kex->hash->text_name);
7018 ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
7020 s->eckey = ssh_ecdhkex_newkey(ssh->kex);
7022 bombout(("Unable to generate key for ECDH"));
7028 int publicPointLength;
7029 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7031 ssh_ecdhkex_freekey(s->eckey);
7032 bombout(("Unable to encode public key for ECDH"));
7035 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
7036 ssh2_pkt_addstring_start(s->pktout);
7037 ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
7041 ssh2_pkt_send_noqueue(ssh, s->pktout);
7043 crWaitUntilV(pktin);
7044 if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
7045 ssh_ecdhkex_freekey(s->eckey);
7046 bombout(("expected ECDH reply packet from server"));
7050 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7051 if (!s->hostkeydata) {
7052 bombout(("unable to parse ECDH reply packet"));
7055 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
7056 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7057 s->hostkeydata, s->hostkeylen);
7061 int publicPointLength;
7062 publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
7064 ssh_ecdhkex_freekey(s->eckey);
7065 bombout(("Unable to encode public key for ECDH hash"));
7068 hash_string(ssh->kex->hash, ssh->exhash,
7069 publicPoint, publicPointLength);
7076 ssh_pkt_getstring(pktin, &keydata, &keylen);
7078 bombout(("unable to parse ECDH reply packet"));
7081 hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
7082 s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
7084 ssh_ecdhkex_freekey(s->eckey);
7085 bombout(("point received in ECDH was not valid"));
7090 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7092 bombout(("unable to parse key exchange reply packet"));
7096 ssh_ecdhkex_freekey(s->eckey);
7098 logeventf(ssh, "Doing RSA key exchange with hash %s",
7099 ssh->kex->hash->text_name);
7100 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
7102 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
7105 crWaitUntilV(pktin);
7106 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
7107 bombout(("expected RSA public key packet from server"));
7111 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
7112 if (!s->hostkeydata) {
7113 bombout(("unable to parse RSA public key packet"));
7116 hash_string(ssh->kex->hash, ssh->exhash,
7117 s->hostkeydata, s->hostkeylen);
7118 s->hkey = ssh->hostkey->newkey(ssh->hostkey,
7119 s->hostkeydata, s->hostkeylen);
7123 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
7125 bombout(("unable to parse RSA public key packet"));
7128 s->rsakeydata = snewn(s->rsakeylen, char);
7129 memcpy(s->rsakeydata, keydata, s->rsakeylen);
7132 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
7134 sfree(s->rsakeydata);
7135 bombout(("unable to parse RSA public key from server"));
7139 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
7142 * Next, set up a shared secret K, of precisely KLEN -
7143 * 2*HLEN - 49 bits, where KLEN is the bit length of the
7144 * RSA key modulus and HLEN is the bit length of the hash
7148 int klen = ssh_rsakex_klen(s->rsakey);
7149 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
7151 unsigned char *kstr1, *kstr2, *outstr;
7152 int kstr1len, kstr2len, outstrlen;
7154 s->K = bn_power_2(nbits - 1);
7156 for (i = 0; i < nbits; i++) {
7158 byte = random_byte();
7160 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
7164 * Encode this as an mpint.
7166 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
7167 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
7168 PUT_32BIT(kstr2, kstr1len);
7169 memcpy(kstr2 + 4, kstr1, kstr1len);
7172 * Encrypt it with the given RSA key.
7174 outstrlen = (klen + 7) / 8;
7175 outstr = snewn(outstrlen, unsigned char);
7176 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
7177 outstr, outstrlen, s->rsakey);
7180 * And send it off in a return packet.
7182 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
7183 ssh2_pkt_addstring_start(s->pktout);
7184 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
7185 ssh2_pkt_send_noqueue(ssh, s->pktout);
7187 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
7194 ssh_rsakex_freekey(s->rsakey);
7196 crWaitUntilV(pktin);
7197 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
7198 sfree(s->rsakeydata);
7199 bombout(("expected signature packet from server"));
7203 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
7205 bombout(("unable to parse signature packet"));
7209 sfree(s->rsakeydata);
7212 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
7213 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
7214 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
7216 ssh->kex_ctx = NULL;
7219 debug(("Exchange hash is:\n"));
7220 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7224 bombout(("Server's host key is invalid"));
7228 if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
7229 (char *)s->exchange_hash,
7230 ssh->kex->hash->hlen)) {
7232 bombout(("Server's host key did not match the signature supplied"));
7237 s->keystr = ssh->hostkey->fmtkey(s->hkey);
7238 if (!s->got_session_id) {
7240 * Make a note of any other host key formats that are available.
7243 int i, j, nkeys = 0;
7245 for (i = 0; i < lenof(hostkey_algs); i++) {
7246 if (hostkey_algs[i].alg == ssh->hostkey)
7249 for (j = 0; j < ssh->n_uncert_hostkeys; j++)
7250 if (ssh->uncert_hostkeys[j] == i)
7253 if (j < ssh->n_uncert_hostkeys) {
7256 newlist = dupprintf("%s/%s", list,
7257 hostkey_algs[i].alg->name);
7259 newlist = dupprintf("%s", hostkey_algs[i].alg->name);
7267 "Server also has %s host key%s, but we "
7268 "don't know %s", list,
7269 nkeys > 1 ? "s" : "",
7270 nkeys > 1 ? "any of them" : "it");
7276 * Authenticate remote host: verify host key. (We've already
7277 * checked the signature of the exchange hash.)
7279 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7280 logevent("Host key fingerprint is:");
7281 logevent(s->fingerprint);
7282 /* First check against manually configured host keys. */
7283 s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
7284 ssh->hostkey, s->hkey);
7285 if (s->dlgret == 0) { /* did not match */
7286 bombout(("Host key did not appear in manually configured list"));
7288 } else if (s->dlgret < 0) { /* none configured; use standard handling */
7289 ssh_set_frozen(ssh, 1);
7290 s->dlgret = verify_ssh_host_key(ssh->frontend,
7291 ssh->savedhost, ssh->savedport,
7292 ssh->hostkey->keytype, s->keystr,
7294 ssh_dialog_callback, ssh);
7298 if (s->dlgret < 0) {
7302 bombout(("Unexpected data from server while waiting"
7303 " for user host key response"));
7306 } while (pktin || inlen > 0);
7307 s->dlgret = ssh->user_response;
7309 ssh_set_frozen(ssh, 0);
7310 if (s->dlgret == 0) {
7311 ssh_disconnect(ssh, "Aborted at host key verification", NULL,
7316 sfree(s->fingerprint);
7318 * Save this host key, to check against the one presented in
7319 * subsequent rekeys.
7321 ssh->hostkey_str = s->keystr;
7322 } else if (ssh->cross_certifying) {
7323 s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
7324 logevent("Storing additional host key for this host:");
7325 logevent(s->fingerprint);
7326 sfree(s->fingerprint);
7327 store_host_key(ssh->savedhost, ssh->savedport,
7328 ssh->hostkey->keytype, s->keystr);
7329 ssh->cross_certifying = FALSE;
7331 * Don't forget to store the new key as the one we'll be
7332 * re-checking in future normal rekeys.
7334 ssh->hostkey_str = s->keystr;
7337 * In a rekey, we never present an interactive host key
7338 * verification request to the user. Instead, we simply
7339 * enforce that the key we're seeing this time is identical to
7340 * the one we saw before.
7342 if (strcmp(ssh->hostkey_str, s->keystr)) {
7344 bombout(("Host key was different in repeat key exchange"));
7350 ssh->hostkey->freekey(s->hkey);
7353 * The exchange hash from the very first key exchange is also
7354 * the session id, used in session key construction and
7357 if (!s->got_session_id) {
7358 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
7359 memcpy(ssh->v2_session_id, s->exchange_hash,
7360 sizeof(s->exchange_hash));
7361 ssh->v2_session_id_len = ssh->kex->hash->hlen;
7362 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
7363 s->got_session_id = TRUE;
7367 * Send SSH2_MSG_NEWKEYS.
7369 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
7370 ssh2_pkt_send_noqueue(ssh, s->pktout);
7371 ssh->outgoing_data_size = 0; /* start counting from here */
7374 * We've sent client NEWKEYS, so create and initialise
7375 * client-to-server session keys.
7377 if (ssh->cs_cipher_ctx)
7378 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7379 ssh->cscipher = s->cscipher_tobe;
7380 if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
7382 if (ssh->cs_mac_ctx)
7383 ssh->csmac->free_context(ssh->cs_mac_ctx);
7384 ssh->csmac = s->csmac_tobe;
7385 ssh->csmac_etm = s->csmac_etm_tobe;
7387 ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
7389 if (ssh->cs_comp_ctx)
7390 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7391 ssh->cscomp = s->cscomp_tobe;
7392 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
7395 * Set IVs on client-to-server keys. Here we use the exchange
7396 * hash from the _first_ key exchange.
7398 if (ssh->cscipher) {
7401 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
7402 ssh->cscipher->padded_keybytes);
7403 ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
7404 smemclr(key, ssh->cscipher->padded_keybytes);
7407 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
7408 ssh->cscipher->blksize);
7409 ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
7410 smemclr(key, ssh->cscipher->blksize);
7416 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
7417 ssh->csmac->keylen);
7418 ssh->csmac->setkey(ssh->cs_mac_ctx, key);
7419 smemclr(key, ssh->csmac->keylen);
7424 logeventf(ssh, "Initialised %.200s client->server encryption",
7425 ssh->cscipher->text_name);
7427 logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
7428 ssh->csmac->text_name,
7429 ssh->csmac_etm ? " (in ETM mode)" : "",
7430 ssh->cscipher->required_mac ? " (required by cipher)" : "");
7431 if (ssh->cscomp->text_name)
7432 logeventf(ssh, "Initialised %s compression",
7433 ssh->cscomp->text_name);
7436 * Now our end of the key exchange is complete, we can send all
7437 * our queued higher-layer packets.
7439 ssh->queueing = FALSE;
7440 ssh2_pkt_queuesend(ssh);
7443 * Expect SSH2_MSG_NEWKEYS from server.
7445 crWaitUntilV(pktin);
7446 if (pktin->type != SSH2_MSG_NEWKEYS) {
7447 bombout(("expected new-keys packet from server"));
7450 ssh->incoming_data_size = 0; /* start counting from here */
7453 * We've seen server NEWKEYS, so create and initialise
7454 * server-to-client session keys.
7456 if (ssh->sc_cipher_ctx)
7457 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7458 if (s->sccipher_tobe) {
7459 ssh->sccipher = s->sccipher_tobe;
7460 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
7463 if (ssh->sc_mac_ctx)
7464 ssh->scmac->free_context(ssh->sc_mac_ctx);
7465 if (s->scmac_tobe) {
7466 ssh->scmac = s->scmac_tobe;
7467 ssh->scmac_etm = s->scmac_etm_tobe;
7468 ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
7471 if (ssh->sc_comp_ctx)
7472 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7473 ssh->sccomp = s->sccomp_tobe;
7474 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
7477 * Set IVs on server-to-client keys. Here we use the exchange
7478 * hash from the _first_ key exchange.
7480 if (ssh->sccipher) {
7483 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
7484 ssh->sccipher->padded_keybytes);
7485 ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
7486 smemclr(key, ssh->sccipher->padded_keybytes);
7489 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
7490 ssh->sccipher->blksize);
7491 ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
7492 smemclr(key, ssh->sccipher->blksize);
7498 key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
7499 ssh->scmac->keylen);
7500 ssh->scmac->setkey(ssh->sc_mac_ctx, key);
7501 smemclr(key, ssh->scmac->keylen);
7505 logeventf(ssh, "Initialised %.200s server->client encryption",
7506 ssh->sccipher->text_name);
7508 logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
7509 ssh->scmac->text_name,
7510 ssh->scmac_etm ? " (in ETM mode)" : "",
7511 ssh->sccipher->required_mac ? " (required by cipher)" : "");
7512 if (ssh->sccomp->text_name)
7513 logeventf(ssh, "Initialised %s decompression",
7514 ssh->sccomp->text_name);
7517 * Free shared secret.
7522 * Update the specials menu to list the remaining uncertified host
7525 update_specials_menu(ssh->frontend);
7528 * Key exchange is over. Loop straight back round if we have a
7529 * deferred rekey reason.
7531 if (ssh->deferred_rekey_reason) {
7532 logevent(ssh->deferred_rekey_reason);
7534 ssh->deferred_rekey_reason = NULL;
7535 goto begin_key_exchange;
7539 * Otherwise, schedule a timer for our next rekey.
7541 ssh->kex_in_progress = FALSE;
7542 ssh->last_rekey = GETTICKCOUNT();
7543 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
7544 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7548 * Now we're encrypting. Begin returning 1 to the protocol main
7549 * function so that other things can run on top of the
7550 * transport. If we ever see a KEXINIT, we must go back to the
7553 * We _also_ go back to the start if we see pktin==NULL and
7554 * inlen negative, because this is a special signal meaning
7555 * `initiate client-driven rekey', and `in' contains a message
7556 * giving the reason for the rekey.
7558 * inlen==-1 means always initiate a rekey;
7559 * inlen==-2 means that userauth has completed successfully and
7560 * we should consider rekeying (for delayed compression).
7562 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
7563 (!pktin && inlen < 0))) {
7565 if (!ssh->protocol_initial_phase_done) {
7566 ssh->protocol_initial_phase_done = TRUE;
7568 * Allow authconn to initialise itself.
7570 do_ssh2_authconn(ssh, NULL, 0, NULL);
7575 logevent("Server initiated key re-exchange");
7579 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
7580 * delayed compression, if it's available.
7582 * draft-miller-secsh-compression-delayed-00 says that you
7583 * negotiate delayed compression in the first key exchange, and
7584 * both sides start compressing when the server has sent
7585 * USERAUTH_SUCCESS. This has a race condition -- the server
7586 * can't know when the client has seen it, and thus which incoming
7587 * packets it should treat as compressed.
7589 * Instead, we do the initial key exchange without offering the
7590 * delayed methods, but note if the server offers them; when we
7591 * get here, if a delayed method was available that was higher
7592 * on our list than what we got, we initiate a rekey in which we
7593 * _do_ list the delayed methods (and hopefully get it as a
7594 * result). Subsequent rekeys will do the same.
7596 assert(!s->userauth_succeeded); /* should only happen once */
7597 s->userauth_succeeded = TRUE;
7598 if (!s->pending_compression)
7599 /* Can't see any point rekeying. */
7600 goto wait_for_rekey; /* this is utterly horrid */
7601 /* else fall through to rekey... */
7602 s->pending_compression = FALSE;
7605 * Now we've decided to rekey.
7607 * Special case: if the server bug is set that doesn't
7608 * allow rekeying, we give a different log message and
7609 * continue waiting. (If such a server _initiates_ a rekey,
7610 * we process it anyway!)
7612 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
7613 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
7615 /* Reset the counters, so that at least this message doesn't
7616 * hit the event log _too_ often. */
7617 ssh->outgoing_data_size = 0;
7618 ssh->incoming_data_size = 0;
7619 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
7621 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
7624 goto wait_for_rekey; /* this is still utterly horrid */
7626 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
7629 goto begin_key_exchange;
7635 * Send data on an SSH channel. In SSH-2, this involves buffering it
7638 static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
7641 if (c->ssh->version == 2) {
7642 bufchain_add(&c->v.v2.outbuffer, buf, len);
7643 return ssh2_try_send(c);
7645 send_packet(c->ssh, SSH1_MSG_CHANNEL_DATA,
7646 PKT_INT, c->remoteid,
7651 * In SSH-1 we can return 0 here - implying that channels are
7652 * never individually throttled - because the only
7653 * circumstance that can cause throttling will be the whole
7654 * SSH connection backing up, in which case _everything_ will
7655 * be throttled as a whole.
7662 * Attempt to send data on an SSH-2 channel.
7664 static int ssh2_try_send(struct ssh_channel *c)
7667 struct Packet *pktout;
7670 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
7673 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
7674 if ((unsigned)len > c->v.v2.remwindow)
7675 len = c->v.v2.remwindow;
7676 if ((unsigned)len > c->v.v2.remmaxpkt)
7677 len = c->v.v2.remmaxpkt;
7678 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
7679 ssh2_pkt_adduint32(pktout, c->remoteid);
7680 ssh2_pkt_addstring_start(pktout);
7681 ssh2_pkt_addstring_data(pktout, data, len);
7682 ssh2_pkt_send(ssh, pktout);
7683 bufchain_consume(&c->v.v2.outbuffer, len);
7684 c->v.v2.remwindow -= len;
7688 * After having sent as much data as we can, return the amount
7691 ret = bufchain_size(&c->v.v2.outbuffer);
7694 * And if there's no data pending but we need to send an EOF, send
7697 if (!ret && c->pending_eof)
7698 ssh_channel_try_eof(c);
7703 static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
7706 if (c->closes & CLOSES_SENT_EOF)
7707 return; /* don't send on channels we've EOFed */
7708 bufsize = ssh2_try_send(c);
7711 case CHAN_MAINSESSION:
7712 /* stdin need not receive an unthrottle
7713 * notification since it will be polled */
7716 x11_unthrottle(c->u.x11.xconn);
7719 /* agent sockets are request/response and need no
7720 * buffer management */
7723 pfd_unthrottle(c->u.pfd.pf);
7729 static int ssh_is_simple(Ssh ssh)
7732 * We use the 'simple' variant of the SSH protocol if we're asked
7733 * to, except not if we're also doing connection-sharing (either
7734 * tunnelling our packets over an upstream or expecting to be
7735 * tunnelled over ourselves), since then the assumption that we
7736 * have only one channel to worry about is not true after all.
7738 return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
7739 !ssh->bare_connection && !ssh->connshare);
7743 * Set up most of a new ssh_channel.
7745 static void ssh_channel_init(struct ssh_channel *c)
7748 c->localid = alloc_channel_id(ssh);
7750 c->pending_eof = FALSE;
7751 c->throttling_conn = FALSE;
7752 if (ssh->version == 2) {
7753 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
7754 ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
7755 c->v.v2.chanreq_head = NULL;
7756 c->v.v2.throttle_state = UNTHROTTLED;
7757 bufchain_init(&c->v.v2.outbuffer);
7759 add234(ssh->channels, c);
7763 * Construct the common parts of a CHANNEL_OPEN.
7765 static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
7768 struct Packet *pktout;
7770 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7771 ssh2_pkt_addstring(pktout, type);
7772 ssh2_pkt_adduint32(pktout, c->localid);
7773 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
7774 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
7779 * CHANNEL_FAILURE doesn't come with any indication of what message
7780 * caused it, so we have to keep track of the outstanding
7781 * CHANNEL_REQUESTs ourselves.
7783 static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
7784 cchandler_fn_t handler, void *ctx)
7786 struct outstanding_channel_request *ocr =
7787 snew(struct outstanding_channel_request);
7789 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7790 ocr->handler = handler;
7793 if (!c->v.v2.chanreq_head)
7794 c->v.v2.chanreq_head = ocr;
7796 c->v.v2.chanreq_tail->next = ocr;
7797 c->v.v2.chanreq_tail = ocr;
7801 * Construct the common parts of a CHANNEL_REQUEST. If handler is not
7802 * NULL then a reply will be requested and the handler will be called
7803 * when it arrives. The returned packet is ready to have any
7804 * request-specific data added and be sent. Note that if a handler is
7805 * provided, it's essential that the request actually be sent.
7807 * The handler will usually be passed the response packet in pktin. If
7808 * pktin is NULL, this means that no reply will ever be forthcoming
7809 * (e.g. because the entire connection is being destroyed, or because
7810 * the server initiated channel closure before we saw the response)
7811 * and the handler should free any storage it's holding.
7813 static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
7815 cchandler_fn_t handler, void *ctx)
7817 struct Packet *pktout;
7819 assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
7820 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7821 ssh2_pkt_adduint32(pktout, c->remoteid);
7822 ssh2_pkt_addstring(pktout, type);
7823 ssh2_pkt_addbool(pktout, handler != NULL);
7824 if (handler != NULL)
7825 ssh2_queue_chanreq_handler(c, handler, ctx);
7829 static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize)
7834 if (ssh->version == 1) {
7835 buflimit = SSH1_BUFFER_LIMIT;
7837 if (ssh_is_simple(ssh))
7840 buflimit = c->v.v2.locmaxwin;
7841 if (bufsize < buflimit)
7842 ssh2_set_window(c, buflimit - bufsize);
7844 if (c->throttling_conn && bufsize <= buflimit) {
7845 c->throttling_conn = 0;
7846 ssh_throttle_conn(ssh, -1);
7851 * Potentially enlarge the window on an SSH-2 channel.
7853 static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
7855 static void ssh2_set_window(struct ssh_channel *c, int newwin)
7860 * Never send WINDOW_ADJUST for a channel that the remote side has
7861 * already sent EOF on; there's no point, since it won't be
7862 * sending any more data anyway. Ditto if _we've_ already sent
7865 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
7869 * Also, never widen the window for an X11 channel when we're
7870 * still waiting to see its initial auth and may yet hand it off
7873 if (c->type == CHAN_X11 && c->u.x11.initial)
7877 * If the remote end has a habit of ignoring maxpkt, limit the
7878 * window so that it has no choice (assuming it doesn't ignore the
7881 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
7882 newwin = OUR_V2_MAXPKT;
7885 * Only send a WINDOW_ADJUST if there's significantly more window
7886 * available than the other end thinks there is. This saves us
7887 * sending a WINDOW_ADJUST for every character in a shell session.
7889 * "Significant" is arbitrarily defined as half the window size.
7891 if (newwin / 2 >= c->v.v2.locwindow) {
7892 struct Packet *pktout;
7896 * In order to keep track of how much window the client
7897 * actually has available, we'd like it to acknowledge each
7898 * WINDOW_ADJUST. We can't do that directly, so we accompany
7899 * it with a CHANNEL_REQUEST that has to be acknowledged.
7901 * This is only necessary if we're opening the window wide.
7902 * If we're not, then throughput is being constrained by
7903 * something other than the maximum window size anyway.
7905 if (newwin == c->v.v2.locmaxwin &&
7906 !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
7907 up = snew(unsigned);
7908 *up = newwin - c->v.v2.locwindow;
7909 pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
7910 ssh2_handle_winadj_response, up);
7911 ssh2_pkt_send(ssh, pktout);
7913 if (c->v.v2.throttle_state != UNTHROTTLED)
7914 c->v.v2.throttle_state = UNTHROTTLING;
7916 /* Pretend the WINDOW_ADJUST was acked immediately. */
7917 c->v.v2.remlocwin = newwin;
7918 c->v.v2.throttle_state = THROTTLED;
7920 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
7921 ssh2_pkt_adduint32(pktout, c->remoteid);
7922 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
7923 ssh2_pkt_send(ssh, pktout);
7924 c->v.v2.locwindow = newwin;
7929 * Find the channel associated with a message. If there's no channel,
7930 * or it's not properly open, make a noise about it and return NULL.
7931 * If the channel is shared, pass the message on to downstream and
7932 * also return NULL (meaning the caller should ignore this message).
7934 static struct ssh_channel *ssh_channel_msg(Ssh ssh, struct Packet *pktin)
7936 unsigned localid = ssh_pkt_getuint32(pktin);
7937 struct ssh_channel *c;
7940 /* Is this message OK on a half-open connection? */
7941 if (ssh->version == 1)
7942 halfopen_ok = (pktin->type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION ||
7943 pktin->type == SSH1_MSG_CHANNEL_OPEN_FAILURE);
7945 halfopen_ok = (pktin->type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION ||
7946 pktin->type == SSH2_MSG_CHANNEL_OPEN_FAILURE);
7947 c = find234(ssh->channels, &localid, ssh_channelfind);
7948 if (!c || (c->type != CHAN_SHARING && (c->halfopen != halfopen_ok))) {
7949 char *buf = dupprintf("Received %s for %s channel %u",
7950 ssh_pkt_type(ssh, pktin->type),
7951 !c ? "nonexistent" :
7952 c->halfopen ? "half-open" : "open",
7954 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
7958 if (c->type == CHAN_SHARING) {
7959 share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
7960 pktin->body, pktin->length);
7966 static void ssh2_handle_winadj_response(struct ssh_channel *c,
7967 struct Packet *pktin, void *ctx)
7969 unsigned *sizep = ctx;
7972 * Winadj responses should always be failures. However, at least
7973 * one server ("boks_sshd") is known to return SUCCESS for channel
7974 * requests it's never heard of, such as "winadj@putty". Raised
7975 * with foxt.com as bug 090916-090424, but for the sake of a quiet
7976 * life, we don't worry about what kind of response we got.
7979 c->v.v2.remlocwin += *sizep;
7982 * winadj messages are only sent when the window is fully open, so
7983 * if we get an ack of one, we know any pending unthrottle is
7986 if (c->v.v2.throttle_state == UNTHROTTLING)
7987 c->v.v2.throttle_state = UNTHROTTLED;
7990 static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
7992 struct ssh_channel *c = ssh_channel_msg(ssh, pktin);
7993 struct outstanding_channel_request *ocr;
7996 ocr = c->v.v2.chanreq_head;
7998 ssh2_msg_unexpected(ssh, pktin);
8001 ocr->handler(c, pktin, ocr->ctx);
8002 c->v.v2.chanreq_head = ocr->next;
8005 * We may now initiate channel-closing procedures, if that
8006 * CHANNEL_REQUEST was the last thing outstanding before we send
8009 ssh2_channel_check_close(c);
8012 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
8014 struct ssh_channel *c;
8015 c = ssh_channel_msg(ssh, pktin);
8018 if (!(c->closes & CLOSES_SENT_EOF)) {
8019 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
8020 ssh2_try_send_and_unthrottle(ssh, c);
8024 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
8028 unsigned ext_type = 0; /* 0 means not extended */
8029 struct ssh_channel *c;
8030 c = ssh_channel_msg(ssh, pktin);
8033 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
8034 ext_type = ssh_pkt_getuint32(pktin);
8035 ssh_pkt_getstring(pktin, &data, &length);
8038 c->v.v2.locwindow -= length;
8039 c->v.v2.remlocwin -= length;
8040 if (ext_type != 0 && ext_type != SSH2_EXTENDED_DATA_STDERR)
8041 length = 0; /* Don't do anything with unknown extended data. */
8042 bufsize = ssh_channel_data(c, ext_type == SSH2_EXTENDED_DATA_STDERR,
8045 * If it looks like the remote end hit the end of its window,
8046 * and we didn't want it to do that, think about using a
8049 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
8050 c->v.v2.locmaxwin < 0x40000000)
8051 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
8053 * If we are not buffering too much data,
8054 * enlarge the window again at the remote side.
8055 * If we are buffering too much, we may still
8056 * need to adjust the window if the server's
8059 if (bufsize < c->v.v2.locmaxwin)
8060 ssh2_set_window(c, c->v.v2.locmaxwin - bufsize);
8062 * If we're either buffering way too much data, or if we're
8063 * buffering anything at all and we're in "simple" mode,
8064 * throttle the whole channel.
8066 if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
8067 && !c->throttling_conn) {
8068 c->throttling_conn = 1;
8069 ssh_throttle_conn(ssh, +1);
8074 static void ssh_check_termination(Ssh ssh)
8076 if (ssh->version == 2 &&
8077 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
8078 (ssh->channels && count234(ssh->channels) == 0) &&
8079 !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
8081 * We used to send SSH_MSG_DISCONNECT here, because I'd
8082 * believed that _every_ conforming SSH-2 connection had to
8083 * end with a disconnect being sent by at least one side;
8084 * apparently I was wrong and it's perfectly OK to
8085 * unceremoniously slam the connection shut when you're done,
8086 * and indeed OpenSSH feels this is more polite than sending a
8087 * DISCONNECT. So now we don't.
8089 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
8093 void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
8094 const char *peerinfo)
8097 logeventf(ssh, "Connection sharing downstream #%u connected from %s",
8100 logeventf(ssh, "Connection sharing downstream #%u connected", id);
8103 void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
8105 logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
8106 ssh_check_termination(ssh);
8109 void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
8114 va_start(ap, logfmt);
8115 buf = dupvprintf(logfmt, ap);
8118 logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
8120 logeventf(ssh, "Connection sharing: %s", buf);
8125 * Close any local socket and free any local resources associated with
8126 * a channel. This converts the channel into a CHAN_ZOMBIE.
8128 static void ssh_channel_close_local(struct ssh_channel *c, char const *reason)
8131 char const *msg = NULL;
8134 case CHAN_MAINSESSION:
8135 ssh->mainchan = NULL;
8136 update_specials_menu(ssh->frontend);
8139 assert(c->u.x11.xconn != NULL);
8140 x11_close(c->u.x11.xconn);
8141 msg = "Forwarded X11 connection terminated";
8144 sfree(c->u.a.message);
8147 assert(c->u.pfd.pf != NULL);
8148 pfd_close(c->u.pfd.pf);
8149 msg = "Forwarded port closed";
8152 c->type = CHAN_ZOMBIE;
8155 logeventf(ssh, "%s %s", msg, reason);
8161 static void ssh_channel_destroy(struct ssh_channel *c)
8165 ssh_channel_close_local(c, NULL);
8167 del234(ssh->channels, c);
8168 if (ssh->version == 2) {
8169 bufchain_clear(&c->v.v2.outbuffer);
8170 assert(c->v.v2.chanreq_head == NULL);
8175 * If that was the last channel left open, we might need to
8178 ssh_check_termination(ssh);
8181 static void ssh2_channel_check_close(struct ssh_channel *c)
8184 struct Packet *pktout;
8186 assert(ssh->version == 2);
8189 * If we've sent out our own CHANNEL_OPEN but not yet seen
8190 * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
8191 * it's too early to be sending close messages of any kind.
8196 if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
8197 c->type == CHAN_ZOMBIE) &&
8198 !c->v.v2.chanreq_head &&
8199 !(c->closes & CLOSES_SENT_CLOSE)) {
8201 * We have both sent and received EOF (or the channel is a
8202 * zombie), and we have no outstanding channel requests, which
8203 * means the channel is in final wind-up. But we haven't sent
8204 * CLOSE, so let's do so now.
8206 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
8207 ssh2_pkt_adduint32(pktout, c->remoteid);
8208 ssh2_pkt_send(ssh, pktout);
8209 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
8212 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
8213 assert(c->v.v2.chanreq_head == NULL);
8215 * We have both sent and received CLOSE, which means we're
8216 * completely done with the channel.
8218 ssh_channel_destroy(c);
8222 static void ssh_channel_got_eof(struct ssh_channel *c)
8224 if (c->closes & CLOSES_RCVD_EOF)
8225 return; /* already seen EOF */
8226 c->closes |= CLOSES_RCVD_EOF;
8228 if (c->type == CHAN_X11) {
8229 assert(c->u.x11.xconn != NULL);
8230 x11_send_eof(c->u.x11.xconn);
8231 } else if (c->type == CHAN_AGENT) {
8232 if (c->u.a.outstanding_requests == 0) {
8233 /* Manufacture an outgoing EOF in response to the incoming one. */
8234 sshfwd_write_eof(c);
8236 } else if (c->type == CHAN_SOCKDATA) {
8237 assert(c->u.pfd.pf != NULL);
8238 pfd_send_eof(c->u.pfd.pf);
8239 } else if (c->type == CHAN_MAINSESSION) {
8242 if (!ssh->sent_console_eof &&
8243 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
8245 * Either from_backend_eof told us that the front end
8246 * wants us to close the outgoing side of the connection
8247 * as soon as we see EOF from the far end, or else we've
8248 * unilaterally decided to do that because we've allocated
8249 * a remote pty and hence EOF isn't a particularly
8250 * meaningful concept.
8252 sshfwd_write_eof(c);
8254 ssh->sent_console_eof = TRUE;
8258 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
8260 struct ssh_channel *c;
8262 c = ssh_channel_msg(ssh, pktin);
8265 ssh_channel_got_eof(c);
8266 ssh2_channel_check_close(c);
8269 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
8271 struct ssh_channel *c;
8273 c = ssh_channel_msg(ssh, pktin);
8278 * When we receive CLOSE on a channel, we assume it comes with an
8279 * implied EOF if we haven't seen EOF yet.
8281 ssh_channel_got_eof(c);
8283 if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
8285 * It also means we stop expecting to see replies to any
8286 * outstanding channel requests, so clean those up too.
8287 * (ssh_chanreq_init will enforce by assertion that we don't
8288 * subsequently put anything back on this list.)
8290 while (c->v.v2.chanreq_head) {
8291 struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
8292 ocr->handler(c, NULL, ocr->ctx);
8293 c->v.v2.chanreq_head = ocr->next;
8299 * And we also send an outgoing EOF, if we haven't already, on the
8300 * assumption that CLOSE is a pretty forceful announcement that
8301 * the remote side is doing away with the entire channel. (If it
8302 * had wanted to send us EOF and continue receiving data from us,
8303 * it would have just sent CHANNEL_EOF.)
8305 if (!(c->closes & CLOSES_SENT_EOF)) {
8307 * Make sure we don't read any more from whatever our local
8308 * data source is for this channel.
8311 case CHAN_MAINSESSION:
8312 ssh->send_ok = 0; /* stop trying to read from stdin */
8315 x11_override_throttle(c->u.x11.xconn, 1);
8318 pfd_override_throttle(c->u.pfd.pf, 1);
8323 * Abandon any buffered data we still wanted to send to this
8324 * channel. Receiving a CHANNEL_CLOSE is an indication that
8325 * the server really wants to get on and _destroy_ this
8326 * channel, and it isn't going to send us any further
8327 * WINDOW_ADJUSTs to permit us to send pending stuff.
8329 bufchain_clear(&c->v.v2.outbuffer);
8332 * Send outgoing EOF.
8334 sshfwd_write_eof(c);
8338 * Now process the actual close.
8340 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
8341 c->closes |= CLOSES_RCVD_CLOSE;
8342 ssh2_channel_check_close(c);
8346 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
8348 struct ssh_channel *c;
8350 c = ssh_channel_msg(ssh, pktin);
8353 assert(c->halfopen); /* ssh_channel_msg will have enforced this */
8354 c->remoteid = ssh_pkt_getuint32(pktin);
8355 c->halfopen = FALSE;
8356 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8357 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
8359 if (c->type == CHAN_SOCKDATA) {
8360 assert(c->u.pfd.pf != NULL);
8361 pfd_confirm(c->u.pfd.pf);
8362 } else if (c->type == CHAN_ZOMBIE) {
8364 * This case can occur if a local socket error occurred
8365 * between us sending out CHANNEL_OPEN and receiving
8366 * OPEN_CONFIRMATION. In this case, all we can do is
8367 * immediately initiate close proceedings now that we know the
8368 * server's id to put in the close message.
8370 ssh2_channel_check_close(c);
8373 * We never expect to receive OPEN_CONFIRMATION for any
8374 * *other* channel type (since only local-to-remote port
8375 * forwardings cause us to send CHANNEL_OPEN after the main
8376 * channel is live - all other auxiliary channel types are
8377 * initiated from the server end). It's safe to enforce this
8378 * by assertion rather than by ssh_disconnect, because the
8379 * real point is that we never constructed a half-open channel
8380 * structure in the first place with any type other than the
8383 assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
8387 ssh_channel_try_eof(c); /* in case we had a pending EOF */
8390 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
8392 static const char *const reasons[] = {
8393 "<unknown reason code>",
8394 "Administratively prohibited",
8396 "Unknown channel type",
8397 "Resource shortage",
8399 unsigned reason_code;
8400 char *reason_string;
8402 struct ssh_channel *c;
8404 c = ssh_channel_msg(ssh, pktin);
8407 assert(c->halfopen); /* ssh_channel_msg will have enforced this */
8409 if (c->type == CHAN_SOCKDATA) {
8410 reason_code = ssh_pkt_getuint32(pktin);
8411 if (reason_code >= lenof(reasons))
8412 reason_code = 0; /* ensure reasons[reason_code] in range */
8413 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
8414 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
8415 reasons[reason_code], reason_length,
8416 NULLTOEMPTY(reason_string));
8418 pfd_close(c->u.pfd.pf);
8419 } else if (c->type == CHAN_ZOMBIE) {
8421 * This case can occur if a local socket error occurred
8422 * between us sending out CHANNEL_OPEN and receiving
8423 * OPEN_FAILURE. In this case, we need do nothing except allow
8424 * the code below to throw the half-open channel away.
8428 * We never expect to receive OPEN_FAILURE for any *other*
8429 * channel type (since only local-to-remote port forwardings
8430 * cause us to send CHANNEL_OPEN after the main channel is
8431 * live - all other auxiliary channel types are initiated from
8432 * the server end). It's safe to enforce this by assertion
8433 * rather than by ssh_disconnect, because the real point is
8434 * that we never constructed a half-open channel structure in
8435 * the first place with any type other than the above.
8437 assert(!"Funny channel type in ssh2_msg_channel_open_failure");
8440 del234(ssh->channels, c);
8444 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
8447 int typelen, want_reply;
8448 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
8449 struct ssh_channel *c;
8450 struct Packet *pktout;
8452 c = ssh_channel_msg(ssh, pktin);
8455 ssh_pkt_getstring(pktin, &type, &typelen);
8456 want_reply = ssh2_pkt_getbool(pktin);
8458 if (c->closes & CLOSES_SENT_CLOSE) {
8460 * We don't reply to channel requests after we've sent
8461 * CHANNEL_CLOSE for the channel, because our reply might
8462 * cross in the network with the other side's CHANNEL_CLOSE
8463 * and arrive after they have wound the channel up completely.
8469 * Having got the channel number, we now look at
8470 * the request type string to see if it's something
8473 if (c == ssh->mainchan) {
8475 * We recognise "exit-status" and "exit-signal" on
8476 * the primary channel.
8478 if (typelen == 11 &&
8479 !memcmp(type, "exit-status", 11)) {
8481 ssh->exitcode = ssh_pkt_getuint32(pktin);
8482 logeventf(ssh, "Server sent command exit status %d",
8484 reply = SSH2_MSG_CHANNEL_SUCCESS;
8486 } else if (typelen == 11 &&
8487 !memcmp(type, "exit-signal", 11)) {
8489 int is_plausible = TRUE, is_int = FALSE;
8490 char *fmt_sig = NULL, *fmt_msg = NULL;
8492 int msglen = 0, core = FALSE;
8493 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
8494 * provide an `int' for the signal, despite its
8495 * having been a `string' in the drafts of RFC 4254 since at
8496 * least 2001. (Fixed in session.c 1.147.) Try to
8497 * infer which we can safely parse it as. */
8499 unsigned char *p = pktin->body +
8501 long len = pktin->length - pktin->savedpos;
8502 unsigned long num = GET_32BIT(p); /* what is it? */
8503 /* If it's 0, it hardly matters; assume string */
8507 int maybe_int = FALSE, maybe_str = FALSE;
8508 #define CHECK_HYPOTHESIS(offset, result) \
8511 int q = toint(offset); \
8512 if (q >= 0 && q+4 <= len) { \
8513 q = toint(q + 4 + GET_32BIT(p+q)); \
8514 if (q >= 0 && q+4 <= len && \
8515 ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
8520 CHECK_HYPOTHESIS(4+1, maybe_int);
8521 CHECK_HYPOTHESIS(4+num+1, maybe_str);
8522 #undef CHECK_HYPOTHESIS
8523 if (maybe_int && !maybe_str)
8525 else if (!maybe_int && maybe_str)
8528 /* Crikey. Either or neither. Panic. */
8529 is_plausible = FALSE;
8532 ssh->exitcode = 128; /* means `unknown signal' */
8535 /* Old non-standard OpenSSH. */
8536 int signum = ssh_pkt_getuint32(pktin);
8537 fmt_sig = dupprintf(" %d", signum);
8538 ssh->exitcode = 128 + signum;
8540 /* As per RFC 4254. */
8543 ssh_pkt_getstring(pktin, &sig, &siglen);
8544 /* Signal name isn't supposed to be blank, but
8545 * let's cope gracefully if it is. */
8547 fmt_sig = dupprintf(" \"%.*s\"",
8552 * Really hideous method of translating the
8553 * signal description back into a locally
8554 * meaningful number.
8559 #define TRANSLATE_SIGNAL(s) \
8560 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
8561 ssh->exitcode = 128 + SIG ## s
8563 TRANSLATE_SIGNAL(ABRT);
8566 TRANSLATE_SIGNAL(ALRM);
8569 TRANSLATE_SIGNAL(FPE);
8572 TRANSLATE_SIGNAL(HUP);
8575 TRANSLATE_SIGNAL(ILL);
8578 TRANSLATE_SIGNAL(INT);
8581 TRANSLATE_SIGNAL(KILL);
8584 TRANSLATE_SIGNAL(PIPE);
8587 TRANSLATE_SIGNAL(QUIT);
8590 TRANSLATE_SIGNAL(SEGV);
8593 TRANSLATE_SIGNAL(TERM);
8596 TRANSLATE_SIGNAL(USR1);
8599 TRANSLATE_SIGNAL(USR2);
8601 #undef TRANSLATE_SIGNAL
8603 ssh->exitcode = 128;
8605 core = ssh2_pkt_getbool(pktin);
8606 ssh_pkt_getstring(pktin, &msg, &msglen);
8608 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
8610 /* ignore lang tag */
8611 } /* else don't attempt to parse */
8612 logeventf(ssh, "Server exited on signal%s%s%s",
8613 fmt_sig ? fmt_sig : "",
8614 core ? " (core dumped)" : "",
8615 fmt_msg ? fmt_msg : "");
8618 reply = SSH2_MSG_CHANNEL_SUCCESS;
8623 * This is a channel request we don't know
8624 * about, so we now either ignore the request
8625 * or respond with CHANNEL_FAILURE, depending
8628 reply = SSH2_MSG_CHANNEL_FAILURE;
8631 pktout = ssh2_pkt_init(reply);
8632 ssh2_pkt_adduint32(pktout, c->remoteid);
8633 ssh2_pkt_send(ssh, pktout);
8637 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
8640 int typelen, want_reply;
8641 struct Packet *pktout;
8643 ssh_pkt_getstring(pktin, &type, &typelen);
8644 want_reply = ssh2_pkt_getbool(pktin);
8647 * We currently don't support any global requests
8648 * at all, so we either ignore the request or
8649 * respond with REQUEST_FAILURE, depending on
8653 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
8654 ssh2_pkt_send(ssh, pktout);
8658 struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
8662 struct X11FakeAuth *auth;
8665 * Make up a new set of fake X11 auth data, and add it to the tree
8666 * of currently valid ones with an indication of the sharing
8667 * context that it's relevant to.
8669 auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
8670 auth->share_cs = share_cs;
8671 auth->share_chan = share_chan;
8676 void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
8678 del234(ssh->x11authtree, auth);
8679 x11_free_fake_auth(auth);
8682 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
8689 const char *error = NULL;
8690 struct ssh_channel *c;
8691 unsigned remid, winsize, pktsize;
8692 unsigned our_winsize_override = 0;
8693 struct Packet *pktout;
8695 ssh_pkt_getstring(pktin, &type, &typelen);
8696 c = snew(struct ssh_channel);
8699 remid = ssh_pkt_getuint32(pktin);
8700 winsize = ssh_pkt_getuint32(pktin);
8701 pktsize = ssh_pkt_getuint32(pktin);
8703 if (typelen == 3 && !memcmp(type, "x11", 3)) {
8706 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8707 addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
8708 peerport = ssh_pkt_getuint32(pktin);
8710 logeventf(ssh, "Received X11 connect request from %s:%d",
8713 if (!ssh->X11_fwd_enabled && !ssh->connshare)
8714 error = "X11 forwarding is not enabled";
8716 c->u.x11.xconn = x11_init(ssh->x11authtree, c,
8719 c->u.x11.initial = TRUE;
8722 * If we are a connection-sharing upstream, then we should
8723 * initially present a very small window, adequate to take
8724 * the X11 initial authorisation packet but not much more.
8725 * Downstream will then present us a larger window (by
8726 * fiat of the connection-sharing protocol) and we can
8727 * guarantee to send a positive-valued WINDOW_ADJUST.
8730 our_winsize_override = 128;
8732 logevent("Opened X11 forward channel");
8736 } else if (typelen == 15 &&
8737 !memcmp(type, "forwarded-tcpip", 15)) {
8738 struct ssh_rportfwd pf, *realpf;
8741 ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
8742 pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
8743 pf.sport = ssh_pkt_getuint32(pktin);
8744 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
8745 peerport = ssh_pkt_getuint32(pktin);
8746 realpf = find234(ssh->rportfwds, &pf, NULL);
8747 logeventf(ssh, "Received remote port %s:%d open request "
8748 "from %.*s:%d", pf.shost, pf.sport,
8749 peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
8752 if (realpf == NULL) {
8753 error = "Remote port is not recognised";
8757 if (realpf->share_ctx) {
8759 * This port forwarding is on behalf of a
8760 * connection-sharing downstream, so abandon our own
8761 * channel-open procedure and just pass the message on
8764 share_got_pkt_from_server(realpf->share_ctx, pktin->type,
8765 pktin->body, pktin->length);
8770 err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
8771 c, ssh->conf, realpf->pfrec->addressfamily);
8772 logeventf(ssh, "Attempting to forward remote port to "
8773 "%s:%d", realpf->dhost, realpf->dport);
8775 logeventf(ssh, "Port open failed: %s", err);
8777 error = "Port open failed";
8779 logevent("Forwarded port opened successfully");
8780 c->type = CHAN_SOCKDATA;
8783 } else if (typelen == 22 &&
8784 !memcmp(type, "auth-agent@openssh.com", 22)) {
8785 if (!ssh->agentfwd_enabled)
8786 error = "Agent forwarding is not enabled";
8788 c->type = CHAN_AGENT; /* identify channel type */
8789 c->u.a.lensofar = 0;
8790 c->u.a.message = NULL;
8791 c->u.a.outstanding_requests = 0;
8794 error = "Unsupported channel type requested";
8797 c->remoteid = remid;
8798 c->halfopen = FALSE;
8800 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
8801 ssh2_pkt_adduint32(pktout, c->remoteid);
8802 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
8803 ssh2_pkt_addstring(pktout, error);
8804 ssh2_pkt_addstring(pktout, "en"); /* language tag */
8805 ssh2_pkt_send(ssh, pktout);
8806 logeventf(ssh, "Rejected channel open: %s", error);
8809 ssh_channel_init(c);
8810 c->v.v2.remwindow = winsize;
8811 c->v.v2.remmaxpkt = pktsize;
8812 if (our_winsize_override) {
8813 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
8814 our_winsize_override;
8816 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
8817 ssh2_pkt_adduint32(pktout, c->remoteid);
8818 ssh2_pkt_adduint32(pktout, c->localid);
8819 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
8820 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
8821 ssh2_pkt_send(ssh, pktout);
8825 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
8826 void *share_cs, void *share_chan,
8827 const char *peer_addr, int peer_port,
8828 int endian, int protomajor, int protominor,
8829 const void *initial_data, int initial_len)
8832 * This function is called when we've just discovered that an X
8833 * forwarding channel on which we'd been handling the initial auth
8834 * ourselves turns out to be destined for a connection-sharing
8835 * downstream. So we turn the channel into a CHAN_SHARING, meaning
8836 * that we completely stop tracking windows and buffering data and
8837 * just pass more or less unmodified SSH messages back and forth.
8839 c->type = CHAN_SHARING;
8840 c->u.sharing.ctx = share_cs;
8841 share_setup_x11_channel(share_cs, share_chan,
8842 c->localid, c->remoteid, c->v.v2.remwindow,
8843 c->v.v2.remmaxpkt, c->v.v2.locwindow,
8844 peer_addr, peer_port, endian,
8845 protomajor, protominor,
8846 initial_data, initial_len);
8849 void sshfwd_x11_is_local(struct ssh_channel *c)
8852 * This function is called when we've just discovered that an X
8853 * forwarding channel is _not_ destined for a connection-sharing
8854 * downstream but we're going to handle it ourselves. We stop
8855 * presenting a cautiously small window and go into ordinary data
8858 c->u.x11.initial = FALSE;
8859 ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
8863 * Buffer banner messages for later display at some convenient point,
8864 * if we're going to display them.
8866 static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
8868 /* Arbitrary limit to prevent unbounded inflation of buffer */
8869 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
8870 bufchain_size(&ssh->banner) <= 131072) {
8871 char *banner = NULL;
8873 ssh_pkt_getstring(pktin, &banner, &size);
8875 bufchain_add(&ssh->banner, banner, size);
8879 /* Helper function to deal with sending tty modes for "pty-req" */
8880 static void ssh2_send_ttymode(void *data,
8881 const struct ssh_ttymode *mode, char *val)
8883 struct Packet *pktout = (struct Packet *)data;
8884 unsigned int arg = 0;
8886 switch (mode->type) {
8888 arg = ssh_tty_parse_specchar(val);
8891 arg = ssh_tty_parse_boolean(val);
8894 ssh2_pkt_addbyte(pktout, mode->opcode);
8895 ssh2_pkt_adduint32(pktout, arg);
8898 static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
8901 struct ssh2_setup_x11_state {
8905 struct Packet *pktout;
8906 crStateP(ssh2_setup_x11_state, ctx);
8910 logevent("Requesting X11 forwarding");
8911 pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
8913 ssh2_pkt_addbool(pktout, 0); /* many connections */
8914 ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
8915 ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
8916 ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
8917 ssh2_pkt_send(ssh, pktout);
8919 /* Wait to be called back with either a response packet, or NULL
8920 * meaning clean up and free our data */
8924 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8925 logevent("X11 forwarding enabled");
8926 ssh->X11_fwd_enabled = TRUE;
8928 logevent("X11 forwarding refused");
8934 static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
8937 struct ssh2_setup_agent_state {
8941 struct Packet *pktout;
8942 crStateP(ssh2_setup_agent_state, ctx);
8946 logevent("Requesting OpenSSH-style agent forwarding");
8947 pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
8948 ssh2_setup_agent, s);
8949 ssh2_pkt_send(ssh, pktout);
8951 /* Wait to be called back with either a response packet, or NULL
8952 * meaning clean up and free our data */
8956 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
8957 logevent("Agent forwarding enabled");
8958 ssh->agentfwd_enabled = TRUE;
8960 logevent("Agent forwarding refused");
8966 static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
8969 struct ssh2_setup_pty_state {
8973 struct Packet *pktout;
8974 crStateP(ssh2_setup_pty_state, ctx);
8978 /* Unpick the terminal-speed string. */
8979 /* XXX perhaps we should allow no speeds to be sent. */
8980 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
8981 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
8982 /* Build the pty request. */
8983 pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
8985 ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
8986 ssh2_pkt_adduint32(pktout, ssh->term_width);
8987 ssh2_pkt_adduint32(pktout, ssh->term_height);
8988 ssh2_pkt_adduint32(pktout, 0); /* pixel width */
8989 ssh2_pkt_adduint32(pktout, 0); /* pixel height */
8990 ssh2_pkt_addstring_start(pktout);
8991 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
8992 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
8993 ssh2_pkt_adduint32(pktout, ssh->ispeed);
8994 ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
8995 ssh2_pkt_adduint32(pktout, ssh->ospeed);
8996 ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
8997 ssh2_pkt_send(ssh, pktout);
8998 ssh->state = SSH_STATE_INTERMED;
9000 /* Wait to be called back with either a response packet, or NULL
9001 * meaning clean up and free our data */
9005 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
9006 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
9007 ssh->ospeed, ssh->ispeed);
9008 ssh->got_pty = TRUE;
9010 c_write_str(ssh, "Server refused to allocate pty\r\n");
9011 ssh->editing = ssh->echoing = 1;
9018 static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
9021 struct ssh2_setup_env_state {
9023 int num_env, env_left, env_ok;
9026 struct Packet *pktout;
9027 crStateP(ssh2_setup_env_state, ctx);
9032 * Send environment variables.
9034 * Simplest thing here is to send all the requests at once, and
9035 * then wait for a whole bunch of successes or failures.
9041 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9043 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
9044 pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
9045 ssh2_pkt_addstring(pktout, key);
9046 ssh2_pkt_addstring(pktout, val);
9047 ssh2_pkt_send(ssh, pktout);
9052 logeventf(ssh, "Sent %d environment variables", s->num_env);
9057 s->env_left = s->num_env;
9059 while (s->env_left > 0) {
9060 /* Wait to be called back with either a response packet,
9061 * or NULL meaning clean up and free our data */
9063 if (!pktin) goto out;
9064 if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
9069 if (s->env_ok == s->num_env) {
9070 logevent("All environment variables successfully set");
9071 } else if (s->env_ok == 0) {
9072 logevent("All environment variables refused");
9073 c_write_str(ssh, "Server refused to set environment variables\r\n");
9075 logeventf(ssh, "%d environment variables refused",
9076 s->num_env - s->env_ok);
9077 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9085 * Handle the SSH-2 userauth and connection layers.
9087 static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
9089 do_ssh2_authconn(ssh, NULL, 0, pktin);
9092 static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
9096 do_ssh2_authconn(c->ssh, NULL, 0, pktin);
9099 static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
9100 struct Packet *pktin)
9102 struct do_ssh2_authconn_state {
9106 AUTH_TYPE_PUBLICKEY,
9107 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
9108 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
9110 AUTH_TYPE_GSSAPI, /* always QUIET */
9111 AUTH_TYPE_KEYBOARD_INTERACTIVE,
9112 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
9114 int done_service_req;
9115 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
9116 int tried_pubkey_config, done_agent;
9121 int kbd_inter_refused;
9122 int we_are_in, userauth_success;
9123 prompts_t *cur_prompt;
9128 void *publickey_blob;
9129 int publickey_bloblen;
9130 int privatekey_available, privatekey_encrypted;
9131 char *publickey_algorithm;
9132 char *publickey_comment;
9133 unsigned char agent_request[5], *agent_response, *agentp;
9134 int agent_responselen;
9135 unsigned char *pkblob_in_agent;
9137 char *pkblob, *alg, *commentp;
9138 int pklen, alglen, commentlen;
9139 int siglen, retlen, len;
9140 char *q, *agentreq, *ret;
9141 struct Packet *pktout;
9144 struct ssh_gss_library *gsslib;
9145 Ssh_gss_ctx gss_ctx;
9146 Ssh_gss_buf gss_buf;
9147 Ssh_gss_buf gss_rcvtok, gss_sndtok;
9148 Ssh_gss_name gss_srv_name;
9149 Ssh_gss_stat gss_stat;
9152 crState(do_ssh2_authconn_state);
9156 /* Register as a handler for all the messages this coroutine handles. */
9157 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
9158 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
9159 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
9160 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
9161 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
9162 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
9163 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
9164 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
9165 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
9166 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
9167 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
9168 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
9169 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
9170 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
9171 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
9172 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
9173 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
9174 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
9175 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
9176 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
9178 s->done_service_req = FALSE;
9179 s->we_are_in = s->userauth_success = FALSE;
9180 s->agent_response = NULL;
9182 s->tried_gssapi = FALSE;
9185 if (!ssh->bare_connection) {
9186 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
9188 * Request userauth protocol, and await a response to it.
9190 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9191 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
9192 ssh2_pkt_send(ssh, s->pktout);
9193 crWaitUntilV(pktin);
9194 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
9195 s->done_service_req = TRUE;
9197 if (!s->done_service_req) {
9199 * Request connection protocol directly, without authentication.
9201 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
9202 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9203 ssh2_pkt_send(ssh, s->pktout);
9204 crWaitUntilV(pktin);
9205 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
9206 s->we_are_in = TRUE; /* no auth required */
9208 bombout(("Server refused service request"));
9213 s->we_are_in = TRUE;
9216 /* Arrange to be able to deal with any BANNERs that come in.
9217 * (We do this now as packets may come in during the next bit.) */
9218 bufchain_init(&ssh->banner);
9219 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
9220 ssh2_msg_userauth_banner;
9223 * Misc one-time setup for authentication.
9225 s->publickey_blob = NULL;
9226 if (!s->we_are_in) {
9229 * Load the public half of any configured public key file
9232 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9233 if (!filename_is_null(s->keyfile)) {
9235 logeventf(ssh, "Reading key file \"%.150s\"",
9236 filename_to_str(s->keyfile));
9237 keytype = key_type(s->keyfile);
9238 if (keytype == SSH_KEYTYPE_SSH2 ||
9239 keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
9240 keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
9243 ssh2_userkey_loadpub(s->keyfile,
9244 &s->publickey_algorithm,
9245 &s->publickey_bloblen,
9246 &s->publickey_comment, &error);
9247 if (s->publickey_blob) {
9248 s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
9249 if (!s->privatekey_available)
9250 logeventf(ssh, "Key file contains public key only");
9251 s->privatekey_encrypted =
9252 ssh2_userkey_encrypted(s->keyfile, NULL);
9255 logeventf(ssh, "Unable to load key (%s)",
9257 msgbuf = dupprintf("Unable to load key file "
9258 "\"%.150s\" (%s)\r\n",
9259 filename_to_str(s->keyfile),
9261 c_write_str(ssh, msgbuf);
9266 logeventf(ssh, "Unable to use this key file (%s)",
9267 key_type_to_str(keytype));
9268 msgbuf = dupprintf("Unable to use key file \"%.150s\""
9270 filename_to_str(s->keyfile),
9271 key_type_to_str(keytype));
9272 c_write_str(ssh, msgbuf);
9274 s->publickey_blob = NULL;
9279 * Find out about any keys Pageant has (but if there's a
9280 * public key configured, filter out all others).
9283 s->agent_response = NULL;
9284 s->pkblob_in_agent = NULL;
9285 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
9289 logevent("Pageant is running. Requesting keys.");
9291 /* Request the keys held by the agent. */
9292 PUT_32BIT(s->agent_request, 1);
9293 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
9294 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
9295 ssh_agent_callback, ssh)) {
9299 bombout(("Unexpected data from server while"
9300 " waiting for agent response"));
9303 } while (pktin || inlen > 0);
9304 r = ssh->agent_response;
9305 s->agent_responselen = ssh->agent_response_len;
9307 s->agent_response = (unsigned char *) r;
9308 if (s->agent_response && s->agent_responselen >= 5 &&
9309 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
9312 p = s->agent_response + 5;
9313 s->nkeys = toint(GET_32BIT(p));
9316 * Vet the Pageant response to ensure that the key
9317 * count and blob lengths make sense.
9320 logeventf(ssh, "Pageant response contained a negative"
9321 " key count %d", s->nkeys);
9323 goto done_agent_query;
9325 unsigned char *q = p + 4;
9326 int lenleft = s->agent_responselen - 5 - 4;
9328 for (keyi = 0; keyi < s->nkeys; keyi++) {
9329 int bloblen, commentlen;
9331 logeventf(ssh, "Pageant response was truncated");
9333 goto done_agent_query;
9335 bloblen = toint(GET_32BIT(q));
9336 if (bloblen < 0 || bloblen > lenleft) {
9337 logeventf(ssh, "Pageant response was truncated");
9339 goto done_agent_query;
9341 lenleft -= 4 + bloblen;
9343 commentlen = toint(GET_32BIT(q));
9344 if (commentlen < 0 || commentlen > lenleft) {
9345 logeventf(ssh, "Pageant response was truncated");
9347 goto done_agent_query;
9349 lenleft -= 4 + commentlen;
9350 q += 4 + commentlen;
9355 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
9356 if (s->publickey_blob) {
9357 /* See if configured key is in agent. */
9358 for (keyi = 0; keyi < s->nkeys; keyi++) {
9359 s->pklen = toint(GET_32BIT(p));
9360 if (s->pklen == s->publickey_bloblen &&
9361 !memcmp(p+4, s->publickey_blob,
9362 s->publickey_bloblen)) {
9363 logeventf(ssh, "Pageant key #%d matches "
9364 "configured key file", keyi);
9366 s->pkblob_in_agent = p;
9370 p += toint(GET_32BIT(p)) + 4; /* comment */
9372 if (!s->pkblob_in_agent) {
9373 logevent("Configured key file not in Pageant");
9378 logevent("Failed to get reply from Pageant");
9386 * We repeat this whole loop, including the username prompt,
9387 * until we manage a successful authentication. If the user
9388 * types the wrong _password_, they can be sent back to the
9389 * beginning to try another username, if this is configured on.
9390 * (If they specify a username in the config, they are never
9391 * asked, even if they do give a wrong password.)
9393 * I think this best serves the needs of
9395 * - the people who have no configuration, no keys, and just
9396 * want to try repeated (username,password) pairs until they
9397 * type both correctly
9399 * - people who have keys and configuration but occasionally
9400 * need to fall back to passwords
9402 * - people with a key held in Pageant, who might not have
9403 * logged in to a particular machine before; so they want to
9404 * type a username, and then _either_ their key will be
9405 * accepted, _or_ they will type a password. If they mistype
9406 * the username they will want to be able to get back and
9409 s->got_username = FALSE;
9410 while (!s->we_are_in) {
9414 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
9416 * We got a username last time round this loop, and
9417 * with change_username turned off we don't try to get
9420 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
9421 int ret; /* need not be kept over crReturn */
9422 s->cur_prompt = new_prompts(ssh->frontend);
9423 s->cur_prompt->to_server = TRUE;
9424 s->cur_prompt->name = dupstr("SSH login name");
9425 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
9426 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9429 crWaitUntilV(!pktin);
9430 ret = get_userpass_input(s->cur_prompt, in, inlen);
9435 * get_userpass_input() failed to get a username.
9438 free_prompts(s->cur_prompt);
9439 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
9442 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
9443 free_prompts(s->cur_prompt);
9446 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
9447 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
9448 c_write_str(ssh, stuff);
9452 s->got_username = TRUE;
9455 * Send an authentication request using method "none": (a)
9456 * just in case it succeeds, and (b) so that we know what
9457 * authentication methods we can usefully try next.
9459 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9461 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9462 ssh2_pkt_addstring(s->pktout, ssh->username);
9463 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
9464 ssh2_pkt_addstring(s->pktout, "none"); /* method */
9465 ssh2_pkt_send(ssh, s->pktout);
9466 s->type = AUTH_TYPE_NONE;
9468 s->we_are_in = FALSE;
9470 s->tried_pubkey_config = FALSE;
9471 s->kbd_inter_refused = FALSE;
9473 /* Reset agent request state. */
9474 s->done_agent = FALSE;
9475 if (s->agent_response) {
9476 if (s->pkblob_in_agent) {
9477 s->agentp = s->pkblob_in_agent;
9479 s->agentp = s->agent_response + 5 + 4;
9485 char *methods = NULL;
9489 * Wait for the result of the last authentication request.
9492 crWaitUntilV(pktin);
9494 * Now is a convenient point to spew any banner material
9495 * that we've accumulated. (This should ensure that when
9496 * we exit the auth loop, we haven't any left to deal
9500 int size = bufchain_size(&ssh->banner);
9502 * Don't show the banner if we're operating in
9503 * non-verbose non-interactive mode. (It's probably
9504 * a script, which means nobody will read the
9505 * banner _anyway_, and moreover the printing of
9506 * the banner will screw up processing on the
9507 * output of (say) plink.)
9509 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
9510 char *banner = snewn(size, char);
9511 bufchain_fetch(&ssh->banner, banner, size);
9512 c_write_untrusted(ssh, banner, size);
9515 bufchain_clear(&ssh->banner);
9517 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
9518 logevent("Access granted");
9519 s->we_are_in = s->userauth_success = TRUE;
9523 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
9524 bombout(("Strange packet received during authentication: "
9525 "type %d", pktin->type));
9532 * OK, we're now sitting on a USERAUTH_FAILURE message, so
9533 * we can look at the string in it and know what we can
9534 * helpfully try next.
9536 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
9537 ssh_pkt_getstring(pktin, &methods, &methlen);
9538 if (!ssh2_pkt_getbool(pktin)) {
9540 * We have received an unequivocal Access
9541 * Denied. This can translate to a variety of
9542 * messages, or no message at all.
9544 * For forms of authentication which are attempted
9545 * implicitly, by which I mean without printing
9546 * anything in the window indicating that we're
9547 * trying them, we should never print 'Access
9550 * If we do print a message saying that we're
9551 * attempting some kind of authentication, it's OK
9552 * to print a followup message saying it failed -
9553 * but the message may sometimes be more specific
9554 * than simply 'Access denied'.
9556 * Additionally, if we'd just tried password
9557 * authentication, we should break out of this
9558 * whole loop so as to go back to the username
9559 * prompt (iff we're configured to allow
9560 * username change attempts).
9562 if (s->type == AUTH_TYPE_NONE) {
9564 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
9565 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
9566 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
9567 c_write_str(ssh, "Server refused our key\r\n");
9568 logevent("Server refused our key");
9569 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
9570 /* This _shouldn't_ happen except by a
9571 * protocol bug causing client and server to
9572 * disagree on what is a correct signature. */
9573 c_write_str(ssh, "Server refused public-key signature"
9574 " despite accepting key!\r\n");
9575 logevent("Server refused public-key signature"
9576 " despite accepting key!");
9577 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
9578 /* quiet, so no c_write */
9579 logevent("Server refused keyboard-interactive authentication");
9580 } else if (s->type==AUTH_TYPE_GSSAPI) {
9581 /* always quiet, so no c_write */
9582 /* also, the code down in the GSSAPI block has
9583 * already logged this in the Event Log */
9584 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
9585 logevent("Keyboard-interactive authentication failed");
9586 c_write_str(ssh, "Access denied\r\n");
9588 assert(s->type == AUTH_TYPE_PASSWORD);
9589 logevent("Password authentication failed");
9590 c_write_str(ssh, "Access denied\r\n");
9592 if (conf_get_int(ssh->conf, CONF_change_username)) {
9593 /* XXX perhaps we should allow
9594 * keyboard-interactive to do this too? */
9595 s->we_are_in = FALSE;
9600 c_write_str(ssh, "Further authentication required\r\n");
9601 logevent("Further authentication required");
9605 in_commasep_string("publickey", methods, methlen);
9607 in_commasep_string("password", methods, methlen);
9608 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
9609 in_commasep_string("keyboard-interactive", methods, methlen);
9611 if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
9612 in_commasep_string("gssapi-with-mic", methods, methlen)) {
9613 /* Try loading the GSS libraries and see if we
9616 ssh->gsslibs = ssh_gss_setup(ssh->conf);
9617 s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
9619 /* No point in even bothering to try to load the
9620 * GSS libraries, if the user configuration and
9621 * server aren't both prepared to attempt GSSAPI
9622 * auth in the first place. */
9623 s->can_gssapi = FALSE;
9628 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
9630 if (s->can_pubkey && !s->done_agent && s->nkeys) {
9633 * Attempt public-key authentication using a key from Pageant.
9636 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9638 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
9640 /* Unpack key from agent response */
9641 s->pklen = toint(GET_32BIT(s->agentp));
9643 s->pkblob = (char *)s->agentp;
9644 s->agentp += s->pklen;
9645 s->alglen = toint(GET_32BIT(s->pkblob));
9646 s->alg = s->pkblob + 4;
9647 s->commentlen = toint(GET_32BIT(s->agentp));
9649 s->commentp = (char *)s->agentp;
9650 s->agentp += s->commentlen;
9651 /* s->agentp now points at next key, if any */
9653 /* See if server will accept it */
9654 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9655 ssh2_pkt_addstring(s->pktout, ssh->username);
9656 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9657 /* service requested */
9658 ssh2_pkt_addstring(s->pktout, "publickey");
9660 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
9661 ssh2_pkt_addstring_start(s->pktout);
9662 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9663 ssh2_pkt_addstring_start(s->pktout);
9664 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9665 ssh2_pkt_send(ssh, s->pktout);
9666 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
9668 crWaitUntilV(pktin);
9669 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9671 /* Offer of key refused. */
9678 if (flags & FLAG_VERBOSE) {
9679 c_write_str(ssh, "Authenticating with "
9681 c_write(ssh, s->commentp, s->commentlen);
9682 c_write_str(ssh, "\" from agent\r\n");
9686 * Server is willing to accept the key.
9687 * Construct a SIGN_REQUEST.
9689 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9690 ssh2_pkt_addstring(s->pktout, ssh->username);
9691 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9692 /* service requested */
9693 ssh2_pkt_addstring(s->pktout, "publickey");
9695 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
9696 ssh2_pkt_addstring_start(s->pktout);
9697 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
9698 ssh2_pkt_addstring_start(s->pktout);
9699 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
9701 /* Ask agent for signature. */
9702 s->siglen = s->pktout->length - 5 + 4 +
9703 ssh->v2_session_id_len;
9704 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9706 s->len = 1; /* message type */
9707 s->len += 4 + s->pklen; /* key blob */
9708 s->len += 4 + s->siglen; /* data to sign */
9709 s->len += 4; /* flags */
9710 s->agentreq = snewn(4 + s->len, char);
9711 PUT_32BIT(s->agentreq, s->len);
9712 s->q = s->agentreq + 4;
9713 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
9714 PUT_32BIT(s->q, s->pklen);
9716 memcpy(s->q, s->pkblob, s->pklen);
9718 PUT_32BIT(s->q, s->siglen);
9720 /* Now the data to be signed... */
9721 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9722 PUT_32BIT(s->q, ssh->v2_session_id_len);
9725 memcpy(s->q, ssh->v2_session_id,
9726 ssh->v2_session_id_len);
9727 s->q += ssh->v2_session_id_len;
9728 memcpy(s->q, s->pktout->data + 5,
9729 s->pktout->length - 5);
9730 s->q += s->pktout->length - 5;
9731 /* And finally the (zero) flags word. */
9733 if (!agent_query(s->agentreq, s->len + 4,
9735 ssh_agent_callback, ssh)) {
9739 bombout(("Unexpected data from server"
9740 " while waiting for agent"
9744 } while (pktin || inlen > 0);
9745 vret = ssh->agent_response;
9746 s->retlen = ssh->agent_response_len;
9751 if (s->retlen >= 9 &&
9752 s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
9753 GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
9754 logevent("Sending Pageant's response");
9755 ssh2_add_sigblob(ssh, s->pktout,
9756 s->pkblob, s->pklen,
9758 GET_32BIT(s->ret + 5));
9759 ssh2_pkt_send(ssh, s->pktout);
9760 s->type = AUTH_TYPE_PUBLICKEY;
9762 /* FIXME: less drastic response */
9763 bombout(("Pageant failed to answer challenge"));
9769 /* Do we have any keys left to try? */
9770 if (s->pkblob_in_agent) {
9771 s->done_agent = TRUE;
9772 s->tried_pubkey_config = TRUE;
9775 if (s->keyi >= s->nkeys)
9776 s->done_agent = TRUE;
9779 } else if (s->can_pubkey && s->publickey_blob &&
9780 s->privatekey_available && !s->tried_pubkey_config) {
9782 struct ssh2_userkey *key; /* not live over crReturn */
9783 char *passphrase; /* not live over crReturn */
9785 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
9787 s->tried_pubkey_config = TRUE;
9790 * Try the public key supplied in the configuration.
9792 * First, offer the public blob to see if the server is
9793 * willing to accept it.
9795 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9796 ssh2_pkt_addstring(s->pktout, ssh->username);
9797 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9798 /* service requested */
9799 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
9800 ssh2_pkt_addbool(s->pktout, FALSE);
9801 /* no signature included */
9802 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
9803 ssh2_pkt_addstring_start(s->pktout);
9804 ssh2_pkt_addstring_data(s->pktout,
9805 (char *)s->publickey_blob,
9806 s->publickey_bloblen);
9807 ssh2_pkt_send(ssh, s->pktout);
9808 logevent("Offered public key");
9810 crWaitUntilV(pktin);
9811 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
9812 /* Key refused. Give up. */
9813 s->gotit = TRUE; /* reconsider message next loop */
9814 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
9815 continue; /* process this new message */
9817 logevent("Offer of public key accepted");
9820 * Actually attempt a serious authentication using
9823 if (flags & FLAG_VERBOSE) {
9824 c_write_str(ssh, "Authenticating with public key \"");
9825 c_write_str(ssh, s->publickey_comment);
9826 c_write_str(ssh, "\"\r\n");
9830 const char *error; /* not live over crReturn */
9831 if (s->privatekey_encrypted) {
9833 * Get a passphrase from the user.
9835 int ret; /* need not be kept over crReturn */
9836 s->cur_prompt = new_prompts(ssh->frontend);
9837 s->cur_prompt->to_server = FALSE;
9838 s->cur_prompt->name = dupstr("SSH key passphrase");
9839 add_prompt(s->cur_prompt,
9840 dupprintf("Passphrase for key \"%.100s\": ",
9841 s->publickey_comment),
9843 ret = get_userpass_input(s->cur_prompt, NULL, 0);
9846 crWaitUntilV(!pktin);
9847 ret = get_userpass_input(s->cur_prompt,
9852 /* Failed to get a passphrase. Terminate. */
9853 free_prompts(s->cur_prompt);
9854 ssh_disconnect(ssh, NULL,
9855 "Unable to authenticate",
9856 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
9861 dupstr(s->cur_prompt->prompts[0]->result);
9862 free_prompts(s->cur_prompt);
9864 passphrase = NULL; /* no passphrase needed */
9868 * Try decrypting the key.
9870 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
9871 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
9873 /* burn the evidence */
9874 smemclr(passphrase, strlen(passphrase));
9877 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
9879 (key == SSH2_WRONG_PASSPHRASE)) {
9880 c_write_str(ssh, "Wrong passphrase\r\n");
9882 /* and loop again */
9884 c_write_str(ssh, "Unable to load private key (");
9885 c_write_str(ssh, error);
9886 c_write_str(ssh, ")\r\n");
9888 break; /* try something else */
9894 unsigned char *pkblob, *sigblob, *sigdata;
9895 int pkblob_len, sigblob_len, sigdata_len;
9899 * We have loaded the private key and the server
9900 * has announced that it's willing to accept it.
9901 * Hallelujah. Generate a signature and send it.
9903 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
9904 ssh2_pkt_addstring(s->pktout, ssh->username);
9905 ssh2_pkt_addstring(s->pktout, "ssh-connection");
9906 /* service requested */
9907 ssh2_pkt_addstring(s->pktout, "publickey");
9909 ssh2_pkt_addbool(s->pktout, TRUE);
9910 /* signature follows */
9911 ssh2_pkt_addstring(s->pktout, key->alg->name);
9912 pkblob = key->alg->public_blob(key->data,
9914 ssh2_pkt_addstring_start(s->pktout);
9915 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
9919 * The data to be signed is:
9923 * followed by everything so far placed in the
9926 sigdata_len = s->pktout->length - 5 + 4 +
9927 ssh->v2_session_id_len;
9928 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
9930 sigdata = snewn(sigdata_len, unsigned char);
9932 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
9933 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
9936 memcpy(sigdata+p, ssh->v2_session_id,
9937 ssh->v2_session_id_len);
9938 p += ssh->v2_session_id_len;
9939 memcpy(sigdata+p, s->pktout->data + 5,
9940 s->pktout->length - 5);
9941 p += s->pktout->length - 5;
9942 assert(p == sigdata_len);
9943 sigblob = key->alg->sign(key->data, (char *)sigdata,
9944 sigdata_len, &sigblob_len);
9945 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
9946 sigblob, sigblob_len);
9951 ssh2_pkt_send(ssh, s->pktout);
9952 logevent("Sent public key signature");
9953 s->type = AUTH_TYPE_PUBLICKEY;
9954 key->alg->freekey(key->data);
9955 sfree(key->comment);
9960 } else if (s->can_gssapi && !s->tried_gssapi) {
9962 /* GSSAPI Authentication */
9967 s->type = AUTH_TYPE_GSSAPI;
9968 s->tried_gssapi = TRUE;
9970 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
9973 * Pick the highest GSS library on the preference
9979 for (i = 0; i < ngsslibs; i++) {
9980 int want_id = conf_get_int_int(ssh->conf,
9981 CONF_ssh_gsslist, i);
9982 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
9983 if (ssh->gsslibs->libraries[j].id == want_id) {
9984 s->gsslib = &ssh->gsslibs->libraries[j];
9985 goto got_gsslib; /* double break */
9990 * We always expect to have found something in
9991 * the above loop: we only came here if there
9992 * was at least one viable GSS library, and the
9993 * preference list should always mention
9994 * everything and only change the order.
9999 if (s->gsslib->gsslogmsg)
10000 logevent(s->gsslib->gsslogmsg);
10002 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
10003 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10004 ssh2_pkt_addstring(s->pktout, ssh->username);
10005 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10006 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
10007 logevent("Attempting GSSAPI authentication");
10009 /* add mechanism info */
10010 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
10012 /* number of GSSAPI mechanisms */
10013 ssh2_pkt_adduint32(s->pktout,1);
10015 /* length of OID + 2 */
10016 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
10017 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
10019 /* length of OID */
10020 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
10022 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
10023 s->gss_buf.length);
10024 ssh2_pkt_send(ssh, s->pktout);
10025 crWaitUntilV(pktin);
10026 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
10027 logevent("GSSAPI authentication request refused");
10031 /* check returned packet ... */
10033 ssh_pkt_getstring(pktin, &data, &len);
10034 s->gss_rcvtok.value = data;
10035 s->gss_rcvtok.length = len;
10036 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
10037 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
10038 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
10039 memcmp((char *)s->gss_rcvtok.value + 2,
10040 s->gss_buf.value,s->gss_buf.length) ) {
10041 logevent("GSSAPI authentication - wrong response from server");
10045 /* now start running */
10046 s->gss_stat = s->gsslib->import_name(s->gsslib,
10049 if (s->gss_stat != SSH_GSS_OK) {
10050 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
10051 logevent("GSSAPI import name failed - Bad service name");
10053 logevent("GSSAPI import name failed");
10057 /* fetch TGT into GSS engine */
10058 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
10060 if (s->gss_stat != SSH_GSS_OK) {
10061 logevent("GSSAPI authentication failed to get credentials");
10062 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10066 /* initial tokens are empty */
10067 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
10068 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
10070 /* now enter the loop */
10072 s->gss_stat = s->gsslib->init_sec_context
10076 conf_get_int(ssh->conf, CONF_gssapifwd),
10080 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
10081 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
10082 logevent("GSSAPI authentication initialisation failed");
10084 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
10085 &s->gss_buf) == SSH_GSS_OK) {
10086 logevent(s->gss_buf.value);
10087 sfree(s->gss_buf.value);
10092 logevent("GSSAPI authentication initialised");
10094 /* Client and server now exchange tokens until GSSAPI
10095 * no longer says CONTINUE_NEEDED */
10097 if (s->gss_sndtok.length != 0) {
10098 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
10099 ssh_pkt_addstring_start(s->pktout);
10100 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
10101 ssh2_pkt_send(ssh, s->pktout);
10102 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
10105 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
10106 crWaitUntilV(pktin);
10107 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
10108 logevent("GSSAPI authentication - bad server response");
10109 s->gss_stat = SSH_GSS_FAILURE;
10112 ssh_pkt_getstring(pktin, &data, &len);
10113 s->gss_rcvtok.value = data;
10114 s->gss_rcvtok.length = len;
10116 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
10118 if (s->gss_stat != SSH_GSS_OK) {
10119 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10120 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10123 logevent("GSSAPI authentication loop finished OK");
10125 /* Now send the MIC */
10127 s->pktout = ssh2_pkt_init(0);
10128 micoffset = s->pktout->length;
10129 ssh_pkt_addstring_start(s->pktout);
10130 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
10131 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
10132 ssh_pkt_addstring(s->pktout, ssh->username);
10133 ssh_pkt_addstring(s->pktout, "ssh-connection");
10134 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
10136 s->gss_buf.value = (char *)s->pktout->data + micoffset;
10137 s->gss_buf.length = s->pktout->length - micoffset;
10139 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
10140 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
10141 ssh_pkt_addstring_start(s->pktout);
10142 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
10143 ssh2_pkt_send(ssh, s->pktout);
10144 s->gsslib->free_mic(s->gsslib, &mic);
10148 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
10149 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
10152 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
10155 * Keyboard-interactive authentication.
10158 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
10160 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
10162 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10163 ssh2_pkt_addstring(s->pktout, ssh->username);
10164 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10165 /* service requested */
10166 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
10168 ssh2_pkt_addstring(s->pktout, ""); /* lang */
10169 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
10170 ssh2_pkt_send(ssh, s->pktout);
10172 logevent("Attempting keyboard-interactive authentication");
10174 crWaitUntilV(pktin);
10175 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
10176 /* Server is not willing to do keyboard-interactive
10177 * at all (or, bizarrely but legally, accepts the
10178 * user without actually issuing any prompts).
10179 * Give up on it entirely. */
10181 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
10182 s->kbd_inter_refused = TRUE; /* don't try it again */
10187 * Loop while the server continues to send INFO_REQUESTs.
10189 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
10191 char *name, *inst, *lang;
10192 int name_len, inst_len, lang_len;
10196 * We've got a fresh USERAUTH_INFO_REQUEST.
10197 * Get the preamble and start building a prompt.
10199 ssh_pkt_getstring(pktin, &name, &name_len);
10200 ssh_pkt_getstring(pktin, &inst, &inst_len);
10201 ssh_pkt_getstring(pktin, &lang, &lang_len);
10202 s->cur_prompt = new_prompts(ssh->frontend);
10203 s->cur_prompt->to_server = TRUE;
10206 * Get any prompt(s) from the packet.
10208 s->num_prompts = ssh_pkt_getuint32(pktin);
10209 for (i = 0; i < s->num_prompts; i++) {
10213 static char noprompt[] =
10214 "<server failed to send prompt>: ";
10216 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10217 echo = ssh2_pkt_getbool(pktin);
10220 prompt_len = lenof(noprompt)-1;
10222 add_prompt(s->cur_prompt,
10223 dupprintf("%.*s", prompt_len, prompt),
10228 /* FIXME: better prefix to distinguish from
10229 * local prompts? */
10230 s->cur_prompt->name =
10231 dupprintf("SSH server: %.*s", name_len, name);
10232 s->cur_prompt->name_reqd = TRUE;
10234 s->cur_prompt->name =
10235 dupstr("SSH server authentication");
10236 s->cur_prompt->name_reqd = FALSE;
10238 /* We add a prefix to try to make it clear that a prompt
10239 * has come from the server.
10240 * FIXME: ugly to print "Using..." in prompt _every_
10241 * time round. Can this be done more subtly? */
10242 /* Special case: for reasons best known to themselves,
10243 * some servers send k-i requests with no prompts and
10244 * nothing to display. Keep quiet in this case. */
10245 if (s->num_prompts || name_len || inst_len) {
10246 s->cur_prompt->instruction =
10247 dupprintf("Using keyboard-interactive authentication.%s%.*s",
10248 inst_len ? "\n" : "", inst_len, inst);
10249 s->cur_prompt->instr_reqd = TRUE;
10251 s->cur_prompt->instr_reqd = FALSE;
10255 * Display any instructions, and get the user's
10259 int ret; /* not live over crReturn */
10260 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10263 crWaitUntilV(!pktin);
10264 ret = get_userpass_input(s->cur_prompt, in, inlen);
10269 * Failed to get responses. Terminate.
10271 free_prompts(s->cur_prompt);
10272 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10273 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10280 * Send the response(s) to the server.
10282 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
10283 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
10284 for (i=0; i < s->num_prompts; i++) {
10285 ssh2_pkt_addstring(s->pktout,
10286 s->cur_prompt->prompts[i]->result);
10288 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10291 * Free the prompts structure from this iteration.
10292 * If there's another, a new one will be allocated
10293 * when we return to the top of this while loop.
10295 free_prompts(s->cur_prompt);
10298 * Get the next packet in case it's another
10301 crWaitUntilV(pktin);
10306 * We should have SUCCESS or FAILURE now.
10310 } else if (s->can_passwd) {
10313 * Plain old password authentication.
10315 int ret; /* not live over crReturn */
10316 int changereq_first_time; /* not live over crReturn */
10318 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
10320 s->cur_prompt = new_prompts(ssh->frontend);
10321 s->cur_prompt->to_server = TRUE;
10322 s->cur_prompt->name = dupstr("SSH password");
10323 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
10328 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10331 crWaitUntilV(!pktin);
10332 ret = get_userpass_input(s->cur_prompt, in, inlen);
10337 * Failed to get responses. Terminate.
10339 free_prompts(s->cur_prompt);
10340 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10341 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10346 * Squirrel away the password. (We may need it later if
10347 * asked to change it.)
10349 s->password = dupstr(s->cur_prompt->prompts[0]->result);
10350 free_prompts(s->cur_prompt);
10353 * Send the password packet.
10355 * We pad out the password packet to 256 bytes to make
10356 * it harder for an attacker to find the length of the
10359 * Anyone using a password longer than 256 bytes
10360 * probably doesn't have much to worry about from
10361 * people who find out how long their password is!
10363 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10364 ssh2_pkt_addstring(s->pktout, ssh->username);
10365 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10366 /* service requested */
10367 ssh2_pkt_addstring(s->pktout, "password");
10368 ssh2_pkt_addbool(s->pktout, FALSE);
10369 ssh2_pkt_addstring(s->pktout, s->password);
10370 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10371 logevent("Sent password");
10372 s->type = AUTH_TYPE_PASSWORD;
10375 * Wait for next packet, in case it's a password change
10378 crWaitUntilV(pktin);
10379 changereq_first_time = TRUE;
10381 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
10384 * We're being asked for a new password
10385 * (perhaps not for the first time).
10386 * Loop until the server accepts it.
10389 int got_new = FALSE; /* not live over crReturn */
10390 char *prompt; /* not live over crReturn */
10391 int prompt_len; /* not live over crReturn */
10395 if (changereq_first_time)
10396 msg = "Server requested password change";
10398 msg = "Server rejected new password";
10400 c_write_str(ssh, msg);
10401 c_write_str(ssh, "\r\n");
10404 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
10406 s->cur_prompt = new_prompts(ssh->frontend);
10407 s->cur_prompt->to_server = TRUE;
10408 s->cur_prompt->name = dupstr("New SSH password");
10409 s->cur_prompt->instruction =
10410 dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
10411 s->cur_prompt->instr_reqd = TRUE;
10413 * There's no explicit requirement in the protocol
10414 * for the "old" passwords in the original and
10415 * password-change messages to be the same, and
10416 * apparently some Cisco kit supports password change
10417 * by the user entering a blank password originally
10418 * and the real password subsequently, so,
10419 * reluctantly, we prompt for the old password again.
10421 * (On the other hand, some servers don't even bother
10422 * to check this field.)
10424 add_prompt(s->cur_prompt,
10425 dupstr("Current password (blank for previously entered password): "),
10427 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
10429 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
10433 * Loop until the user manages to enter the same
10438 ret = get_userpass_input(s->cur_prompt, NULL, 0);
10441 crWaitUntilV(!pktin);
10442 ret = get_userpass_input(s->cur_prompt, in, inlen);
10447 * Failed to get responses. Terminate.
10449 /* burn the evidence */
10450 free_prompts(s->cur_prompt);
10451 smemclr(s->password, strlen(s->password));
10452 sfree(s->password);
10453 ssh_disconnect(ssh, NULL, "Unable to authenticate",
10454 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
10460 * If the user specified a new original password
10461 * (IYSWIM), overwrite any previously specified
10463 * (A side effect is that the user doesn't have to
10464 * re-enter it if they louse up the new password.)
10466 if (s->cur_prompt->prompts[0]->result[0]) {
10467 smemclr(s->password, strlen(s->password));
10468 /* burn the evidence */
10469 sfree(s->password);
10471 dupstr(s->cur_prompt->prompts[0]->result);
10475 * Check the two new passwords match.
10477 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
10478 s->cur_prompt->prompts[2]->result)
10481 /* They don't. Silly user. */
10482 c_write_str(ssh, "Passwords do not match\r\n");
10487 * Send the new password (along with the old one).
10488 * (see above for padding rationale)
10490 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
10491 ssh2_pkt_addstring(s->pktout, ssh->username);
10492 ssh2_pkt_addstring(s->pktout, "ssh-connection");
10493 /* service requested */
10494 ssh2_pkt_addstring(s->pktout, "password");
10495 ssh2_pkt_addbool(s->pktout, TRUE);
10496 ssh2_pkt_addstring(s->pktout, s->password);
10497 ssh2_pkt_addstring(s->pktout,
10498 s->cur_prompt->prompts[1]->result);
10499 free_prompts(s->cur_prompt);
10500 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
10501 logevent("Sent new password");
10504 * Now see what the server has to say about it.
10505 * (If it's CHANGEREQ again, it's not happy with the
10508 crWaitUntilV(pktin);
10509 changereq_first_time = FALSE;
10514 * We need to reexamine the current pktin at the top
10515 * of the loop. Either:
10516 * - we weren't asked to change password at all, in
10517 * which case it's a SUCCESS or FAILURE with the
10519 * - we sent a new password, and the server was
10520 * either OK with it (SUCCESS or FAILURE w/partial
10521 * success) or unhappy with the _old_ password
10522 * (FAILURE w/o partial success)
10523 * In any of these cases, we go back to the top of
10524 * the loop and start again.
10529 * We don't need the old password any more, in any
10530 * case. Burn the evidence.
10532 smemclr(s->password, strlen(s->password));
10533 sfree(s->password);
10536 char *str = dupprintf("No supported authentication methods available"
10537 " (server sent: %.*s)",
10540 ssh_disconnect(ssh, str,
10541 "No supported authentication methods available",
10542 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
10552 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
10554 /* Clear up various bits and pieces from authentication. */
10555 if (s->publickey_blob) {
10556 sfree(s->publickey_algorithm);
10557 sfree(s->publickey_blob);
10558 sfree(s->publickey_comment);
10560 if (s->agent_response)
10561 sfree(s->agent_response);
10563 if (s->userauth_success && !ssh->bare_connection) {
10565 * We've just received USERAUTH_SUCCESS, and we haven't sent any
10566 * packets since. Signal the transport layer to consider enacting
10567 * delayed compression.
10569 * (Relying on we_are_in is not sufficient, as
10570 * draft-miller-secsh-compression-delayed is quite clear that it
10571 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
10572 * become set for other reasons.)
10574 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
10577 ssh->channels = newtree234(ssh_channelcmp);
10580 * Set up handlers for some connection protocol messages, so we
10581 * don't have to handle them repeatedly in this coroutine.
10583 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
10584 ssh2_msg_channel_window_adjust;
10585 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
10586 ssh2_msg_global_request;
10589 * Create the main session channel.
10591 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
10592 ssh->mainchan = NULL;
10594 ssh->mainchan = snew(struct ssh_channel);
10595 ssh->mainchan->ssh = ssh;
10596 ssh_channel_init(ssh->mainchan);
10598 if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
10600 * Just start a direct-tcpip channel and use it as the main
10603 ssh_send_port_open(ssh->mainchan,
10604 conf_get_str(ssh->conf, CONF_ssh_nc_host),
10605 conf_get_int(ssh->conf, CONF_ssh_nc_port),
10607 ssh->ncmode = TRUE;
10609 s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
10610 logevent("Opening session as main channel");
10611 ssh2_pkt_send(ssh, s->pktout);
10612 ssh->ncmode = FALSE;
10614 crWaitUntilV(pktin);
10615 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
10616 bombout(("Server refused to open channel"));
10618 /* FIXME: error data comes back in FAILURE packet */
10620 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
10621 bombout(("Server's channel confirmation cited wrong channel"));
10624 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
10625 ssh->mainchan->halfopen = FALSE;
10626 ssh->mainchan->type = CHAN_MAINSESSION;
10627 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
10628 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
10629 update_specials_menu(ssh->frontend);
10630 logevent("Opened main channel");
10634 * Now we have a channel, make dispatch table entries for
10635 * general channel-based messages.
10637 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
10638 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
10639 ssh2_msg_channel_data;
10640 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
10641 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
10642 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
10643 ssh2_msg_channel_open_confirmation;
10644 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
10645 ssh2_msg_channel_open_failure;
10646 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
10647 ssh2_msg_channel_request;
10648 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
10649 ssh2_msg_channel_open;
10650 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
10651 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
10654 * Now the connection protocol is properly up and running, with
10655 * all those dispatch table entries, so it's safe to let
10656 * downstreams start trying to open extra channels through us.
10658 if (ssh->connshare)
10659 share_activate(ssh->connshare, ssh->v_s);
10661 if (ssh->mainchan && ssh_is_simple(ssh)) {
10663 * This message indicates to the server that we promise
10664 * not to try to run any other channel in parallel with
10665 * this one, so it's safe for it to advertise a very large
10666 * window and leave the flow control to TCP.
10668 s->pktout = ssh2_chanreq_init(ssh->mainchan,
10669 "simple@putty.projects.tartarus.org",
10671 ssh2_pkt_send(ssh, s->pktout);
10675 * Enable port forwardings.
10677 ssh_setup_portfwd(ssh, ssh->conf);
10679 if (ssh->mainchan && !ssh->ncmode) {
10681 * Send the CHANNEL_REQUESTS for the main session channel.
10682 * Each one is handled by its own little asynchronous
10686 /* Potentially enable X11 forwarding. */
10687 if (conf_get_int(ssh->conf, CONF_x11_forward)) {
10689 x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
10691 if (!ssh->x11disp) {
10692 /* FIXME: return an error message from x11_setup_display */
10693 logevent("X11 forwarding not enabled: unable to"
10694 " initialise X display");
10696 ssh->x11auth = x11_invent_fake_auth
10697 (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
10698 ssh->x11auth->disp = ssh->x11disp;
10700 ssh2_setup_x11(ssh->mainchan, NULL, NULL);
10704 /* Potentially enable agent forwarding. */
10705 if (ssh_agent_forwarding_permitted(ssh))
10706 ssh2_setup_agent(ssh->mainchan, NULL, NULL);
10708 /* Now allocate a pty for the session. */
10709 if (!conf_get_int(ssh->conf, CONF_nopty))
10710 ssh2_setup_pty(ssh->mainchan, NULL, NULL);
10712 /* Send environment variables. */
10713 ssh2_setup_env(ssh->mainchan, NULL, NULL);
10716 * Start a shell or a remote command. We may have to attempt
10717 * this twice if the config data has provided a second choice
10724 if (ssh->fallback_cmd) {
10725 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
10726 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
10728 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
10729 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
10733 s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
10734 ssh2_response_authconn, NULL);
10735 ssh2_pkt_addstring(s->pktout, cmd);
10737 s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
10738 ssh2_response_authconn, NULL);
10739 ssh2_pkt_addstring(s->pktout, cmd);
10741 s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
10742 ssh2_response_authconn, NULL);
10744 ssh2_pkt_send(ssh, s->pktout);
10746 crWaitUntilV(pktin);
10748 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
10749 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
10750 bombout(("Unexpected response to shell/command request:"
10751 " packet type %d", pktin->type));
10755 * We failed to start the command. If this is the
10756 * fallback command, we really are finished; if it's
10757 * not, and if the fallback command exists, try falling
10758 * back to it before complaining.
10760 if (!ssh->fallback_cmd &&
10761 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
10762 logevent("Primary command failed; attempting fallback");
10763 ssh->fallback_cmd = TRUE;
10766 bombout(("Server refused to start a shell/command"));
10769 logevent("Started a shell/command");
10774 ssh->editing = ssh->echoing = TRUE;
10777 ssh->state = SSH_STATE_SESSION;
10778 if (ssh->size_needed)
10779 ssh_size(ssh, ssh->term_width, ssh->term_height);
10780 if (ssh->eof_needed)
10781 ssh_special(ssh, TS_EOF);
10787 ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
10795 * _All_ the connection-layer packets we expect to
10796 * receive are now handled by the dispatch table.
10797 * Anything that reaches here must be bogus.
10800 bombout(("Strange packet received: type %d", pktin->type));
10802 } else if (ssh->mainchan) {
10804 * We have spare data. Add it to the channel buffer.
10806 ssh_send_channel_data(ssh->mainchan, (char *)in, inlen);
10814 * Handlers for SSH-2 messages that might arrive at any moment.
10816 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
10818 /* log reason code in disconnect message */
10820 int reason, msglen;
10822 reason = ssh_pkt_getuint32(pktin);
10823 ssh_pkt_getstring(pktin, &msg, &msglen);
10825 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
10826 buf = dupprintf("Received disconnect message (%s)",
10827 ssh2_disconnect_reasons[reason]);
10829 buf = dupprintf("Received disconnect message (unknown"
10830 " type %d)", reason);
10834 buf = dupprintf("Disconnection message text: %.*s",
10835 msglen, NULLTOEMPTY(msg));
10837 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
10839 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
10840 ssh2_disconnect_reasons[reason] : "unknown",
10841 msglen, NULLTOEMPTY(msg)));
10845 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
10847 /* log the debug message */
10851 /* XXX maybe we should actually take notice of the return value */
10852 ssh2_pkt_getbool(pktin);
10853 ssh_pkt_getstring(pktin, &msg, &msglen);
10855 logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
10858 static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
10860 do_ssh2_transport(ssh, NULL, 0, pktin);
10864 * Called if we receive a packet that isn't allowed by the protocol.
10865 * This only applies to packets whose meaning PuTTY understands.
10866 * Entirely unknown packets are handled below.
10868 static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
10870 char *buf = dupprintf("Server protocol violation: unexpected %s packet",
10871 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
10873 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
10877 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
10879 struct Packet *pktout;
10880 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
10881 ssh2_pkt_adduint32(pktout, pktin->sequence);
10883 * UNIMPLEMENTED messages MUST appear in the same order as the
10884 * messages they respond to. Hence, never queue them.
10886 ssh2_pkt_send_noqueue(ssh, pktout);
10890 * Handle the top-level SSH-2 protocol.
10892 static void ssh2_protocol_setup(Ssh ssh)
10897 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10899 for (i = 0; i < 256; i++)
10900 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10903 * Initially, we only accept transport messages (and a few generic
10904 * ones). do_ssh2_authconn will add more when it starts.
10905 * Messages that are understood but not currently acceptable go to
10906 * ssh2_msg_unexpected.
10908 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10909 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
10910 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
10911 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
10912 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
10913 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
10914 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
10915 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
10916 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
10917 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
10918 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
10919 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
10920 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
10921 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
10922 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
10923 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
10924 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
10925 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
10926 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
10927 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10928 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10929 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10930 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10931 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10932 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10933 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10934 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10935 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10936 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10937 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10938 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10939 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10940 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10943 * These messages have a special handler from the start.
10945 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10946 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
10947 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10950 static void ssh2_bare_connection_protocol_setup(Ssh ssh)
10955 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
10957 for (i = 0; i < 256; i++)
10958 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
10961 * Initially, we set all ssh-connection messages to 'unexpected';
10962 * do_ssh2_authconn will fill things in properly. We also handle a
10963 * couple of messages from the transport protocol which aren't
10964 * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
10967 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
10968 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
10969 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
10970 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
10971 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
10972 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
10973 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
10974 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
10975 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
10976 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
10977 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
10978 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
10979 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
10980 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
10982 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
10985 * These messages have a special handler from the start.
10987 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
10988 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
10989 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
10992 static void ssh2_timer(void *ctx, unsigned long now)
10994 Ssh ssh = (Ssh)ctx;
10996 if (ssh->state == SSH_STATE_CLOSED)
10999 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11000 conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
11001 now == ssh->next_rekey) {
11002 do_ssh2_transport(ssh, "timeout", -1, NULL);
11006 static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
11007 struct Packet *pktin)
11009 const unsigned char *in = (const unsigned char *)vin;
11010 if (ssh->state == SSH_STATE_CLOSED)
11014 ssh->incoming_data_size += pktin->encrypted_len;
11015 if (!ssh->kex_in_progress &&
11016 ssh->max_data_size != 0 &&
11017 ssh->incoming_data_size > ssh->max_data_size)
11018 do_ssh2_transport(ssh, "too much data received", -1, NULL);
11022 ssh->packet_dispatch[pktin->type](ssh, pktin);
11023 else if (!ssh->protocol_initial_phase_done)
11024 do_ssh2_transport(ssh, in, inlen, pktin);
11026 do_ssh2_authconn(ssh, in, inlen, pktin);
11029 static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
11030 struct Packet *pktin)
11032 const unsigned char *in = (const unsigned char *)vin;
11033 if (ssh->state == SSH_STATE_CLOSED)
11037 ssh->packet_dispatch[pktin->type](ssh, pktin);
11039 do_ssh2_authconn(ssh, in, inlen, pktin);
11042 static void ssh_cache_conf_values(Ssh ssh)
11044 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
11048 * Called to set up the connection.
11050 * Returns an error message, or NULL on success.
11052 static const char *ssh_init(void *frontend_handle, void **backend_handle,
11054 const char *host, int port, char **realhost,
11055 int nodelay, int keepalive)
11060 ssh = snew(struct ssh_tag);
11061 ssh->conf = conf_copy(conf);
11062 ssh_cache_conf_values(ssh);
11063 ssh->version = 0; /* when not ready yet */
11065 ssh->cipher = NULL;
11066 ssh->v1_cipher_ctx = NULL;
11067 ssh->crcda_ctx = NULL;
11068 ssh->cscipher = NULL;
11069 ssh->cs_cipher_ctx = NULL;
11070 ssh->sccipher = NULL;
11071 ssh->sc_cipher_ctx = NULL;
11073 ssh->cs_mac_ctx = NULL;
11075 ssh->sc_mac_ctx = NULL;
11076 ssh->cscomp = NULL;
11077 ssh->cs_comp_ctx = NULL;
11078 ssh->sccomp = NULL;
11079 ssh->sc_comp_ctx = NULL;
11081 ssh->kex_ctx = NULL;
11082 ssh->hostkey = NULL;
11083 ssh->hostkey_str = NULL;
11084 ssh->exitcode = -1;
11085 ssh->close_expected = FALSE;
11086 ssh->clean_exit = FALSE;
11087 ssh->state = SSH_STATE_PREPACKET;
11088 ssh->size_needed = FALSE;
11089 ssh->eof_needed = FALSE;
11091 ssh->logctx = NULL;
11092 ssh->deferred_send_data = NULL;
11093 ssh->deferred_len = 0;
11094 ssh->deferred_size = 0;
11095 ssh->fallback_cmd = 0;
11096 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
11097 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
11098 ssh->x11disp = NULL;
11099 ssh->x11auth = NULL;
11100 ssh->x11authtree = newtree234(x11_authcmp);
11101 ssh->v1_compressing = FALSE;
11102 ssh->v2_outgoing_sequence = 0;
11103 ssh->ssh1_rdpkt_crstate = 0;
11104 ssh->ssh2_rdpkt_crstate = 0;
11105 ssh->ssh2_bare_rdpkt_crstate = 0;
11106 ssh->ssh_gotdata_crstate = 0;
11107 ssh->do_ssh1_connection_crstate = 0;
11108 ssh->do_ssh_init_state = NULL;
11109 ssh->do_ssh_connection_init_state = NULL;
11110 ssh->do_ssh1_login_state = NULL;
11111 ssh->do_ssh2_transport_state = NULL;
11112 ssh->do_ssh2_authconn_state = NULL;
11115 ssh->mainchan = NULL;
11116 ssh->throttled_all = 0;
11117 ssh->v1_stdout_throttling = 0;
11119 ssh->queuelen = ssh->queuesize = 0;
11120 ssh->queueing = FALSE;
11121 ssh->qhead = ssh->qtail = NULL;
11122 ssh->deferred_rekey_reason = NULL;
11123 bufchain_init(&ssh->queued_incoming_data);
11124 ssh->frozen = FALSE;
11125 ssh->username = NULL;
11126 ssh->sent_console_eof = FALSE;
11127 ssh->got_pty = FALSE;
11128 ssh->bare_connection = FALSE;
11129 ssh->X11_fwd_enabled = FALSE;
11130 ssh->connshare = NULL;
11131 ssh->attempting_connshare = FALSE;
11132 ssh->session_started = FALSE;
11133 ssh->specials = NULL;
11134 ssh->n_uncert_hostkeys = 0;
11135 ssh->cross_certifying = FALSE;
11137 *backend_handle = ssh;
11140 if (crypto_startup() == 0)
11141 return "Microsoft high encryption pack not installed!";
11144 ssh->frontend = frontend_handle;
11145 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
11146 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
11148 ssh->channels = NULL;
11149 ssh->rportfwds = NULL;
11150 ssh->portfwds = NULL;
11155 ssh->conn_throttle_count = 0;
11156 ssh->overall_bufsize = 0;
11157 ssh->fallback_cmd = 0;
11159 ssh->protocol = NULL;
11161 ssh->protocol_initial_phase_done = FALSE;
11163 ssh->pinger = NULL;
11165 ssh->incoming_data_size = ssh->outgoing_data_size =
11166 ssh->deferred_data_size = 0L;
11167 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11168 CONF_ssh_rekey_data));
11169 ssh->kex_in_progress = FALSE;
11172 ssh->gsslibs = NULL;
11175 random_ref(); /* do this now - may be needed by sharing setup code */
11177 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
11186 static void ssh_free(void *handle)
11188 Ssh ssh = (Ssh) handle;
11189 struct ssh_channel *c;
11190 struct ssh_rportfwd *pf;
11191 struct X11FakeAuth *auth;
11193 if (ssh->v1_cipher_ctx)
11194 ssh->cipher->free_context(ssh->v1_cipher_ctx);
11195 if (ssh->cs_cipher_ctx)
11196 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
11197 if (ssh->sc_cipher_ctx)
11198 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
11199 if (ssh->cs_mac_ctx)
11200 ssh->csmac->free_context(ssh->cs_mac_ctx);
11201 if (ssh->sc_mac_ctx)
11202 ssh->scmac->free_context(ssh->sc_mac_ctx);
11203 if (ssh->cs_comp_ctx) {
11205 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
11207 zlib_compress_cleanup(ssh->cs_comp_ctx);
11209 if (ssh->sc_comp_ctx) {
11211 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
11213 zlib_decompress_cleanup(ssh->sc_comp_ctx);
11216 dh_cleanup(ssh->kex_ctx);
11217 sfree(ssh->savedhost);
11219 while (ssh->queuelen-- > 0)
11220 ssh_free_packet(ssh->queue[ssh->queuelen]);
11223 while (ssh->qhead) {
11224 struct queued_handler *qh = ssh->qhead;
11225 ssh->qhead = qh->next;
11228 ssh->qhead = ssh->qtail = NULL;
11230 if (ssh->channels) {
11231 while ((c = delpos234(ssh->channels, 0)) != NULL) {
11232 ssh_channel_close_local(c, NULL);
11233 if (ssh->version == 2) {
11234 struct outstanding_channel_request *ocr, *nocr;
11235 ocr = c->v.v2.chanreq_head;
11237 ocr->handler(c, NULL, ocr->ctx);
11242 bufchain_clear(&c->v.v2.outbuffer);
11246 freetree234(ssh->channels);
11247 ssh->channels = NULL;
11250 if (ssh->connshare)
11251 sharestate_free(ssh->connshare);
11253 if (ssh->rportfwds) {
11254 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
11256 freetree234(ssh->rportfwds);
11257 ssh->rportfwds = NULL;
11259 sfree(ssh->deferred_send_data);
11261 x11_free_display(ssh->x11disp);
11262 while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
11263 x11_free_fake_auth(auth);
11264 freetree234(ssh->x11authtree);
11265 sfree(ssh->do_ssh_init_state);
11266 sfree(ssh->do_ssh1_login_state);
11267 sfree(ssh->do_ssh2_transport_state);
11268 sfree(ssh->do_ssh2_authconn_state);
11271 sfree(ssh->fullhostname);
11272 sfree(ssh->hostkey_str);
11273 sfree(ssh->specials);
11274 if (ssh->crcda_ctx) {
11275 crcda_free_context(ssh->crcda_ctx);
11276 ssh->crcda_ctx = NULL;
11279 ssh_do_close(ssh, TRUE);
11280 expire_timer_context(ssh);
11282 pinger_free(ssh->pinger);
11283 bufchain_clear(&ssh->queued_incoming_data);
11284 sfree(ssh->username);
11285 conf_free(ssh->conf);
11288 ssh_gss_cleanup(ssh->gsslibs);
11296 * Reconfigure the SSH backend.
11298 static void ssh_reconfig(void *handle, Conf *conf)
11300 Ssh ssh = (Ssh) handle;
11301 const char *rekeying = NULL;
11302 int rekey_mandatory = FALSE;
11303 unsigned long old_max_data_size;
11306 pinger_reconfig(ssh->pinger, ssh->conf, conf);
11308 ssh_setup_portfwd(ssh, conf);
11310 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
11311 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
11313 unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
11314 unsigned long now = GETTICKCOUNT();
11316 if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
11317 rekeying = "timeout shortened";
11319 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
11323 old_max_data_size = ssh->max_data_size;
11324 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
11325 CONF_ssh_rekey_data));
11326 if (old_max_data_size != ssh->max_data_size &&
11327 ssh->max_data_size != 0) {
11328 if (ssh->outgoing_data_size > ssh->max_data_size ||
11329 ssh->incoming_data_size > ssh->max_data_size)
11330 rekeying = "data limit lowered";
11333 if (conf_get_int(ssh->conf, CONF_compression) !=
11334 conf_get_int(conf, CONF_compression)) {
11335 rekeying = "compression setting changed";
11336 rekey_mandatory = TRUE;
11339 for (i = 0; i < CIPHER_MAX; i++)
11340 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
11341 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
11342 rekeying = "cipher settings changed";
11343 rekey_mandatory = TRUE;
11345 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
11346 conf_get_int(conf, CONF_ssh2_des_cbc)) {
11347 rekeying = "cipher settings changed";
11348 rekey_mandatory = TRUE;
11351 conf_free(ssh->conf);
11352 ssh->conf = conf_copy(conf);
11353 ssh_cache_conf_values(ssh);
11355 if (!ssh->bare_connection && rekeying) {
11356 if (!ssh->kex_in_progress) {
11357 do_ssh2_transport(ssh, rekeying, -1, NULL);
11358 } else if (rekey_mandatory) {
11359 ssh->deferred_rekey_reason = rekeying;
11365 * Called to send data down the SSH connection.
11367 static int ssh_send(void *handle, const char *buf, int len)
11369 Ssh ssh = (Ssh) handle;
11371 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11374 ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
11376 return ssh_sendbuffer(ssh);
11380 * Called to query the current amount of buffered stdin data.
11382 static int ssh_sendbuffer(void *handle)
11384 Ssh ssh = (Ssh) handle;
11385 int override_value;
11387 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
11391 * If the SSH socket itself has backed up, add the total backup
11392 * size on that to any individual buffer on the stdin channel.
11394 override_value = 0;
11395 if (ssh->throttled_all)
11396 override_value = ssh->overall_bufsize;
11398 if (ssh->version == 1) {
11399 return override_value;
11400 } else if (ssh->version == 2) {
11401 if (!ssh->mainchan)
11402 return override_value;
11404 return (override_value +
11405 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
11412 * Called to set the size of the window from SSH's POV.
11414 static void ssh_size(void *handle, int width, int height)
11416 Ssh ssh = (Ssh) handle;
11417 struct Packet *pktout;
11419 ssh->term_width = width;
11420 ssh->term_height = height;
11422 switch (ssh->state) {
11423 case SSH_STATE_BEFORE_SIZE:
11424 case SSH_STATE_PREPACKET:
11425 case SSH_STATE_CLOSED:
11426 break; /* do nothing */
11427 case SSH_STATE_INTERMED:
11428 ssh->size_needed = TRUE; /* buffer for later */
11430 case SSH_STATE_SESSION:
11431 if (!conf_get_int(ssh->conf, CONF_nopty)) {
11432 if (ssh->version == 1) {
11433 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
11434 PKT_INT, ssh->term_height,
11435 PKT_INT, ssh->term_width,
11436 PKT_INT, 0, PKT_INT, 0, PKT_END);
11437 } else if (ssh->mainchan) {
11438 pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
11440 ssh2_pkt_adduint32(pktout, ssh->term_width);
11441 ssh2_pkt_adduint32(pktout, ssh->term_height);
11442 ssh2_pkt_adduint32(pktout, 0);
11443 ssh2_pkt_adduint32(pktout, 0);
11444 ssh2_pkt_send(ssh, pktout);
11452 * Return a list of the special codes that make sense in this
11455 static const struct telnet_special *ssh_get_specials(void *handle)
11457 static const struct telnet_special ssh1_ignore_special[] = {
11458 {"IGNORE message", TS_NOP}
11460 static const struct telnet_special ssh2_ignore_special[] = {
11461 {"IGNORE message", TS_NOP},
11463 static const struct telnet_special ssh2_rekey_special[] = {
11464 {"Repeat key exchange", TS_REKEY},
11466 static const struct telnet_special ssh2_session_specials[] = {
11469 /* These are the signal names defined by RFC 4254.
11470 * They include all the ISO C signals, but are a subset of the POSIX
11471 * required signals. */
11472 {"SIGINT (Interrupt)", TS_SIGINT},
11473 {"SIGTERM (Terminate)", TS_SIGTERM},
11474 {"SIGKILL (Kill)", TS_SIGKILL},
11475 {"SIGQUIT (Quit)", TS_SIGQUIT},
11476 {"SIGHUP (Hangup)", TS_SIGHUP},
11477 {"More signals", TS_SUBMENU},
11478 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
11479 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
11480 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
11481 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
11482 {NULL, TS_EXITMENU}
11484 static const struct telnet_special specials_end[] = {
11485 {NULL, TS_EXITMENU}
11488 struct telnet_special *specials = NULL;
11489 int nspecials = 0, specialsize = 0;
11491 Ssh ssh = (Ssh) handle;
11493 sfree(ssh->specials);
11495 #define ADD_SPECIALS(name) do \
11497 int len = lenof(name); \
11498 if (nspecials + len > specialsize) { \
11499 specialsize = (nspecials + len) * 5 / 4 + 32; \
11500 specials = sresize(specials, specialsize, struct telnet_special); \
11502 memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
11503 nspecials += len; \
11506 if (ssh->version == 1) {
11507 /* Don't bother offering IGNORE if we've decided the remote
11508 * won't cope with it, since we wouldn't bother sending it if
11510 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11511 ADD_SPECIALS(ssh1_ignore_special);
11512 } else if (ssh->version == 2) {
11513 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
11514 ADD_SPECIALS(ssh2_ignore_special);
11515 if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
11516 ADD_SPECIALS(ssh2_rekey_special);
11518 ADD_SPECIALS(ssh2_session_specials);
11520 if (ssh->n_uncert_hostkeys) {
11521 static const struct telnet_special uncert_start[] = {
11523 {"Cache new host key type", TS_SUBMENU},
11525 static const struct telnet_special uncert_end[] = {
11526 {NULL, TS_EXITMENU},
11530 ADD_SPECIALS(uncert_start);
11531 for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
11532 struct telnet_special uncert[1];
11533 const struct ssh_signkey *alg =
11534 hostkey_algs[ssh->uncert_hostkeys[i]].alg;
11535 uncert[0].name = alg->name;
11536 uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
11537 ADD_SPECIALS(uncert);
11539 ADD_SPECIALS(uncert_end);
11541 } /* else we're not ready yet */
11544 ADD_SPECIALS(specials_end);
11546 ssh->specials = specials;
11553 #undef ADD_SPECIALS
11557 * Send special codes. TS_EOF is useful for `plink', so you
11558 * can send an EOF and collect resulting output (e.g. `plink
11561 static void ssh_special(void *handle, Telnet_Special code)
11563 Ssh ssh = (Ssh) handle;
11564 struct Packet *pktout;
11566 if (code == TS_EOF) {
11567 if (ssh->state != SSH_STATE_SESSION) {
11569 * Buffer the EOF in case we are pre-SESSION, so we can
11570 * send it as soon as we reach SESSION.
11572 if (code == TS_EOF)
11573 ssh->eof_needed = TRUE;
11576 if (ssh->version == 1) {
11577 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
11578 } else if (ssh->mainchan) {
11579 sshfwd_write_eof(ssh->mainchan);
11580 ssh->send_ok = 0; /* now stop trying to read from stdin */
11582 logevent("Sent EOF message");
11583 } else if (code == TS_PING || code == TS_NOP) {
11584 if (ssh->state == SSH_STATE_CLOSED
11585 || ssh->state == SSH_STATE_PREPACKET) return;
11586 if (ssh->version == 1) {
11587 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
11588 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
11590 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
11591 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
11592 ssh2_pkt_addstring_start(pktout);
11593 ssh2_pkt_send_noqueue(ssh, pktout);
11596 } else if (code == TS_REKEY) {
11597 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11598 ssh->version == 2) {
11599 do_ssh2_transport(ssh, "at user request", -1, NULL);
11601 } else if (code >= TS_LOCALSTART) {
11602 ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
11603 ssh->cross_certifying = TRUE;
11604 if (!ssh->kex_in_progress && !ssh->bare_connection &&
11605 ssh->version == 2) {
11606 do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
11608 } else if (code == TS_BRK) {
11609 if (ssh->state == SSH_STATE_CLOSED
11610 || ssh->state == SSH_STATE_PREPACKET) return;
11611 if (ssh->version == 1) {
11612 logevent("Unable to send BREAK signal in SSH-1");
11613 } else if (ssh->mainchan) {
11614 pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
11615 ssh2_pkt_adduint32(pktout, 0); /* default break length */
11616 ssh2_pkt_send(ssh, pktout);
11619 /* Is is a POSIX signal? */
11620 const char *signame = NULL;
11621 if (code == TS_SIGABRT) signame = "ABRT";
11622 if (code == TS_SIGALRM) signame = "ALRM";
11623 if (code == TS_SIGFPE) signame = "FPE";
11624 if (code == TS_SIGHUP) signame = "HUP";
11625 if (code == TS_SIGILL) signame = "ILL";
11626 if (code == TS_SIGINT) signame = "INT";
11627 if (code == TS_SIGKILL) signame = "KILL";
11628 if (code == TS_SIGPIPE) signame = "PIPE";
11629 if (code == TS_SIGQUIT) signame = "QUIT";
11630 if (code == TS_SIGSEGV) signame = "SEGV";
11631 if (code == TS_SIGTERM) signame = "TERM";
11632 if (code == TS_SIGUSR1) signame = "USR1";
11633 if (code == TS_SIGUSR2) signame = "USR2";
11634 /* The SSH-2 protocol does in principle support arbitrary named
11635 * signals, including signame@domain, but we don't support those. */
11637 /* It's a signal. */
11638 if (ssh->version == 2 && ssh->mainchan) {
11639 pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
11640 ssh2_pkt_addstring(pktout, signame);
11641 ssh2_pkt_send(ssh, pktout);
11642 logeventf(ssh, "Sent signal SIG%s", signame);
11645 /* Never heard of it. Do nothing */
11650 void *new_sock_channel(void *handle, struct PortForwarding *pf)
11652 Ssh ssh = (Ssh) handle;
11653 struct ssh_channel *c;
11654 c = snew(struct ssh_channel);
11657 ssh_channel_init(c);
11658 c->halfopen = TRUE;
11659 c->type = CHAN_SOCKDATA;/* identify channel type */
11664 unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
11666 struct ssh_channel *c;
11667 c = snew(struct ssh_channel);
11670 ssh_channel_init(c);
11671 c->type = CHAN_SHARING;
11672 c->u.sharing.ctx = sharing_ctx;
11676 void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
11678 struct ssh_channel *c;
11680 c = find234(ssh->channels, &localid, ssh_channelfind);
11682 ssh_channel_destroy(c);
11685 void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
11686 const void *data, int datalen,
11687 const char *additional_log_text)
11689 struct Packet *pkt;
11691 pkt = ssh2_pkt_init(type);
11692 pkt->downstream_id = id;
11693 pkt->additional_log_text = additional_log_text;
11694 ssh2_pkt_adddata(pkt, data, datalen);
11695 ssh2_pkt_send(ssh, pkt);
11699 * This is called when stdout/stderr (the entity to which
11700 * from_backend sends data) manages to clear some backlog.
11702 static void ssh_unthrottle(void *handle, int bufsize)
11704 Ssh ssh = (Ssh) handle;
11706 if (ssh->version == 1) {
11707 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
11708 ssh->v1_stdout_throttling = 0;
11709 ssh_throttle_conn(ssh, -1);
11713 ssh_channel_unthrottle(ssh->mainchan, bufsize);
11717 * Now process any SSH connection data that was stashed in our
11718 * queue while we were frozen.
11720 ssh_process_queued_incoming_data(ssh);
11723 void ssh_send_port_open(void *channel, const char *hostname, int port,
11726 struct ssh_channel *c = (struct ssh_channel *)channel;
11728 struct Packet *pktout;
11730 logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
11732 if (ssh->version == 1) {
11733 send_packet(ssh, SSH1_MSG_PORT_OPEN,
11734 PKT_INT, c->localid,
11737 /* PKT_STR, <org:orgport>, */
11740 pktout = ssh2_chanopen_init(c, "direct-tcpip");
11742 char *trimmed_host = host_strduptrim(hostname);
11743 ssh2_pkt_addstring(pktout, trimmed_host);
11744 sfree(trimmed_host);
11746 ssh2_pkt_adduint32(pktout, port);
11748 * We make up values for the originator data; partly it's
11749 * too much hassle to keep track, and partly I'm not
11750 * convinced the server should be told details like that
11751 * about my local network configuration.
11752 * The "originator IP address" is syntactically a numeric
11753 * IP address, and some servers (e.g., Tectia) get upset
11754 * if it doesn't match this syntax.
11756 ssh2_pkt_addstring(pktout, "0.0.0.0");
11757 ssh2_pkt_adduint32(pktout, 0);
11758 ssh2_pkt_send(ssh, pktout);
11762 static int ssh_connected(void *handle)
11764 Ssh ssh = (Ssh) handle;
11765 return ssh->s != NULL;
11768 static int ssh_sendok(void *handle)
11770 Ssh ssh = (Ssh) handle;
11771 return ssh->send_ok;
11774 static int ssh_ldisc(void *handle, int option)
11776 Ssh ssh = (Ssh) handle;
11777 if (option == LD_ECHO)
11778 return ssh->echoing;
11779 if (option == LD_EDIT)
11780 return ssh->editing;
11784 static void ssh_provide_ldisc(void *handle, void *ldisc)
11786 Ssh ssh = (Ssh) handle;
11787 ssh->ldisc = ldisc;
11790 static void ssh_provide_logctx(void *handle, void *logctx)
11792 Ssh ssh = (Ssh) handle;
11793 ssh->logctx = logctx;
11796 static int ssh_return_exitcode(void *handle)
11798 Ssh ssh = (Ssh) handle;
11799 if (ssh->s != NULL)
11802 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
11806 * cfg_info for SSH is the protocol running in this session.
11807 * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
11808 * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
11810 static int ssh_cfg_info(void *handle)
11812 Ssh ssh = (Ssh) handle;
11813 if (ssh->version == 0)
11814 return 0; /* don't know yet */
11815 else if (ssh->bare_connection)
11818 return ssh->version;
11822 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
11823 * that fails. This variable is the means by which scp.c can reach
11824 * into the SSH code and find out which one it got.
11826 extern int ssh_fallback_cmd(void *handle)
11828 Ssh ssh = (Ssh) handle;
11829 return ssh->fallback_cmd;
11832 Backend ssh_backend = {
11842 ssh_return_exitcode,
11846 ssh_provide_logctx,
11849 ssh_test_for_upstream,